@aifeatures/admin-react 0.17.0 → 0.19.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 +129 -6
- package/dist/index.d.ts +129 -6
- package/dist/index.js +4 -4
- package/dist/styles.css +1 -1
- package/package.json +14 -13
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import*as Xa from"react";var ir="aifeatures:analytics:timezone",or;function Us(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function oi(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function fs(){return lr()??Us()}function lr(){if(or!==void 0)return or;try{let e=window.localStorage.getItem(ir);return oi(e)?e:null}catch{return null}}function cr(e){if(!(e!==null&&!oi(e))){or=e;try{e===null?window.localStorage.removeItem(ir):window.localStorage.setItem(ir,e)}catch{}}}function nn(e,a){let s=new URLSearchParams({period:String(e)}),t=fs();return t&&s.set("timezone",t),a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var Wt=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function ur(e,a){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${a}`}function dr(e,a="https://aifeatures.dev"){async function s(t,n={}){let i=`${a}${t}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let m;try{m=await o.json()}catch{}throw new Wt(ur(m?.error,o.status),o.status,m)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(t){return s(`/api/v1/forms/${t}`)},async createForm(t){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(t)})},async updateForm(t,n){return s(`/api/v1/forms/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(t){await s(`/api/v1/forms/${t}`,{method:"DELETE"})},async getSubmissions(t,n={}){let i=new URLSearchParams;n.limit!==void 0&&i.set("limit",String(n.limit)),n.offset!==void 0&&i.set("offset",String(n.offset));let o=i.toString(),m=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(m)},async getSubmission(t){return s(`/api/v1/submissions/${t}`)},async deleteSubmission(t){await s(`/api/v1/submissions/${t}`,{method:"DELETE"})},async downloadAttachment(t,n){let i=typeof n=="string"?{name:n}:n,o=i.name,m=i.id??i.name,d=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(m)}`,f=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!f.ok){let v;try{v=await f.json()}catch{}throw new Wt(ur(v?.error,f.status),f.status,v)}let r=await f.blob(),g=URL.createObjectURL(r),b=document.createElement("a");b.href=g,b.download=o,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(g)},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(t){let n=new URLSearchParams({limit:"10"});return t&&n.set("cursor",t),s(`/api/v1/promos?${n}`)},getPromo(t){return s(`/api/v1/promos/${encodeURIComponent(t)}`)},createPromo(t){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(t)})},disablePromo(t){return s(`/api/v1/promos/${encodeURIComponent(t)}/disable`,{method:"POST"})},replacePromo(t,n){return s(`/api/v1/promos/${encodeURIComponent(t)}/replace`,{method:"POST",body:JSON.stringify(n)})},async getProducts(t={}){let n=new URLSearchParams;t.include&&n.set("include",t.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(t){return s(`/api/v1/products/${t}`)},async createProduct(t){return s("/api/v1/products",{method:"POST",body:JSON.stringify(t)})},async updateProduct(t,n){return s(`/api/v1/products/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(t){await s(`/api/v1/products/${t}`,{method:"DELETE"})},async attachProductFile(t,n){let i=new FormData;i.append("file",n);let o=await fetch(`${a}/api/v1/products/${t}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let m;try{m=await o.json()}catch{}throw new Wt(ur(m?.error,o.status),o.status,m)}return o.json()},async attachProductFileFromUrl(t,n){return s(`/api/v1/products/${t}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(t,n){return s(`/api/v1/products/${t}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(t,n){return s(`/api/v1/options/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(t){await s(`/api/v1/options/${t}`,{method:"DELETE"})},async createVariant(t,n){return s(`/api/v1/products/${t}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(t,n){return s(`/api/v1/variants/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(t){await s(`/api/v1/variants/${t}`,{method:"DELETE"})},async setVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(t={}){let n=new URLSearchParams;t.email?n.set("email",t.email):t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(t){return s(`/api/v1/customers/${t}`)},async getOrders(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.source&&n.set("source",t.source),t.excludeStatus?.length&&n.set("exclude_status",t.excludeStatus.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.unfulfilledOnly&&n.set("unfulfilled_only","true"),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(t){return s(`/api/v1/orders/${t}`)},async getInvoices(t={}){let n=new URLSearchParams;t.labels?.length&&n.set("label",t.labels.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.customerId&&n.set("customer_id",t.customerId),t.q&&n.set("q",t.q),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.includeAggregates&&n.set("include","aggregates"),t.retainerId&&n.set("retainer_id",t.retainerId),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(t){return s(`/api/v1/invoices/${t}`)},async getInvoicePreview(t){return s(`/api/v1/invoices/${t}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(t={}){let n=new URLSearchParams;t.statuses?.length&&n.set("status",t.statuses.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(t){return s(`/api/v1/retainers/${t}`)},async resendOrderReceipt(t){await s(`/api/v1/orders/${t}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(t){return s(`/api/v1/orders/${t}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(t,n){return s(`/api/v1/orders/${t}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){let t=new URLSearchParams,n=fs();n&&t.set("timezone",n);let i=t.toString();return s(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${nn(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${nn(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${nn(t,n)}`)},async getAnalyticsConversions(t){return s((()=>{let n=new URLSearchParams({period:String(t)}),i=fs();return i&&n.set("timezone",i),`/api/v1/analytics/conversions?${n.toString()}`})())},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${nn(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;n.set("tz_offset_minutes",String(t.tzOffsetMinutes));let i=fs();return i&&n.set("timezone",i),s(`/api/v1/summary?${n.toString()}`)},async getPeople(t={}){let n=new URLSearchParams;t.since&&n.set("since",t.since),t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(t){return s(`/api/v1/people/${encodeURIComponent(t)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(t){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(t)})},async updateEventDestination(t,n){return s(`/api/v1/event-destinations/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(t){await s(`/api/v1/event-destinations/${t}`,{method:"DELETE"})},async rotateEventDestinationSecret(t){return s(`/api/v1/event-destinations/${t}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(t){return(await s(`/api/v1/event-destinations/${t}/secret`)).secret},async getEventDeliveries(t,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${t}/deliveries${i}`)).deliveries},async retryEventDelivery(t,n){return s(`/api/v1/event-destinations/${t}/deliveries/${n}/retry`,{method:"POST"})}}}import{jsx as Vs,jsxs as el}from"react/jsx-runtime";var li=Xa.createContext(null);function Qo(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 Xo({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Xa.useMemo(()=>Qo(e),[e]),o=Xa.useMemo(()=>dr(e,a),[e,a]),m=Xa.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?Vs("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:el("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[Vs("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),Vs("p",{className:"af-text-sm af-text-destructive",children:i})]})}):Vs(li.Provider,{value:m,children:Vs("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function ie(){let e=Xa.useContext(li);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as ts from"react";import{ArrowLeft as tc,Settings as ac,Inbox as sc}from"lucide-react";import*as rn from"react";import*as ba from"@radix-ui/react-tabs";import{clsx as tl}from"clsx";import{extendTailwindMerge as al}from"tailwind-merge";var sl=al({prefix:"af-"});function K(...e){return sl(tl(e))}import{jsx as fr}from"react/jsx-runtime";var on=ba.Root,$s=rn.forwardRef(({className:e,...a},s)=>fr(ba.List,{ref:s,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),...a}));$s.displayName=ba.List.displayName;var ya=rn.forwardRef(({className:e,...a},s)=>fr(ba.Trigger,{ref:s,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),...a}));ya.displayName=ba.Trigger.displayName;var ha=rn.forwardRef(({className:e,...a},s)=>fr(ba.Content,{ref:s,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),...a}));ha.displayName=ba.Content.displayName;import*as ci from"react";import{Slot as nl}from"@radix-ui/react-slot";import{cva as rl}from"class-variance-authority";import{jsx as ol}from"react/jsx-runtime";var il=rl("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=ci.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>ol(t?nl:"button",{className:K(il({variant:a,size:s,className:e})),ref:i,...n}));w.displayName="Button";import{Inbox as ui,Settings as ul}from"lucide-react";import*as qa from"react";import{jsx as za}from"react/jsx-runtime";var Be=qa.forwardRef(({className:e,...a},s)=>za("div",{className:"af-relative af-w-full af-overflow-auto",children:za("table",{ref:s,className:K("af-w-full af-caption-bottom af-text-sm",e),...a})}));Be.displayName="Table";var Fe=qa.forwardRef(({className:e,...a},s)=>za("thead",{ref:s,className:K("[&_tr]:af-border-b",e),...a}));Fe.displayName="TableHeader";var Me=qa.forwardRef(({className:e,...a},s)=>za("tbody",{ref:s,className:K("[&_tr:last-child]:af-border-0",e),...a}));Me.displayName="TableBody";var ll=qa.forwardRef(({className:e,...a},s)=>za("tfoot",{ref:s,className:K("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));ll.displayName="TableFooter";var pe=qa.forwardRef(({className:e,...a},s)=>za("tr",{ref:s,className:K("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));pe.displayName="TableRow";var F=qa.forwardRef(({className:e,...a},s)=>za("th",{ref:s,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),...a}));F.displayName="TableHead";var M=qa.forwardRef(({className:e,...a},s)=>za("td",{ref:s,className:K("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));M.displayName="TableCell";var cl=qa.forwardRef(({className:e,...a},s)=>za("caption",{ref:s,className:K("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));cl.displayName="TableCaption";import*as xa from"react";function ws(){let{api:e}=ie(),[a,s]=xa.useState([]),[t,n]=xa.useState(!0),[i,o]=xa.useState(null),m=xa.useCallback(async()=>{try{n(!0),o(null);let g=await e.getForms();s(g)}catch(g){o(g instanceof Error?g:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);xa.useEffect(()=>{m()},[m]);let d=xa.useCallback(async g=>{let b=await e.createForm(g);return s(v=>[...v,b]),b},[e]),f=xa.useCallback(async(g,b)=>{let v=await e.updateForm(g,b);return s(u=>u.map(l=>l.id===g?v:l)),v},[e]),r=xa.useCallback(async g=>{await e.deleteForm(g),s(b=>b.filter(v=>v.id!==g))},[e]);return{forms:a,isLoading:t,error:i,refetch:m,createForm:d,updateForm:f,deleteForm:r}}import{jsx as Et,jsxs as ja}from"react/jsx-runtime";function ln({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=ws();return t?Et("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Et("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Et("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:ja("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?ja("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Et(ui,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),ja("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Et("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Et("div",{className:a,children:ja(Be,{children:[Et(Fe,{children:ja(pe,{children:[Et(F,{children:"Name"}),Et(F,{children:"Endpoint"}),Et(F,{className:"af-text-right",children:"Actions"})]})}),Et(Me,{children:s.map(i=>ja(pe,{children:[Et(M,{className:"af-font-medium",children:i.name}),Et(M,{children:Et("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url.replace("https://aifeatures.dev","")})}),Et(M,{className:"af-text-right",children:ja("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[ja(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[Et(ui,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),ja(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[Et(ul,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as pl}from"lucide-react";import{cva as dl}from"class-variance-authority";import{jsx as ml}from"react/jsx-runtime";var fl=dl("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:a,...s}){return ml("div",{className:K(fl({variant:a}),e),...s})}import{jsx as ms,jsxs as cn}from"react/jsx-runtime";var gl={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 un(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 mr(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function vl(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:a="Email needs attention"}){return mr(e)?cn("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:[ms(pl,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function Ia({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||mr([n]));return t.length?ms("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=un(n),o=vl(n);return cn("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[cn("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[ms("span",{className:"af-font-medium",children:gl[n.kind]??"Email notification"}),ms(te,{variant:i.variant,children:i.label})]}),cn("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&mr([n])&&ms("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."}),i.detail&&ms("p",{className:"af-mt-1",children:i.detail}),o&&ms("p",{className:"af-mt-1",children:o})]},n.id)})}):null}import*as zs from"react";import{ChevronLeft as El,ChevronRight as Al,Eye as Il,Inbox as Dl,Paperclip as Ll}from"lucide-react";import*as es from"react";import*as we from"@radix-ui/react-select";import{Check as bl,ChevronDown as di,ChevronUp as yl}from"lucide-react";import{jsx as Lt,jsxs as pr}from"react/jsx-runtime";var ca=we.Root;var ua=we.Value,aa=es.forwardRef(({className:e,children:a,...s},t)=>pr(we.Trigger,{ref:t,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),...s,children:[a,Lt(we.Icon,{asChild:!0,children:Lt(di,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));aa.displayName=we.Trigger.displayName;var fi=es.forwardRef(({className:e,...a},s)=>Lt(we.ScrollUpButton,{ref:s,className:K("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Lt(yl,{className:"af-h-4 af-w-4"})}));fi.displayName=we.ScrollUpButton.displayName;var mi=es.forwardRef(({className:e,...a},s)=>Lt(we.ScrollDownButton,{ref:s,className:K("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Lt(di,{className:"af-h-4 af-w-4"})}));mi.displayName=we.ScrollDownButton.displayName;var sa=es.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>Lt(we.Portal,{children:pr(we.Content,{ref:n,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",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...t,children:[Lt(fi,{}),Lt(we.Viewport,{className:K("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:a}),Lt(mi,{})]})}));sa.displayName=we.Content.displayName;var hl=es.forwardRef(({className:e,...a},s)=>Lt(we.Label,{ref:s,className:K("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));hl.displayName=we.Label.displayName;var Ge=es.forwardRef(({className:e,children:a,...s},t)=>pr(we.Item,{ref:t,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),...s,children:[Lt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:Lt(we.ItemIndicator,{children:Lt(bl,{className:"af-h-4 af-w-4"})})}),Lt(we.ItemText,{children:a})]}));Ge.displayName=we.Item.displayName;var xl=es.forwardRef(({className:e,...a},s)=>Lt(we.Separator,{ref:s,className:K("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));xl.displayName=we.Separator.displayName;import*as da from"react";function dn({formId:e,initialPageSize:a=25}){let{api:s}=ie(),[t,n]=da.useState([]),[i,o]=da.useState(0),[m,d]=da.useState(!0),[f,r]=da.useState(null),[g,b]=da.useState(0),[v,u]=da.useState(a),l=da.useCallback(async()=>{if(e)try{d(!0),r(null);let x={limit:v,offset:g*v},D=await s.getSubmissions(e,x);n(D.submissions),o(D.total)}catch(x){r(x instanceof Error?x:new Error("Failed to fetch submissions"))}finally{d(!1)}},[s,e,g,v]);da.useEffect(()=>{l()},[l]);let p=da.useCallback(async x=>{await s.deleteSubmission(x),n(D=>D.filter(O=>O.id!==x)),o(D=>D-1)},[s]),h=Math.ceil(i/v);return{submissions:t,total:i,isLoading:m,error:f,page:g,pageSize:v,hasNextPage:g<h-1,hasPreviousPage:g>0,setPage:b,setPageSize:x=>{u(x),b(0)},refetch:l,deleteSubmission:p}}import*as gi from"react";import{ArrowLeft as wl,Download as Nl,Globe as Sl,Clock as _l,FileText as Rl,Loader2 as Pl,Monitor as Cl,Mail as Tl}from"lucide-react";import{jsx as lt,jsxs as ct}from"react/jsx-runtime";function pi(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function kl(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function fn({submission:e,onBack:a}){let{api:s}=ie(),[t,n]=gi.useState(null),i=d=>d.id??d.name,o=async d=>{n(i(d));try{await s.downloadAttachment(e.id,d)}catch(f){console.error("Download failed:",f)}finally{n(null)}},m=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return ct("div",{children:[ct("div",{className:"af-mb-6",children:[ct(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[lt(wl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),lt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),ct("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",pi(e.metadata.submitted_at)]})]}),ct("div",{className:"af-space-y-6",children:[lt(Ia,{deliveries:e.email_deliveries}),ct("div",{children:[lt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),ct("div",{className:"af-space-y-3",children:[m.map(([d,f])=>ct("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[lt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),lt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof f=="string"&&f.includes(`
|
|
3
|
-
`)?lt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:f}):String(f)})]},d)),m.length===0&<("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&ct("div",{children:[lt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),lt("div",{className:"af-space-y-2",children:e.attachments.map((d,f)=>ct("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[ct("div",{className:"af-flex af-items-center af-gap-2",children:[lt(Rl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),lt("span",{className:"af-text-sm",children:d.name}),ct("span",{className:"af-text-xs af-text-muted-foreground",children:["(",kl(d.size),")"]})]}),ct(w,{variant:"ghost",size:"sm",onClick:()=>o(d),disabled:t===i(d),children:[t===i(d)?lt(Pl,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):lt(Nl,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(d)?"Downloading...":"Download"]})]},f))})]}),ct("div",{children:[lt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),ct("div",{className:"af-space-y-2 af-text-sm",children:[ct("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[lt(_l,{className:"af-h-4 af-w-4"}),lt("span",{children:pi(e.metadata.submitted_at)})]}),e.metadata.ip_address&&ct("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[lt(Sl,{className:"af-h-4 af-w-4"}),ct("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&ct("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[lt(Cl,{className:"af-h-4 af-w-4 af-mt-0.5"}),lt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&ct("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[lt(Tl,{className:"af-h-4 af-w-4"}),ct("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as Te,jsxs as St}from"react/jsx-runtime";function Ol(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Bl(e){let a=["email","Email","EMAIL","e-mail","mail"];for(let s of a)if(typeof e[s]=="string")return e[s];return null}function Fl(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")&&!n.toLowerCase().includes("email"));if(a.length===0)return"";let[,s]=a[0],t=String(s);return t.length>50?t.slice(0,50)+"...":t}function mn({formId:e,className:a,defaultSubmissionId:s}){let{submissions:t,total:n,isLoading:i,error:o,page:m,pageSize:d,hasNextPage:f,hasPreviousPage:r,setPage:g,setPageSize:b}=dn({formId:e}),[v,u]=zs.useState("list"),[l,p]=zs.useState(null);zs.useEffect(()=>{if(s&&t.length>0){let c=t.find(k=>k.id===s);c&&(p(c),u("detail"))}},[s,t]);let h=c=>{p(c),u("detail")},x=()=>{u("list"),p(null)};if(v==="detail"&&l)return Te("div",{className:a,children:Te(fn,{submission:l,onBack:x})});if(i)return Te("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Te("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return Te("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:St("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&m===0)return St("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Te(Dl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),St("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",Te("br",{}),"Submissions will appear here when visitors use your form."]})]});let D=m*d+1,O=Math.min((m+1)*d,n);return St("div",{className:a,children:[St(Be,{children:[Te(Fe,{children:St(pe,{children:[Te(F,{children:"Email"}),Te(F,{children:"Preview"}),Te(F,{children:"Date"}),Te(F,{className:"af-text-right",children:"Actions"})]})}),Te(Me,{children:t.map(c=>{let k=Bl(c.data),A=Fl(c.data);return St(pe,{children:[St(M,{className:"af-font-medium",children:[St("div",{className:"af-flex af-items-center af-gap-2",children:[k||Te("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&St("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[Te(Ll,{className:"af-h-3 af-w-3"}),Te("span",{className:"af-text-xs",children:c.attachments.length})]})]}),Te(Hs,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),Te(M,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:A||Te("span",{className:"af-italic",children:"No preview available"})}),Te(M,{className:"af-text-muted-foreground",children:Ol(c.metadata.submitted_at)}),Te(M,{className:"af-text-right",children:Te(w,{variant:"ghost",size:"icon",onClick:()=>h(c),title:"View details",children:Te(Il,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),St("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[St("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[St("span",{children:["Showing ",D,"-",O," of ",n]}),St(ca,{value:String(d),onValueChange:c=>b(Number(c)),children:[Te(aa,{className:"af-w-[70px] af-h-8",children:Te(ua,{})}),St(sa,{children:[Te(Ge,{value:"10",children:"10"}),Te(Ge,{value:"25",children:"25"}),Te(Ge,{value:"50",children:"50"}),Te(Ge,{value:"100",children:"100"})]})]}),Te("span",{children:"per page"})]}),St("div",{className:"af-flex af-items-center af-gap-2",children:[St(w,{variant:"outline",size:"sm",onClick:()=>g(m-1),disabled:!r,children:[Te(El,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),St(w,{variant:"outline",size:"sm",onClick:()=>g(m+1),disabled:!f,children:["Next",Te(Al,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as ra from"react";import{Plus as Yl,X as Ql,Loader2 as Xl,Check as ec}from"lucide-react";import*as vi from"react";import{jsx as Ml}from"react/jsx-runtime";var ge=vi.forwardRef(({className:e,type:a,...s},t)=>Ml("input",{type:a,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:t,...s}));ge.displayName="Input";import*as bi from"react";import{cva as Ul}from"class-variance-authority";import{jsx as $l}from"react/jsx-runtime";var Vl=Ul("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ve=bi.forwardRef(({className:e,...a},s)=>$l("label",{ref:s,className:K(Vl(),e),...a}));ve.displayName="Label";import*as ma from"react";import{Plus as jl,Loader2 as vr,Copy as Wl,Check as Gl,Trash2 as Kl,RefreshCw as Zl,AlertTriangle as Jl}from"lucide-react";import*as qs from"react";import*as ht from"@radix-ui/react-dialog";import{X as Hl}from"lucide-react";import{jsx as Wa,jsxs as gr}from"react/jsx-runtime";var Da=ht.Root;var zl=ht.Portal;var yi=qs.forwardRef(({className:e,...a},s)=>Wa(ht.Overlay,{ref:s,className:K("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));yi.displayName=ht.Overlay.displayName;var wa=qs.forwardRef(({className:e,children:a,...s},t)=>Wa(zl,{children:gr("div",{className:"aifeatures-admin",children:[Wa(yi,{}),gr(ht.Content,{ref:t,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),...s,children:[a,gr(ht.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:[Wa(Hl,{className:"af-h-4 af-w-4"}),Wa("span",{className:"af-sr-only",children:"Close"})]})]})]})}));wa.displayName=ht.Content.displayName;var Na=({className:e,...a})=>Wa("div",{className:K("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});Na.displayName="DialogHeader";var Sa=({className:e,...a})=>Wa("div",{className:K("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});Sa.displayName="DialogFooter";var _a=qs.forwardRef(({className:e,...a},s)=>Wa(ht.Title,{ref:s,className:K("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));_a.displayName=ht.Title.displayName;var Ra=qs.forwardRef(({className:e,...a},s)=>Wa(ht.Description,{ref:s,className:K("af-text-sm af-text-muted-foreground",e),...a}));Ra.displayName=ht.Description.displayName;import*as na from"react";function pn(){let{api:e}=ie(),[a,s]=na.useState([]),[t,n]=na.useState(!0),[i,o]=na.useState(null),m=na.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(v){o(v instanceof Error?v:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);na.useEffect(()=>{m()},[m]);let d=na.useCallback(async v=>{let u=await e.createEventDestination(v);return s(l=>[u,...l]),u},[e]),f=na.useCallback(async(v,u)=>{let l=await e.updateEventDestination(v,u);return s(p=>p.map(h=>h.id===v?l:h)),l},[e]),r=na.useCallback(async v=>{await e.deleteEventDestination(v),s(u=>u.filter(l=>l.id!==v))},[e]),g=na.useCallback(async v=>{let u=await e.rotateEventDestinationSecret(v);return s(l=>l.map(p=>p.id===v?u:p)),u},[e]),b=na.useCallback(v=>e.getEventDestinationSecret(v),[e]);return{destinations:a,isLoading:t,error:i,refetch:m,createDestination:d,updateDestination:f,deleteDestination:r,rotateSecret:g,getSecret:b}}import*as Ga from"react";import{Loader2 as hi,RotateCw as ql}from"lucide-react";import{jsx as fa,jsxs as js}from"react/jsx-runtime";function gn({destinationId:e,limit:a=25,className:s}){let{api:t}=ie(),[n,i]=Ga.useState([]),[o,m]=Ga.useState(!0),[d,f]=Ga.useState(null),[r,g]=Ga.useState(null),b=Ga.useCallback(async()=>{try{m(!0),f(null),i(await t.getEventDeliveries(e,a))}catch(u){f(u instanceof Error?u.message:"Failed to load deliveries")}finally{m(!1)}},[t,e,a]);Ga.useEffect(()=>{b()},[b]);let v=async u=>{try{g(u.id),f(null);let l=await t.retryEventDelivery(e,u.id);i(p=>p.map(h=>h.id===u.id?l:h))}catch(l){f(l instanceof Error?l.message:"Retry failed")}finally{g(null)}};return o?js("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[fa(hi,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):d?fa("div",{className:"af-text-sm af-text-destructive af-py-2",children:d}):n.length===0?fa("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):fa("div",{className:s,children:fa("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let l=u.delivered_at!==null;return js("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[js("div",{className:"af-min-w-0",children:[js("div",{className:"af-flex af-items-center af-gap-2",children:[l?fa(te,{variant:"secondary",children:u.last_status??200}):fa(te,{variant:"destructive",children:u.last_status??"failed"}),fa("span",{className:"af-text-sm af-truncate",children:u.type})]}),js("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!l&&u.last_error&&fa("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),fa(w,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>v(u),children:r===u.id?fa(hi,{className:"af-h-4 af-w-4 af-animate-spin"}):fa(ql,{className:"af-h-4 af-w-4"})})]},u.id)})})})}import{jsx as ke,jsxs as ft}from"react/jsx-runtime";function vn({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:m,updateDestination:d,deleteDestination:f,rotateSecret:r,getSecret:g}=pn(),[b,v]=ma.useState(""),[u,l]=ma.useState(!1),[p,h]=ma.useState(null),[x,D]=ma.useState(null),[O,c]=ma.useState(null),[k,A]=ma.useState(!1),[X,S]=ma.useState(null),[T,B]=ma.useState(null),[y,j]=ma.useState(null),Q=ma.useMemo(()=>n.filter(W=>W.form_id===e),[n,e]),$=async()=>{let W=b.trim();if(W){if(!W.startsWith("https://")){h("Webhook URLs must start with https://");return}try{l(!0),h(null),await m({url:W,form_id:e,...a&&a.length>0?{topics:a}:{}}),v("")}catch(he){h(he instanceof Error?he.message:"Failed to add webhook")}finally{l(!1)}}},ce=async W=>{try{B(W.id),h(null),await r(W.id),A(!1),c(await g(W.id))}catch(he){h(he instanceof Error?he.message:"Failed to rotate secret")}finally{B(null)}},q=async W=>{try{B(W.id),h(null),await d(W.id,{status:"active"})}catch(he){h(he instanceof Error?he.message:"Failed to re-enable")}finally{B(null)}},G=async()=>{if(X)try{B(X.id),await f(X.id),S(null)}catch(W){h(W instanceof Error?W.message:"Failed to delete")}finally{B(null)}},H=async W=>{if(x===W.id){D(null),c(null);return}try{B(W.id),h(null),A(!1),D(W.id),c(await g(W.id))}catch(he){D(null),h(he instanceof Error?he.message:"Failed to read secret")}finally{B(null)}},se=async()=>{if(O)try{await navigator.clipboard.writeText(O),A(!0)}catch{}};return ft("div",{className:t,children:[ft("div",{className:"af-space-y-1",children:[ke(ve,{children:"Webhooks"}),ke("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),ft("div",{className:"af-flex af-gap-2 af-mt-4",children:[ke(ge,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:W=>v(W.target.value),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),$())},disabled:u}),ft(w,{onClick:$,disabled:u||!b.trim(),children:[u?ke(vr,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(jl,{className:"af-h-4 af-w-4"}),ke("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&ke("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),ft("div",{className:"af-mt-4 af-space-y-2",children:[i&&ft("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ke(vr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&Q.length===0&&ke("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),Q.map(W=>ft("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[ft("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[ft("div",{className:"af-min-w-0",children:[ft("div",{className:"af-flex af-items-center af-gap-2",children:[ke("span",{className:"af-font-mono af-text-sm af-truncate",children:W.url}),W.status==="disabled"?ke(te,{variant:"destructive",children:"Disabled"}):ke(te,{variant:"secondary",children:"Active"})]}),ke("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:W.topics.includes("*")?"All events":W.topics.join(", ")})]}),ft("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[ke(w,{variant:"ghost",size:"sm",onClick:()=>j(y===W.id?null:W.id),children:y===W.id?"Hide log":"Deliveries"}),ke(w,{variant:"ghost",size:"sm",onClick:()=>H(W),disabled:T===W.id,children:x===W.id?"Hide secret":"Show secret"}),ke(w,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:T===W.id,onClick:()=>S(W),children:ke(Kl,{className:"af-h-4 af-w-4"})})]})]}),W.status==="disabled"&&ft("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[ke(Jl,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),ft("div",{className:"af-text-sm",children:[ft("p",{children:["We stopped sending after repeated failures."," ",W.disabled_reason]}),ke(w,{variant:"outline",size:"sm",className:"af-mt-2",disabled:T===W.id,onClick:()=>q(W),children:"Re-enable"})]})]}),x===W.id&&O&&ft("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[ke("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."}),ft("div",{className:"af-flex af-gap-2",children:[ke(ge,{readOnly:!0,value:O,className:"af-font-mono"}),ke(w,{variant:"outline",title:"Copy signing secret",onClick:se,children:k?ke(Gl,{className:"af-h-4 af-w-4"}):ke(Wl,{className:"af-h-4 af-w-4"})}),ke(w,{variant:"outline",title:"Rotate signing secret",disabled:T===W.id,onClick:()=>ce(W),children:T===W.id?ke(vr,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(Zl,{className:"af-h-4 af-w-4"})})]})]}),y===W.id&&ke(gn,{destinationId:W.id})]},W.id))]}),ke(Da,{open:!!X,onOpenChange:W=>{!W&&!T&&S(null)},children:ft(wa,{children:[ft(Na,{children:[ke(_a,{children:"Delete this webhook?"}),ft(Ra,{children:["New submissions will stop being sent to ",X?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),ft(Sa,{children:[ke(w,{variant:"outline",onClick:()=>S(null),disabled:!!T,children:"Cancel"}),ke(w,{variant:"destructive",onClick:G,disabled:!!T,children:T?"Deleting...":"Delete"})]})]})})]})}import{jsx as Le,jsxs as Pa}from"react/jsx-runtime";function bn({form:e,onSaved:a,className:s}){let{updateForm:t}=ws(),[n,i]=ra.useState(!1),[o,m]=ra.useState(null),[d,f]=ra.useState(null),[r,g]=ra.useState(e.name),[b,v]=ra.useState(e.redirect_url||""),[u,l]=ra.useState(e.email_recipients),[p,h]=ra.useState("");ra.useEffect(()=>{g(e.name),v(e.redirect_url||""),l(e.email_recipients),f(null)},[e]);let x=ra.useCallback(async A=>{try{i(!0),f(null);let X=await t(e.id,A);m(new Date),a?.(X)}catch(X){f(X instanceof Error?X.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);ra.useEffect(()=>{if(o){let A=setTimeout(()=>m(null),2e3);return()=>clearTimeout(A)}},[o]);let D=async()=>{let A=p.trim().toLowerCase();if(!A)return;if(!A.includes("@")){f("Please enter a valid email address");return}if(u.includes(A)){f("This email is already added");return}let X=[...u,A];l(X),h(""),f(null),await x({email_recipients:X})},O=async A=>{let X=u.filter(S=>S!==A);l(X),await x({email_recipients:X})},c=async()=>{r!==e.name&&await x({name:r})},k=async()=>{let A=b||null;A!==e.redirect_url&&await x({redirect_url:A})};return Pa("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&Le("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?Pa("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:[Le(Xl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),Le("span",{className:"af-text-sm",children:"Saving..."})]}):Pa("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:[Le(ec,{className:"af-h-4 af-w-4 af-text-green-600"}),Le("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Pa("div",{className:"af-space-y-2",children:[Le(ve,{htmlFor:"form-name",children:"Form Name"}),Le(ge,{id:"form-name",value:r,onChange:A=>g(A.target.value),onBlur:c,placeholder:"Contact Form"}),Le("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),Pa("div",{className:"af-space-y-2",children:[Le(ve,{children:"Email Recipients"}),Le("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),Pa("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(A=>Pa(te,{variant:"secondary",className:"af-gap-1",children:[A,Le("button",{type:"button",onClick:()=>O(A),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:Le(Ql,{className:"af-h-3 af-w-3"})})]},A)),u.length===0&&Le("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Pa("div",{className:"af-flex af-gap-2",children:[Le(ge,{type:"email",value:p,onChange:A=>h(A.target.value),placeholder:"Add email address",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),D())},disabled:n}),Le(w,{type:"button",variant:"outline",onClick:D,disabled:!p.trim()||n,children:Le(Yl,{className:"af-h-4 af-w-4"})})]})]}),Pa("div",{className:"af-space-y-2",children:[Le(ve,{htmlFor:"redirect-url",children:"Redirect URL"}),Le(ge,{id:"redirect-url",value:b,onChange:A=>v(A.target.value),onBlur:k,placeholder:"/thank-you"}),Le("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."})]}),Pa("div",{className:"af-space-y-2",children:[Le(ve,{children:"Form Endpoint"}),Le("div",{className:"af-flex af-items-center af-gap-2",children:Le("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})}),Le("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),Pa("div",{className:"af-space-y-2",children:[Le(ve,{children:"Captcha Protection"}),Le("div",{className:"af-flex af-items-center af-gap-2",children:Le(te,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),Le("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),Le(vn,{formId:e.id}),d&&Le("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d})]})}import{jsx as Ft,jsxs as La}from"react/jsx-runtime";function xi({className:e,submissionId:a}){let{api:s}=ie(),[t,n]=ts.useState("list"),[i,o]=ts.useState(null),[m,d]=ts.useState("submissions"),[f,r]=ts.useState(a),[g,b]=ts.useState(!!a);ts.useEffect(()=>{if(!a)return;async function p(){try{let h=await s.getSubmission(a),x=await s.getForm(h.form_id);o(x),n("detail"),d("submissions"),r(a)}catch(h){console.error("Failed to load submission for deep link:",h)}finally{b(!1)}}p()},[a,s]);let v=(p,h)=>{o(p),n("detail"),d(h),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},l=p=>{o(p)};return g?Ft("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Ft("div",{className:"af-text-muted-foreground",children:"Loading..."})}):La("div",{className:e,children:[t==="list"&&La("div",{children:[La("div",{className:"af-mb-6",children:[Ft("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Ft("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Ft(ln,{onSelectForm:v})]}),t==="detail"&&i&&La("div",{children:[La("div",{className:"af-mb-6",children:[La(w,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[Ft(tc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),Ft("h2",{className:"af-text-lg af-font-semibold",children:i.name}),Ft("p",{className:"af-text-sm af-text-muted-foreground",children:Ft("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),La(on,{value:m,onValueChange:p=>d(p),children:[La($s,{className:"af-mb-4",children:[La(ya,{value:"submissions",className:"af-gap-2",children:[Ft(sc,{className:"af-h-4 af-w-4"}),"Submissions"]}),La(ya,{value:"settings",className:"af-gap-2",children:[Ft(ac,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Ft(ha,{value:"submissions",children:Ft(mn,{formId:i.id,defaultSubmissionId:f})}),Ft(ha,{value:"settings",children:Ft(bn,{form:i,onSaved:l})})]})]})]})}import*as Oe from"react";import*as Oa from"react";function as(){let{api:e}=ie(),[a,s]=Oa.useState(null),[t,n]=Oa.useState(!0),[i,o]=Oa.useState(null),m=Oa.useRef(0),d=Oa.useCallback(async()=>{let f=++m.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(f!==m.current)return;s(r)}catch(r){if(f!==m.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{f===m.current&&n(!1)}},[e]);return Oa.useEffect(()=>{d()},[d]),{status:a,isLoading:t,error:i,refetch:d}}var nc=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function pa(e){return nc.has(e.toLowerCase())}function z(e,a,s){let t=pa(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function Ka(e){let a=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+a}function Gt(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=pa(a)?s:s*100;return Math.round(t)}function mt(e,a){return pa(a)?e:e/100}function yn(e){return e.amount_paid??Math.max(0,Ka(e)-(e.credit_applied??0))}import{Fragment as oc,jsx as Ie,jsxs as He}from"react/jsx-runtime";function Ws(e){return e instanceof Wt&&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 wi(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${z(e.amount_off,e.currency)} off`:"Discount unavailable"}function Ns(){let{api:e,siteToken:a}=ie();return Ie(rc,{api:e},a)}function rc({api:e}){let{status:a,error:s}=as(),[t,n]=Oe.useState([]),[i,o]=Oe.useState(null),[m,d]=Oe.useState(null),[f,r]=Oe.useState(!1),[g,b]=Oe.useState(!1),[v,u]=Oe.useState(""),[l,p]=Oe.useState(null),[h,x]=Oe.useState(null),[D,O]=Oe.useState(!1),c=Oe.useRef(0),k=Oe.useCallback(async S=>{let T=++c.current;r(!0),u("");try{let B=await e.getPromos(S);if(T!==c.current)return;n(y=>S?[...y,...B.promos.filter(j=>!y.some(Q=>Q.id===j.id))]:B.promos),o(B.next_cursor),d(B.checkout_enabled)}catch(B){T===c.current&&u(Ws(B))}finally{T===c.current&&r(!1)}},[e]);Oe.useEffect(()=>(k(),()=>{c.current++}),[k]);async function A(S){let T=++c.current;r(!0),u(""),O(!1);try{let B=await e.getPromo(S);T===c.current&&p(B)}catch(B){T===c.current&&u(Ws(B))}finally{T===c.current&&r(!1)}}async function X(){if(l){b(!0),r(!0),u("");try{let S=await e.disablePromo(l.id);if(p(S),!["inactive","expired","exhausted"].includes(S.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");O(!1),await k()}catch(S){u(Ws(S))}finally{b(!1),r(!1)}}}return h?Ie(ic,{currency:a?.currency??void 0,replaces:h.replaces,onCancel:()=>x(null),onSave:async S=>{let T=h.replaces?await e.replacePromo(h.replaces.id,S):await e.createPromo(S),B=await e.getPromo(T.id);if(B.status==="pending"||B.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(B),x(null),await k()}}):He("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[He("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[Ie("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),Ie(w,{disabled:f||!a?.currency,onClick:()=>{u(""),x({})},children:"Create promo code"})]}),Ie("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."}),m===!1&&Ie("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."}),!a?.currency&&Ie("p",{className:"af-text-sm",children:s?Ws(s):"Connect Stripe and set the payment currency before creating codes."}),v&&He("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[v," ",Ie(w,{variant:"outline",disabled:f,onClick:()=>l?void A(l.id):void k(),children:"Refresh"})]}),l?He("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Ie(w,{variant:"ghost",disabled:g,onClick:()=>{p(null),O(!1),k()},children:"Back to codes"}),He("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),He("p",{children:[wi(l)," \xB7 ",l.status]}),He("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),He("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${z(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),He("p",{className:"af-text-sm",children:["Subscription discount:"," ",l.duration==="repeating"?`${l.duration_in_months} months`:l.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),Ie("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),He("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{variant:"outline",disabled:f,onClick:()=>void A(l.id),children:"Refresh details"}),Ie(w,{variant:"outline",disabled:f||l.status==="pending"||l.status==="unavailable"||!a?.currency,onClick:()=>x({replaces:l}),children:"Replace with new code"}),Ie(w,{variant:"outline",disabled:f||!["active","pending","unavailable"].includes(l.status),onClick:()=>O(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),D&&He("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[He("p",{className:"af-text-sm",children:[l.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${l.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),Ie(w,{disabled:f,onClick:()=>void X(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Ie(w,{variant:"ghost",disabled:f,onClick:()=>O(!1),children:"Cancel"})]})]}):He(oc,{children:[t.map(S=>He("button",{type:"button",disabled:f,onClick:()=>void A(S.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[He("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Ie("span",{className:"af-font-semibold af-break-all",children:S.code}),Ie("span",{className:"af-text-sm",children:S.status})]}),He("div",{className:"af-text-sm",children:[wi(S)," \xB7"," ",S.times_redeemed==null?"Usage unavailable":`${S.times_redeemed} redemptions`]})]},S.id)),!f&&!v&&t.length===0&&Ie("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),f&&Ie("p",{role:"status",children:"Loading promo codes\u2026"}),i&&Ie(w,{variant:"outline",disabled:f,onClick:()=>void k(i),children:"Load more"})]})]})}function ic({currency:e,replaces:a,onCancel:s,onSave:t}){let[n,i]=Oe.useState(""),[o,m]=Oe.useState(a?.name??""),[d,f]=Oe.useState(a?.amount_off!=null?"fixed":"percent"),[r,g]=Oe.useState(a?.percent_off?.toString()??(a?.amount_off!=null&&e?String(mt(a.amount_off,e)):"")),[b,v]=Oe.useState(a?.minimum_amount!=null&&e?String(mt(a.minimum_amount,e)):""),[u,l]=Oe.useState(()=>{if(!a?.expires_at)return"";let q=new Date(a.expires_at);return Number.isFinite(q.getTime())?new Date(q.getTime()-q.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,h]=Oe.useState(a?.max_redemptions?.toString()??""),[x,D]=Oe.useState(a?.duration??"once"),[O,c]=Oe.useState(a?.duration_in_months?.toString()??"3"),[k,A]=Oe.useState(null),[X,S]=Oe.useState(!1),[T,B]=Oe.useState(""),y=Oe.useRef(!1),j=e&&pa(e)?"1":"0.01";async function Q(q){if(q.preventDefault(),y.current)return;B("");let G=k;if(!G){if(!e){B("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){B("Choose a different code for the replacement.");return}let H=Gt(r,e),se=b?Gt(b,e):null;if(d==="fixed"&&(!H||H>999999999999)||b&&(!se||se>999999999999)){B("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){B("Choose a future expiry.");return}G={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:x,...d==="percent"?{percent_off:Number(r)}:{amount_off:H,currency:e},...b?{minimum_amount:se,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...x==="repeating"?{duration_in_months:Number(O)}:{}},A(G)}y.current=!0,S(!0);try{await t(G)}catch(H){B(Ws(H)),H instanceof Wt&&H.status>=400&&H.status<500&&H.details?.retryable!==!0&&A(null)}finally{y.current=!1,S(!1)}}let $=(q,G,H,se={})=>He("label",{className:"af-grid af-gap-1 af-text-sm",children:[q,Ie(ge,{"aria-label":q,value:G,onChange:W=>H(W.target.value),...se})]}),ce="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return He("form",{onSubmit:Q,className:"af-max-w-xl af-space-y-4","aria-label":a?"Replace promo code":"Create promo code",children:[Ie("h3",{className:"af-text-lg af-font-semibold",children:a?`Replace ${a.code}`:"Create promo code"}),a&&Ie("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."}),He("fieldset",{disabled:X||!!k,className:"af-grid af-gap-4",children:[$("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),$("Name",o,m,{required:!0,maxLength:40}),He("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",He("select",{"aria-label":"Discount type",className:ce,value:d,onChange:q=>f(q.target.value),children:[Ie("option",{value:"percent",children:"Percentage"}),He("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),$("Discount",r,g,{type:"number",required:!0,min:d==="percent"?"0.01":j,max:d==="percent"?"100":void 0,step:d==="percent"?"0.01":j}),$("Minimum order amount",b,v,{type:"number",min:j,step:j,placeholder:e?.toUpperCase()}),He("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),$("Expires at (local time)",u,l,{type:"datetime-local",step:1}),$("Maximum redemptions",p,h,{type:"number",min:1,max:1e6,step:1}),He("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",He("select",{"aria-label":"Subscription duration",className:ce,value:x,onChange:q=>D(q.target.value),children:[Ie("option",{value:"once",children:"First invoice only"}),Ie("option",{value:"forever",children:"Every invoice"}),Ie("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&$("Months",O,c,{type:"number",required:!0,min:1,max:36,step:1})]}),T&&Ie("p",{role:"alert",className:"af-text-sm af-text-destructive",children:T}),k&&!X&&He("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",Ie("span",{className:"af-break-all",children:k.request_id})]}),He("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{type:"submit",disabled:X,children:X?"Saving\u2026":k?"Retry same request":a?"Create replacement":"Create code"}),Ie(w,{type:"button",variant:"ghost",disabled:X||!!k,onClick:s,children:"Cancel"})]})]})}import*as Es from"react";import{ArrowLeft as Eu,FileText as Au,Package as Iu,Receipt as Du,Settings as Lu,Users as Ou}from"lucide-react";import*as hn from"react";import{Package as lc,Pencil as cc,Plus as Ni,Trash2 as uc}from"lucide-react";import{jsx as Ue,jsxs as Ot}from"react/jsx-runtime";function dc(e){if(e.allow_custom_amount){let a=e.min_amount!==null?z(e.min_amount,e.currency):"?",s=e.max_amount!==null?z(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":z(e.unit_amount,e.currency)}function fc(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function xn({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:m}=e,[d,f]=hn.useState(null),[r,g]=hn.useState(!1),[b,v]=hn.useState(null),u=async()=>{if(d)try{g(!0),v(null),await m(d.id),f(null)}catch(l){v(l instanceof Error?l.message:"Failed to delete product")}finally{g(!1)}};return i?Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ue("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?Ue("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ot("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Ot("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ue(lc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ot("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",Ue("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Ot(w,{variant:"outline",onClick:()=>s?.(),children:[Ue(Ni,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Ot("div",{className:t,children:[Ue("div",{className:"af-flex af-justify-end af-mb-4",children:Ot(w,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Ue(Ni,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Ot(Be,{children:[Ue(Fe,{children:Ot(pe,{children:[Ue(F,{children:"Name"}),Ue(F,{children:"Price"}),Ue(F,{children:"Fulfillment"}),Ue(F,{children:"Status"}),Ue(F,{className:"af-text-right",children:"Actions"})]})}),Ue(Me,{children:n.map(l=>Ot(pe,{children:[Ue(M,{className:"af-font-medium",children:l.name}),Ue(M,{children:dc(l)}),Ue(M,{className:"af-text-muted-foreground",children:fc(l)}),Ue(M,{children:Ue(te,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),Ue(M,{className:"af-text-right",children:Ot("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ot(w,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[Ue(cc,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Ot(w,{variant:"ghost",size:"sm",onClick:()=>{v(null),f(l)},children:[Ue(uc,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),Ue(Da,{open:!!d,onOpenChange:l=>{!l&&!r&&f(null)},children:Ot(wa,{children:[Ot(Na,{children:[Ue(_a,{children:"Delete product?"}),Ot(Ra,{children:['"',d?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&Ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),Ot(Sa,{children:[Ue(w,{variant:"outline",onClick:()=>f(null),disabled:r,children:"Cancel"}),Ue(w,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as Ze from"react";import{FileText as pc,Link2 as gc,Loader2 as Ri,Plus as vc,Upload as bc,X as yc}from"lucide-react";import*as pt from"react";import{Loader2 as Si,Plus as br,Trash2 as _i,X as mc}from"lucide-react";import{jsx as Z,jsxs as de}from"react/jsx-runtime";function yr(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function wn({productId:e,currency:a,className:s}){let{api:t}=ie(),n=pa(a)?"1":"0.01",[i,o]=pt.useState(null),[m,d]=pt.useState(!0),[f,r]=pt.useState(null),[g,b]=pt.useState(null),[v,u]=pt.useState(!1),l=pt.useRef(!0);pt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let p=pt.useCallback(async()=>{try{let _=await t.getProduct(e);if(!l.current)return;o(_)}catch(_){if(!l.current)return;r(_ instanceof Error?_.message:"Failed to load product")}finally{l.current&&d(!1)}},[t,e]);pt.useEffect(()=>{p()},[p]);let h=async _=>{b(null),u(!0);try{await _(),await p()}catch(I){l.current&&b(I instanceof Error?I.message:"Something went wrong")}finally{l.current&&u(!1)}},[x,D]=pt.useState(""),[O,c]=pt.useState(""),[k,A]=pt.useState({}),X=()=>h(async()=>{let _=x.trim(),I=O.split(",").map(E=>E.trim()).filter(Boolean);if(!_)throw new Error("Option name is required");if(I.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:_,values:I}),l.current&&(D(""),c(""))}),S=_=>h(async()=>{let I=(k[_.id]??"").trim();if(!I)throw new Error("Enter a value");await t.updateOption(_.id,{add_values:[I]}),l.current&&A(E=>({...E,[_.id]:""}))}),T=(_,I)=>h(()=>t.updateOption(_.id,{remove_values:[I]})),B=_=>h(()=>t.deleteOption(_.id)),[y,j]=pt.useState(null),[Q,$]=pt.useState(null),[ce,q]=pt.useState(!1),[G,H]=pt.useState(null),se=i?.options??[],W=i?.variants??[],he=()=>{$(null),j({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(se.map(_=>[_.id,_.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Ke=_=>{$(null);let I=_.inventory?.on_hand??0,E=I<0?"":String(I);j({variant:_,title:_.title??"",sku:_.sku??"",unitAmount:_.unit_amount!=null?String(mt(_.unit_amount,a)):"",compareAt:_.compare_at_amount!=null?String(mt(_.compare_at_amount,a)):"",active:_.active,optionValues:{},tracked:_.inventory?.tracked??!1,onHand:E,initialOnHand:E,allowBackorder:_.inventory?.allow_backorder??!1})},rt=async()=>{if(!y)return;$(null);let _=y.variant?.allow_custom_amount??!1,I=null,E=null;if(!_){if(I=Gt(y.unitAmount,a),I===null||I<=0){$("Enter a valid price");return}if(y.compareAt.trim()&&(E=Gt(y.compareAt,a),E===null||E<=I)){$("Compare-at price must be greater than the price");return}}let ue=y.onHand.trim()!==y.initialOnHand.trim(),me=parseInt(y.onHand,10);if(y.tracked&&ue&&(!Number.isFinite(me)||me<0)){$("On-hand quantity must be zero or more");return}try{if(q(!0),y.variant)await t.updateVariant(y.variant.id,{title:y.title.trim()||null,sku:y.sku.trim()||null,..._?{}:{unit_amount:I,compare_at_amount:E},active:y.active}),await t.setVariantInventory(y.variant.id,{tracked:y.tracked,on_hand:y.tracked&&ue?me:void 0,allow_backorder:y.allowBackorder});else{let Se={};for(let Ce of se){let et=y.optionValues[Ce.id];if(!et){$(`Choose a ${Ce.title}`),q(!1);return}Se[Ce.title]=et}await t.createVariant(e,{title:y.title.trim()||null,sku:y.sku.trim()||null,unit_amount:I,compare_at_amount:E,active:y.active,option_values:se.length>0?Se:void 0,inventory:y.tracked?{tracked:!0,on_hand:me,allow_backorder:y.allowBackorder}:{tracked:!1,allow_backorder:y.allowBackorder}})}await p(),l.current&&j(null)}catch(Se){if(l.current&&$(Se instanceof Error?Se.message:"Failed to save variant"),y.variant)try{let Ce=await t.getProduct(e);l.current&&o(Ce)}catch{}}finally{l.current&&q(!1)}},Re=()=>h(async()=>{G&&(await t.deleteVariant(G.id),l.current&&H(null))}),qe=y?.variant?.allow_custom_amount??!1,Xe=y?.variant!=null&&y.variant.option_values.length===0&&se.length>0&&!y.variant.active,xe=y?.variant?.inventory!=null&&y.variant.inventory.on_hand<0?-y.variant.inventory.on_hand:null;function Tt(_){let I=_.inventory;if(!I||!I.tracked)return Z("span",{className:"af-text-muted-foreground",children:"Unlimited"});let E=I.available??I.on_hand;return E<0?de("span",{children:[-E," backordered"]}):de("span",{children:[E," in stock",I.allow_backorder&&Z("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return m?Z("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:Z(Si,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):f?Z("div",{className:s,children:Z("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})}):de("div",{className:`af-space-y-6 ${s||""}`,children:[de("div",{className:"af-space-y-3",children:[de("div",{children:[Z(ve,{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."})]}),se.length>0&&Z("div",{className:"af-space-y-3",children:se.map(_=>de("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[de("div",{className:"af-flex af-items-center af-justify-between",children:[Z("span",{className:"af-text-sm af-font-medium",children:_.title}),Z(w,{variant:"ghost",size:"sm",onClick:()=>B(_),disabled:v,children:Z(_i,{className:"af-h-4 af-w-4"})})]}),Z("div",{className:"af-flex af-flex-wrap af-gap-2",children:_.values.map(I=>de(te,{variant:"secondary",className:"af-gap-1",children:[I.value,Z("button",{type:"button",onClick:()=>T(_,I.value),className:"af-ml-1 hover:af-text-destructive",disabled:v,title:"Remove value",children:Z(mc,{className:"af-h-3 af-w-3"})})]},I.id))}),de("div",{className:"af-flex af-gap-2",children:[Z(ge,{value:k[_.id]??"",onChange:I=>A(E=>({...E,[_.id]:I.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),S(_))},disabled:v}),Z(w,{type:"button",variant:"outline",size:"sm",onClick:()=>S(_),disabled:v||!(k[_.id]??"").trim(),children:Z(br,{className:"af-h-4 af-w-4"})})]})]},_.id))}),de("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[de("div",{className:"af-space-y-1",children:[Z(ve,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),Z(ge,{id:"new-option-title",value:x,onChange:_=>D(_.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:v})]}),de("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[Z(ve,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),Z(ge,{id:"new-option-values",value:O,onChange:_=>c(_.target.value),placeholder:"S, M, L",disabled:v})]}),de(w,{type:"button",variant:"outline",onClick:X,disabled:v||!x.trim()||!O.trim(),children:[Z(br,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),de("div",{className:"af-space-y-3",children:[de("div",{className:"af-flex af-items-center af-justify-between",children:[Z(ve,{children:"Variants"}),de(w,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:v||se.length===0,children:[Z(br,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),se.length===0&&Z("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),W.length===0?Z("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):de(Be,{children:[Z(Fe,{children:de(pe,{children:[Z(F,{children:"Variant"}),Z(F,{children:"SKU"}),Z(F,{children:"Price"}),Z(F,{children:"Stock"}),Z(F,{children:"Status"}),Z(F,{className:"af-text-right",children:"Actions"})]})}),Z(Me,{children:W.map(_=>de(pe,{children:[Z(M,{className:"af-font-medium",children:yr(_)}),Z(M,{className:"af-text-muted-foreground",children:_.sku||"-"}),Z(M,{children:_.unit_amount!=null?de("span",{children:[_.compare_at_amount!=null&&Z("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:z(_.compare_at_amount,_.currency)}),z(_.unit_amount,_.currency)]}):_.allow_custom_amount?Z("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),Z(M,{children:Tt(_)}),Z(M,{children:Z(te,{variant:_.active?"success":"secondary",children:_.active?"Active":"Inactive"})}),Z(M,{className:"af-text-right",children:de("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[Z(w,{variant:"ghost",size:"sm",onClick:()=>Ke(_),disabled:v,children:"Edit"}),Z(w,{variant:"ghost",size:"icon",onClick:()=>H(_),disabled:v,title:"Delete variant",children:Z(_i,{className:"af-h-4 af-w-4"})})]})})]},_.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(Da,{open:y!==null,onOpenChange:_=>{!_&&!ce&&j(null)},children:de(wa,{children:[de(Na,{children:[Z(_a,{children:y?.variant?"Edit variant":"Add variant"}),Z(Ra,{children:"Price, markdown, and stock live on the variant."})]}),y&&de("div",{className:"af-space-y-3",children:[y.variant?y.variant.option_values.length>0&&de("div",{className:"af-text-sm",children:[Z("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),yr(y.variant)]}):se.map(_=>de("div",{className:"af-space-y-1",children:[Z(ve,{className:"af-text-xs af-text-muted-foreground",children:_.title}),de(ca,{value:y.optionValues[_.id]??"",onValueChange:I=>j(E=>E&&{...E,optionValues:{...E.optionValues,[_.id]:I}}),children:[Z(aa,{children:Z(ua,{placeholder:`Choose ${_.title}`})}),Z(sa,{children:_.values.map(I=>Z(Ge,{value:I.value,children:I.value},I.id))})]})]},_.id)),qe?de("div",{className:"af-space-y-1",children:[Z(ve,{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."})]}):de("div",{className:"af-flex af-gap-3",children:[de("div",{className:"af-space-y-1",children:[de(ve,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),Z(ge,{id:"variant-price",type:"number",min:"0",step:n,value:y.unitAmount,onChange:_=>j(I=>I&&{...I,unitAmount:_.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),de("div",{className:"af-space-y-1",children:[Z(ve,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),Z(ge,{id:"variant-compare",type:"number",min:"0",step:n,value:y.compareAt,onChange:_=>j(I=>I&&{...I,compareAt:_.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),de("div",{className:"af-space-y-1",children:[Z(ve,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),Z(ge,{id:"variant-sku",value:y.sku,onChange:_=>j(I=>I&&{...I,sku:_.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),de("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Z("input",{type:"checkbox",checked:y.tracked,onChange:_=>j(I=>I&&{...I,tracked:_.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),y.tracked&&de("div",{className:"af-space-y-1 af-pl-6",children:[de("div",{className:"af-flex af-items-end af-gap-3",children:[de("div",{className:"af-space-y-1",children:[Z(ve,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),Z(ge,{id:"variant-onhand",type:"number",min:"0",step:"1",value:y.onHand,onChange:_=>j(I=>I&&{...I,onHand:_.target.value}),placeholder:xe!=null?"0":void 0,className:"af-w-[100px]"})]}),de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[Z("input",{type:"checkbox",checked:y.allowBackorder,onChange:_=>j(I=>I&&{...I,allowBackorder:_.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),xe!=null&&de("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",xe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),de("div",{className:"af-space-y-1",children:[de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Z("input",{type:"checkbox",checked:y.active,onChange:_=>j(I=>I&&{...I,active:_.target.checked}),className:"af-h-4 af-w-4",disabled:Xe}),"Active (buyers can purchase this variant)"]}),Xe&&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."})]}),Q&&Z("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Q})]}),de(Sa,{children:[Z(w,{variant:"outline",onClick:()=>j(null),disabled:ce,children:"Cancel"}),de(w,{onClick:rt,disabled:ce,children:[ce?Z(Si,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?.variant?"Save":"Add variant"]})]})]})}),Z(Da,{open:G!==null,onOpenChange:_=>{!_&&!v&&H(null)},children:de(wa,{children:[de(Na,{children:[Z(_a,{children:"Delete variant?"}),Z(Ra,{children:G&&`"${yr(G)}" will no longer be purchasable. Past orders are unaffected.`})]}),de(Sa,{children:[Z(w,{variant:"outline",onClick:()=>H(null),disabled:v,children:"Cancel"}),Z(w,{variant:"destructive",onClick:Re,disabled:v,children:"Delete"})]})]})})]})}import{Fragment as xc,jsx as fe,jsxs as _e}from"react/jsx-runtime";function hc(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function Nn({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:m,attachProductFileFromUrl:d}=e,f=!!a,r=a?.currency??s,g=pa(r)?"1":"0.01",b=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[v,u]=Ze.useState(!1),[l,p]=Ze.useState(null),h=Ze.useRef(!0);Ze.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);let[x,D]=Ze.useState(a?.name??""),[O,c]=Ze.useState(a?.description??""),[k,A]=Ze.useState(a?.allow_custom_amount?"custom":"fixed"),[X,S]=Ze.useState(a?.unit_amount!=null?String(mt(a.unit_amount,r)):""),[T,B]=Ze.useState(a?.min_amount!=null?String(mt(a.min_amount,r)):""),[y,j]=Ze.useState(a?.max_amount!=null?String(mt(a.max_amount,r)):""),[Q,$]=Ze.useState(String(a?.max_quantity??10)),ce=Ze.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(mt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(mt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(mt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[q,G]=Ze.useState(a?.collect_shipping_address??!1),[H,se]=Ze.useState(a?.active??!0),[W,he]=Ze.useState(a?.images??[]),[Ke,rt]=Ze.useState(""),[Re,qe]=Ze.useState(a?.fulfillment??null),[Xe,xe]=Ze.useState(!1),[Tt,_]=Ze.useState(""),[I,E]=Ze.useState(null),ue=Ze.useRef(null),me=v||Xe,Se=()=>{let re=Ke.trim();if(re){if(W.includes(re)){p("This image URL is already added");return}he(Ee=>[...Ee,re]),rt(""),p(null)}},Ce=re=>{he(Ee=>Ee.filter(it=>it!==re))},et=async()=>{if(p(null),!x.trim()){p("Product name is required");return}let re=null,Ee=null,it=null,ta=!f||k!==ce.pricingMode||(k==="fixed"?X!==ce.unitAmount:T!==ce.minAmount||y!==ce.maxAmount),yt=!f||Q!==ce.maxQuantity,kt=b||k==="fixed";if(!(b||!ta))if(k==="fixed"){if(re=Gt(X,r),re===null||re<=0){p("Enter a valid price");return}}else{if(Ee=Gt(T,r),it=Gt(y,r),Ee===null||it===null){p("Enter valid minimum and maximum amounts");return}if(it<Ee){p("Maximum amount must be at least the minimum amount");return}}let zt=parseInt(Q,10);if(kt&&yt&&(!Number.isFinite(zt)||zt<1)){p("Max quantity must be at least 1");return}try{u(!0);let $e;if(f&&a){let tt={name:x.trim(),description:O.trim()||null,images:W,collect_shipping_address:q,active:H};!b&&ta&&(tt.allow_custom_amount=k==="custom",k==="fixed"?tt.unit_amount=re:(tt.min_amount=Ee,tt.max_amount=it)),kt&&yt&&(tt.max_quantity=zt),$e=await o(a.id,tt),ce.pricingMode=$e.allow_custom_amount?"custom":"fixed",ce.unitAmount=$e.unit_amount!=null?String(mt($e.unit_amount,r)):"",ce.minAmount=$e.min_amount!=null?String(mt($e.min_amount,r)):"",ce.maxAmount=$e.max_amount!=null?String(mt($e.max_amount,r)):"",ce.maxQuantity=String($e.max_quantity)}else{let tt={name:x.trim(),allow_custom_amount:k==="custom",collect_shipping_address:q,active:H};O.trim()&&(tt.description=O.trim()),W.length>0&&(tt.images=W),k==="fixed"?(tt.unit_amount=re,tt.max_quantity=zt):(tt.min_amount=Ee,tt.max_amount=it),$e=await i(tt)}if(!h.current)return;qe($e.fulfillment),t?.($e)}catch($e){if(!h.current)return;p($e instanceof Error?$e.message:"Failed to save product")}finally{h.current&&u(!1)}},Ve=async re=>{let Ee=re.target.files?.[0];if(!(!Ee||!a))try{xe(!0),E(null);let it=await m(a.id,Ee);if(!h.current)return;qe(it.fulfillment),t?.(it)}catch(it){if(!h.current)return;E(it instanceof Error?it.message:"Failed to upload file")}finally{h.current&&(xe(!1),ue.current&&(ue.current.value=""))}},je=async()=>{let re=Tt.trim();if(!(!re||!a))try{xe(!0),E(null);let Ee=await d(a.id,re);if(!h.current)return;qe(Ee.fulfillment),_(""),t?.(Ee)}catch(Ee){if(!h.current)return;E(Ee instanceof Error?Ee.message:"Failed to fetch file")}finally{h.current&&xe(!1)}};return _e("div",{className:`af-space-y-6 ${n||""}`,children:[_e("div",{className:"af-space-y-2",children:[fe(ve,{htmlFor:"product-name",children:"Name"}),fe(ge,{id:"product-name",value:x,onChange:re=>D(re.target.value),placeholder:"My product"})]}),_e("div",{className:"af-space-y-2",children:[fe(ve,{htmlFor:"product-description",children:"Description"}),fe("textarea",{id:"product-description",value:O,onChange:re=>c(re.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"})]}),_e("div",{className:"af-space-y-2",children:[fe(ve,{children:"Pricing"}),b?fe("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):_e(xc,{children:[_e(ca,{value:k,onValueChange:re=>A(re),children:[fe(aa,{className:"af-w-[260px]",children:fe(ua,{})}),_e(sa,{children:[fe(Ge,{value:"fixed",children:"Fixed price"}),fe(Ge,{value:"custom",children:"Buyer chooses the amount"})]})]}),k==="fixed"?fe("div",{className:"af-flex af-items-end af-gap-3",children:_e("div",{className:"af-space-y-1",children:[_e(ve,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),fe(ge,{id:"product-price",type:"number",min:"0",step:g,value:X,onChange:re=>S(re.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):_e("div",{className:"af-space-y-1",children:[_e("div",{className:"af-flex af-items-end af-gap-3",children:[_e("div",{className:"af-space-y-1",children:[_e(ve,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),fe(ge,{id:"product-min-amount",type:"number",min:"0",step:g,value:T,onChange:re=>B(re.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),_e("div",{className:"af-space-y-1",children:[_e(ve,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),fe(ge,{id:"product-max-amount",type:"number",min:"0",step:g,value:y,onChange:re=>j(re.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),fe("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."})]}),_e("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",r.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||k==="fixed")&&_e("div",{className:"af-space-y-1",children:[fe(ve,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),fe(ge,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Q,onChange:re=>$(re.target.value),className:"af-w-[140px]"})]})]}),_e("div",{className:"af-space-y-2",children:[fe(ve,{children:"Images"}),fe("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),_e("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[W.map(re=>_e(te,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[fe("span",{className:"af-truncate",children:re}),fe("button",{type:"button",onClick:()=>Ce(re),className:"af-ml-1 hover:af-text-destructive",disabled:v,children:fe(yc,{className:"af-h-3 af-w-3"})})]},re)),W.length===0&&fe("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),_e("div",{className:"af-flex af-gap-2",children:[fe(ge,{type:"url",value:Ke,onChange:re=>rt(re.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:re=>{re.key==="Enter"&&(re.preventDefault(),Se())},disabled:v}),fe(w,{type:"button",variant:"outline",onClick:Se,disabled:!Ke.trim()||v,children:fe(vc,{className:"af-h-4 af-w-4"})})]})]}),_e("div",{className:"af-space-y-2",children:[fe(ve,{children:"Digital File"}),fe("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."}),f?_e("div",{className:"af-space-y-3",children:[Re?.type==="download"&&_e("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[fe(pc,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),fe("span",{className:"af-text-sm",children:Re.filename}),Re.size!=null&&_e("span",{className:"af-text-xs af-text-muted-foreground",children:["(",hc(Re.size),")"]})]}),Re?.type==="redirect"&&Re.url&&_e("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[fe(gc,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),_e("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Re.url]})]}),_e("div",{className:"af-flex af-items-center af-gap-2",children:[fe("input",{ref:ue,type:"file",onChange:Ve,className:"af-hidden",disabled:me}),_e(w,{type:"button",variant:"outline",size:"sm",onClick:()=>ue.current?.click(),disabled:me,children:[Xe?fe(Ri,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):fe(bc,{className:"af-h-4 af-w-4 af-mr-1"}),Re?.type==="download"?"Replace file":"Upload file"]}),fe("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),fe(ge,{type:"url",value:Tt,onChange:re=>_(re.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Xe}),fe(w,{type:"button",variant:"outline",size:"sm",onClick:je,disabled:!Tt.trim()||me,children:"Fetch from URL"})]}),I&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:I})]}):fe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),_e("div",{className:"af-space-y-2",children:[fe(ve,{children:"Settings"}),_e("div",{className:"af-space-y-2",children:[_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[fe("input",{type:"checkbox",checked:q,onChange:re=>G(re.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),_e("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[fe("input",{type:"checkbox",checked:H,onChange:re=>se(re.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),f&&a&&_e("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[fe(ve,{children:"Options & Variants"}),fe(wn,{productId:a.id,currency:r})]}),l&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),fe("div",{className:"af-flex af-items-center af-gap-2",children:_e(w,{type:"button",onClick:et,disabled:me,children:[v?fe(Ri,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,f?"Save changes":"Create product"]})})]})}import*as _t from"react";import{ChevronLeft as qc,ChevronRight as Mi,Loader2 as jc,Receipt as Wc,Search as Gc,SlidersHorizontal as Kc}from"lucide-react";import*as ot from"react";var wc=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Sn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=ot.useState([]),[i,o]=ot.useState(0),[m,d]=ot.useState(!0),[f,r]=ot.useState(null),[g,b]=ot.useState(0),[v,u]=ot.useState(e),[l,p]=ot.useState(void 0),[h,x]=ot.useState(""),[D,O]=ot.useState(""),[c,k]=ot.useState(""),[A,X]=ot.useState(!1),[S,T]=ot.useState(!1),[B,y]=ot.useState(void 0),j=B?B.join(","):"",Q=ot.useMemo(()=>{if(!j)return;let G=new Set(j.split(","));return wc.filter(H=>!G.has(H))},[j]),$=ot.useRef(0),ce=ot.useCallback(async()=>{let G=++$.current;try{d(!0),r(null);let H={limit:v,offset:g*v};l?H.status=l:Q?H.excludeStatus=Q:A||(H.excludeStatus=["pending","expired"]),h.trim()&&(H.customerEmail=h.trim()),D.trim()&&(H.from=D.trim()),c.trim()&&(H.to=c.trim()),S&&(H.unfulfilledOnly=!0);let se=await s.getOrders(H);if(G!==$.current)return;n(se.orders),o(se.total)}catch(H){if(G!==$.current)return;r(H instanceof Error?H:new Error("Failed to fetch orders"))}finally{G===$.current&&d(!1)}},[s,g,v,l,Q,A,S,h,D,c,a]);ot.useEffect(()=>{ce()},[ce]);let q=Math.ceil(i/v);return{orders:t,total:i,isLoading:m,error:f,page:g,pageSize:v,hasNextPage:g<q-1,hasPreviousPage:g>0,setPage:b,setPageSize:G=>{u(G),b(0)},status:l,setStatus:G=>{p(G),b(0)},statusIn:B,setStatusIn:G=>{y(G&&G.length>0?G:void 0),b(0)},customerEmail:h,setCustomerEmail:G=>{x(G),b(0)},from:D,setFrom:G=>{O(G),b(0)},to:c,setTo:G=>{k(G),b(0)},showAbandoned:A,setShowAbandoned:G=>{X(G),b(0)},unfulfilledOnly:S,setUnfulfilledOnly:G=>{T(G),b(0)},clearFilters:()=>{p(void 0),y(void 0),X(!1),T(!1),x(""),O(""),k(""),b(0)},refetch:ce}}import*as ut from"react";import{ArrowLeft as _c,Check as Ei,ChevronLeft as Rc,ChevronRight as Pc,ClipboardCopy as Cc,Copy as Tc,Download as kc,Loader2 as Rn,Mail as Ai,MoreHorizontal as Ec,Package as Ac,RotateCcw as Ic,Truck as Dc,Undo2 as Ii}from"lucide-react";import*as Pi from"react";import*as Ba from"@radix-ui/react-popover";import{jsx as hr}from"react/jsx-runtime";var Ci=Ba.Root,Ti=Ba.Trigger;var xr=Pi.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>hr(Ba.Portal,{children:hr("div",{className:"aifeatures-admin",children:hr(Ba.Content,{ref:n,align:a,sideOffset:s,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),...t})})}));xr.displayName=Ba.Content.displayName;import{jsx as _n}from"react/jsx-runtime";var Nc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Sc(e){return Nc[e]??e}function ki(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function ps({status:e,className:a}){return _n(te,{variant:ki(e),className:a,children:Sc(e)})}function gs({status:e}){return _n(ps,{status:e})}function Ss({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?_n(te,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?_n(te,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Za(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as $c,jsx as R,jsxs as Y}from"react/jsx-runtime";var Bi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",vs="af-text-xs af-text-muted-foreground";function wr(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Lc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fi(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 Pn=24,Oc=["paid","partially_refunded"],Bc=["paid","partially_refunded","disputed"],Fc=/^[A-Za-z0-9 _-]*$/,Di=100;function _r(e,a,s,t,n){let i=Oc.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="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."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${Pn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Pn} tries used). Nothing is being retried while the order is ${t.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:a==="failed_final"?s<Pn&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<Pn&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:a==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${t==="refunded"?"because the order was refunded":t==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:a==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(a),variant:"secondary",detail:null}}function Li({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:m}){if(m)return Y("div",{children:[R(Ia,{deliveries:[m]}),o&&R("div",{className:"af-mt-2",children:o})]});let d=_r(n,s,t,i,a);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:[R("div",{className:"af-text-sm",children:e}),a&&R("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:a})]}),R(te,{variant:d.variant,className:"af-shrink-0",children:d.label})]}),d.detail&&R("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:d.detail}),o&&R("div",{className:"af-mt-2",children:o})]})}function Oi(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=Lc(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&a.push(i)}let t=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");t&&a.push(t),typeof s.country=="string"&&s.country&&a.push(s.country)}return a.length>0?a:Object.entries(e).map(([t,n])=>`${t}: ${Fi(n)}`)}function Mc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Rr({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=ut.useState(!1);if(!Mc())return null;let m=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},d=i?R(Ei,{className:"af-h-3 af-w-3"}):R(Tc,{className:"af-h-3 af-w-3"});return n==="icon"?R(w,{variant:"ghost",size:"icon",className:K("af-h-6 af-w-6 af-shrink-0",t),onClick:m,title:a,"aria-label":a,children:d}):Y(w,{variant:"outline",size:"sm",className:t,onClick:m,"aria-label":a,children:[i?R(Ei,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):R(Cc,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Nr({label:e,value:a}){return Y("div",{children:[R("div",{className:vs,children:e}),Y("div",{className:"af-flex af-items-center af-gap-1",children:[R("code",{className:"af-text-xs af-font-mono af-break-all",children:a}),R(Rr,{value:a,label:`Copy ${e}`})]})]})}function Uc({src:e}){let[a,s]=ut.useState(!1);return!e||a?R("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:R(Ac,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):R("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Fa({title:e,action:a,children:s,className:t}){return Y("section",{className:K("af-rounded-lg af-border af-p-4",t),children:[Y("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[R("h4",{className:Bi,children:e}),a]}),R("div",{className:"af-mt-3",children:s})]})}function Kt({label:e,emphasis:a,divider:s,children:t}){return Y("div",{className:K("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[R("span",{className:a?"af-text-base af-font-semibold":vs,children:e}),R("span",{className:K("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Sr({onSelect:e,disabled:a,icon:s,children:t}){return Y(w,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:a,children:[R("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),t]})}function Vc(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?a.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${z(yn(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),t=s?un(s):_r("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);a.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),t=s?un(s):_r("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);a.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&a.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&&a.push({key:"refunded",text:`Refunded ${z(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&a.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),a}function Cn({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:m=!1,hasNextOrder:d=!1}){let{api:f}=ie(),[r,g]=ut.useState(e),[b,v]=ut.useState(null),[u,l]=ut.useState(null),[p,h]=ut.useState(!1),[x,D]=ut.useState(!1),[O,c]=ut.useState(!1),[k,A]=ut.useState(!1),[X,S]=ut.useState(""),[T,B]=ut.useState(!1),[y,j]=ut.useState(null),[Q,$]=ut.useState(!1),[ce,q]=ut.useState(""),[G,H]=ut.useState([]),[se,W]=ut.useState(!1),[he,Ke]=ut.useState(!1),[rt,Re]=ut.useState(null);ut.useEffect(()=>{g(e)},[e]);let qe=C=>{let Ae=C.id===r.id&&C.email_deliveries===void 0?{...C,email_deliveries:r.email_deliveries}:C;g(Ae),t?.(Ae)},Xe=Object.entries(r.metadata??{}),xe=Math.max(0,yn(r)-r.amount_refunded),Tt=(r.status==="paid"||r.status==="partially_refunded")&&xe>0,_=r.exclusive_tax_total!=null,I=C=>typeof C.amountNet=="number"?C.amountNet+(C.exclusiveTax??0):(typeof C.unitAmount=="number"?C.unitAmount:0)*(typeof C.quantity=="number"&&C.quantity>0?C.quantity:1),E=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),ue=G.reduce((C,Ae)=>C+I(r.line_items[Ae]??{}),0)+(se?E:0),me=r.tax_total??0,Se=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((C,Ae)=>C+(Ae.exclusiveTax??0),0)),Ce=_?se&&E>0?Se:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&me>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,me-(r.tax_refunded??0)),Math.round(me*ue/(r.amount_total+(r.shipping_total??0)))):0,et=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(ue+Ce,xe):ue+Ce,Ve=G.length>0||se,je=Ve?et:Gt(ce,r.currency),re=pa(r.currency)?"1":"0.01",Ee=async()=>{try{h(!0),v(null),l(null),await f.resendOrderReceipt(r.id);let C=await f.getOrder(r.id);qe(C),l("Receipt email queued.")}catch(C){v(C instanceof Error?C.message:"Failed to resend receipt")}finally{h(!1)}},it=async()=>{try{D(!0),v(null),l(null);let C=await f.resetOrderDownloads(r.id);qe(C),c(!1),l("Download count reset.")}catch(C){v(C instanceof Error?C.message:"Failed to reset downloads")}finally{D(!1)}},ta=r.line_items.some(C=>C.collectShippingAddress===!0&&!C.refunded&&!C.unavailableReason),yt=typeof r.merchant_fulfilled_at=="string",kt=Bc.includes(r.status)||r.status==="refunded"&&r.line_items.some(C=>C.collectShippingAddress===!0&&C.amountNet===0&&!C.refunded&&!C.unavailableReason),zt=X.trim(),$e=Fc.test(zt)&&zt.length<=Di,tt=async C=>{try{B(!0),j(null),l(null);let Ae=await f.setOrderFulfillment(r.id,{fulfilled:C,...C&&zt?{trackingNumber:zt}:{}});qe(Ae),S(""),l(C?"Marked as shipped.":"Marked as not shipped.")}catch(Ae){Ae instanceof Wt&&Ae.status===409?j(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):j(Ae instanceof Error?Ae.message:"Failed to update the order")}finally{B(!1)}},Qa=()=>{Re(null),q(String(mt(xe,r.currency))),H([]),W(!1),$(!0)},Fs=C=>H(Ae=>Ae.includes(C)?Ae.filter(jt=>jt!==C):[...Ae,C]),Dt=async(C,Ae)=>{if(s)try{Ke(!0),Re(null),await s(r,C,Ae);let jt=await f.getOrder(r.id);qe(jt),$(!1),l("Refund issued.")}catch(jt){Re(jt instanceof Error?jt.message:"Refund failed")}finally{Ke(!1)}},sn=async()=>{if(Ve){if(et<=0){Re("The lines you picked were charged nothing");return}if(et>xe){Re(`That selection exceeds the refundable remainder (${z(xe,r.currency)})`);return}await Dt(et,{...G.length>0?{line_items:[...G].sort((Ae,jt)=>Ae-jt)}:{},...se?{shipping:!0}:{}});return}let C=Gt(ce,r.currency);if(C===null||C<=0){Re("Enter a valid refund amount");return}if(C>xe){Re(`Amount exceeds the refundable remainder (${z(xe,r.currency)})`);return}await Dt(C,{amount:C})},U=()=>Dt(xe,{full:!0}),We=!r.subscription_history_only&&r.fulfillment_type==="download",V=!r.subscription_history_only&&n&&ta,qt=Vc(r),Jo=r.shipping_address?Oi(r.shipping_address).join(`
|
|
4
|
-
`):"",ti=r.shipping_total!=null,rr=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),ai=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-rr):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,si=rr>0,Yo=ai>0,ni=r.amount_subtotal!=null||ti||si||(r.discount_total??0)>0,Ms=[];return r.subscription_history_only||Ms.push(R(Sr,{icon:p?R(Rn,{className:"af-h-4 af-w-4 af-animate-spin"}):R(Ai,{className:"af-h-4 af-w-4"}),disabled:p||r.fulfillment_status!=="fulfilled",onSelect:()=>{A(!1),Ee()},children:"Resend receipt"},"resend")),We&&Ms.push(R(Sr,{icon:R(Ic,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{A(!1),c(!0)},children:"Reset download count"},"reset")),Tt&&Ms.push(Y("div",{children:[R(Sr,{icon:R(Ii,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{A(!1),Qa()},children:"Refund\u2026"}),!s&&R("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(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[R(_c,{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:[R("h3",{className:"af-text-xl af-font-semibold",children:Za(r)}),R(ps,{status:r.status}),n&&!r.subscription_history_only&&R(Ss,{order:r}),r.is_test&&R(te,{variant:"outline",children:"Test"})]}),Y("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",wr(r.created_at)]}),r.is_test&&R("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:[(i||o)&&Y("div",{className:"af-flex af-items-center",children:[R(w,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!m,"aria-label":"Previous order",children:R(Rc,{className:"af-h-4 af-w-4"})}),R(w,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!d,"aria-label":"Next order",children:R(Pc,{className:"af-h-4 af-w-4"})})]}),V&&(yt?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",r.merchant_fulfilled_at?` \xB7 ${wr(r.merchant_fulfilled_at)}`:""]}),kt&&Y(w,{variant:"ghost",size:"sm",onClick:()=>tt(!1),disabled:T,children:[T?R(Rn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(Ii,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):kt?Y("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[R(ge,{value:X,onChange:C=>S(C.target.value),placeholder:"Tracking number (optional)",maxLength:Di,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:T}),Y(w,{variant:"default",className:"af-shrink-0",onClick:()=>tt(!0),disabled:T||!$e,children:[T?R(Rn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ms.length>0&&Y(Ci,{open:k,onOpenChange:A,children:[R(Ti,{asChild:!0,children:R(w,{variant:"outline",size:"icon","aria-label":"More actions",children:R(Ec,{className:"af-h-4 af-w-4"})})}),R(xr,{children:R("div",{className:"af-space-y-0.5",children:Ms})})]})]})]}),V&&!yt&&!$e&&R("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."}),y&&R("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:y}),u&&R("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:u}),b&&R("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})]}),Y("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[Y("div",{className:"af-space-y-6",children:[r.line_items.length>0&&R(Fa,{title:"Items",children:R("ul",{className:"af-space-y-3",children:r.line_items.map((C,Ae)=>{let jt=typeof C.name=="string"&&C.name?C.name:"Item",ri=typeof C.quantity=="number"&&C.quantity>0?C.quantity:1,ii=typeof C.unitAmount=="number";return Y("li",{className:"af-flex af-items-start af-gap-3",children:[R(Uc,{src:typeof C.imageUrl=="string"&&C.imageUrl?C.imageUrl:void 0}),Y("div",{className:"af-min-w-0 af-flex-1",children:[Y("div",{className:"af-text-sm af-font-medium",children:[jt,typeof C.variantTitle=="string"&&C.variantTitle&&Y("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",C.variantTitle]})]}),Y("div",{className:vs,children:[ri," \xD7"," ",ii?z(C.unitAmount,r.currency):"\u2014"]}),C.unavailableReason==="oversold"&&!C.refunded&&R(te,{variant:"secondary",className:"af-mt-1",children:C.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),C.refunded===!0&&R(te,{variant:"secondary",className:"af-mt-1",children:C.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),R("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof C.amountNet=="number"||ii?z(C.amountNet??C.unitAmount*ri,r.currency):"\u2014"})]},Ae)})})}),Xe.length>0&&R(Fa,{title:"Order details",children:R("dl",{className:"af-space-y-2",children:Xe.map(([C,Ae])=>Y("div",{children:[R("dt",{className:K(vs,"af-capitalize"),children:C.replace(/_/g," ")}),R("dd",{className:"af-text-sm af-break-words",children:Fi(Ae)})]},C))})}),R(Fa,{title:"Totals",children:Y("div",{className:"af-w-full",children:[ni&&R(Kt,{label:"Subtotal",children:z(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&Y(Kt,{label:"Discount",children:["\u2212",z(r.discount_total,r.currency)]}),ti&&R(Kt,{label:"Shipping",children:r.shipping_total===0?"Free":z(r.shipping_total??0,r.currency)}),si&&R(Kt,{label:"Tax",children:z(rr,r.currency)}),R(Kt,{label:"Total",emphasis:!0,divider:ni,children:z(Ka(r),r.currency)}),(r.credit_applied??0)>0&&Y(Kt,{label:"Credit applied",children:["\u2212",z(r.credit_applied,r.currency)]}),r.amount_paid!=null&&R(Kt,{label:"Amount paid",children:z(r.amount_paid,r.currency)}),Yo&&R(Kt,{label:"incl. tax",children:z(ai,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&Y(Kt,{label:"Your price",children:[z(r.base_amount_total,r.base_currency),Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&Y($c,{children:[Y(Kt,{label:"Refunded",children:["\u2212",z(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",z(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),R(Kt,{label:"Net",children:R("span",{className:"af-font-medium",children:z(Math.max(0,yn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&Y(Fa,{title:"Platform fee",children:[r.application_fee_original!=null&&R(Kt,{label:"Collected",children:z(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&R(Kt,{label:"Returned",children:z(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&R(Kt,{label:"Retained",children:z(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&R("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:r.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),R(Fa,{title:"Timeline",children:R("ol",{className:"af-space-y-3",children:qt.map(C=>Y("li",{className:"af-flex af-gap-3",children:[R("span",{"aria-hidden":"true",className:K("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",C.tone==="destructive"?"af-bg-destructive":C.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),Y("div",{className:"af-min-w-0",children:[R("div",{className:"af-text-sm af-break-words",children:C.text}),C.at&&R("div",{className:"af-text-xs af-text-muted-foreground",children:wr(C.at)})]})]},C.key))})})]}),Y("div",{className:"af-space-y-6",children:[R(Fa,{title:"Customer",children:Y("div",{className:"af-space-y-2",children:[Y("div",{children:[R("div",{className:vs,children:"Email"}),Y("div",{className:"af-flex af-items-center af-gap-1",children:[R("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||R("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&R(Rr,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&Y("div",{children:[R("div",{className:vs,children:"Name"}),R("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&Y("div",{children:[R("div",{className:vs,children:"Customer record"}),Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[R("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),R(te,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&R(Fa,{title:"Ship to",action:R(Rr,{value:Jo,label:"Copy address",size:"sm",children:"Copy address"}),children:R("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Oi(r.shipping_address).map((C,Ae)=>R("div",{children:C},Ae))})}),r.subscription_history_only?R(Fa,{title:"Subscription history",children:R("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(Fa,{title:"Emails",children:[R(Ia,{deliveries:r.email_deliveries?.filter(C=>!["purchase_receipt","merchant_sale"].includes(C.kind)),problemsOnly:!0,className:"af-mb-4"}),Y("div",{className:"af-space-y-4",children:[R(Li,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(C=>C.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:Y(w,{variant:"outline",size:"sm",onClick:Ee,disabled:p||r.fulfillment_status!=="fulfilled",children:[p?R(Rn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),R(Li,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(C=>C.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),We&&R(Fa,{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:[R(kc,{className:"af-h-4 af-w-4"}),Y("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&R("a",{href:r.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:[R("summary",{className:K(Bi,"af-cursor-pointer af-select-none"),children:"Technical details"}),Y("div",{className:"af-mt-3 af-space-y-2",children:[R(Nr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&R(Nr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&R(Nr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),R(Da,{open:O,onOpenChange:C=>{!C&&!x&&c(!1)},children:Y(wa,{children:[Y(Na,{children:[R(_a,{children:"Reset download count?"}),R(Ra,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),Y(Sa,{children:[R(w,{variant:"outline",onClick:()=>c(!1),disabled:x,children:"Cancel"}),R(w,{onClick:it,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),R(Da,{open:Q,onOpenChange:C=>{!C&&!he&&$(!1)},children:Y(wa,{children:[Y(Na,{children:[R(_a,{children:"Refund order"}),Y(Ra,{children:["Refund up to ",z(xe,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),Y("div",{className:"af-space-y-4",children:[(r.line_items.length>0||E>0)&&Y("div",{className:"af-space-y-2",children:[R(ve,{children:"Items"}),Y("div",{className:"af-space-y-2",children:[r.line_items.map((C,Ae)=>{let jt=C.refunded===!0;return Y("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[R("input",{type:"checkbox",checked:G.includes(Ae),onChange:()=>Fs(Ae),disabled:he||jt||!!C.unavailableReason||I(C)<=0,className:"af-h-4 af-w-4"}),Y("span",{className:jt?"af-text-muted-foreground af-line-through":void 0,children:[typeof C.name=="string"&&C.name?C.name:"Item",typeof C.variantTitle=="string"&&C.variantTitle?` \u2014 ${C.variantTitle}`:"",typeof C.quantity=="number"&&C.quantity>1?` \xD7 ${C.quantity}`:""]}),R("span",{className:"af-ml-auto af-text-muted-foreground",children:jt?"Refunded":z(I(C),r.currency)})]},Ae)}),E>0&&Y("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[R("input",{type:"checkbox",checked:se,onChange:C=>W(C.target.checked),disabled:he,className:"af-h-4 af-w-4"}),R("span",{children:"Shipping"}),R("span",{className:"af-ml-auto af-text-muted-foreground",children:z(E,r.currency)})]})]})]}),Y("div",{className:"af-space-y-2",children:[Y(ve,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),R(ge,{id:"refund-amount",type:"number",min:"0",step:re,value:Ve?String(mt(et,r.currency)):ce,onChange:C=>q(C.target.value),disabled:he||Ve}),Ve&&R("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),rt&&R("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:rt}),Y(Sa,{children:[R(w,{variant:"outline",onClick:()=>$(!1),disabled:he,children:"Cancel"}),R(w,{variant:"outline",onClick:U,disabled:he,children:"Refund everything"}),R(w,{variant:"destructive",onClick:sn,disabled:he,children:he?"Refunding...":je!==null&&je>0?`Refund ${z(je,r.currency)}`:"Refund"})]})]})})]})}import*as Tn from"react";import{ArrowLeft as Hc,RefreshCw as zc}from"lucide-react";import{jsx as Zt,jsxs as ss}from"react/jsx-runtime";function xt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=Tn.useRef(null);return Tn.useEffect(()=>{i.current?.focus()},[]),ss("div",{className:K("af-bg-background",n),children:[ss("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:[Zt("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&ss(w,{type:"button",variant:"outline",size:"sm",onClick:a,className:"af-order-first af-shrink-0",children:[Zt(Hc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Zt("div",{className:"af-p-4",children:t})]})}function ae({className:e}){return Zt("div",{"aria-hidden":"true",className:K("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function at({label:e,children:a,detail:s,valueClassName:t}){return ss("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Zt("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Zt("div",{className:K("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&Zt("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function ia({message:e,onRetry:a}){return ss("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Zt("span",{children:e}),ss(w,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[Zt(zc,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ca({icon:e,children:a}){return ss("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Zt("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}function _s({icon:e,heading:a,body:s,action:t,className:n,children:i}){return ss("div",{className:K("af-px-6 af-py-10 af-text-center",n),children:[Zt(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),Zt("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:a}),Zt("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),t&&Zt(w,{type:"button",className:"af-mt-4",onClick:t.onClick,children:t.label}),i]})}import{jsx as L,jsxs as ye}from"react/jsx-runtime";var Zc={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Ui={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Vi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function $i(e){let a=Array.isArray(e.line_items)?e.line_items:[],s=a[0];if(!s)return"\u2014";let t=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${t} \xD7${n}`:t;return a.length>1?`${i} +${a.length-1} more`:i}function kn(e){return e.customer?.name||e.customer_name||null}function Jc({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o,maxRows:m,onViewAll:d}){let f=typeof m=="number",{api:r}=ie(),g=Sn({refreshKey:s}),{orders:b,total:v,isLoading:u,error:l,page:p,pageSize:h,hasNextPage:x,hasPreviousPage:D,setPage:O,setPageSize:c,customerEmail:k,setCustomerEmail:A,setStatusIn:X,from:S,setFrom:T,to:B,setTo:y,showAbandoned:j,setShowAbandoned:Q,setUnfulfilledOnly:$,refetch:ce}=g,[q,G]=_t.useState("list"),[H,se]=_t.useState(null),[W,he]=_t.useState(""),[Ke,rt]=_t.useState(""),[Re,qe]=_t.useState(!f&&n?"needs_shipping":"all"),[Xe,xe]=_t.useState(!1),[Tt,_]=_t.useState(!!t&&!f),[I,E]=_t.useState(null);_t.useEffect(()=>{if(!t||f)return;let V=!1;return _(!0),E(null),r.getOrder(t).then(qt=>{V||(se(qt),G("detail"))}).catch(()=>{V||E("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{V||_(!1)}),()=>{V=!0}},[r,t,f]);let ue=_t.useCallback(V=>{qe(V);let qt=Ui[V];X(qt.statusIn),$(qt.unfulfilledOnly)},[X,$]);_t.useEffect(()=>{n&&!f&&$(!0)},[]);let me=_t.useRef(!n);_t.useEffect(()=>{me.current||u||(me.current=!0,b.length===0&&ue("all"))},[u,b.length,ue]);let Se=q==="detail"&&!!H;_t.useEffect(()=>{o?.(Se)},[Se,o]);let Ce=(S?1:0)+(B?1:0)+(j?1:0),et=Ce>0||!!k||!!Ke,Ve=!!S&&!!B&&S>B,je=!f||!!d,re=V=>{if(f){d?.();return}se(V),G("detail")},Ee=()=>{G("list"),se(null),ce()},it=V=>{let qt=V.trim();if(!qt){rt(""),k&&A("");return}if(qt.startsWith("#")||/^\d+$/.test(qt)){rt(qt),k&&A("");return}rt(""),A(qt)},ta=()=>{he(""),rt(""),A(""),T(""),y(""),Q(!1),xe(!1)},yt=Ke.replace(/^#/,"").toLowerCase(),kt=yt?b.filter(V=>String(V.order_number??"")===yt||V.id.toLowerCase().startsWith(yt)):b,zt=f?kt.slice(0,m):kt,$e=H?b.findIndex(V=>V.id===H.id):-1,tt=$e>0,Qa=$e>=0&&$e<b.length-1;if(Tt)return L("div",{className:a,children:L("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:L(jc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(q==="detail"&&H)return L("div",{className:a,children:L(Cn,{order:H,onBack:Ee,onRefund:e,onOrderUpdated:V=>se(V),allowFulfillment:n,onPrevOrder:tt?()=>se(b[$e-1]):void 0,onNextOrder:Qa?()=>se(b[$e+1]):void 0,hasPrevOrder:tt,hasNextOrder:Qa},H.id)});let Dt=ye("div",{className:"af-mb-4 af-space-y-3",children:[I&&L("p",{className:"af-text-xs af-text-muted-foreground",children:I}),ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[L("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(V=>L("button",{type:"button","aria-pressed":Re===V,onClick:()=>ue(V),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",Re===V?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Zc[V]},V))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[L(Gc,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),L(ge,{type:"text",value:W,onChange:V=>he(V.target.value),onBlur:()=>it(W),onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),it(W))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),ye(w,{type:"button",variant:Ce>0?"secondary":"ghost",size:"sm",onClick:()=>xe(V=>!V),"aria-expanded":Xe,children:[L(Kc,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ce>0&&L(te,{variant:"secondary",className:"af-ml-2",children:Ce})]}),et&&L(w,{type:"button",variant:"ghost",size:"sm",onClick:ta,children:"Clear filters"})]}),(Xe||!!S||!!B)&&ye("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:[L(ve,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),L(ge,{id:"orders-from",type:"date",value:S,max:B||void 0,onChange:V=>T(V.target.value),className:"af-w-[170px]"}),L(ve,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),L(ge,{id:"orders-to",type:"date",value:B,min:S||void 0,onChange:V=>y(V.target.value),className:"af-w-[170px]"}),!Ui[Re].statusIn&&L(w,{type:"button",variant:j?"secondary":"ghost",size:"sm",onClick:()=>Q(!j),"aria-pressed":j,children:j?"Hide abandoned":"Show abandoned"})]}),Ve&&L("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(u)return ye("div",{className:a,children:[f?null:Dt,L("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(V=>ye("div",{className:"af-rounded-md af-border af-p-3",children:[ye("div",{className:"af-flex af-items-center af-justify-between",children:[L(ae,{className:"af-h-4 af-w-16"}),L(ae,{className:"af-h-4 af-w-14"})]}),L(ae,{className:"af-mt-2 af-h-3 af-w-40"}),L(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},V))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[L(Fe,{children:ye(pe,{children:[L(F,{children:"Order"}),L(F,{children:"Date"}),L(F,{children:"Customer"}),L(F,{children:"Items"}),L(F,{className:"af-text-right",children:"Total"}),L(F,{children:"Status"}),L(F,{className:"af-w-8"})]})}),L(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(V=>ye(pe,{children:[L(M,{children:L(ae,{className:"af-h-4 af-w-14"})}),L(M,{children:L(ae,{className:"af-h-4 af-w-24"})}),L(M,{children:L(ae,{className:"af-h-4 af-w-40"})}),L(M,{children:L(ae,{className:"af-h-4 af-w-32"})}),L(M,{children:L(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),L(M,{children:L(ae,{className:"af-h-5 af-w-16"})}),L(M,{})]},V))})]})}),L("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return ye("div",{className:a,children:[f?null:Dt,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[L("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),L(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let sn=Re!=="all";if(kt.length===0&&p===0)return et||sn?ye("div",{className:a,children:[!f&&Dt,L(Ca,{children:"No orders match these filters."})]}):L("div",{className:a,children:L(_s,{icon:Wc,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!f&&L(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Q(!0),children:"Show abandoned checkouts"})})});let U=p*h+1,We=Math.min((p+1)*h,v);return ye("div",{className:a,children:[f?null:Dt,L("div",{className:"af-space-y-3 lg:af-hidden",children:zt.map(V=>ye("button",{type:"button",onClick:()=>re(V),disabled:!je,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${je?" hover:af-bg-muted/50":""}`,children:[ye("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[L("span",{className:"af-font-medium",children:Za(V)}),L("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:z(Ka(V),V.currency)})]}),ye("div",{className:"af-mt-1 af-min-w-0",children:[ye("div",{className:"af-truncate af-text-sm",children:[V.customer_email||L("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),kn(V)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",kn(V)]})]}),L("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:$i(V)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",z(V.amount_refunded,V.currency)," refunded"]})]}),ye("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[L(ps,{status:V.status}),L(Hs,{deliveries:V.email_deliveries}),V.is_test&&L(te,{variant:"outline",children:"Test"}),n&&L(Ss,{order:V}),L("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Vi(V.created_at)})]})]},V.id))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[L(Fe,{children:ye(pe,{children:[L(F,{children:"Order"}),L(F,{children:"Date"}),L(F,{children:"Customer"}),L(F,{children:"Items"}),L(F,{className:"af-text-right",children:"Total"}),L(F,{children:"Status"}),L(F,{className:"af-w-8"})]})}),L(Me,{children:zt.map(V=>ye(pe,{onClick:je?()=>re(V):void 0,className:je?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[ye(M,{className:"af-whitespace-nowrap af-font-medium",children:[L("button",{type:"button",onClick:qt=>{qt.stopPropagation(),re(V)},disabled:!je,"aria-label":`Open order ${Za(V)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${je?" hover:af-underline":""}`,children:Za(V)}),V.is_test&&L(te,{variant:"outline",className:"af-ml-2",children:"Test"})]}),L(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Vi(V.created_at)}),ye(M,{className:"af-max-w-[220px]",children:[L("div",{className:"af-truncate",children:V.customer_email||L("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),kn(V)&&L("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:kn(V)})]}),L(M,{className:"af-max-w-[220px]",children:L("div",{className:"af-truncate af-text-muted-foreground",children:$i(V)})}),ye(M,{className:"af-whitespace-nowrap af-text-right",children:[L("div",{className:"af-font-medium af-tabular-nums",children:z(Ka(V),V.currency)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",z(V.amount_refunded,V.currency)," ","refunded"]})]}),L(M,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[L(ps,{status:V.status}),L(Hs,{deliveries:V.email_deliveries}),n&&L(Ss,{order:V})]})}),L(M,{className:"af-w-8 af-text-right",children:L(Mi,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},V.id))})]})}),f?null:ye("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ye("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[L("span",{children:yt?`${kt.length} matching this page`:`Showing ${U}-${We} of ${v}`}),ye(ca,{value:String(h),onValueChange:V=>c(Number(V)),children:[L(aa,{className:"af-w-[70px] af-h-8",children:L(ua,{})}),ye(sa,{children:[L(Ge,{value:"10",children:"10"}),L(Ge,{value:"25",children:"25"}),L(Ge,{value:"50",children:"50"}),L(Ge,{value:"100",children:"100"})]})]}),L("span",{children:"per page"})]}),ye("div",{className:"af-flex af-items-center af-gap-2",children:[ye(w,{variant:"outline",size:"sm",onClick:()=>O(p-1),disabled:!D,children:[L(qc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ye(w,{variant:"outline",size:"sm",onClick:()=>O(p+1),disabled:!x,children:["Next",L(Mi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function ns(e){return L(Jc,{...e},e.maxRows==null?"full":"compact")}import*as In from"react";import{ChevronLeft as eu,ChevronRight as tu,Eye as au,Search as su,Users as nu}from"lucide-react";import*as Jt from"react";function En({initialPageSize:e=25}={}){let{api:a}=ie(),[s,t]=Jt.useState([]),[n,i]=Jt.useState(0),[o,m]=Jt.useState(!0),[d,f]=Jt.useState(null),[r,g]=Jt.useState(0),[b,v]=Jt.useState(e),[u,l]=Jt.useState(""),p=Jt.useRef(0),h=Jt.useCallback(async()=>{let D=++p.current;try{m(!0),f(null);let O={limit:b,offset:r*b};u.trim()&&(O.email=u.trim());let c=await a.getCustomers(O);if(D!==p.current)return;t(c.customers),i(c.total)}catch(O){if(D!==p.current)return;f(O instanceof Error?O:new Error("Failed to fetch customers"))}finally{D===p.current&&m(!1)}},[a,r,b,u]);Jt.useEffect(()=>{h()},[h]);let x=Math.ceil(n/b);return{customers:s,total:n,isLoading:o,error:d,page:r,pageSize:b,hasNextPage:r<x-1,hasPreviousPage:r>0,setPage:g,setPageSize:D=>{v(D),g(0)},email:u,setEmail:D=>{l(D),g(0)},refetch:h}}import*as bs from"react";import{ArrowLeft as Yc,Loader2 as Qc}from"lucide-react";import{jsx as De,jsxs as At}from"react/jsx-runtime";function Hi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Xc(e){let a=[];e.name&&a.push(e.name),a.push(e.line1),e.line2&&a.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&a.push(s),e.country&&a.push(e.country),a}function An({customer:e,onBack:a,className:s}){let{api:t}=ie(),[n,i]=bs.useState(null),[o,m]=bs.useState([]),[d,f]=bs.useState(!0),[r,g]=bs.useState(null);bs.useEffect(()=>{let u=!1;return f(!0),g(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,p])=>{u||(i(l),m(p.orders))}).catch(l=>{u||g(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{u||f(!1)}),()=>{u=!0}},[t,e.id,e.email]);let b=n?.addresses??[],v=n?.order_count??o.length;return At("div",{className:s,children:[At("div",{className:"af-mb-6",children:[At(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[De(Yc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),De("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),At("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Hi(e.created_at)]})]}),d?De("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:De(Qc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?De("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):At("div",{className:"af-space-y-6",children:[De(Ia,{deliveries:n?.email_deliveries}),At("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),At("div",{className:"af-space-y-1 af-text-sm",children:[At("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),De("span",{children:e.email})]}),e.name&&At("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),De("span",{children:e.name})]}),e.phone&&At("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),De("span",{children:e.phone})]}),At("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),De("span",{children:v})]})]})]}),b.length>0&&At("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),De("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(u=>At("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&De(te,{variant:"secondary",className:"af-mb-1",children:"Default"}),Xc(u).map((l,p)=>De("div",{children:l},p))]},u.id))})]}),At("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?De("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):At(Be,{children:[De(Fe,{children:At(pe,{children:[De(F,{children:"Date"}),De(F,{children:"Amount"}),De(F,{children:"Status"})]})}),De(Me,{children:o.map(u=>At(pe,{children:[De(M,{className:"af-text-muted-foreground",children:Hi(u.created_at)}),De(M,{children:z(Ka(u),u.currency)}),De(M,{children:De(gs,{status:u.status})})]},u.id))})]})]})]})]})}import{Fragment as iu,jsx as Pe,jsxs as gt}from"react/jsx-runtime";function ru(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Dn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:m,hasPreviousPage:d,setPage:f,setPageSize:r,email:g,setEmail:b,refetch:v}=En(),[u,l]=In.useState("list"),[p,h]=In.useState(null),[x,D]=In.useState(""),O=S=>{h(S),l("detail")},c=()=>{l("list"),h(null),v()};if(u==="detail"&&p)return Pe("div",{className:e,children:Pe(An,{customer:p,onBack:c})});let k=gt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Pe(ge,{type:"email",value:x,onChange:S=>D(S.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),b(x.trim()))}}),gt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>b(x.trim()),children:[Pe(su,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&Pe(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{D(""),b("")},children:"Clear"})]});if(t)return gt("div",{className:e,children:[k,Pe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Pe("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return gt("div",{className:e,children:[k,Pe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:gt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return gt("div",{className:e,children:[g&&k,gt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Pe(nu,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Pe("p",{className:"af-text-muted-foreground af-text-center",children:g?"No customers match that email.":gt(iu,{children:["No customers yet.",Pe("br",{}),"Customers appear here after their first purchase."]})})]})]});let A=i*o+1,X=Math.min((i+1)*o,s);return gt("div",{className:e,children:[k,gt(Be,{children:[Pe(Fe,{children:gt(pe,{children:[Pe(F,{children:"Email"}),Pe(F,{children:"Name"}),Pe(F,{children:"Customer since"}),Pe(F,{className:"af-text-right",children:"Actions"})]})}),Pe(Me,{children:a.map(S=>gt(pe,{children:[Pe(M,{className:"af-font-medium",children:S.email}),Pe(M,{children:S.name||Pe("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Pe(M,{className:"af-text-muted-foreground",children:ru(S.created_at)}),Pe(M,{className:"af-text-right",children:Pe(w,{variant:"ghost",size:"icon",onClick:()=>O(S),title:"View customer",children:Pe(au,{className:"af-h-4 af-w-4"})})})]},S.id))})]}),gt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[gt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[gt("span",{children:["Showing ",A,"-",X," of ",s]}),gt(ca,{value:String(o),onValueChange:S=>r(Number(S)),children:[Pe(aa,{className:"af-w-[70px] af-h-8",children:Pe(ua,{})}),gt(sa,{children:[Pe(Ge,{value:"10",children:"10"}),Pe(Ge,{value:"25",children:"25"}),Pe(Ge,{value:"50",children:"50"}),Pe(Ge,{value:"100",children:"100"})]})]}),Pe("span",{children:"per page"})]}),gt("div",{className:"af-flex af-items-center af-gap-2",children:[gt(w,{variant:"outline",size:"sm",onClick:()=>f(i-1),disabled:!d,children:[Pe(eu,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),gt(w,{variant:"outline",size:"sm",onClick:()=>f(i+1),disabled:!m,children:["Next",Pe(tu,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ne from"react";import{ArrowLeft as ou,ChevronLeft as lu,ChevronRight as zi,Copy as cu,Download as uu,ExternalLink as du,FileText as Wi,Loader2 as fu,Search as mu}from"lucide-react";import*as vt from"react";function Rs({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=ie(),[n,i]=vt.useState([]),[o,m]=vt.useState(0),[d,f]=vt.useState(null),[r,g]=vt.useState(!0),[b,v]=vt.useState(null),[u,l]=vt.useState(0),[p,h]=vt.useState(e),[x,D]=vt.useState(void 0),[O,c]=vt.useState(""),[k,A]=vt.useState(""),[X,S]=vt.useState(""),[T,B]=vt.useState(""),[y,j]=vt.useState(""),Q=x?x.join(","):"",$=vt.useRef(0),ce=vt.useCallback(async()=>{let G=++$.current;g(!0),v(null);try{let H={labels:Q?Q.split(","):void 0,customerEmail:O||void 0,q:k||void 0,from:X||void 0,to:T||void 0,retainerId:y||void 0,includeAggregates:s,limit:p,offset:u*p},se=await t.getInvoices(H);if(G!==$.current)return;if(u>0&&u*p>=se.total){l(Math.max(0,Math.ceil(se.total/p)-1));return}i(se.invoices),m(se.total),s&&f(se.aggregates??null)}catch(H){if(G!==$.current)return;v(H instanceof Error?H:new Error("Failed to fetch invoices"))}finally{G===$.current&&g(!1)}},[t,Q,O,k,X,T,y,u,p,s]);vt.useEffect(()=>{ce()},[ce,a]);let q=G=>H=>{l(0),G(H)};return{invoices:n,total:o,aggregates:d,isLoading:r,error:b,page:u,pageSize:p,hasNextPage:(u+1)*p<o,hasPreviousPage:u>0,setPage:l,setPageSize:q(h),labels:x,setLabels:q(D),customerEmail:O,setCustomerEmail:q(c),q:k,setQ:q(A),from:X,setFrom:q(S),to:T,setTo:q(B),retainerId:y,setRetainerId:q(j),clearFilters:()=>{l(0),D(void 0),c(""),A(""),S(""),B(""),j("")},refetch:ce}}import{Fragment as wu,jsx as P,jsxs as J}from"react/jsx-runtime";var pu={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 kr(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:pu[e.label]??e.label}function gu(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var Tr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},vu={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Gs({invoice:e,className:a}){return J("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[P(te,{variant:gu(e.label),className:a,children:kr(e)}),e.collection_method==="charge_automatically"&&P(te,{variant:"secondary",children:"Managed in Stripe"})]})}function Bn({delivery:e,className:a}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return P(te,{variant:s,className:a,children:Tr[e.state]??e.state})}function Ps(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function va(e){if(!e)return"\u2014";let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var qi={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Ln={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0};function bu(e){let a=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(a),t=s?`'${a}`:a;return s||/[",;\r\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}var Pr=100,Cr=5e3;async function yu(e,a){let s=[],t=0;for(let n=0;n<Cr;n+=Pr){let i=await e.getInvoices({...a,limit:Pr,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<Pr||s.length>=t)break}return{invoices:s.slice(0,Cr),total:t,truncated:t>s.length||t>Cr}}function Gi(e){let a=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(t=>[t.id,Ps(t),kr(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),z(t.amount_subtotal,t.currency),z(t.tax_total,t.currency),z(t.amount_total,t.currency),t.amount_due===null?"":z(t.amount_due,t.currency),t.amount_paid===null?"":z(t.amount_paid,t.currency),z(t.amount_refunded,t.currency),t.payment_method??"",t.pay_url??"",t.retainer_id??"",t.replaces_order_id??"",t.replaced_by_order_id??"",t.tax_behavior??"",t.discount_total===void 0?"":z(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(bu).join(",")).join(`
|
|
5
|
-
`)}function hu(e){if(typeof document>"u")return;let a=new Blob([Gi(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(a),t=document.createElement("a");t.href=s,t.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(s)}function xu({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:m=null,onClearRetainerFilter:d,maxRows:f,onViewAll:r}){let g=typeof f=="number",{api:b}=ie(),{invoices:v,total:u,isLoading:l,error:p,page:h,pageSize:x,hasNextPage:D,hasPreviousPage:O,setPage:c,labels:k,setLabels:A,customerEmail:X,setCustomerEmail:S,q:T,setQ:B,from:y,setFrom:j,to:Q,setTo:$,retainerId:ce,setRetainerId:q,refetch:G}=Rs({refreshKey:a}),[H,se]=Ne.useState(typeof f=="number"?"all":"open"),[W,he]=Ne.useState(""),[Ke,rt]=Ne.useState(null),Re=Ne.useRef(0),qe=!g||!!r,Xe=Ne.useCallback(U=>{if(g){r?.();return}Re.current++,Tt(!1),rt(U)},[g,r]),[xe,Tt]=Ne.useState(!1),[_,I]=Ne.useState(0),[E,ue]=Ne.useState(null),[me,Se]=Ne.useState(!1),[Ce,et]=Ne.useState(0);Ne.useEffect(()=>{rt(U=>{if(!U)return U;let We=v.find(V=>V.id===U.id);return We&&We!==U?We:U})},[v]);let[Ve,je]=Ne.useState(!1),[re,Ee]=Ne.useState(null),it=async()=>{if(!Ve){je(!0),Ee(null);try{let{invoices:U,total:We,truncated:V}=await yu(b,{labels:k,customerEmail:X,q:T,from:y,to:Q,retainerId:ce});hu(U),Ee(V?`Exported the first ${U.length.toLocaleString()} of ${We.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ee("Couldn't export \u2014 try again.")}finally{je(!1)}}},ta=!X&&!T&&!y&&!Q&&!ce,[yt,kt]=Ne.useState(null);Ne.useEffect(()=>{if(l||u>0||!ta||H!=="open")return;let U=!1;return b.getInvoices({limit:1}).then(We=>{U||kt(We.total>0)}).catch(()=>{U||kt(!0)}),()=>{U=!0}},[b,l,u,ta,H,a]),Ne.useEffect(()=>{A(g?Ln.all:Ln.open)},[]),Ne.useEffect(()=>{let U=m?.id??"";U!==ce&&(q(U),U&&(se("all"),A(Ln.all),S(""),B(""),he(""),j(""),$("")))},[m?.id]),Ne.useEffect(()=>{let U=!1;return Se(!1),b.getInvoiceSettings().then(We=>{U||ue({payments_active:We.payments_active,blocked:We.blocked})}).catch(()=>{U||Se(!0)}),()=>{U=!0}},[b,a,Ce]),Ne.useEffect(()=>{if(!s||g)return;let U=!1,We=Re.current;return Tt(!1),b.getInvoice(s).then(V=>{!U&&We===Re.current&&rt(V)}).catch(()=>{!U&&We===Re.current&&Tt(!0)}),()=>{U=!0}},[b,s,_,g]),Ne.useEffect(()=>{t?.(Ke!==null)},[Ke,t]);let zt=U=>{se(U),A(Ln[U])},$e=U=>{let We=U.trim();if(!We){T&&B(""),X&&S("");return}if(We.includes("@")){T&&B(""),S(We);return}X&&S(""),B(We.replace(/^#/,""))},tt=v,Qa=g?tt.slice(0,f):tt,Fs=xe&&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. ",P(w,{type:"button",variant:"link",size:"sm",onClick:()=>I(U=>U+1),children:"Retry opening invoice"})]});if(Ke)return J("div",{className:e,children:[Fs,P(Er,{invoice:Ke,refreshKey:a,onBack:()=>{Xe(null),G()}},Ke.id)]});let Dt=J("div",{className:"af-mb-4 af-space-y-3",children:[me&&J("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",P(w,{type:"button",variant:"link",size:"sm",onClick:()=>et(U=>U+1),children:"Retry setup check"})]}),Fs,E?.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",E.blocked.reason?`: ${E.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),m&&J("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[J(te,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",m.label]}),d&&P(w,{type:"button",variant:"link",size:"sm",onClick:d,children:"Clear schedule filter"})]}),J("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[P("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(qi).map(U=>P("button",{type:"button","aria-pressed":H===U,onClick:()=>zt(U),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",H===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:qi[U]},U))}),J("div",{className:"af-relative af-w-full af-max-w-xs",children:[P(mu,{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"}),P(ge,{type:"text",value:W,onChange:U=>he(U.target.value),onBlur:()=>$e(W),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),$e(W))},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:[P(ve,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),P(ge,{id:"invoices-from",type:"date",value:y,max:Q||void 0,onChange:U=>j(U.target.value),className:"af-invoice-date af-w-[150px]"})]}),J("div",{className:"af-flex af-items-center af-gap-2",children:[P(ve,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),P(ge,{id:"invoices-to",type:"date",value:Q,min:y||void 0,onChange:U=>$(U.target.value),className:"af-invoice-date af-w-[150px]"})]}),J(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void it(),disabled:Ve||l||!!p||u===0,"aria-busy":Ve,children:[P(uu,{className:"af-h-4 af-w-4 af-mr-1"}),Ve?"Exporting\u2026":"Export CSV (all matching)"]})]}),re&&P("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:re})]});return l?J("div",{className:e,children:[g?null:Dt,P("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(U=>J("div",{className:"af-rounded-md af-border af-p-3",children:[J("div",{className:"af-flex af-items-center af-justify-between",children:[P(ae,{className:"af-h-4 af-w-20"}),P(ae,{className:"af-h-4 af-w-16"})]}),P(ae,{className:"af-mt-2 af-h-3 af-w-40"})]},U))})]}):p?J("div",{className:e,children:[g?null:Dt,J("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",P(w,{type:"button",variant:"link",size:"sm",onClick:()=>void G(),children:"Retry"})]})]}):u===0&&ta&&(H==="all"||yt===!1)&&(H==="open"||H==="all")?E?.blocked?J("div",{className:e,children:[g?null:Dt,P(On,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?J("div",{className:e,children:[g?null:Dt,P(On,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):E&&!E.payments_active?J("div",{className:e,children:[g?null:Dt,P(On,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):J("div",{className:e,children:[g?null:Dt,P(On,{heading:"No invoices yet",body:!E||me?"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:Dt,Qa.length===0?P("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(wu,{children:[P("div",{className:"af-space-y-3 lg:af-hidden",children:Qa.map(U=>J("button",{type:"button",onClick:()=>Xe(U),disabled:!qe,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${qe?" hover:af-bg-muted/50":""}`,children:[J("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[P("span",{className:"af-font-medium",children:Ps(U)}),P(Gs,{invoice:U})]}),P("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:U.customer_name??U.customer_email??"\u2014"}),U.delivery&&P("div",{className:"af-mt-1",children:P(Bn,{delivery:U.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:[P("span",{children:U.collection_method==="charge_automatically"?"Automatic collection":U.due_at?`Due ${va(U.due_at)}`:"Due on receipt"}),P("span",{className:"af-font-medium af-tabular-nums",children:z(U.amount_due??U.amount_total,U.currency)})]})]},U.id))}),P("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:J(Be,{children:[P(Fe,{children:J(pe,{children:[P(F,{children:"Invoice"}),P(F,{children:"Created"}),P(F,{children:"Customer"}),P(F,{children:"Due"}),P(F,{className:"af-text-right",children:"Amount"}),P(F,{children:"Status"}),P(F,{children:"Delivery"}),P(F,{className:"af-w-8"})]})}),P(Me,{children:Qa.map(U=>J(pe,{className:qe?"af-cursor-pointer":void 0,onClick:qe?()=>Xe(U):void 0,children:[P(M,{className:"af-font-medium",children:P("button",{type:"button",disabled:!qe,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${qe?" hover:af-underline":""}`,onClick:We=>{We.stopPropagation(),Xe(U)},"aria-label":`Open invoice ${Ps(U)}`,children:Ps(U)})}),P(M,{children:va(U.created_at)}),J(M,{children:[P("div",{children:U.customer_name??"\u2014"}),P("div",{className:"af-text-xs af-text-muted-foreground",children:U.customer_email})]}),P(M,{children:U.collection_method==="charge_automatically"?"Automatic":U.due_at?va(U.due_at):"On receipt"}),P(M,{className:"af-text-right af-tabular-nums",children:z(U.amount_due??U.amount_total,U.currency)}),P(M,{children:P(Gs,{invoice:U})}),P(M,{children:P(Bn,{delivery:U.delivery})}),P(M,{children:P(zi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},U.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:[u," invoice",u===1?"":"s"]}),J("div",{className:"af-flex af-items-center af-gap-1",children:[P(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(h-1),disabled:!O,"aria-label":"Previous page",children:P(lu,{className:"af-h-4 af-w-4"})}),J("span",{className:"af-tabular-nums",children:[h*x+1,"\u2013",Math.min((h+1)*x,u)]}),P(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(h+1),disabled:!D,"aria-label":"Next page",children:P(zi,{className:"af-h-4 af-w-4"})})]})]})]})]})}function On({heading:e,body:a,action:s}){return P(_s,{icon:Wi,heading:e,body:a,action:s})}function is(e){return P(xu,{...e},e.maxRows==null?"full":"compact")}var Ja="af-text-xs af-text-muted-foreground";function ji(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Er({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=ie(),i=Ne.useRef(null);Ne.useEffect(()=>{i.current?.focus()},[e.id]);let[o,m]=Ne.useState(!1),[d,f]=Ne.useState(null),[r,g]=Ne.useState(!1),[b,v]=Ne.useState(!1),u=Ne.useRef(0),[l,p]=Ne.useState(null),[h,x]=Ne.useState(!1),[D,O]=Ne.useState(0);Ne.useEffect(()=>{let y=!1;return x(!1),n.getInvoice(e.id).then(j=>{y||p({source:e,value:j})}).catch(()=>{y||x(!0)}),()=>{y=!0}},[n,e,s,D]);let c=l?.source===e?l.value:e,k=c.collection_method==="charge_automatically";Ne.useEffect(()=>(u.current++,f(null),g(!1),v(!1),m(!1),()=>{u.current++}),[n,c,s]);let A=y=>y==null?"\u2014":z(y,c.currency),X=async()=>{if(!(!c.pay_url||!ji()))try{await navigator.clipboard.writeText(c.pay_url),m(!0),setTimeout(()=>m(!1),1500)}catch{}},S=async()=>{if(d){f(null);return}let y=++u.current;v(!1),g(!0);try{let j=await n.getInvoicePreview(c.id);y===u.current&&f(j)}catch{y===u.current&&v(!0)}finally{y===u.current&&g(!1)}},T=c.bill_to,B=T?[T.company,T.name,T.address?.line1,T.address?.line2,[T.address?.city,T.address?.state,T.address?.postal_code].filter(Boolean).join(", "),T.address?.country,T.tax_id?`${T.tax_id.value}`:null,T.po_number?`PO ${T.po_number}`:null,T.service_period?`Service period: ${T.service_period}`:null].filter(y=>!!y&&y.length>0):[];return J("div",{className:t,children:[J("div",{className:"af-mb-4",children:[J(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[P(ou,{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:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Ps(c)]}),P(Gs,{invoice:c}),P(Bn,{delivery:c.delivery})]}),J("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),h&&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. ",P(w,{type:"button",variant:"link",size:"sm",onClick:()=>O(y=>y+1),children:"Retry details"})]}),c.label==="failed"&&P("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."}),c.label==="creating"&&P("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(Be,{children:[P(Fe,{children:J(pe,{children:[P(F,{children:"Description"}),P(F,{className:"af-text-right",children:"Qty"}),P(F,{className:"af-text-right",children:"Amount"})]})}),P(Me,{children:c.line_items.map((y,j)=>J(pe,{children:[P(M,{style:{overflowWrap:"anywhere"},children:y.description}),P(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:y.quantity}),P(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:A(y.amount)})]},j))})]}),J("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[P(rs,{label:"Subtotal",value:A(c.amount_subtotal)}),(c.discount_total??0)>0&&P(rs,{label:"Discount",value:`-${A(c.discount_total)}`}),c.tax_total>0&&P(rs,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:A(c.tax_total)}),P(rs,{label:"Total",value:A(c.amount_total),strong:!0}),c.credit_applied>0&&P(rs,{label:"Credit applied",value:`-${A(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&P(rs,{label:"Amount due",value:A(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&P(rs,{label:"Amount paid",value:A(c.amount_paid)}),c.amount_refunded>0&&P(rs,{label:"Refunded",value:A(c.amount_refunded)})]}),c.credit_notes?.length>0&&J("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[P("div",{className:Ja,children:"Credit notes"}),c.credit_notes.map(y=>J("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[J("span",{className:"af-text-muted-foreground",children:[va(y.created_at)," \xB7 ",y.origin==="dashboard"?"issued in Stripe":"refund",y.stripe_credit_note_id?"":" \xB7 being created"]}),J("span",{className:"af-tabular-nums",children:["-",z(y.amount,y.currency)]})]},y.id))]})]}),(c.note||c.footer)&&J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&J("div",{children:[P("div",{className:Ja,children:"Note"}),P("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&J("div",{children:[P("div",{className:Ja,children:"Footer"}),P("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),d&&!k&&J("section",{className:"af-rounded-md af-border af-p-4",children:[J("div",{className:K(Ja,"af-break-words"),children:["Email preview \u2014 ",d.subject]}),P("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),P("iframe",{title:"Invoice email preview",srcDoc:d.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),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:[P(ga,{label:"Created",value:va(c.created_at)}),P(ga,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?va(c.due_at):"On receipt"}),c.paid_at&&P(ga,{label:"Paid",value:va(c.paid_at)}),c.payment_method&&P(ga,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&P(ga,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&P(ga,{label:"Delivery",value:`${Tr[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&P(ga,{label:"Written off",value:va(c.marked_uncollectible_at)}),c.correction_reason&&P(ga,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&P(ga,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?P(ga,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&P(ga,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&P(ga,{label:"Replaces",value:c.replaces_order_id})]}),J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[P("div",{className:Ja,children:"Reminders"}),k?P("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?P("div",{children:"Off for this invoice."}):c.reminders.paused_until?J("div",{children:["Paused until ",va(c.reminders.paused_until),"."]}):c.reminders.next_at?J("div",{children:["Next on ",va(c.reminders.next_at),"."]}):c.reminders.final_sent_at?J("div",{children:["Final reminder sent ",va(c.reminders.final_sent_at),"."]}):P("div",{children:"None scheduled."}),!k&&J("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(y=>y<0?`${-y}d before`:y===0?"due day":`${y}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[P("div",{className:Ja,children:"Email delivery history"}),c.communications.map(y=>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:[vu[y.kind]??y.kind,y.kind==="reminder"&&y.slot!==null?` #${y.slot}`:"",J("span",{className:"af-text-muted-foreground",children:[" \xB7 ",y.recipient]})]}),J("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Tr[y.state]??y.state," \xB7 ",va(y.state_at??y.created_at)]})]},y.id))]}),B.length>0&&J("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[P("div",{className:Ja,children:"Bill to"}),B.map((y,j)=>P("div",{className:"af-break-words",children:y},j))]}),J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&J(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void X(),disabled:!ji(),children:[P(cu,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":k?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&P(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:J("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[P(du,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!k&&J(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void S(),disabled:r,children:[r?P(fu,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(Wi,{className:"af-h-4 af-w-4 af-mr-1"}),d?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!k&&P("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&P("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),P("p",{className:"af-text-xs af-text-muted-foreground",children:k?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function ga({label:e,value:a}){return J("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[P("span",{className:K(Ja,"af-shrink-0"),children:e}),P("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function rs({label:e,value:a,strong:s}){return J("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[P("dt",{className:K(Ja,s&&"af-font-medium af-text-foreground"),children:e}),P("dd",{className:K("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as Nu}from"lucide-react";import{jsx as bt,jsxs as Ta}from"react/jsx-runtime";var Su={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Ki={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function _u(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 Zi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>Ki[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>Ki[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Su[e.status]}function Ji(e){let a=e.interval==="year"?"every year":"every month";return`${z(e.amount,e.currency)} ${a}`}function Ru(e){return e.status==="canceled"?`Ended ${Fn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Fn(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 ${Fn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Fn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Fn(e){if(!e)return"\u2014";let a=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(a);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ar({retainer:e,className:a}){return bt(te,{variant:_u(e.status),className:K("af-max-w-full af-whitespace-normal af-break-words",a),children:Zi(e)})}function Cs({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:m=0,isLoadingMore:d=!1,onLoadMore:f,includeEnded:r=!1,onIncludeEndedChange:g,className:b}){let v=!!g;if(!a&&!s&&e.length===0&&!(v&&(r||m>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return Ta("section",{className:K("af-mb-6",b),"aria-label":"Recurring invoices",children:[Ta("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[bt(Nu,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),bt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),bt("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."}),v&&bt(w,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>g?.(!r),children:r?"Hide ended recurring invoices":m>0&&e.length===0?`Show ended recurring invoices (${m})`:"Show ended recurring invoices"})]}),s?Ta("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",bt(w,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?bt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>Ta("div",{className:"af-rounded-md af-border af-p-3",children:[bt(ae,{className:"af-h-4 af-w-48"}),bt(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?bt("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:r?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):bt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let p=i===l.id;return Ta("li",{className:K("af-rounded-md af-border af-p-3",p&&"af-border-primary af-bg-muted/40"),children:[Ta("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Ta("div",{className:"af-min-w-0",children:[bt("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),bt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),bt(Ar,{retainer:l})]}),l.collection_method==="charge_automatically"?Ta("div",{className:"af-mt-2 af-space-y-1",children:[bt(te,{variant:"secondary",children:"Managed in Stripe"}),bt("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."})]}):bt("div",{className:"af-mt-2 af-text-sm",children:Ji(l)}),Ta("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:[Ta("span",{children:[Ru(l)," \xB7 ",l.cycles.count===0?"no invoices yet":`${l.cycles.paid} paid${l.cycles.open>0?`, ${l.cycles.open} open`:""}`]}),l.cycles.count>0&&bt(w,{type:"button",variant:p?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":p,children:p?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&Ta("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!a&&!s&&u>0&&f&&bt("div",{className:"af-mt-2",children:bt(w,{type:"button",variant:"outline",size:"sm",onClick:f,disabled:d,children:d?"Loading\u2026":`Load more (${u} more)`})})]})}import*as Qi from"react";import{AlertTriangle as Yi,CheckCircle2 as Pu,CreditCard as Ir,Loader2 as Cu,RefreshCw as Tu}from"lucide-react";import{jsx as st,jsxs as Rt}from"react/jsx-runtime";function Mn({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=as(),[m,d]=Qi.useState(!1),f=async()=>{d(!0);try{await o()}finally{d(!1)}};return n&&!t?st("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:st("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?st("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Rt("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?st("div",{className:s,children:Rt("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:[st(Pu,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Rt("div",{children:[st("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),Rt("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",t.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):Rt("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&Rt("div",{className:"af-space-y-3",children:[Rt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[st(Ir,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Rt("div",{children:[st("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),st("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?Rt(w,{onClick:e,children:[st(Ir,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):st("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),t.reason==="needs_paid_plan"&&Rt("div",{className:"af-space-y-3",children:[Rt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[st(Yi,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Rt("div",{children:[st("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),st("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."})]})]}),a?st(w,{onClick:a,children:"Upgrade plan"}):st("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&Rt("div",{className:"af-space-y-3",children:[Rt("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:[st(Yi,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Rt("div",{children:[st("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?st("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."}):st("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."})]})]}),Rt("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&Rt(w,{onClick:e,children:[st(Ir,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Rt(w,{variant:"outline",onClick:f,disabled:m,children:[m?st(Cu,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):st(Tu,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Mt from"react";function Dr(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function Ts({includeStats:e=!1,refreshKey:a}={}){let{api:s}=ie(),[t,n]=Mt.useState([]),[i,o]=Mt.useState(!0),[m,d]=Mt.useState(null),f=Mt.useRef(0),r=Mt.useCallback(async()=>{let p=++f.current;try{o(!0),d(null);let h=await s.getProducts(e?{include:"stats"}:{});if(p!==f.current)return;n(h)}catch(h){if(p!==f.current)return;d(h instanceof Error?h:new Error("Failed to fetch products"))}finally{p===f.current&&o(!1)}},[s,e,a]);Mt.useEffect(()=>{r()},[r]);let g=Mt.useCallback(async p=>{let h=await s.createProduct(p);return n(x=>[h,...x]),h},[s]),b=Mt.useCallback(async(p,h)=>{let x=await s.updateProduct(p,h);return n(D=>Dr(D,p,x)),x},[s]),v=Mt.useCallback(async p=>{await s.deleteProduct(p),n(h=>h.filter(x=>x.id!==p))},[s]),u=Mt.useCallback(async(p,h)=>{let x=await s.attachProductFile(p,h);return n(D=>Dr(D,p,x)),x},[s]),l=Mt.useCallback(async(p,h)=>{let x=await s.attachProductFileFromUrl(p,h);return n(D=>Dr(D,p,x)),x},[s]);return{products:t,isLoading:i,error:m,refetch:r,createProduct:g,updateProduct:b,deleteProduct:v,attachProductFile:u,attachProductFileFromUrl:l}}import*as Ut from"react";var Xi=["creating","active","paused","canceling"],ku=["canceled","failed"];function ks({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=ie(),[n,i]=Ut.useState([]),[o,m]=Ut.useState(0),[d,f]=Ut.useState(0),[r,g]=Ut.useState(!0),[b,v]=Ut.useState(!1),[u,l]=Ut.useState(null),[p,h]=Ut.useState(a),x=Ut.useRef(0),D=Ut.useCallback(async()=>{let c=++x.current;g(!0),v(!1),l(null);try{let k=await t.getRetainers({statuses:p?void 0:Xi,limit:s,offset:0});if(c!==x.current)return;if(i(k.retainers),m(k.total),!p&&k.total===0){let A=await t.getRetainers({statuses:ku,limit:1,offset:0});if(c!==x.current)return;f(A.total)}else f(0)}catch(k){if(c!==x.current)return;l(k instanceof Error?k:new Error("Failed to fetch retainers"))}finally{c===x.current&&g(!1)}},[t,p,s]);Ut.useEffect(()=>{D()},[D,e]);let O=Ut.useCallback(async()=>{if(r||b||n.length>=o)return;let c=x.current;v(!0);try{let k=await t.getRetainers({statuses:p?void 0:Xi,limit:s,offset:n.length});if(c!==x.current)return;i(A=>{let X=new Set(A.map(S=>S.id));return[...A,...k.retainers.filter(S=>!X.has(S.id))]}),m(k.total)}catch(k){if(c!==x.current)return;l(k instanceof Error?k:new Error("Failed to fetch retainers"))}finally{c===x.current&&v(!1)}},[t,p,s,r,b,n.length,o]);return{retainers:n,total:o,endedTotal:d,hasMore:n.length<o,isLoading:r,isLoadingMore:b,error:u,includeEnded:p,setIncludeEnded:h,loadMore:O,refetch:D}}import{Fragment as Fu,jsx as ze,jsxs as Yt}from"react/jsx-runtime";function eo({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=Es.useState(a),[m,d]=Es.useState("list"),[f,r]=Es.useState(null),g=Ts(),{status:b,error:v}=as(),u=b?.currency,l=D=>{r(D),d("edit")},p=()=>{r(null),d("create")},h=()=>{d("list"),r(null)},x=D=>{r(D),d("edit")};return Yt("div",{className:e,children:[Yt("div",{className:"af-mb-6",children:[ze("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),ze("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Yt(on,{value:i,onValueChange:D=>o(D),children:[Yt($s,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Yt(ya,{value:"products",className:"af-gap-2",children:[ze(Iu,{className:"af-h-4 af-w-4"}),"Products"]}),Yt(ya,{value:"orders",className:"af-gap-2",children:[ze(Du,{className:"af-h-4 af-w-4"}),"Orders"]}),Yt(ya,{value:"invoices",className:"af-gap-2",children:[ze(Au,{className:"af-h-4 af-w-4"}),"Invoices"]}),Yt(ya,{value:"customers",className:"af-gap-2",children:[ze(Ou,{className:"af-h-4 af-w-4"}),"Customers"]}),ze(ya,{value:"promos",children:"Promo codes"}),Yt(ya,{value:"setup",className:"af-gap-2",children:[ze(Lu,{className:"af-h-4 af-w-4"}),"Setup"]})]}),ze(ha,{value:"products",children:m==="list"?ze(xn,{productsState:g,onSelectProduct:l,onCreateProduct:p}):Yt("div",{children:[Yt("div",{className:"af-mb-6",children:[Yt(w,{variant:"ghost",size:"sm",onClick:h,className:"af-mb-2 af--ml-2",children:[ze(Eu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),ze("h3",{className:"af-text-lg af-font-semibold",children:m==="create"?"New Product":f?.name})]}),m==="create"&&!u?ze("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:v?Yt("div",{className:"af-text-destructive",children:["Error: ",v.message]}):ze("div",{className:"af-text-muted-foreground",children:"Loading..."})}):ze(Nn,{productsState:g,product:m==="edit"?f:null,currency:u??"usd",onSaved:x},m==="edit"?f?.id??"edit":"new")]})}),ze(ha,{value:"orders",children:ze(ns,{onRefund:t})}),ze(ha,{value:"invoices",children:ze(Bu,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),ze(ha,{value:"customers",children:ze(Dn,{})}),ze(ha,{value:"promos",children:ze(Ns,{})}),ze(ha,{value:"setup",children:ze(Mn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Bu({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=ks(),[n,i]=Es.useState(null),[o,m]=Es.useState(!1);return Yt(Fu,{children:[!o&&ze(Cs,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:d=>i(f=>f?.id===d.id?null:d),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),ze(is,{onDetailOpenChange:m,onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}import*as ao from"react";import*as Ma from"react";function As({refreshKey:e}={}){let{api:a}=ie(),[s,t]=Ma.useState(null),[n,i]=Ma.useState(!0),[o,m]=Ma.useState(null),d=Ma.useRef(0),f=Ma.useCallback(async()=>{let r=++d.current;try{i(!0),m(null);let g=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==d.current)return;t(g)}catch(g){if(r!==d.current)return;m(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{r===d.current&&i(!1)}},[a,e]);return Ma.useEffect(()=>{f()},[f]),{summary:s,isLoading:n,error:o,refetch:f}}import{Fragment as Lr,jsx as Pt,jsxs as Or}from"react/jsx-runtime";function to(e,a){if(e.settled.complete)return{headline:z(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:z(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${z(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:z(0,a),extra:[]}}function so({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:m,error:d,refetch:f}=As({refreshKey:e}),[r,g]=ao.useState(!1),b=Pt("div",{className:"af-mb-6",children:d&&!o?Pt(ia,{message:"Couldn't load your revenue summary.",onRetry:()=>f()}):Pt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!o?Or(Lr,{children:[Pt(at,{label:"This week",children:Pt(ae,{className:"af-h-6 af-w-24"})}),Pt(at,{label:"Today",children:Pt(ae,{className:"af-h-6 af-w-24"})}),Pt(at,{label:"Needs attention",children:Pt(ae,{className:"af-h-6 af-w-10"})})]}):Pt(Lr,{children:(()=>{let v=to(o.revenue.d7,o.currency),u=to(o.revenue.today,o.currency);return Or(Lr,{children:[Pt(at,{label:"This week",detail:v.extra.length>0?Pt("div",{children:v.extra.map(l=>Pt("div",{children:l},l))}):void 0,children:v.headline}),Pt(at,{label:"Today",detail:u.extra.length>0?Pt("div",{children:u.extra.map(l=>Pt("div",{children:l},l))}):void 0,children:u.headline}),Pt(at,{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 Or(xt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[b,Pt(ns,{refreshKey:e,initialOrderId:a,onDetailOpenChange:g,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as Va from"react";import{ImageOff as Hu,Package as zu,Search as qu}from"lucide-react";import*as Ua from"react";import{ArrowLeft as Vu,ImageOff as $u}from"lucide-react";import{jsx as ka,jsxs as Ks}from"react/jsx-runtime";var no="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",os="af-text-xs af-text-muted-foreground",Un="af-text-sm af-font-medium af-tabular-nums",Mu=3;function Uu(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let d=e.min_amount??a?.min_amount??null,f=e.max_amount??a?.max_amount??null;return d!==null&&f!==null?{text:`Buyer chooses (${z(d,s)} \u2013 ${z(f,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=a?.min_amount??e.unit_amount,i=a?.max_amount??e.unit_amount;if(n===null||i===null)return{text:"Varies by variant",compareAt:null};let o=n===i?z(n,s):`${z(n,s)} \u2013 ${z(i,s)}`,m=a?.compare_at_amount??null;return{text:o,compareAt:m!==null&&m>i?z(m,s):null}}function Vn({product:e,className:a}){let s=Uu(e);return Ks("div",{className:a,children:[ka("span",{className:Un,children:s.text}),s.compareAt&&ka("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function $n({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?ka(te,{variant:"destructive",children:"Out of stock"}):a.low_stock?Ks(te,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?ka(te,{variant:"secondary",children:"Backorder"}):a.available===null?null:Ks(te,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?ka(te,{variant:"warning",children:"Low stock"}):null}function Hn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function zn(e){return e.map(a=>z(a.amount,a.currency)).join(" + ")}function ro(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${z(e.min_amount,e.currency)} \u2013 ${z(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":z(e.unit_amount,e.currency)}function io({variant:e}){let a=e.inventory;if(!a||!a.tracked)return ka("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?Ks("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ka("span",{className:"af-tabular-nums",children:Math.max(0,s)}),ka(te,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?ka(te,{variant:"destructive",children:"Out of stock"}):Ks("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ka("span",{className:"af-tabular-nums",children:s}),s<=Mu&&ka(te,{variant:"warning",children:"Low"})]})}import{jsx as le,jsxs as Je}from"react/jsx-runtime";function Zs({title:e,children:a,className:s}){return Je("section",{className:K("af-rounded-lg af-border af-p-4",s),children:[le("h4",{className:no,children:e}),le("div",{className:"af-mt-3",children:a})]})}function oo({src:e,className:a}){let[s,t]=Ua.useState(!1);return Ua.useEffect(()=>t(!1),[e]),!e||s?le("div",{"aria-hidden":"true",className:K("af-flex af-items-center af-justify-center af-bg-muted",a),children:le($u,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):le("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:K("af-object-cover",a)})}function lo({product:e,showStats:a=!1,onBack:s}){let{api:t}=ie(),[n,i]=Ua.useState(null),[o,m]=Ua.useState(!0),[d,f]=Ua.useState(null),[r,g]=Ua.useState(0),[b,v]=Ua.useState(0);Ua.useEffect(()=>{let c=!1;return m(!0),f(null),t.getProduct(e.id).then(k=>{c||i(k)}).catch(k=>{c||f(k instanceof Error?k:new Error("Failed to load product"))}).finally(()=>{c||m(!1)}),()=>{c=!0}},[t,e.id,r]);let u=n?{...e,...n}:e,l=u.images.length>0?u.images:e.images,p=l[b]??l[0],h=Hn(u),x=a?u.stats:void 0,D=n?.variants??[],O=D.length>1;return Je("div",{children:[Je("div",{className:"af-mb-6",children:[Je(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[le(Vu,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),Je("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[le("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),le(te,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),le($n,{product:u})]}),le(Vn,{product:u,className:"af-mt-1"}),!u.active&&le("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),Je("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[Je("div",{className:"af-space-y-2",children:[le(oo,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&le("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((c,k)=>le("button",{type:"button",onClick:()=>v(k),"aria-label":`Show photo ${k+1} of ${l.length}`,"aria-pressed":k===b,className:K("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",k===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:le(oo,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${k}`))})]}),Je("div",{className:"af-space-y-6",children:[u.description&&le(Zs,{title:"Description",children:le("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?Je(Zs,{title:"Variants",children:[le("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>Je("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[le(ae,{className:"af-h-4 af-w-28"}),le(ae,{className:"af-h-4 af-w-20"}),le(ae,{className:"af-h-4 af-w-16"})]},c))}),le("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):d?le(ia,{message:"Couldn't load this product's variants.",onRetry:()=>g(c=>c+1)}):O?le(Zs,{title:`Variants \xB7 ${D.length}`,children:le("div",{className:"af-overflow-x-auto",children:Je(Be,{children:[le(Fe,{children:Je(pe,{children:[le(F,{children:"Variant"}),le(F,{children:"SKU"}),le(F,{className:"af-text-right",children:"Price"}),le(F,{children:"Stock"})]})}),le(Me,{children:D.map(c=>Je(pe,{children:[Je(M,{className:"af-font-medium",children:[c.title||c.option_values.map(k=>k.value).join(" / ")||"\u2014",!c.active&&le(te,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),le(M,{className:"af-text-muted-foreground",children:c.sku?le("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),Je(M,{className:"af-whitespace-nowrap af-text-right",children:[le("div",{className:Un,children:ro(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&le("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:z(c.compare_at_amount,c.currency)})]}),le(M,{className:"af-text-sm",children:le(io,{variant:c})})]},c.id))})]})})}):null,le(Zs,{title:"Details",children:Je("dl",{className:"af-space-y-2",children:[Je("div",{children:[le("dt",{className:os,children:"Delivery"}),le("dd",{className:"af-text-sm",children:h==="Digital download"?u.fulfillment.filename??"Digital download":h??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&Je("div",{children:[le("dt",{className:os,children:"Sends buyers to"}),le("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),Je("div",{children:[le("dt",{className:os,children:"Shipping address"}),le("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),Je("div",{children:[le("dt",{className:os,children:"Most one buyer can order"}),le("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),x&&le(Zs,{title:"Last 30 days",children:Je("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[Je("div",{children:[le("dt",{className:os,children:"Units sold"}),le("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),Je("div",{children:[le("dt",{className:os,children:"Orders"}),le("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),Je("div",{children:[le("dt",{className:os,children:"Gross"}),le("dd",{className:Un,children:x.gross.length>0?zn(x.gross):"\u2014"})]})]})}),le("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 ls,jsx as ne,jsxs as Ye}from"react/jsx-runtime";var ju={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Wu=["all","active","draft","low_stock","out_of_stock"];function co(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function uo(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Gu(e){return e.inventory?.out_of_stock??!1}function Ku(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return uo(e);case"out_of_stock":return Gu(e);default:return!0}}function Zu({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Hn(e),o=e.variant_count??0;return Ye("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[t?ne("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):ne("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:ne(Hu,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ye("div",{className:"af-space-y-2 af-p-3",children:[Ye("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ye("div",{className:"af-min-w-0",children:[ne("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),ne(Vn,{product:e,className:"af-mt-0.5"})]}),!e.active&&ne(te,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ne($n,{product:e}),o>1&&Ye(te,{variant:"outline",children:[o," variants"]}),i&&ne(te,{variant:"outline",children:i})]}),n&&Ye("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${zn(n.gross)}`:""," ",ne("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Ju(){return ne("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=>Ye("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[ne("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Ye("div",{className:"af-space-y-2 af-p-3",children:[ne(ae,{className:"af-w-32"}),ne(ae,{className:"af-w-16"}),ne(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function fo({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:m}=Ts({includeStats:a,refreshKey:e}),[d,f]=Va.useState(!1),[r,g]=Va.useState(null),[b,v]=Va.useState("all"),[u,l]=Va.useState(""),[p,h]=Va.useState("newest"),x=Va.useMemo(()=>{if(!a)return null;let y=null;for(let j of n)!j.stats||j.stats.units_sold===0||(!y||j.stats.units_sold>(y.stats?.units_sold??0))&&(y=j);return y},[n,a]),D=Va.useMemo(()=>n.filter(uo).length,[n]),O=u.trim().toLowerCase(),c=Va.useMemo(()=>{let j=[...n.filter(Q=>Ku(Q,b)&&(!O||Q.name.toLowerCase().includes(O)))];return p==="name"?j.sort((Q,$)=>Q.name.localeCompare($.name)):p==="best_selling"?j.sort((Q,$)=>($.stats?.units_sold??0)-(Q.stats?.units_sold??0)):j.sort((Q,$)=>co($.created_at)-co(Q.created_at)),j},[n,b,O,p]),k=b!=="all"||!!O,A=()=>{v("all"),l("")},X=i||o!==null&&n.length===0,S=ne("div",{className:"af-mb-6",children:ne("div",{className:K("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:X?Ye(ls,{children:[ne(at,{label:"Products",children:ne(ae,{className:"af-h-6 af-w-10"})}),a?Ye(ls,{children:[ne(at,{label:"Best seller",children:ne(ae,{className:"af-h-6 af-w-28"})}),ne(at,{label:"Low stock",children:ne(ae,{className:"af-h-6 af-w-10"})})]}):ne(at,{label:"Active",children:ne(ae,{className:"af-h-6 af-w-10"})})]}):Ye(ls,{children:[ne(at,{label:"Products",children:n.length}),a?Ye(ls,{children:[ne(at,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:x?`${x.stats?.units_sold??0} sold, last 30 days`:void 0,children:x?ne("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:x.name}):ne("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),ne(at,{label:"Low stock",children:D})]}):ne(at,{label:"Active",children:n.filter(y=>y.active).length})]})})}),T=Ye("div",{className:"af-mb-4 af-space-y-3",children:[Ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ne("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:Wu.map(y=>ne("button",{type:"button","aria-pressed":b===y,onClick:()=>v(y),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===y?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:ju[y]},y))}),Ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[ne(qu,{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"}),ne(ge,{type:"text",value:u,onChange:y=>l(y.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ye(ca,{value:p,onValueChange:y=>h(y),children:[ne(aa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:ne(ua,{})}),Ye(sa,{children:[ne(Ge,{value:"newest",children:"Newest"}),ne(Ge,{value:"name",children:"Name A\u2013Z"}),a&&ne(Ge,{value:"best_selling",children:"Best selling"})]})]}),k&&ne(w,{type:"button",variant:"ghost",size:"sm",onClick:A,children:"Clear filters"})]}),i&&n.length===0?ne(ae,{className:"af-h-4 af-w-28"}):ne("p",{className:"af-text-sm af-text-muted-foreground",children:k?`${c.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${D>0?` \xB7 ${D} low stock`:""}`})]}),B;return r?B=ne(lo,{product:r,showStats:a,onBack:()=>{g(null),m()}},r.id):i&&n.length===0?B=Ye(ls,{children:[T,ne(Ju,{}),ne("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?B=ne("div",{className:"af-flex af-justify-center af-py-8",children:ne(ia,{message:"Couldn't load your products.",onRetry:()=>m()})}):n.length===0?B=Ye(Ca,{icon:ne(zu,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",ne("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):B=Ye(ls,{children:[T,o&&ne("div",{className:"af-mb-4",children:ne(ia,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>m()})}),c.length===0?Ye(Ca,{children:["No products match these filters.",ne("br",{}),ne(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:A,children:"Show all products"})]}):ne("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:c.map(y=>ne(Zu,{product:y,showStats:a,onOpen:()=>g(y)},y.id))})]}),ne(xt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:d?Ye(ls,{children:[ne(w,{variant:"ghost",onClick:()=>f(!1),children:"Back to products"}),ne(Ns,{})]}):Ye(ls,{children:[!r&&ne("div",{className:"af-mb-4 af-flex af-justify-end",children:ne(w,{variant:"outline",onClick:()=>f(!0),children:"Promo codes"})}),!r&&S,B]})})}import*as Ea from"react";import{ArrowLeft as bo,Check as Yu,ChevronLeft as mo,ChevronRight as po,ClipboardCopy as Qu,Mail as Fr,Search as Xu,Users as ed}from"lucide-react";import*as oa from"react";function qn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=oa.useState([]),[i,o]=oa.useState(!0),[m,d]=oa.useState(null),[f,r]=oa.useState(0),[g]=oa.useState(e),[b,v]=oa.useState(""),u=oa.useRef(0),l=oa.useCallback(async()=>{let p=++u.current;try{o(!0),d(null);let h={limit:g,offset:f*g};b.trim()&&(h.q=b.trim());let x=await s.getPeople(h);if(p!==u.current)return;n(x.people)}catch(h){if(p!==u.current)return;d(h instanceof Error?h:new Error("Failed to fetch people"))}finally{p===u.current&&o(!1)}},[s,f,g,b,a]);return oa.useEffect(()=>{l()},[l]),{people:t,isLoading:i,error:m,page:f,pageSize:g,hasNextPage:t.length===g,hasPreviousPage:f>0,setPage:r,q:b,setQ:p=>{v(p),r(0)},refetch:l}}import*as $a from"react";function jn(e,{refreshKey:a}={}){let{api:s}=ie(),[t,n]=$a.useState(null),[i,o]=$a.useState(e!==null),[m,d]=$a.useState(null),f=$a.useRef(0),r=$a.useCallback(async()=>{if(e===null){n(null),o(!1),d(null);return}let g=++f.current;try{o(!0),d(null);let b=await s.getPerson(e);if(g!==f.current)return;n(b)}catch(b){if(g!==f.current)return;d(b instanceof Error?b:new Error("Failed to fetch person"))}finally{g===f.current&&o(!1)}},[s,e,a]);return $a.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:m,refetch:r}}import{jsx as N,jsxs as oe}from"react/jsx-runtime";var Br="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",td="af-text-xs af-text-muted-foreground";function Is(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Mr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function ad(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function sd({value:e,label:a}){let[s,t]=Ea.useState(!1);return ad()?oe(w,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),t(!0),setTimeout(()=>t(!1),1500)}catch{}},"aria-label":a,className:"af-shrink-0",children:[s?N(Yu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):N(Qu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function go(e){return oe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&oe(te,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&N(te,{variant:"secondary",children:"Contact form"})]})}function vo(e){return e.name?e.name:e.email?e.email:N("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var nd=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,rd=40;function id(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>nd.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=rd).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return t?{message:String(t[1]),rest:a.filter(([n])=>n!==t[0])}:{message:null,rest:a}}function od(e){return e.replace(/_/g," ")}function ld(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function cd({data:e}){let{message:a,rest:s}=id(e);return a===null&&s.length===0?N("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):oe("div",{className:"af-space-y-3",children:[a!==null&&N("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&N("dl",{className:"af-space-y-1",children:s.map(([t,n])=>oe("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[N("dt",{className:K(td,"af-w-28 af-shrink-0 af-capitalize"),children:od(t)}),N("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ld(n)})]},t))})]})}function yo({formName:e,createdAt:a,data:s}){return oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[N(te,{variant:"outline",children:"Form submission (unverified)"}),e&&N("span",{className:"af-text-xs af-text-muted-foreground",children:e}),N("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Is(a)})]}),N(cd,{data:s})]})}function ud(e){return e.charged_total??e.amount_total}function dd({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=jn(e,{refreshKey:a}),m=Mr(e,t?.submissions[0]?.form_name);return oe("div",{children:[oe("div",{className:"af-mb-6",children:[oe(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[N(bo,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),oe("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[oe("div",{className:"af-min-w-0",children:[n?N(ae,{className:"af-h-7 af-w-48"}):N("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),oe("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[N("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),N(sd,{value:e,label:"Copy email address"})]})]}),N(w,{asChild:!0,children:oe("a",{href:m,children:[N(Fr,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?oe("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(d=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[N(ae,{className:"af-w-40"}),N(ae,{className:"af-mt-2 af-w-64"})]},d)),N("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?N("div",{className:"af-flex af-justify-center af-py-8",children:N(ia,{message:"Couldn't load this person.",onRetry:()=>o()})}):oe("div",{className:"af-space-y-6",children:[t.customer&&oe("div",{children:[N("h4",{className:K(Br,"af-mb-3"),children:"Customer"}),oe("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&oe("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),N("dd",{children:t.customer.name})]}),t.customer.phone&&oe("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),N("dd",{children:t.customer.phone})]}),oe("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),N("dd",{children:Is(t.customer.created_at)})]})]})]}),t.orders.length>0&&oe("div",{children:[N("h4",{className:K(Br,"af-mb-3"),children:"Purchases"}),N("div",{className:"af-overflow-x-auto",children:oe(Be,{children:[N(Fe,{children:oe(pe,{children:[N(F,{children:"Order"}),N(F,{children:"Date"}),N(F,{className:"af-text-right",children:"Total"}),N(F,{children:"Status"})]})}),N(Me,{children:t.orders.map(d=>oe(pe,{children:[N(M,{className:"af-whitespace-nowrap af-font-medium",children:Za(d)}),N(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Is(d.created_at)}),N(M,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:z(ud(d),d.currency)}),N(M,{children:N(gs,{status:d.status})})]},d.id))})]})}),N("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."})]}),t.submissions.length>0&&oe("div",{children:[N("h4",{className:K(Br,"af-mb-3"),children:"Messages"}),N("div",{className:"af-space-y-3",children:t.submissions.map(d=>N(yo,{formName:d.form_name,createdAt:d.created_at,data:d.data},d.id))})]})]})]})}function fd({submissionId:e,onBack:a}){let{api:s}=ie(),[t,n]=Ea.useState(null),[i,o]=Ea.useState(!0),[m,d]=Ea.useState(null),[f,r]=Ea.useState(0);return Ea.useEffect(()=>{let g=!1;return o(!0),d(null),s.getSubmission(e).then(b=>{g||n(b)}).catch(b=>{g||d(b instanceof Error?b:new Error("Failed to load submission"))}).finally(()=>{g||o(!1)}),()=>{g=!0}},[s,e,f]),oe("div",{children:[oe("div",{className:"af-mb-6",children:[oe(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[N(bo,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),N("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?N(ae,{className:"af-mt-1 af-h-4 af-w-32"}):t&&N("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Is(t.metadata.submitted_at)})]}),i?oe("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[N(ae,{className:"af-w-40"}),N(ae,{className:"af-mt-2 af-w-64"}),N(ae,{className:"af-mt-2 af-w-52"}),N("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):m||!t?N("div",{className:"af-flex af-justify-center af-py-8",children:N(ia,{message:"Couldn't load this submission.",onRetry:()=>r(g=>g+1)})}):oe("div",{className:"af-space-y-3",children:[N(yo,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),N("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 md={all:"All",customers:"Customers",leads:"Leads"},pd=["all","customers","leads"];function gd(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function vd({refreshKey:e,onBackToWebsite:a,className:s,maxRows:t,onViewAll:n}){let i=typeof t=="number",{people:o,isLoading:m,error:d,page:f,pageSize:r,hasNextPage:g,hasPreviousPage:b,setPage:v,q:u,setQ:l,refetch:p}=qn({refreshKey:e}),[h,x]=Ea.useState({kind:"list"}),[D,O]=Ea.useState(""),[c,k]=Ea.useState("all"),A=!i||!!n,X=Q=>{if(i){n?.();return}Q.email?x({kind:"person",email:Q.email}):Q.submission_id&&x({kind:"submission",submissionId:Q.submission_id})},S=()=>{x({kind:"list"}),p()},T=Q=>{let $=Q.trim();$!==u&&l($)},B=o.filter(Q=>gd(Q,c)),y=i?B.slice(0,t):B,j;if(h.kind==="person")j=N(dd,{email:h.email,refreshKey:e,onBack:S});else if(h.kind==="submission")j=N(fd,{submissionId:h.submissionId,onBack:S});else{let Q=oe("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[N("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:pd.map($=>N("button",{type:"button","aria-pressed":c===$,onClick:()=>k($),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",c===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:md[$]},$))}),oe("div",{className:"af-relative af-w-full af-max-w-xs",children:[N(Xu,{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"}),N(ge,{type:"text",value:D,onChange:$=>O($.target.value),onBlur:()=>T(D),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),T(D))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),u&&N(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{O(""),l("")},children:"Clear search"})]});if(m)j=oe("div",{children:[i?null:Q,N("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map($=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-flex af-items-center af-justify-between",children:[N(ae,{className:"af-h-4 af-w-32"}),N(ae,{className:"af-h-4 af-w-16"})]}),N(ae,{className:"af-mt-2 af-h-5 af-w-28"}),N(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},$))}),N("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[N(Fe,{children:oe(pe,{children:[N(F,{children:"Person"}),N(F,{children:"Came from"}),N(F,{children:"Latest message"}),N(F,{children:"Last activity"}),N(F,{className:"af-w-8"}),N(F,{className:"af-w-8"})]})}),N(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map($=>oe(pe,{children:[N(M,{children:N(ae,{className:"af-h-4 af-w-40"})}),N(M,{children:N(ae,{className:"af-h-5 af-w-24"})}),N(M,{children:N(ae,{className:"af-h-4 af-w-56"})}),N(M,{children:N(ae,{className:"af-h-4 af-w-24"})}),N(M,{}),N(M,{})]},$))})]})}),N("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(d)j=oe("div",{children:[i?null:Q,N("div",{className:"af-flex af-justify-center af-py-8",children:N(ia,{message:"Couldn't load your leads.",onRetry:()=>p()})})]});else if(y.length===0&&f===0){let $=!!u||c!=="all";j=oe("div",{children:[$&&Q,$?N(Ca,{children:u?"Nobody matches that search.":c==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):N(_s,{icon:ed,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)j=oe("div",{children:[i?null:Q,N(Ca,{children:"No more results."}),N("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:oe(w,{variant:"outline",size:"sm",onClick:()=>v(f-1),children:[N(mo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let $=f*r+1,ce=f*r+o.length;j=oe("div",{children:[i?null:Q,N("div",{className:"af-space-y-3 lg:af-hidden",children:y.map((q,G)=>oe("div",{onClick:A?()=>X(q):void 0,className:`af-rounded-md af-border af-p-3${A?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[oe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[oe("div",{className:"af-min-w-0",children:[N("button",{type:"button",onClick:H=>{H.stopPropagation(),X(q)},disabled:!A,"aria-label":`Open ${q.name||q.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${A?" hover:af-underline":""}`,children:vo(q)}),q.name&&q.email&&N("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:q.email})]}),oe("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[N("span",{className:"af-text-xs af-text-muted-foreground",children:Is(q.last_activity_at)}),q.email&&N(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:N("a",{href:Mr(q.email),onClick:H=>H.stopPropagation(),"aria-label":`Email ${q.email}`,children:N(Fr,{className:"af-h-4 af-w-4"})})})]})]}),N("div",{className:"af-mt-2",children:go(q)}),q.latest_message_excerpt&&N("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:q.latest_message_excerpt})]},q.email??q.submission_id??G))}),N("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[N(Fe,{children:oe(pe,{children:[N(F,{children:"Person"}),N(F,{children:"Came from"}),N(F,{children:"Latest message"}),N(F,{children:"Last activity"}),N(F,{className:"af-w-8",children:N("span",{className:"af-sr-only",children:"Reply"})}),N(F,{className:"af-w-8"})]})}),N(Me,{children:y.map((q,G)=>oe(pe,{onClick:A?()=>X(q):void 0,className:A?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[oe(M,{className:"af-max-w-[260px] af-font-medium",children:[N("button",{type:"button",onClick:H=>{H.stopPropagation(),X(q)},disabled:!A,"aria-label":`Open ${q.name||q.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${A?" hover:af-underline":""}`,children:vo(q)}),q.name&&q.email&&N("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:q.email})]}),N(M,{children:go(q)}),N(M,{className:"af-max-w-[320px]",children:q.latest_message_excerpt?N("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:q.latest_message_excerpt}):N("span",{className:"af-text-muted-foreground",children:"\u2014"})}),N(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Is(q.last_activity_at)}),N(M,{className:"af-w-8",children:q.email&&N(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:N("a",{href:Mr(q.email),onClick:H=>H.stopPropagation(),"aria-label":`Email ${q.email}`,children:N(Fr,{className:"af-h-4 af-w-4"})})})}),N(M,{className:"af-w-8 af-text-right",children:N(po,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},q.email??q.submission_id??G))})]})}),!i&&oe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[N("span",{className:"af-text-sm af-text-muted-foreground",children:c==="all"?`Showing ${$}-${ce}`:`${y.length} of ${o.length} on this page`}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[oe(w,{variant:"outline",size:"sm",onClick:()=>v(f-1),disabled:!b,children:[N(mo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),oe(w,{variant:"outline",size:"sm",onClick:()=>v(f+1),disabled:!g,children:["Next",N(po,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?N("div",{className:s,children:j}):N(xt,{title:"Leads",onBackToWebsite:a,hideBackButton:h.kind!=="list",className:s,children:j})}function Wn(e){return N(vd,{...e},e.maxRows==null?"full":"compact")}import{ChevronLeft as ho,ChevronRight as bd,Repeat as yd}from"lucide-react";import*as Qt from"react";function Gn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=Qt.useState([]),[i,o]=Qt.useState(0),[m,d]=Qt.useState(!0),[f,r]=Qt.useState(null),[g,b]=Qt.useState(0),[v,u]=Qt.useState(e),[l,p]=Qt.useState(void 0),h=Qt.useRef(0),x=Qt.useCallback(async()=>{let O=++h.current;try{d(!0),r(null);let c={limit:v,offset:g*v};l&&(c.status=l);let k=await s.getSubscriptions(c);if(O!==h.current)return;n(k.subscriptions),o(k.total)}catch(c){if(O!==h.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{O===h.current&&d(!1)}},[s,g,v,l,a]);Qt.useEffect(()=>{x()},[x]);let D=Math.ceil(i/v);return{subscriptions:t,total:i,isLoading:m,error:f,page:g,pageSize:v,hasNextPage:g<D-1,hasPreviousPage:g>0,setPage:b,setPageSize:O=>{u(O),b(0)},status:l,setStatus:O=>{p(O),b(0)},refetch:x}}import{jsx as ee,jsxs as Qe}from"react/jsx-runtime";function xo(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function wo({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 hd(e,a){let s=z(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function No({sub:e}){let a=e.current_amount!==e.plan_amount;return Qe("div",{children:[ee("div",{className:"af-font-medium af-tabular-nums",children:hd(e,e.current_amount)}),a&&Qe("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",z(e.plan_amount,e.currency)]})]})}function So(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${xo(e.current_period_end)}`:"Ends at period end":e.current_period_end?xo(e.current_period_end):"\u2014"}function _o({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:m,pageSize:d,hasNextPage:f,hasPreviousPage:r,setPage:g,refetch:b}=Gn({refreshKey:e}),v;if(i)v=Qe("div",{children:[ee("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>Qe("div",{className:"af-rounded-md af-border af-p-3",children:[Qe("div",{className:"af-flex af-items-center af-justify-between",children:[ee(ae,{className:"af-h-4 af-w-40"}),ee(ae,{className:"af-h-4 af-w-20"})]}),ee(ae,{className:"af-mt-2 af-h-3 af-w-32"}),ee(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),ee("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Qe(Be,{children:[ee(Fe,{children:Qe(pe,{children:[ee(F,{children:"Subscriber"}),ee(F,{children:"Plan"}),ee(F,{className:"af-text-right",children:"Amount"}),ee(F,{children:"Renews"}),ee(F,{children:"Status"})]})}),ee(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>Qe(pe,{children:[ee(M,{children:ee(ae,{className:"af-h-4 af-w-44"})}),ee(M,{children:ee(ae,{className:"af-h-4 af-w-32"})}),ee(M,{className:"af-text-right",children:ee(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),ee(M,{children:ee(ae,{className:"af-h-4 af-w-24"})}),ee(M,{children:ee(ae,{className:"af-h-5 af-w-20"})})]},u))})]})}),ee("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)v=ee("div",{className:"af-flex af-justify-center af-py-8",children:ee(ia,{message:"Couldn't load your subscriptions.",onRetry:()=>b()})});else if(t.length===0&&m===0)v=ee(Ca,{icon:ee(yd,{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(t.length===0)v=Qe("div",{children:[ee(Ca,{children:"No more results."}),ee("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Qe(w,{variant:"outline",size:"sm",onClick:()=>g(m-1),children:[ee(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=m*d+1,l=m*d+t.length;v=Qe("div",{children:[ee("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(p=>Qe("div",{className:"af-rounded-md af-border af-p-3",children:[Qe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Qe("div",{className:"af-min-w-0",children:[ee("div",{className:"af-truncate af-text-sm af-font-medium",children:p.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:p.plan_title||"Untitled plan"})]}),ee("div",{className:"af-shrink-0 af-text-right",children:ee(No,{sub:p})})]}),Qe("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(wo,{sub:p}),p.is_test&&ee(te,{variant:"outline",children:"Test"}),ee("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:So(p)})]}),ee(Ia,{deliveries:p.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},p.id))}),ee("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Qe(Be,{children:[ee(Fe,{children:Qe(pe,{children:[ee(F,{children:"Subscriber"}),ee(F,{children:"Plan"}),ee(F,{className:"af-text-right",children:"Amount"}),ee(F,{children:"Renews"}),ee(F,{children:"Status"})]})}),ee(Me,{children:t.map(p=>Qe(pe,{children:[ee(M,{className:"af-max-w-[240px]",children:ee("div",{className:"af-truncate af-font-medium",children:p.customer_email||ee("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),ee(M,{className:"af-max-w-[220px]",children:ee("div",{className:"af-truncate",children:p.plan_title||ee("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),ee(M,{className:"af-whitespace-nowrap af-text-right",children:ee(No,{sub:p})}),ee(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:So(p)}),Qe(M,{children:[Qe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(wo,{sub:p}),p.is_test&&ee(te,{variant:"outline",children:"Test"})]}),ee(Ia,{deliveries:p.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},p.id))})]})}),Qe("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 ${u}-${l} of ${n}`}),Qe("div",{className:"af-flex af-items-center af-gap-2",children:[Qe(w,{variant:"outline",size:"sm",onClick:()=>g(m-1),disabled:!r,children:[ee(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Qe(w,{variant:"outline",size:"sm",onClick:()=>g(m+1),disabled:!f,children:["Next",ee(bd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ee(xt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:v})}import*as Ur from"react";import{Fragment as Ro,jsx as la,jsxs as Kn}from"react/jsx-runtime";function Po({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:m,isLoading:d,error:f,refetch:r}=Rs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=ks({refreshKey:e}),[b,v]=Ur.useState(!1),[u,l]=Ur.useState(null),p=la("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!d&&!m?Kn("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. ",la(w,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):d||!m?Kn(Ro,{children:[la(at,{label:"Outstanding",children:la(ae,{className:"af-h-6 af-w-24"})}),la(at,{label:"Overdue",children:la(ae,{className:"af-h-6 af-w-24"})}),la(at,{label:"Paid this month",children:la(ae,{className:"af-h-6 af-w-24"})})]}):Kn(Ro,{children:[la(at,{label:"Outstanding",detail:`${m.outstanding.count} open`,children:z(m.outstanding.amount,m.currency)}),la(at,{label:"Overdue",detail:m.overdue.count===0?"Nothing overdue":`${m.overdue.count} overdue`,valueClassName:m.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:z(m.overdue.amount,m.currency)}),la(at,{label:"Paid this month",detail:`${m.paid_this_month.count} paid`,children:z(m.paid_this_month.amount,m.currency)})]})});return Kn(xt,{title:"Invoices",onBackToWebsite:s,hideBackButton:b,className:o,children:[p,!b&&la(Cs,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:u?.id??null,onShowCycles:h=>l(x=>x?.id===h.id?null:h),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded}),la(is,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:v,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:u?{id:u.id,label:`${u.customer_name??u.customer_email??"Recurring invoices"} \u2014 ${u.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}import*as wt from"react";var xd=2e3,It=()=>({data:null,error:null,isLoading:!0});function Ds(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=ie(),[i,o]=wt.useState(It),[m,d]=wt.useState(It),[f,r]=wt.useState(It),[g,b]=wt.useState(It),[v,u]=wt.useState(It),l=H=>Object.fromEntries(H.map(se=>[se,It()])),[p,h]=wt.useState(()=>l(s)),x=wt.useRef(0),D=wt.useRef(0),O=wt.useRef("idle"),c=s.join(","),k=fs()??"",A=JSON.stringify(t),X=`${e}:${c}:${A}:${k}`,[S,T]=wt.useState({api:n,fetchIdentity:X});(S.api!==n||S.fetchIdentity!==X)&&(T({api:n,fetchIdentity:X}),x.current+=1,o(It),d(It),r(It),b(It),h(l(c?c.split(","):[])));let B=`${e}:${String(a??"")}:${k}`,[y,j]=wt.useState({api:n,conversionsIdentity:B});(y.api!==n||y.conversionsIdentity!==B)&&(j({api:n,conversionsIdentity:B}),D.current+=1,O.current="idle",u(It));let Q=wt.useCallback(async H=>{let se=++x.current,W=c?c.split(","):[];o(It),d(It),r(It),b(It),h(Object.fromEntries(W.map(_=>[_,It()])));let he=O.current!=="pending"&&(H?.force===!0||O.current==="idle"),Ke=(_,I)=>I.then(E=>{se===x.current&&_({data:E,error:null,isLoading:!1})},E=>{se===x.current&&_({data:null,error:E instanceof Error?E:new Error("Failed to fetch report"),isLoading:!1})}),rt=n.getAnalyticsStatus(),Re=Ke(o,rt),qe=Symbol("status-timeout"),Xe,xe=await Promise.race([rt.then(_=>_,()=>null),new Promise(_=>{Xe=setTimeout(()=>_(qe),xd)})]);if(clearTimeout(Xe),se!==x.current)return;if(xe===qe&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),xe!==null&&xe!==qe&&(xe.collecting!==!0||xe.first_seen===null&&!xe.first_seen_unavailable||xe.first_seen!==null&&xe.first_seen_in_reports===!1)){let _={data:null,error:null,isLoading:!1};d(_),r(_),b(_),h(Object.fromEntries(W.map(I=>[I,{..._}]))),he&&(u(_),O.current="done"),await Re;return}await Promise.all([xe===qe?Promise.resolve():Re,Ke(d,n.getAnalyticsSummary(e,t)),Ke(r,n.getAnalyticsTimeseries(e,t)),Ke(b,n.getAnalyticsChannels(e,t)),he?(()=>{O.current="pending";let _=++D.current;return u(It),n.getAnalyticsConversions(e).then(I=>{_===D.current&&(u({data:I,error:null,isLoading:!1}),O.current="done")},I=>{_===D.current&&(u({data:null,error:I instanceof Error?I:new Error("Failed to fetch report"),isLoading:!1}),O.current="done")})})():Promise.resolve(),...W.map(_=>n.getAnalyticsBreakdown(_,e,t).then(I=>{se===x.current&&h(E=>({...E,[_]:{data:I,error:null,isLoading:!1}}))},I=>{se===x.current&&h(E=>({...E,[_]:{data:null,error:I instanceof Error?I:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,c,A,B,k]),$=wt.useCallback(async()=>{let H=x.current;try{let se=await n.getAnalyticsStatus();if(H!==x.current)return;o({data:se,error:null,isLoading:!1})}catch(se){if(H!==x.current)return;o(W=>({data:W.data,error:se instanceof Error?se:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ce=wt.useCallback(()=>Q({force:!0}),[Q]);wt.useEffect(()=>{Q()},[Q,a]);let q=i.isLoading||m.isLoading||f.isLoading||g.isLoading||v.isLoading||Object.values(p).some(H=>H.isLoading),G=[f,m,g,v,...Object.values(p)].map(H=>H.data?.status==="ok"?H.data.timezone:void 0).find(H=>H!==void 0);return{status:i,summary:m,timeseries:f,channels:g,conversions:v,breakdowns:p,reportedZone:G,isLoading:q,refetch:ce,refetchStatus:$}}import*as Nt from"react";var Vr=3e4,$r=3;function Zn(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=ie(),[o,m]=Nt.useState(null),[d,f]=Nt.useState(null),[r,g]=Nt.useState(!1),[b,v]=Nt.useState(null),[u,l]=Nt.useState(!1),[p,h]=Nt.useState(!0),[x,D]=Nt.useState(0),O=Nt.useRef(0),c=Nt.useRef(0),k=Nt.useRef(void 0);s!==void 0&&(k.current=s);let A=a?k.current===!0||k.current===void 0&&t:!0,[X,S]=Nt.useState({api:i,identity:n}),T=n!==void 0&&n!==X.identity;(X.api!==i||T)&&(k.current=void 0,S({api:i,identity:n}),c.current+=1,O.current=0,m(null),f(null),g(!1),v(null),l(!1),h(!0),D(0));let B=Nt.useRef(()=>{}),y=Nt.useRef(null),j=Nt.useCallback(async()=>{if(y.current!==null&&y.current===c.current)return;let Q=++c.current;y.current=Q;try{let $=await i.getAnalyticsRealtime();if(Q!==c.current)return;if($.status==="unreachable"){l(!0),g(!0),h(!1),D(ce=>ce+1);return}O.current=0,l(!1),m($.data.current_visitors),f($.as_of),g(!1),v(null),h(!1),D(ce=>ce+1)}catch($){if(Q!==c.current)return;O.current+=1,h(!1),D(ce=>ce+1),g(!0),O.current>=$r&&v($ instanceof Error?$:new Error("Realtime unavailable"))}finally{y.current===Q&&(y.current=null)}},[i]);return B.current=()=>void j(),Nt.useEffect(()=>{let Q,$=()=>{Q===void 0&&(Q=setInterval(()=>B.current(),Vr))},ce=()=>{Q!==void 0&&(clearInterval(Q),Q=void 0)},q=()=>{typeof document<"u"&&document.hidden?ce():(B.current(),$())};return A?((typeof document>"u"||!document.hidden)&&(B.current(),$()),document?.addEventListener("visibilitychange",q),()=>{ce(),document?.removeEventListener("visibilitychange",q),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",q)}},[X.api,X.identity,A]),{currentVisitors:o,asOf:d,isStale:r,error:b,isUnreachable:u,isInitialLoad:p,polls:x}}import*as nt from"react";import*as To from"react";import{jsx as Hr,jsxs as Co}from"react/jsx-runtime";function wd(){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 zr({value:e,chosen:a,onChange:s}){let t=Us(),n=a===null&&t!==null&&e===t,i=To.useMemo(()=>{let o=wd();return o.includes(e)?o:[e,...o]},[e]);return Co("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Hr("span",{className:"af-sr-only",children:"Reporting timezone"}),Co("select",{value:n?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[Hr("option",{value:"",children:t?`${t.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),i.map(o=>Hr("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Jn=(e,{published:a}={})=>{let s=a===!1,t=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),n=!t&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,i=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=n||i;return{notCollecting:t,awaitingFirstVisit:n,firstVisitTooRecent:i,holdingForFirstData:o,nothingToReport:t||o}};import*as Js from"react";var Nd=3e4;function Yn({status:e,holdingForFirstData:a,refetchStatus:s,refetch:t}){Js.useEffect(()=>{if(!a)return;let i,o=()=>{i===void 0&&(i=setInterval(()=>void s(),Nd))},m=()=>{i!==void 0&&(clearInterval(i),i=void 0)},d=()=>{typeof document<"u"&&document.hidden?m():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",d),()=>{m(),document?.removeEventListener("visibilitychange",d)}},[a,s]);let n=Js.useRef(void 0);Js.useEffect(()=>{if(!e){n.current=void 0;return}let i=n.current;n.current=a,i===!0&&!a&&t()},[e,a,t])}import*as hs from"react";var Sd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vt(e){let a=Math.abs(e);if(a<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[t,n]of s)if(a>=t){let i=e/t,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&t!==1e9?Vt(o*t):`${o}${n}`}return String(e)}function Ls(e){return`${(e*100).toFixed(1)}%`}function Ys(e){let a=Math.max(0,Math.round(e));if(a<60)return`${a}s`;let s=Math.floor(a/60);return s<60?`${s}m ${a%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Eo(e){let a=Math.max(0,Math.round(e));return a>=3600&&a%3600===0?`${a/3600}h`:a>=60&&a%60===0?`${a/60}m`:Ys(a)}function Ao(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function Io(e,a){if(!(!Number.isFinite(e)||e<=0))for(let s of a){let t=Math.ceil(e/s);if(t<=5)return Array.from({length:t+1},(n,i)=>Number((i*s).toPrecision(12)))}}function Qs(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Do(e){let a=new Date(e);return Number.isNaN(a.getTime())?"as of an unknown time":`as of ${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}function qr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${Sd[a-1]} ${s}`}function ko(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function _d(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Lo(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=ko(e.to,s);for(let o=ko(e.from,s);o<i;o=_d(o))n.push(t.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Oo(e){let a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=new Date(`${e}T00:00:00Z`);if(Number.isNaN(t.getTime()))return e;let n=String(t.getUTCDate()).padStart(2,"0");return`${a[t.getUTCDay()]}, ${n} ${s[t.getUTCMonth()]}`}import{Fragment as Pd,jsx as cs,jsxs as Rd}from"react/jsx-runtime";function Bo({what:e="This report",onRetry:a,collecting:s}){return Rd("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:[cs("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),cs("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),a?cs("button",{type:"button",onClick:a,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 Qn({what:e="No data"}){return cs("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 Ya({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?cs("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?cs(Bo,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?cs(Bo,{what:t,onRetry:n,collecting:i}):cs(Pd,{children:o(e.data)})}import{Fragment as Cd,jsx as Xt,jsxs as ys}from"react/jsx-runtime";function jr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:m,maxRows:d=9}){let[f,r]=hs.useState(!1);if(e.length===0)return Xt(Qn,{what:i});let g=e.reduce((u,l)=>Math.max(u,Number(l[s]??0)),0)||1,b=Math.max(0,e.length-d),v=f?e:e.slice(0,d);return ys(Cd,{children:[ys("table",{className:"af-w-full af-text-sm",children:[Xt("thead",{children:ys("tr",{className:"af-text-xs af-text-muted-foreground",children:[Xt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),Xt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),Xt("tbody",{children:v.map((u,l)=>{let p=Number(u[s]??0),h=u[a]??null,x=Qs(h),D=n?u[n]:null,O=h!==null&&(m?m(h,D):!0);return ys("tr",{className:"af-border-t af-border-border",children:[ys("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Xt("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)}%`}}),h!==null&&o&&O?Xt("button",{type:"button",onClick:()=>o(h,D),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):Xt("span",{className:"af-relative af-break-words af-text-foreground",children:x}),D?Xt("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:D}):null]}),Xt("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(p)})]},`${x}-${D??""}-${l}`)})})]}),b>0?Xt("button",{type:"button",onClick:()=>r(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:f?"Show fewer":`Show all ${e.length}`}):null]})}function Xs({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=hs.useState(s),o=a.find(v=>v.id===n)??a[0],m=hs.useId(),d=v=>`${m}-tab-${v}`,f=v=>`${m}-panel-${v}`,r=hs.useRef(null),g=(v,u)=>{v.preventDefault();let l=(u+a.length)%a.length;i(a[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return ys("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[ys("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:[Xt("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:v=>{let u=a.findIndex(l=>l.id===n);v.key==="ArrowRight"&&g(v,u+1),v.key==="ArrowLeft"&&g(v,u-1),v.key==="Home"&&g(v,0),v.key==="End"&&g(v,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(v=>Xt("button",{id:d(v.id),role:"tab",type:"button","aria-selected":v.id===n,"aria-controls":f(v.id),tabIndex:v.id===n?0:-1,onClick:()=>i(v.id),className:v.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:v.label},v.id))}),t]}),o?Xt("div",{id:f(o.id),role:"tabpanel","aria-labelledby":d(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as ea from"react";import*as us from"@radix-ui/react-popover";var Os=3,Bs=100;import{jsx as dt,jsxs as Ha}from"react/jsx-runtime";var en={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"},Td=Object.keys(en);function Fo(e){let a=en[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>Qs(n)).join(" or ");return`${a} ${s} ${t}`}function Wr(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function kd(e,a){let s={};for(let[t,n]of Object.entries(a)){let i=e.get(t)??new Set;for(let o of n)i.add(o);e.set(t,i),s[t]=[...i]}return s}function Mo(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));return s>=0?e.map((t,n)=>n===s?a:t):a.values.length>100||e.length>=3?e:[...e,a]}function Ed(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Uo(e,a,s,t={}){if(e.api!==a.api||e.period!==a.period)return e.api=a.api,e.period=a.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=kd(e.byDimension,s);for(let[i,o]of Object.entries(t)){let m=e.foldsByLabel.get(i)??new Set;for(let d of o)m.add(d);e.foldsByLabel.set(i,m)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Vo(e){let{filters:a,onChange:s}=e,t=a.length>=3;return ea.useEffect(()=>{if(a.length===0)return;let n=i=>{let o=i.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||i.key==="Escape"&&s([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[a.length,s]),Ha("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>Ha("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:[dt("span",{className:"af-text-foreground",children:Fo(n)}),dt("button",{type:"button","aria-label":`Remove filter ${Fo(n)}`,onClick:()=>s(a.filter((o,m)=>m!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),dt(Ad,{...e,disabled:t}),a.length>0?dt("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Ad({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,m]=ea.useState(!1),d=ea.useRef(null),[f,r]=ea.useState(null);ea.useEffect(()=>{r(d.current?.closest(".aifeatures-admin")??null)},[]);let[g,b]=ea.useState(null),[v,u]=ea.useState("is"),[l,p]=ea.useState(""),[h,x]=ea.useState([]);ea.useEffect(()=>{o||(b(null),u("is"),p(""),x([]))},[o]);let D=ea.useRef(t);D.current!==t&&(D.current=t,o&&m(!1),g!==null&&b(null),h.length>0&&x([]),l!==""&&p(""),v!=="is"&&u("is"));let O=T=>{let B=Ed(T);b(B.dimension),x(B.picked),p(B.search),u(B.operator)},k=(g?s[g]??[]:[]).filter(T=>T.toLowerCase().includes(l.trim().toLowerCase())),A=g===null||h.length===0?null:Wr(e,{dimension:g,operator:v,values:i?i(g,h):h}),X=A!==null&&A!==e,S=()=>{let T=A;!T||T===e||(a(T),m(!1))};return Ha(us.Root,{open:o,onOpenChange:m,children:[dt(us.Trigger,{asChild:!0,children:dt("button",{ref:d,type:"button",disabled:!1,title:n?`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"})}),dt(us.Portal,{container:f,children:dt(us.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?Ha("div",{children:[dt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),dt("div",{className:"af-max-h-96 af-overflow-y-auto",children:Td.filter(T=>s[T]!==void 0).map(T=>{let B=s[T]?.length??0,y=!e.some(j=>j.dimension===T)&&e.length>=3;return Ha("button",{type:"button",onClick:()=>O(T),disabled:B===0||y,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:[dt("span",{children:en[T]}),dt("span",{className:"af-text-muted-foreground",children:B===0?"no data":y?"no room":B})]},T)})})]}):Ha("div",{children:[Ha("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[dt("button",{type:"button",onClick:()=>O(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),dt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:en[g]}),Ha("select",{"aria-label":"Operator",value:v,onChange:T=>u(T.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:[dt("option",{value:"is",children:"is"}),dt("option",{value:"is_not",children:"is not"})]})]}),dt("input",{type:"text",value:l,onChange:T=>p(T.target.value),placeholder:"Search\u2026","aria-label":`Search ${en[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"}),dt("div",{className:"af-max-h-48 af-overflow-y-auto",children:k.length===0?Ha("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):k.map(T=>Ha("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:[dt("input",{type:"checkbox",checked:h.includes(T),disabled:!h.includes(T)&&h.length>=100,onChange:B=>x(y=>B.target.checked?[...y,T]:y.filter(j=>j!==T))}),dt("span",{className:"af-break-all",children:Qs(T)})]},T))}),dt("button",{type:"button",onClick:S,disabled:!X,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:h.length<=1?"Apply filter":h.length>=100?`Apply filter (${h.length} values \u2014 the maximum)`:`Apply filter (${h.length} values)`})]})})})]})}import{Fragment as Ld,jsx as $t,jsxs as Xn}from"react/jsx-runtime";var Id=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Vt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Vt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Vt,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:Ls,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ys,chart:"visit_duration_seconds"}];function Dd({current:e,previous:a,downIsGood:s}){if(a===0)return null;let t=(e-a)/a;if(Math.abs(t)<5e-4)return null;let n=t>0,i=s?!n:n,o=`${n?"+":""}${(t*100).toFixed(1)}%`;return $t("span",{className:i?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function $o({summary:e,selected:a,onSelect:s}){return $t("div",{className:"af-@container",children:$t("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Id.map(t=>{let n=t.chart===a,i=s!==void 0,o=Xn(Ld,{children:[$t("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),Xn("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[$t("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?$t(Dd,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?$t("button",{type:"button","aria-pressed":n,onClick:()=>s(t.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},t.key):$t("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function Gr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return Xn("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:[$t("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),$t("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return $t("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?Do(a):"freshness unknown",m=i?" across the whole site, not the current filter,":"",d=s?`${e} current visitors${m} ${o} (not updating)`:`${e} current visitors${m} ${o}`;return Xn("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:d,children:[$t("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),$t("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),$t("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),$t("span",{className:"af-sr-only",children:d})]})}import*as zo from"react";import{Star as Od}from"lucide-react";import{Fragment as Ho,jsx as Ct,jsxs as xs}from"react/jsx-runtime";function er(e,a){return!a||e.goal!==a.goal?!1:a.implicit===void 0||e.implicit===a.implicit}function tr({rows:e,denominator:a,windowPrecedesCollection:s=!1,coverageUnknown:t=!1,emptyCopy:n="No conversions in this period",maxRows:i=9,primaryConversion:o}){let[m,d]=zo.useState(!1),f=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||er(p,o)),r=s?Ct("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."}):t?Ct("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(f.length===0)return xs(Ho,{children:[Ct(Qn,{what:n}),r]});let g=f.slice(0,i),b=o?f.find(p=>er(p,o)):void 0,v=b&&!g.includes(b)?f.filter(p=>g.includes(p)||p===b).slice(0,Math.max(0,i-1)).concat(b):g,u=m?e:v,l=Math.max(0,e.length-v.length);return xs(Ho,{children:[xs("table",{className:"af-w-full af-text-sm",children:[Ct("thead",{children:xs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Ct("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),Ct("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),Ct("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),Ct("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),Ct("tbody",{children:u.map((p,h)=>xs("tr",{className:"af-border-t af-border-border","aria-current":er(p,o)?"true":void 0,children:[Ct("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:er(p,o)?xs("span",{className:"af-flex af-items-center af-gap-1.5",children:[Ct(Od,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),Ct("span",{className:"af-font-medium af-text-foreground",children:p.goal}),Ct("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),Ct("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(p.visitors)}),Ct("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(p.events)}),Ct("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?Ct("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Ls(p.conversion_rate)})]},`${p.goal}-${h}`))})]}),l>0?Ct("button",{type:"button",onClick:()=>d(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:m?"Show fewer":`Show all ${e.length} goals`}):null,xs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Vt(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),r]})}import{Area as Bd,AreaChart as Fd,CartesianGrid as Md,ResponsiveContainer as Ud,Tooltip as Vd,XAxis as $d,YAxis as Hd}from"recharts";import{jsx as Ht,jsxs as tn}from"react/jsx-runtime";var ar={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Zr={visitors:Vt,visits:Vt,pageviews:Vt,views_per_visit:e=>e.toFixed(2),bounce_rate:Ls,visit_duration_seconds:Ys},zd=31,qd=new Set(["visitors","visits","pageviews"]),jd={...Zr,bounce_rate:Ao,visit_duration_seconds:Eo},Kr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Wd=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Gd=[.01,.02,.05,.1,.2,.25,.5,1],Kd=[.25,.5,1,2,5,10,25,50],Zd={visitors:Kr,visits:Kr,pageviews:Kr,views_per_visit:Kd,bounce_rate:Gd,visit_duration_seconds:Wd};function Jd({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return tn("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:[Ht("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:ar[t]}),tn("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Ht("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Ht("span",{className:"af-text-muted-foreground",children:Oo(String(s))}),Ht("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Zr[t](Number(n[t]??0))})]})]})}function sr({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=Lo(a,e,t),o=Zr[s],m=jd[s],d=Io(i.reduce((r,g)=>Math.max(r,Number(g[s]??0)),0),Zd[s]),f=`${ar[s]} by day: ${i.map(r=>`${qr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return tn("figure",{"aria-label":`${ar[s]} over time`,className:"af-m-0",children:[Ht(Ud,{width:"100%",height:n,children:tn(Fd,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Ht("defs",{children:tn("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Ht("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Ht("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Ht(Md,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Ht($d,{dataKey:"date",tickFormatter:qr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Ht(Hd,{allowDecimals:!qd.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...d?{ticks:d,domain:[0,d[d.length-1]]}:{},tickFormatter:r=>m(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Ht(Vd,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Ht(Jd,{metric:s})}),Ht(Bd,{type:"linear",dataKey:s,name:ar[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=zd?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Ht("figcaption",{className:"af-sr-only",children:f})]})}import{Fragment as Jr,jsx as be,jsxs as Bt}from"react/jsx-runtime";var Yd="2026-08-13",Qd=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Xd=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function ef({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,primaryConversion:n,className:i,published:o,lastPublishedAt:m}){let[d,f]=nt.useState(30),[r,g]=nt.useState(()=>lr()),b=e!==void 0&&a!==void 0,[v,u]=nt.useState(e??[]),{api:l}=ie(),[p,h]=nt.useState(l);p!==l&&(h(l),!b&&v.length>0&&u([]));let x=b?e:v,D=nt.useCallback(E=>{a&&a(E),b||u(E)},[a,b]),O=nt.useCallback((E,ue,me)=>{let Se=Array.isArray(ue)?ue:[ue];if(Se.length===0)return null;let Ce=Wr(x,{dimension:E,operator:"is",values:Se});if(me&&(!me.value||(Ce=Mo(Ce,{dimension:me.dimension,operator:"is",values:[me.value]}),!Ce.find(je=>je.dimension===me.dimension&&je.operator!=="is_not")?.values.includes(me.value))))return null;let et=Ce.find(Ve=>Ve.dimension===E&&Ve.operator!=="is_not");return Se.every(Ve=>et?.values.includes(Ve))?JSON.stringify(Ce)===JSON.stringify(x)?null:Ce:null},[x]),c=nt.useCallback((E,ue,me)=>O(E,ue,me)!==null,[O]),k=nt.useCallback((E,ue,me)=>{let Se=O(E,ue,me);Se&&D(Se)},[O,D]),[A,X]=nt.useState("visitors"),S=Ds(d,{refreshKey:s,breakdowns:Xd,filters:x}),T=S.status.data,B=S.reportedZone??T?.timezone,y=B??r??Us()??"UTC",{notCollecting:j,awaitingFirstVisit:Q,firstVisitTooRecent:$,holdingForFirstData:ce}=Jn(T,{published:o}),q=o===!1,G=Zn({collecting:Q||j?!1:T?.collecting,statusFailed:S.status.error!=null,identity:T?.analytics_id}),H=nt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),se=nt.useMemo(()=>{let E=S.breakdowns.sources?.data,ue={};if(!E||E.status!=="ok")return ue;for(let me of E.data){let Se=me.source,Ce=me.sources;typeof Se=="string"&&Array.isArray(Ce)&&Ce.length>0&&(ue[Se]=Ce)}return ue},[S.breakdowns.sources?.data]),W=nt.useMemo(()=>{let E=(Se,Ce)=>{let et=S.breakdowns[Se]?.data;return!et||et.status!=="ok"?[]:[...new Set(et.data.map(Ve=>Ve[Ce]).filter(Ve=>typeof Ve=="string"&&Ve!==""))]};return{channel:S.channels.data?.status==="ok"?[...new Set(S.channels.data.data.map(Se=>Se.channel))]:[],source:E("sources","source"),campaign:E("utm/campaign","campaign"),page:E("pages","pathname"),entry_page:E("entry-pages","pathname"),exit_page:E("exit-pages","pathname"),country:E("countries","country"),browser:E("browsers","browser"),os:E("operating-systems","os"),device:E("devices","device")}},[S.breakdowns,S.channels.data]),[he,Ke]=nt.useState({}),rt=JSON.stringify(W),[Re,qe]=nt.useState(new Map),Xe=JSON.stringify(se);nt.useEffect(()=>{let{suggestions:E,folds:ue}=Uo(H.current,{api:l,period:d},JSON.parse(rt),JSON.parse(Xe));Ke(E),qe(ue)},[rt,Xe,l,d]);let xe=nt.useCallback((E,ue)=>E!=="source"?ue:[...new Set(ue.flatMap(me=>{let Se=[...Re.get(me)??[],...se[me]??[]];return Se.length>0?Se:[me]}))],[Re,se]),Tt=nt.useMemo(()=>{let E=S.conversions.error;return E instanceof Wt&&E.details?.code==="goals_exceed_report_budget"?E.message:null},[S.conversions.error]),_=nt.useMemo(()=>{let E=[S.summary,S.timeseries,S.channels,...Object.values(S.breakdowns)];for(let ue of E){let me=ue?.error;if(me instanceof Wt&&me.details?.code==="filter_unsupported")return me.message}return null},[S.summary,S.timeseries,S.channels,S.breakdowns]),I=(E,ue,me,Se,Ce,et,Ve,je,re)=>()=>{let Ee=S.breakdowns[E];return be(Ya,{sourced:Ee?.data??null,error:Ee?.error,isLoading:Ee?.isLoading,what:ue,collecting:T?.collecting,onRetry:S.refetch,children:it=>{let ta=yt=>je?xe(je,[yt]):yt;return be(jr,{rows:it,dimension:me,metric:Se,metricLabel:Ce,secondary:et,emptyCopy:x.length>0?"No data for this filter":Ve,canFilter:je?(yt,kt)=>c(je,ta(yt),re?{dimension:re,value:kt}:void 0):()=>!1,onFilter:je?(yt,kt)=>k(je,ta(yt),re?{dimension:re,value:kt}:void 0):void 0})}})};if(Yn({status:T,holdingForFirstData:ce,refetchStatus:S.refetchStatus,refetch:S.refetch}),j){let E=!!m&&String(m).slice(0,10)<Yd;return be(xt,{title:"Analytics",onBackToWebsite:t,className:i,children:Bt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),be("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:q?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":E?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return Q?be(xt,{title:"Analytics",onBackToWebsite:t,className:i,children:Bt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),be("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."})]})}):$?Bt(xt,{title:"Analytics",onBackToWebsite:t,className:i,children:[be("div",{className:"af-mb-3 af-flex af-justify-end",children:be(zr,{value:y,chosen:r,onChange:E=>{cr(E),g(E)}})}),Bt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Bt("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",T?.timezone?` ${T.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),be("div",{className:"af-mt-4 af-flex af-justify-center",children:be(Gr,{currentVisitors:G.currentVisitors,asOf:G.asOf,isStale:G.isStale,isUnreachable:G.isUnreachable||G.error!==null,isInitialLoad:G.isInitialLoad})})]})]}):be(xt,{title:"Analytics",onBackToWebsite:t,className:i,children:Bt("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Bt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[be("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Qd.map(E=>be("button",{type:"button","aria-pressed":E.value===d,onClick:()=>f(E.value),className:E.value===d?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:E.label},E.value))}),be(zr,{value:y,chosen:r,onChange:E=>{cr(E),g(E)}}),be(Gr,{currentVisitors:G.currentVisitors,asOf:G.asOf,isStale:G.isStale,isUnreachable:G.isUnreachable||G.error!==null,isInitialLoad:G.isInitialLoad,scopeIsSiteWide:x.length>0})]}),be(Vo,{filters:x,onChange:D,suggestions:he,expandValues:xe,resetKey:l}),_?Bt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),be("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:_}),be("button",{type:"button",onClick:()=>D([]),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,!_&&T?.timezone_defaulted?be("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,_?null:Bt(Jr,{children:[be(Ya,{sourced:S.summary.data,error:S.summary.error,isLoading:S.summary.isLoading,what:"The traffic summary",collecting:T?.collecting,onRetry:S.refetch,children:E=>Bt(Jr,{children:[be($o,{summary:E,selected:A,onSelect:X}),E.previous_unavailable?Bt("p",{className:"af-text-xs af-text-muted-foreground",children:[E.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]})}),be("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:be(Ya,{sourced:S.timeseries.data,error:S.timeseries.error,isLoading:S.timeseries.isLoading,what:"The visitors chart",collecting:T?.collecting,onRetry:S.refetch,children:E=>{let ue=S.timeseries.data?.status==="ok"?S.timeseries.data.window:{from:"",to:""};return be(sr,{rows:E,window:ue,metric:A,timeZone:B??"UTC"})}})}),Bt("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[be(Xs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>be(Ya,{sourced:S.channels.data,error:S.channels.error,isLoading:S.channels.isLoading,what:"Channels",collecting:T?.collecting,onRetry:S.refetch,children:E=>be(jr,{rows:E,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:ue=>c("channel",ue),onFilter:ue=>k("channel",ue)})})},{id:"sources",label:"Sources",render:I("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:I("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),be(Xs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:I("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:I("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:I("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),be(Xs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:I("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:I("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:I("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),be(Xs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:I("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:I("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:I("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Bt("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[be("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:be("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Bt("div",{className:"af-px-3 af-py-2",children:[x.length>0?Bt("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,Tt!==null?Bt("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:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),be("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Tt})]}):be(Ya,{sourced:S.conversions.data,error:S.conversions.error,isLoading:S.conversions.isLoading,what:"Conversions",collecting:T?.collecting,onRetry:S.refetch,children:E=>{let ue=S.conversions.data?.status==="ok"?S.conversions.data:null;return be(Jr,{children:be(tr,{rows:E,primaryConversion:n,denominator:ue?.denominator??0,windowPrecedesCollection:ue?.window_precedes_collection??!1,coverageUnknown:ue?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import{Phone as qo,Mail as Yr,ShoppingBag as tf,ExternalLink as af,MessageCircle as sf,Download as nf,Target as rf}from"lucide-react";import{jsx as Wo,jsxs as uf}from"react/jsx-runtime";function of(e){let a=[e];e.startsWith("//")?a.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||a.push(`https://${e}`);for(let s of a)try{let{hostname:t}=new URL(s);if(t)return t.toLowerCase().replace(/^www\./,"")}catch{}return null}function lf(e){if(Qr(e,"whatsapp"))return!0;let a=of(e);return a===null?!1:["wa.me","whatsapp.com"].some(s=>a===s||a.endsWith(`.${s}`))}function Qr(e,a){return e.slice(0,a.length+1).toLowerCase()===`${a}:`}var jo=[{goal:"Contact",target:e=>Qr(e,"tel"),icon:qo,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Qr(e,"mailto"),icon:Yr,line:"This site is set up to get you emails."},{goal:"Contact",icon:qo,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>lf(e),icon:sf,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:af,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Yr,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Yr,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:tf,line:"This site is set up to sell."},{goal:"File Download",icon:nf,line:"This site is set up to get your file downloaded."}];function Go(e){let{goal:a,target:s}=e;return e.implicit!==!0?null:(s?jo.find(n=>n.goal===a&&n.target?.(s)):void 0)??jo.find(n=>n.goal===a&&!n.target)??null}function cf(e){return Go(e)?.icon??rf}function Ko({primaryConversion:e}){if(!e?.goal)return null;let a=Go(e),s=e.label?.trim(),t=cf(e),n=s?`Your main conversion is ${s}.`:a?.line??`Your main conversion is ${e.goal}.`;return uf("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Wo(t,{className:"af-h-4 af-w-4 af-shrink-0"}),Wo("span",{children:n})]})}import{Fragment as df,jsx as ds,jsxs as nr}from"react/jsx-runtime";function Zo({refreshKey:e,onViewAll:a,primaryConversion:s}){let t=Ds(7,{refreshKey:e,breakdowns:[]}),n=t.status.data??void 0,{nothingToReport:i,notCollecting:o,holdingForFirstData:m}=Jn(n);return Yn({status:n,holdingForFirstData:m,refetchStatus:t.refetchStatus,refetch:t.refetch}),nr("section",{className:"af-rounded-md af-border af-p-3",children:[nr("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[ds("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),a&&ds(w,{type:"button",variant:"ghost",size:"sm",onClick:a,children:"View all analytics"})]}),i?ds("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."}):nr(df,{children:[ds(Ya,{sourced:t.timeseries.data,error:t.timeseries.error,isLoading:t.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:t.refetch,children:d=>{let f=t.timeseries.data?.status==="ok"?t.timeseries.data:null;return ds(sr,{rows:d,window:f?.window??{from:"",to:""},metric:"visitors",timeZone:f?.timezone,height:140})}}),nr("div",{className:"af-mt-3",children:[ds("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),ds(Ya,{sourced:t.conversions.data,error:t.conversions.error,isLoading:t.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:t.refetch,children:d=>{let f=t.conversions.data?.status==="ok"?t.conversions.data:null;return ds(tr,{rows:d,primaryConversion:s,denominator:f?.denominator??0,windowPrecedesCollection:f?.window_precedes_collection??!1,coverageUnknown:f?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as Aa,jsxs as an}from"react/jsx-runtime";var Xr=5;function ei({title:e,viewAllLabel:a,onViewAll:s}){return an("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[Aa("h3",{className:"af-text-sm af-font-medium",children:e}),s&&Aa(w,{type:"button",variant:"ghost",size:"sm",onClick:s,children:a})]})}function ff({refreshKey:e,onBackToWebsite:a,primaryConversion:s,onOpenSurface:t,needsPaidPlan:n,onUpgradePlan:i,onConnectStripe:o}){let m=As({refreshKey:e}),d=(m.summary?.products.count??0)>0||(m.summary?.commerce?.storefront_orders??!1),f=d||(m.summary?.commerce?.invoicing??!1);return Aa(xt,{title:"Dashboard",onBackToWebsite:a,children:an("div",{className:"af-flex af-flex-col af-gap-4",children:[Aa(Ko,{primaryConversion:s}),Aa(Zo,{refreshKey:e,onViewAll:t&&(()=>t("analytics")),primaryConversion:s}),an("section",{className:"af-rounded-md af-border af-p-3",children:[Aa(ei,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:t&&(()=>t("leads"))}),Aa(Wn,{refreshKey:e,maxRows:Xr,onViewAll:t&&(()=>t("leads"))})]}),d&&an("section",{className:"af-rounded-md af-border af-p-3",children:[Aa(ei,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:t&&(()=>t("orders"))}),Aa(ns,{refreshKey:e,maxRows:Xr,onViewAll:t&&(()=>t("orders"))})]}),f&&an("section",{className:"af-rounded-md af-border af-p-3",children:[Aa(ei,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:t&&(()=>t("invoices"))}),Aa(is,{refreshKey:e,maxRows:Xr,onViewAll:t&&(()=>t("invoices")),needsPaidPlan:n,onUpgradePlan:i,onConnectStripe:o})]})]})})}export{Wt as AifeaturesApiError,Xo as AifeaturesProvider,ef as AnalyticsView,An as CustomerDetail,Dn as CustomersList,ff as DashboardView,bn as FormSettings,mn as FormSubmissions,xi as FormsDashboard,ln as FormsList,Er as InvoiceDetail,Gs as InvoiceLabelBadge,is as InvoicesList,Po as InvoicesView,Wn as LeadsView,Os as MAX_ANALYTICS_FILTERS,Bs as MAX_ANALYTICS_FILTER_VALUES,Cn as OrderDetail,gs as OrderStatusBadge,ns as OrdersList,so as OrdersView,eo as PaymentsDashboard,Mn as PaymentsSetup,Nn as ProductSettings,xn as ProductsList,fo as ProductsView,Ns as PromosPanel,$r as REALTIME_FAILURES_BEFORE_ERROR,Vr as REALTIME_POLL_MS,Ar as RetainerStatusBadge,Cs as RetainersPanel,fn as SubmissionDetail,_o as SubscriptionsView,wn as VariantsEditor,xt as ViewShell,gn as WebhookDeliveries,vn as WebhookSettings,Ka as chargedTotal,dr as createApiClient,z as formatPrice,pa as isZeroDecimalCurrency,mt as toMajorUnits,Gt as toMinorUnits,ie as useAifeatures,ie as useAifeaturesContext,Ds as useAnalytics,As as useBusinessSummary,En as useCustomers,pn as useEventDestinations,ws as useForms,Rs as useInvoices,Sn as useOrders,as as usePaymentsStatus,qn as usePeople,jn as usePerson,Ts as useProducts,Zn as useRealtimeVisitors,ks as useRetainers,dn as useSubmissions,Gn as useSubscriptions};
|
|
2
|
+
import*as ns from"react";var pr="aifeatures:analytics:timezone",gr;function qs(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function gi(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function ss(){return vr()??qs()}function vr(){if(gr!==void 0)return gr;try{let e=window.localStorage.getItem(pr);return gi(e)?e:null}catch{return null}}function br(e){if(!(e!==null&&!gi(e))){gr=e;try{e===null?window.localStorage.removeItem(pr):window.localStorage.setItem(pr,e)}catch{}}}function dn(e,a){let s=new URLSearchParams({period:String(e)}),t=ss();return t&&s.set("timezone",t),a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var Ot=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function yr(e,a){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${a}`}function hr(e,a="https://aifeatures.dev"){async function s(t,n={}){let i=`${a}${t}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let d;try{d=await o.json()}catch{}throw new Ot(yr(d?.error,o.status),o.status,d)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(t){return s(`/api/v1/forms/${t}`)},async createForm(t){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(t)})},async updateForm(t,n){return s(`/api/v1/forms/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(t){await s(`/api/v1/forms/${t}`,{method:"DELETE"})},async getSubmissions(t,n={}){let i=new URLSearchParams;n.limit!==void 0&&i.set("limit",String(n.limit)),n.offset!==void 0&&i.set("offset",String(n.offset));let o=i.toString(),d=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(d)},async getSubmission(t){return s(`/api/v1/submissions/${t}`)},async deleteSubmission(t){await s(`/api/v1/submissions/${t}`,{method:"DELETE"})},async downloadAttachment(t,n){let i=typeof n=="string"?{name:n}:n,o=i.name,d=i.id??i.name,f=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(d)}`,u=await fetch(f,{headers:{Authorization:`Bearer ${e}`}});if(!u.ok){let g;try{g=await u.json()}catch{}throw new Ot(yr(g?.error,u.status),u.status,g)}let r=await u.blob(),p=URL.createObjectURL(r),b=document.createElement("a");b.href=p,b.download=o,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(p)},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(t){let n=new URLSearchParams({limit:"10"});return t&&n.set("cursor",t),s(`/api/v1/promos?${n}`)},getPromo(t){return s(`/api/v1/promos/${encodeURIComponent(t)}`)},createPromo(t){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(t)})},disablePromo(t){return s(`/api/v1/promos/${encodeURIComponent(t)}/disable`,{method:"POST"})},replacePromo(t,n){return s(`/api/v1/promos/${encodeURIComponent(t)}/replace`,{method:"POST",body:JSON.stringify(n)})},async getProducts(t={}){let n=new URLSearchParams;t.include&&n.set("include",t.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(t){return s(`/api/v1/products/${t}`)},async createProduct(t){return s("/api/v1/products",{method:"POST",body:JSON.stringify(t)})},async updateProduct(t,n){return s(`/api/v1/products/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(t){await s(`/api/v1/products/${t}`,{method:"DELETE"})},async attachProductFile(t,n){let i=new FormData;i.append("file",n);let o=await fetch(`${a}/api/v1/products/${t}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let d;try{d=await o.json()}catch{}throw new Ot(yr(d?.error,o.status),o.status,d)}return o.json()},async attachProductFileFromUrl(t,n){return s(`/api/v1/products/${t}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(t,n){return s(`/api/v1/products/${t}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(t,n){return s(`/api/v1/options/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(t){await s(`/api/v1/options/${t}`,{method:"DELETE"})},async createVariant(t,n){return s(`/api/v1/products/${t}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(t,n){return s(`/api/v1/variants/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(t){await s(`/api/v1/variants/${t}`,{method:"DELETE"})},async setVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(t={}){let n=new URLSearchParams;t.email?n.set("email",t.email):t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(t){return s(`/api/v1/customers/${t}`)},async getOrders(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.source&&n.set("source",t.source),t.excludeStatus?.length&&n.set("exclude_status",t.excludeStatus.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.unfulfilledOnly&&n.set("unfulfilled_only","true"),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(t){return s(`/api/v1/orders/${t}`)},async getInvoices(t={}){let n=new URLSearchParams;t.labels?.length&&n.set("label",t.labels.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.customerId&&n.set("customer_id",t.customerId),t.q&&n.set("q",t.q),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.includeAggregates&&n.set("include","aggregates"),t.retainerId&&n.set("retainer_id",t.retainerId),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(t){return s(`/api/v1/invoices/${t}`)},async getInvoicePreview(t){return s(`/api/v1/invoices/${t}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(t={}){let n=new URLSearchParams;t.statuses?.length&&n.set("status",t.statuses.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(t){return s(`/api/v1/retainers/${t}`)},async resendOrderReceipt(t){await s(`/api/v1/orders/${t}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(t){return s(`/api/v1/orders/${t}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(t,n){return s(`/api/v1/orders/${t}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){let t=new URLSearchParams,n=ss();n&&t.set("timezone",n);let i=t.toString();return s(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${dn(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${dn(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${dn(t,n)}`)},async getAnalyticsConversions(t){return s((()=>{let n=new URLSearchParams({period:String(t)}),i=ss();return i&&n.set("timezone",i),`/api/v1/analytics/conversions?${n.toString()}`})())},async getAnalyticsGoalTargets(t,n,i){let o=new URLSearchParams({goal:t,period:String(n)}),d=ss();return d&&o.set("timezone",d),i!==void 0&&o.set("limit",String(i)),s(`/api/v1/analytics/conversions/targets?${o.toString()}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${dn(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;n.set("tz_offset_minutes",String(t.tzOffsetMinutes));let i=ss();return i&&n.set("timezone",i),s(`/api/v1/summary?${n.toString()}`)},async getPeople(t={}){let n=new URLSearchParams;t.since&&n.set("since",t.since),t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(t){return s(`/api/v1/people/${encodeURIComponent(t)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(t){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(t)})},async updateEventDestination(t,n){return s(`/api/v1/event-destinations/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(t){await s(`/api/v1/event-destinations/${t}`,{method:"DELETE"})},async rotateEventDestinationSecret(t){return s(`/api/v1/event-destinations/${t}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(t){return(await s(`/api/v1/event-destinations/${t}/secret`)).secret},async getEventDeliveries(t,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${t}/deliveries${i}`)).deliveries},async retryEventDelivery(t,n){return s(`/api/v1/event-destinations/${t}/deliveries/${n}/retry`,{method:"POST"})}}}import{jsx as js,jsxs as ml}from"react/jsx-runtime";var vi=ns.createContext(null);function dl(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 fl({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=ns.useMemo(()=>dl(e),[e]),o=ns.useMemo(()=>hr(e,a),[e,a]),d=ns.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?js("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:ml("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[js("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),js("p",{className:"af-text-sm af-text-destructive",children:i})]})}):js(vi.Provider,{value:d,children:js("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function se(){let e=ns.useContext(vi);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as Ya from"react";import{ArrowLeft as vc,Settings as bc,Inbox as yc}from"lucide-react";import*as fn from"react";import*as xa from"@radix-ui/react-tabs";import{clsx as pl}from"clsx";import{extendTailwindMerge as gl}from"tailwind-merge";var vl=gl({prefix:"af-"});function J(...e){return vl(pl(e))}import{jsx as xr}from"react/jsx-runtime";var mn=xa.Root,Gs=fn.forwardRef(({className:e,...a},s)=>xr(xa.List,{ref:s,className:J("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...a}));Gs.displayName=xa.List.displayName;var wa=fn.forwardRef(({className:e,...a},s)=>xr(xa.Trigger,{ref:s,className:J("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...a}));wa.displayName=xa.Trigger.displayName;var Na=fn.forwardRef(({className:e,...a},s)=>xr(xa.Content,{ref:s,className:J("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...a}));Na.displayName=xa.Content.displayName;import*as bi from"react";import{Slot as bl}from"@radix-ui/react-slot";import{cva as yl}from"class-variance-authority";import{jsx as xl}from"react/jsx-runtime";var hl=yl("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=bi.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>xl(t?bl:"button",{className:J(hl({variant:a,size:s,className:e})),ref:i,...n}));w.displayName="Button";import{Inbox as yi,Settings as Sl}from"lucide-react";import*as Wa from"react";import{jsx as Ga}from"react/jsx-runtime";var Be=Wa.forwardRef(({className:e,...a},s)=>Ga("div",{className:"af-relative af-w-full af-overflow-auto",children:Ga("table",{ref:s,className:J("af-w-full af-caption-bottom af-text-sm",e),...a})}));Be.displayName="Table";var Fe=Wa.forwardRef(({className:e,...a},s)=>Ga("thead",{ref:s,className:J("[&_tr]:af-border-b",e),...a}));Fe.displayName="TableHeader";var Me=Wa.forwardRef(({className:e,...a},s)=>Ga("tbody",{ref:s,className:J("[&_tr:last-child]:af-border-0",e),...a}));Me.displayName="TableBody";var wl=Wa.forwardRef(({className:e,...a},s)=>Ga("tfoot",{ref:s,className:J("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));wl.displayName="TableFooter";var pe=Wa.forwardRef(({className:e,...a},s)=>Ga("tr",{ref:s,className:J("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));pe.displayName="TableRow";var $=Wa.forwardRef(({className:e,...a},s)=>Ga("th",{ref:s,className:J("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));$.displayName="TableHead";var U=Wa.forwardRef(({className:e,...a},s)=>Ga("td",{ref:s,className:J("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));U.displayName="TableCell";var Nl=Wa.forwardRef(({className:e,...a},s)=>Ga("caption",{ref:s,className:J("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));Nl.displayName="TableCaption";import*as Sa from"react";function Rs(){let{api:e}=se(),[a,s]=Sa.useState([]),[t,n]=Sa.useState(!0),[i,o]=Sa.useState(null),d=Sa.useCallback(async()=>{try{n(!0),o(null);let p=await e.getForms();s(p)}catch(p){o(p instanceof Error?p:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);Sa.useEffect(()=>{d()},[d]);let f=Sa.useCallback(async p=>{let b=await e.createForm(p);return s(g=>[...g,b]),b},[e]),u=Sa.useCallback(async(p,b)=>{let g=await e.updateForm(p,b);return s(c=>c.map(l=>l.id===p?g:l)),g},[e]),r=Sa.useCallback(async p=>{await e.deleteForm(p),s(b=>b.filter(g=>g.id!==p))},[e]);return{forms:a,isLoading:t,error:i,refetch:d,createForm:f,updateForm:u,deleteForm:r}}import{jsx as Wt,jsxs as Ka}from"react/jsx-runtime";function pn({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=Rs();return t?Wt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Wt("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Wt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ka("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?Ka("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Wt(yi,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ka("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",Wt("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Wt("div",{className:a,children:Ka(Be,{children:[Wt(Fe,{children:Ka(pe,{children:[Wt($,{children:"Name"}),Wt($,{className:"af-text-right",children:"Actions"})]})}),Wt(Me,{children:s.map(i=>Ka(pe,{children:[Wt(U,{className:"af-font-medium",children:i.name}),Wt(U,{className:"af-text-right",children:Ka("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ka(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[Wt(yi,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ka(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[Wt(Sl,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as Cl}from"lucide-react";import{cva as _l}from"class-variance-authority";import{jsx as Pl}from"react/jsx-runtime";var Rl=_l("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:a,...s}){return Pl("div",{className:J(Rl({variant:a}),e),...s})}import{jsx as vs,jsxs as gn}from"react/jsx-runtime";var Tl={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 vn(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 wr(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function kl(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:a="Email needs attention"}){return wr(e)?gn("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:[vs(Cl,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function Oa({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||wr([n]));return t.length?vs("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=vn(n),o=kl(n);return gn("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[gn("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[vs("span",{className:"af-font-medium",children:Tl[n.kind]??"Email notification"}),vs(te,{variant:i.variant,children:i.label})]}),gn("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&wr([n])&&vs("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."}),i.detail&&vs("p",{className:"af-mt-1",children:i.detail}),o&&vs("p",{className:"af-mt-1",children:o})]},n.id)})}):null}import*as Ps from"react";import{ArrowLeft as zl,ChevronLeft as ql,ChevronRight as jl,Eye as Gl,Inbox as Wl,Paperclip as Kl}from"lucide-react";import*as rs from"react";import*as we from"@radix-ui/react-select";import{Check as El,ChevronDown as hi,ChevronUp as Al}from"lucide-react";import{jsx as Bt,jsxs as Nr}from"react/jsx-runtime";var da=we.Root;var fa=we.Value,na=rs.forwardRef(({className:e,children:a,...s},t)=>Nr(we.Trigger,{ref:t,className:J("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[a,Bt(we.Icon,{asChild:!0,children:Bt(hi,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));na.displayName=we.Trigger.displayName;var xi=rs.forwardRef(({className:e,...a},s)=>Bt(we.ScrollUpButton,{ref:s,className:J("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Bt(Al,{className:"af-h-4 af-w-4"})}));xi.displayName=we.ScrollUpButton.displayName;var wi=rs.forwardRef(({className:e,...a},s)=>Bt(we.ScrollDownButton,{ref:s,className:J("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Bt(hi,{className:"af-h-4 af-w-4"})}));wi.displayName=we.ScrollDownButton.displayName;var ra=rs.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>Bt(we.Portal,{children:Nr(we.Content,{ref:n,className:J("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...t,children:[Bt(xi,{}),Bt(we.Viewport,{className:J("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:a}),Bt(wi,{})]})}));ra.displayName=we.Content.displayName;var Il=rs.forwardRef(({className:e,...a},s)=>Bt(we.Label,{ref:s,className:J("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));Il.displayName=we.Label.displayName;var Ke=rs.forwardRef(({className:e,children:a,...s},t)=>Nr(we.Item,{ref:t,className:J("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[Bt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:Bt(we.ItemIndicator,{children:Bt(El,{className:"af-h-4 af-w-4"})})}),Bt(we.ItemText,{children:a})]}));Ke.displayName=we.Item.displayName;var Dl=rs.forwardRef(({className:e,...a},s)=>Bt(we.Separator,{ref:s,className:J("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));Dl.displayName=we.Separator.displayName;import*as ma from"react";function bn({formId:e,initialPageSize:a=25}){let{api:s}=se(),[t,n]=ma.useState([]),[i,o]=ma.useState(0),[d,f]=ma.useState(!0),[u,r]=ma.useState(null),[p,b]=ma.useState(0),[g,c]=ma.useState(a),l=ma.useCallback(async()=>{if(e)try{f(!0),r(null);let x={limit:g,offset:p*g},D=await s.getSubmissions(e,x);n(D.submissions),o(D.total)}catch(x){r(x instanceof Error?x:new Error("Failed to fetch submissions"))}finally{f(!1)}},[s,e,p,g]);ma.useEffect(()=>{l()},[l]);let v=ma.useCallback(async x=>{await s.deleteSubmission(x),n(D=>D.filter(B=>B.id!==x)),o(D=>D-1)},[s]),h=Math.ceil(i/g);return{submissions:t,total:i,isLoading:d,error:u,page:p,pageSize:g,hasNextPage:p<h-1,hasPreviousPage:p>0,setPage:b,setPageSize:x=>{c(x),b(0)},refetch:l,deleteSubmission:v}}import*as Si from"react";import{ArrowLeft as Ll,Download as Ol,Globe as Bl,Clock as Fl,FileText as Ml,Loader2 as $l,Monitor as Ul,Mail as Vl}from"lucide-react";import{jsx as ct,jsxs as ut}from"react/jsx-runtime";function Ni(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Hl(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function yn({submission:e,onBack:a}){let{api:s}=se(),[t,n]=Si.useState(null),i=f=>f.id??f.name,o=async f=>{n(i(f));try{await s.downloadAttachment(e.id,f)}catch(u){console.error("Download failed:",u)}finally{n(null)}},d=Object.entries(e.data).filter(([f])=>!f.startsWith("_"));return ut("div",{children:[ut("div",{className:"af-mb-6",children:[ut(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[ct(Ll,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),ct("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),ut("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Ni(e.metadata.submitted_at)]})]}),ut("div",{className:"af-space-y-6",children:[ct(Oa,{deliveries:e.email_deliveries}),ut("div",{children:[ct("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),ut("div",{className:"af-space-y-3",children:[d.map(([f,u])=>ut("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[ct("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:f.replace(/_/g," ")}),ct("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof u=="string"&&u.includes(`
|
|
3
|
+
`)?ct("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:u}):String(u)})]},f)),d.length===0&&ct("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&ut("div",{children:[ct("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),ct("div",{className:"af-space-y-2",children:e.attachments.map((f,u)=>ut("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[ut("div",{className:"af-flex af-items-center af-gap-2",children:[ct(Ml,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ct("span",{className:"af-text-sm",children:f.name}),ut("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Hl(f.size),")"]})]}),ut(w,{variant:"ghost",size:"sm",onClick:()=>o(f),disabled:t===i(f),children:[t===i(f)?ct($l,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):ct(Ol,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(f)?"Downloading...":"Download"]})]},u))})]}),ut("div",{children:[ct("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),ut("div",{className:"af-space-y-2 af-text-sm",children:[ut("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ct(Fl,{className:"af-h-4 af-w-4"}),ct("span",{children:Ni(e.metadata.submitted_at)})]}),e.metadata.ip_address&&ut("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ct(Bl,{className:"af-h-4 af-w-4"}),ut("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&ut("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[ct(Ul,{className:"af-h-4 af-w-4 af-mt-0.5"}),ct("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&ut("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ct(Vl,{className:"af-h-4 af-w-4"}),ut("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as Ne,jsxs as mt}from"react/jsx-runtime";function Zl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Jl(e){let a=["email","Email","EMAIL","e-mail","mail"];for(let s of a)if(typeof e[s]=="string")return e[s];return null}var Yl=["message","comments","comment","inquiry","question","details","body","notes"];function Ql(e){let a=Object.entries(e).filter(([i,o])=>!i.startsWith("_")&&!i.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),s=new Map(a.map(([i,o])=>[i.toLowerCase(),o])),n=(Yl.map(i=>s.get(i)).find(Boolean)??a.reduce((i,[,o])=>o.length>i.length?o:i,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function hn({formId:e,className:a,defaultSubmissionId:s,submissionId:t,onSelectSubmission:n}){let{api:i}=se(),{submissions:o,total:d,isLoading:f,error:u,page:r,pageSize:p,hasNextPage:b,hasPreviousPage:g,setPage:c,setPageSize:l}=bn({formId:e}),[v,h]=Ps.useState(s??null),x=n?t??null:v,D=n??h,B=O=>!!O&&O.id===x&&O.form_id===e,m=o.find(B),[N,R]=Ps.useState(null),A=B(N)?N:null,[S,k]=Ps.useState(null);if(Ps.useEffect(()=>{if(k(null),!x||m||A)return;let O=!1;return i.getSubmission(x).then(K=>{if(!O){if(K.form_id!==e){k("This submission could not be found.");return}R(K)}}).catch(()=>{O||k("This submission could not be found.")}),()=>{O=!0}},[i,e,x,m,A]),x){let O=m??A;return O?Ne("div",{className:a,children:Ne(yn,{submission:O,onBack:()=>D(null)})}):S?mt("div",{className:a,children:[mt(w,{variant:"ghost",size:"sm",onClick:()=>D(null),className:"af-mb-2 af--ml-2",children:[Ne(zl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Ne("p",{className:"af-text-sm af-text-destructive",children:S})]}):Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ne("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(f)return Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ne("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(u)return Ne("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:mt("div",{className:"af-text-destructive",children:["Error: ",u.message]})});if(o.length===0&&r===0)return mt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Ne(Wl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),mt("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 M=r*p+1,y=Math.min((r+1)*p,d);return mt("div",{className:a,children:[mt(Be,{children:[Ne(Fe,{children:mt(pe,{children:[Ne($,{children:"Email"}),Ne($,{children:"Preview"}),Ne($,{children:"Date"}),Ne($,{className:"af-text-right",children:"Actions"})]})}),Ne(Me,{children:o.map(O=>{let K=Jl(O.data),V=Ql(O.data);return mt(pe,{children:[mt(U,{className:"af-font-medium",children:[mt("div",{className:"af-flex af-items-center af-gap-2",children:[K||Ne("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),O.attachments.length>0&&mt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${O.attachments.length} attachment(s)`,children:[Ne(Kl,{className:"af-h-3 af-w-3"}),Ne("span",{className:"af-text-xs",children:O.attachments.length})]})]}),Ne(Ws,{deliveries:O.email_deliveries,label:"Notification email needs attention"})]}),Ne(U,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:V||Ne("span",{className:"af-italic",children:"No preview available"})}),Ne(U,{className:"af-text-muted-foreground",children:Zl(O.metadata.submitted_at)}),Ne(U,{className:"af-text-right",children:Ne(w,{variant:"ghost",size:"icon",onClick:()=>D(O.id),title:"View details",children:Ne(Gl,{className:"af-h-4 af-w-4"})})})]},O.id)})})]}),mt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[mt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[mt("span",{children:["Showing ",M,"-",y," of ",d]}),mt(da,{value:String(p),onValueChange:O=>l(Number(O)),children:[Ne(na,{className:"af-w-[70px] af-h-8",children:Ne(fa,{})}),mt(ra,{children:[Ne(Ke,{value:"10",children:"10"}),Ne(Ke,{value:"25",children:"25"}),Ne(Ke,{value:"50",children:"50"}),Ne(Ke,{value:"100",children:"100"})]})]}),Ne("span",{children:"per page"})]}),mt("div",{className:"af-flex af-items-center af-gap-2",children:[mt(w,{variant:"outline",size:"sm",onClick:()=>c(r-1),disabled:!g,children:[Ne(ql,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),mt(w,{variant:"outline",size:"sm",onClick:()=>c(r+1),disabled:!b,children:["Next",Ne(jl,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as oa from"react";import{Plus as fc,X as mc,Loader2 as pc,Check as gc}from"lucide-react";import*as _i from"react";import{jsx as Xl}from"react/jsx-runtime";var ge=_i.forwardRef(({className:e,type:a,...s},t)=>Xl("input",{type:a,className:J("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:t,...s}));ge.displayName="Input";import*as Ri from"react";import{cva as ec}from"class-variance-authority";import{jsx as ac}from"react/jsx-runtime";var tc=ec("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ve=Ri.forwardRef(({className:e,...a},s)=>ac("label",{ref:s,className:J(tc(),e),...a}));ve.displayName="Label";import*as ga from"react";import{Plus as ic,Loader2 as _r,Copy as oc,Check as lc,Trash2 as cc,RefreshCw as uc,AlertTriangle as dc}from"lucide-react";import*as Ks from"react";import*as wt from"@radix-ui/react-dialog";import{X as sc}from"lucide-react";import{jsx as Za,jsxs as Sr}from"react/jsx-runtime";var Ba=wt.Root;var nc=wt.Portal;var Pi=Ks.forwardRef(({className:e,...a},s)=>Za(wt.Overlay,{ref:s,className:J("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));Pi.displayName=wt.Overlay.displayName;var _a=Ks.forwardRef(({className:e,children:a,...s},t)=>Za(nc,{children:Sr("div",{className:"aifeatures-admin",children:[Za(Pi,{}),Sr(wt.Content,{ref:t,className:J("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[a,Sr(wt.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:[Za(sc,{className:"af-h-4 af-w-4"}),Za("span",{className:"af-sr-only",children:"Close"})]})]})]})}));_a.displayName=wt.Content.displayName;var Ra=({className:e,...a})=>Za("div",{className:J("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});Ra.displayName="DialogHeader";var Pa=({className:e,...a})=>Za("div",{className:J("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});Pa.displayName="DialogFooter";var Ca=Ks.forwardRef(({className:e,...a},s)=>Za(wt.Title,{ref:s,className:J("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));Ca.displayName=wt.Title.displayName;var Ta=Ks.forwardRef(({className:e,...a},s)=>Za(wt.Description,{ref:s,className:J("af-text-sm af-text-muted-foreground",e),...a}));Ta.displayName=wt.Description.displayName;import*as ia from"react";function xn(){let{api:e}=se(),[a,s]=ia.useState([]),[t,n]=ia.useState(!0),[i,o]=ia.useState(null),d=ia.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(g){o(g instanceof Error?g:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);ia.useEffect(()=>{d()},[d]);let f=ia.useCallback(async g=>{let c=await e.createEventDestination(g);return s(l=>[c,...l]),c},[e]),u=ia.useCallback(async(g,c)=>{let l=await e.updateEventDestination(g,c);return s(v=>v.map(h=>h.id===g?l:h)),l},[e]),r=ia.useCallback(async g=>{await e.deleteEventDestination(g),s(c=>c.filter(l=>l.id!==g))},[e]),p=ia.useCallback(async g=>{let c=await e.rotateEventDestinationSecret(g);return s(l=>l.map(v=>v.id===g?c:v)),c},[e]),b=ia.useCallback(g=>e.getEventDestinationSecret(g),[e]);return{destinations:a,isLoading:t,error:i,refetch:d,createDestination:f,updateDestination:u,deleteDestination:r,rotateSecret:p,getSecret:b}}import*as Ja from"react";import{Loader2 as Ci,RotateCw as rc}from"lucide-react";import{jsx as pa,jsxs as Zs}from"react/jsx-runtime";function wn({destinationId:e,limit:a=25,className:s}){let{api:t}=se(),[n,i]=Ja.useState([]),[o,d]=Ja.useState(!0),[f,u]=Ja.useState(null),[r,p]=Ja.useState(null),b=Ja.useCallback(async()=>{try{d(!0),u(null),i(await t.getEventDeliveries(e,a))}catch(c){u(c instanceof Error?c.message:"Failed to load deliveries")}finally{d(!1)}},[t,e,a]);Ja.useEffect(()=>{b()},[b]);let g=async c=>{try{p(c.id),u(null);let l=await t.retryEventDelivery(e,c.id);i(v=>v.map(h=>h.id===c.id?l:h))}catch(l){u(l instanceof Error?l.message:"Retry failed")}finally{p(null)}};return o?Zs("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[pa(Ci,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?pa("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?pa("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):pa("div",{className:s,children:pa("div",{className:"af-divide-y af-border af-rounded",children:n.map(c=>{let l=c.delivered_at!==null;return Zs("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Zs("div",{className:"af-min-w-0",children:[Zs("div",{className:"af-flex af-items-center af-gap-2",children:[l?pa(te,{variant:"secondary",children:c.last_status??200}):pa(te,{variant:"destructive",children:c.last_status??"failed"}),pa("span",{className:"af-text-sm af-truncate",children:c.type})]}),Zs("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"}`]}),!l&&c.last_error&&pa("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),pa(w,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===c.id,onClick:()=>g(c),children:r===c.id?pa(Ci,{className:"af-h-4 af-w-4 af-animate-spin"}):pa(rc,{className:"af-h-4 af-w-4"})})]},c.id)})})})}import{jsx as ke,jsxs as pt}from"react/jsx-runtime";function Nn({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:d,updateDestination:f,deleteDestination:u,rotateSecret:r,getSecret:p}=xn(),[b,g]=ga.useState(""),[c,l]=ga.useState(!1),[v,h]=ga.useState(null),[x,D]=ga.useState(null),[B,m]=ga.useState(null),[N,R]=ga.useState(!1),[A,S]=ga.useState(null),[k,M]=ga.useState(null),[y,O]=ga.useState(null),K=ga.useMemo(()=>n.filter(W=>W.form_id===e),[n,e]),V=async()=>{let W=b.trim();if(W){if(!W.startsWith("https://")){h("Webhook URLs must start with https://");return}try{l(!0),h(null),await d({url:W,form_id:e,...a&&a.length>0?{topics:a}:{}}),g("")}catch(he){h(he instanceof Error?he.message:"Failed to add webhook")}finally{l(!1)}}},ce=async W=>{try{M(W.id),h(null),await r(W.id),R(!1),m(await p(W.id))}catch(he){h(he instanceof Error?he.message:"Failed to rotate secret")}finally{M(null)}},G=async W=>{try{M(W.id),h(null),await f(W.id,{status:"active"})}catch(he){h(he instanceof Error?he.message:"Failed to re-enable")}finally{M(null)}},Z=async()=>{if(A)try{M(A.id),await u(A.id),S(null)}catch(W){h(W instanceof Error?W.message:"Failed to delete")}finally{M(null)}},q=async W=>{if(x===W.id){D(null),m(null);return}try{M(W.id),h(null),R(!1),D(W.id),m(await p(W.id))}catch(he){D(null),h(he instanceof Error?he.message:"Failed to read secret")}finally{M(null)}},ne=async()=>{if(B)try{await navigator.clipboard.writeText(B),R(!0)}catch{}};return pt("div",{className:t,children:[pt("div",{className:"af-space-y-1",children:[ke(ve,{children:"Webhooks"}),ke("p",{className:"af-text-sm af-text-muted-foreground",children:s??"Send this form's submissions to your own system as they arrive \u2014 a Zapier or Make hook, a CRM, or your own endpoint."})]}),pt("div",{className:"af-flex af-gap-2 af-mt-4",children:[ke(ge,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:W=>g(W.target.value),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),V())},disabled:c}),pt(w,{onClick:V,disabled:c||!b.trim(),children:[c?ke(_r,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(ic,{className:"af-h-4 af-w-4"}),ke("span",{className:"af-ml-1",children:"Add"})]})]}),(v||o)&&ke("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:v||o?.message}),pt("div",{className:"af-mt-4 af-space-y-2",children:[i&&pt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ke(_r,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&K.length===0&&ke("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),K.map(W=>pt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[pt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[pt("div",{className:"af-min-w-0",children:[pt("div",{className:"af-flex af-items-center af-gap-2",children:[ke("span",{className:"af-font-mono af-text-sm af-truncate",children:W.url}),W.status==="disabled"?ke(te,{variant:"destructive",children:"Disabled"}):ke(te,{variant:"secondary",children:"Active"})]}),ke("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:W.topics.includes("*")?"All events":W.topics.join(", ")})]}),pt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[ke(w,{variant:"ghost",size:"sm",onClick:()=>O(y===W.id?null:W.id),children:y===W.id?"Hide log":"Deliveries"}),ke(w,{variant:"ghost",size:"sm",onClick:()=>q(W),disabled:k===W.id,children:x===W.id?"Hide secret":"Show secret"}),ke(w,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:k===W.id,onClick:()=>S(W),children:ke(cc,{className:"af-h-4 af-w-4"})})]})]}),W.status==="disabled"&&pt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[ke(dc,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),pt("div",{className:"af-text-sm",children:[pt("p",{children:["We stopped sending after repeated failures."," ",W.disabled_reason]}),ke(w,{variant:"outline",size:"sm",className:"af-mt-2",disabled:k===W.id,onClick:()=>G(W),children:"Re-enable"})]})]}),x===W.id&&B&&pt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[ke("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."}),pt("div",{className:"af-flex af-gap-2",children:[ke(ge,{readOnly:!0,value:B,className:"af-font-mono"}),ke(w,{variant:"outline",title:"Copy signing secret",onClick:ne,children:N?ke(lc,{className:"af-h-4 af-w-4"}):ke(oc,{className:"af-h-4 af-w-4"})}),ke(w,{variant:"outline",title:"Rotate signing secret",disabled:k===W.id,onClick:()=>ce(W),children:k===W.id?ke(_r,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(uc,{className:"af-h-4 af-w-4"})})]})]}),y===W.id&&ke(wn,{destinationId:W.id})]},W.id))]}),ke(Ba,{open:!!A,onOpenChange:W=>{!W&&!k&&S(null)},children:pt(_a,{children:[pt(Ra,{children:[ke(Ca,{children:"Delete this webhook?"}),pt(Ta,{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."]})]}),pt(Pa,{children:[ke(w,{variant:"outline",onClick:()=>S(null),disabled:!!k,children:"Cancel"}),ke(w,{variant:"destructive",onClick:Z,disabled:!!k,children:k?"Deleting...":"Delete"})]})]})})]})}import{jsx as Le,jsxs as ka}from"react/jsx-runtime";function Sn({form:e,onSaved:a,className:s}){let{updateForm:t}=Rs(),[n,i]=oa.useState(!1),[o,d]=oa.useState(null),[f,u]=oa.useState(null),[r,p]=oa.useState(e.name),[b,g]=oa.useState(e.redirect_url||""),[c,l]=oa.useState(e.email_recipients),[v,h]=oa.useState("");oa.useEffect(()=>{p(e.name),g(e.redirect_url||""),l(e.email_recipients),u(null)},[e]);let x=oa.useCallback(async R=>{try{i(!0),u(null);let A=await t(e.id,R);d(new Date),a?.(A)}catch(A){u(A instanceof Error?A.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);oa.useEffect(()=>{if(o){let R=setTimeout(()=>d(null),2e3);return()=>clearTimeout(R)}},[o]);let D=async()=>{let R=v.trim().toLowerCase();if(!R)return;if(!R.includes("@")){u("Please enter a valid email address");return}if(c.includes(R)){u("This email is already added");return}let A=[...c,R];l(A),h(""),u(null),await x({email_recipients:A})},B=async R=>{let A=c.filter(S=>S!==R);l(A),await x({email_recipients:A})},m=async()=>{r!==e.name&&await x({name:r})},N=async()=>{let R=b||null;R!==e.redirect_url&&await x({redirect_url:R})};return ka("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&Le("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?ka("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:[Le(pc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),Le("span",{className:"af-text-sm",children:"Saving..."})]}):ka("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:[Le(gc,{className:"af-h-4 af-w-4 af-text-green-600"}),Le("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),ka("div",{className:"af-space-y-2",children:[Le(ve,{htmlFor:"form-name",children:"Form Name"}),Le(ge,{id:"form-name",value:r,onChange:R=>p(R.target.value),onBlur:m,placeholder:"Contact Form"}),Le("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),ka("div",{className:"af-space-y-2",children:[Le(ve,{children:"Email Recipients"}),Le("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),ka("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(R=>ka(te,{variant:"secondary",className:"af-gap-1",children:[R,Le("button",{type:"button",onClick:()=>B(R),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:Le(mc,{className:"af-h-3 af-w-3"})})]},R)),c.length===0&&Le("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),ka("div",{className:"af-flex af-gap-2",children:[Le(ge,{type:"email",value:v,onChange:R=>h(R.target.value),placeholder:"Add email address",onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),D())},disabled:n}),Le(w,{type:"button",variant:"outline",onClick:D,disabled:!v.trim()||n,children:Le(fc,{className:"af-h-4 af-w-4"})})]})]}),ka("div",{className:"af-space-y-2",children:[Le(ve,{htmlFor:"redirect-url",children:"Redirect URL"}),Le(ge,{id:"redirect-url",value:b,onChange:R=>g(R.target.value),onBlur:N,placeholder:"/thank-you"}),Le("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."})]}),ka("div",{className:"af-space-y-2",children:[Le(ve,{children:"Form Endpoint"}),Le("div",{className:"af-flex af-items-center af-gap-2",children:Le("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})}),Le("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),ka("div",{className:"af-space-y-2",children:[Le(ve,{children:"Captcha Protection"}),Le("div",{className:"af-flex af-items-center af-gap-2",children:Le(te,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),Le("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),Le(Nn,{formId:e.id}),f&&Le("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}import{jsx as Kt,jsxs as Fa}from"react/jsx-runtime";function Ti({className:e,location:a,onNavigate:s,submissionId:t}){let{api:n}=se(),[i,o]=Ya.useState({submissionId:t});Ya.useEffect(()=>{t&&o({submissionId:t})},[t]);let d=s?a??{}:i,f=s??o,[u,r]=Ya.useState(null),p=`${d.formId??""}|${d.submissionId??""}`,[b,g]=Ya.useState(null),c=b?.key===p?b.message:null,l=d.formId??(u&&u.submissionId===d.submissionId?u.formId:void 0);Ya.useEffect(()=>{let R=d.submissionId;if(!R||d.formId)return;let A=!1;return n.getSubmission(R).then(S=>{A||(g(null),r({submissionId:R,formId:S.form_id}))}).catch(()=>{A||g({key:p,message:"This submission could not be found."})}),()=>{A=!0}},[n,d.submissionId,d.formId,p]);let[v,h]=Ya.useState(null);Ya.useEffect(()=>{if(!l||v?.id===l)return;let R=!1;return n.getForm(l).then(A=>{R||(g(null),h(A))}).catch(()=>{R||g({key:p,message:"This form could not be found."})}),()=>{R=!0}},[n,l,v?.id,p]);let x=(R,A)=>{h(R),f({formId:R.id,tab:A})},D=()=>f({});if(!d.formId&&!d.submissionId)return Fa("div",{className:e,children:[Fa("div",{className:"af-mb-6",children:[Kt("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Kt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Kt(pn,{onSelectForm:x})]});let m=Fa(w,{variant:"ghost",size:"sm",onClick:D,className:"af-mb-2 af--ml-2",children:[Kt(vc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(c)return Fa("div",{className:e,children:[m,Kt("p",{className:"af-text-sm af-text-destructive",children:c})]});if(!l||v?.id!==l)return Kt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Kt("div",{className:"af-text-muted-foreground",children:"Loading..."})});let N=d.submissionId?"submissions":d.tab??"submissions";return Fa("div",{className:e,children:[Fa("div",{className:"af-mb-6",children:[m,Kt("h2",{className:"af-text-lg af-font-semibold",children:v.name})]}),Fa(mn,{value:N,onValueChange:R=>f({formId:l,tab:R}),children:[Fa(Gs,{className:"af-mb-4",children:[Fa(wa,{value:"submissions",className:"af-gap-2",children:[Kt(yc,{className:"af-h-4 af-w-4"}),"Submissions"]}),Fa(wa,{value:"settings",className:"af-gap-2",children:[Kt(bc,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Kt(Na,{value:"submissions",children:Kt(hn,{formId:l,submissionId:d.submissionId,onSelectSubmission:R=>f({formId:l,tab:"submissions",submissionId:R??void 0})})}),Kt(Na,{value:"settings",children:Kt(Sn,{form:v,onSaved:h})})]})]})}import*as Oe from"react";import*as Ma from"react";function is(){let{api:e}=se(),[a,s]=Ma.useState(null),[t,n]=Ma.useState(!0),[i,o]=Ma.useState(null),d=Ma.useRef(0),f=Ma.useCallback(async()=>{let u=++d.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(u!==d.current)return;s(r)}catch(r){if(u!==d.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{u===d.current&&n(!1)}},[e]);return Ma.useEffect(()=>{f()},[f]),{status:a,isLoading:t,error:i,refetch:f}}var hc=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function va(e){return hc.has(e.toLowerCase())}function j(e,a,s){let t=va(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function Qa(e){let a=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+a}function Zt(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=va(a)?s:s*100;return Math.round(t)}function gt(e,a){return va(a)?e:e/100}function _n(e){return e.amount_paid??Math.max(0,Qa(e)-(e.credit_applied??0))}import{Fragment as Nc,jsx as Ie,jsxs as He}from"react/jsx-runtime";function Js(e){return e instanceof Ot&&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 ki(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 Cs(){let{api:e,siteToken:a}=se();return Ie(xc,{api:e},a)}function xc({api:e}){let{status:a,error:s}=is(),[t,n]=Oe.useState([]),[i,o]=Oe.useState(null),[d,f]=Oe.useState(null),[u,r]=Oe.useState(!1),[p,b]=Oe.useState(!1),[g,c]=Oe.useState(""),[l,v]=Oe.useState(null),[h,x]=Oe.useState(null),[D,B]=Oe.useState(!1),m=Oe.useRef(0),N=Oe.useCallback(async S=>{let k=++m.current;r(!0),c("");try{let M=await e.getPromos(S);if(k!==m.current)return;n(y=>S?[...y,...M.promos.filter(O=>!y.some(K=>K.id===O.id))]:M.promos),o(M.next_cursor),f(M.checkout_enabled)}catch(M){k===m.current&&c(Js(M))}finally{k===m.current&&r(!1)}},[e]);Oe.useEffect(()=>(N(),()=>{m.current++}),[N]);async function R(S){let k=++m.current;r(!0),c(""),B(!1);try{let M=await e.getPromo(S);k===m.current&&v(M)}catch(M){k===m.current&&c(Js(M))}finally{k===m.current&&r(!1)}}async function A(){if(l){b(!0),r(!0),c("");try{let S=await e.disablePromo(l.id);if(v(S),!["inactive","expired","exhausted"].includes(S.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");B(!1),await N()}catch(S){c(Js(S))}finally{b(!1),r(!1)}}}return h?Ie(wc,{currency:a?.currency??void 0,replaces:h.replaces,onCancel:()=>x(null),onSave:async S=>{let k=h.replaces?await e.replacePromo(h.replaces.id,S):await e.createPromo(S),M=await e.getPromo(k.id);if(M.status==="pending"||M.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");v(M),x(null),await N()}}):He("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[He("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[Ie("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),Ie(w,{disabled:u||!a?.currency,onClick:()=>{c(""),x({})},children:"Create promo code"})]}),Ie("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&&Ie("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."}),!a?.currency&&Ie("p",{className:"af-text-sm",children:s?Js(s):"Connect Stripe and set the payment currency before creating codes."}),g&&He("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[g," ",Ie(w,{variant:"outline",disabled:u,onClick:()=>l?void R(l.id):void N(),children:"Refresh"})]}),l?He("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Ie(w,{variant:"ghost",disabled:p,onClick:()=>{v(null),B(!1),N()},children:"Back to codes"}),He("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),He("p",{children:[ki(l)," \xB7 ",l.status]}),He("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),He("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${j(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),He("p",{className:"af-text-sm",children:["Subscription discount:"," ",l.duration==="repeating"?`${l.duration_in_months} months`:l.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),Ie("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),He("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{variant:"outline",disabled:u,onClick:()=>void R(l.id),children:"Refresh details"}),Ie(w,{variant:"outline",disabled:u||l.status==="pending"||l.status==="unavailable"||!a?.currency,onClick:()=>x({replaces:l}),children:"Replace with new code"}),Ie(w,{variant:"outline",disabled:u||!["active","pending","unavailable"].includes(l.status),onClick:()=>B(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),D&&He("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[He("p",{className:"af-text-sm",children:[l.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${l.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),Ie(w,{disabled:u,onClick:()=>void A(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Ie(w,{variant:"ghost",disabled:u,onClick:()=>B(!1),children:"Cancel"})]})]}):He(Nc,{children:[t.map(S=>He("button",{type:"button",disabled:u,onClick:()=>void R(S.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[He("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Ie("span",{className:"af-font-semibold af-break-all",children:S.code}),Ie("span",{className:"af-text-sm",children:S.status})]}),He("div",{className:"af-text-sm",children:[ki(S)," \xB7"," ",S.times_redeemed==null?"Usage unavailable":`${S.times_redeemed} redemptions`]})]},S.id)),!u&&!g&&t.length===0&&Ie("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&&Ie("p",{role:"status",children:"Loading promo codes\u2026"}),i&&Ie(w,{variant:"outline",disabled:u,onClick:()=>void N(i),children:"Load more"})]})]})}function wc({currency:e,replaces:a,onCancel:s,onSave:t}){let[n,i]=Oe.useState(""),[o,d]=Oe.useState(a?.name??""),[f,u]=Oe.useState(a?.amount_off!=null?"fixed":"percent"),[r,p]=Oe.useState(a?.percent_off?.toString()??(a?.amount_off!=null&&e?String(gt(a.amount_off,e)):"")),[b,g]=Oe.useState(a?.minimum_amount!=null&&e?String(gt(a.minimum_amount,e)):""),[c,l]=Oe.useState(()=>{if(!a?.expires_at)return"";let G=new Date(a.expires_at);return Number.isFinite(G.getTime())?new Date(G.getTime()-G.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[v,h]=Oe.useState(a?.max_redemptions?.toString()??""),[x,D]=Oe.useState(a?.duration??"once"),[B,m]=Oe.useState(a?.duration_in_months?.toString()??"3"),[N,R]=Oe.useState(null),[A,S]=Oe.useState(!1),[k,M]=Oe.useState(""),y=Oe.useRef(!1),O=e&&va(e)?"1":"0.01";async function K(G){if(G.preventDefault(),y.current)return;M("");let Z=N;if(!Z){if(!e){M("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){M("Choose a different code for the replacement.");return}let q=Zt(r,e),ne=b?Zt(b,e):null;if(f==="fixed"&&(!q||q>999999999999)||b&&(!ne||ne>999999999999)){M("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){M("Choose a future expiry.");return}Z={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:x,...f==="percent"?{percent_off:Number(r)}:{amount_off:q,currency:e},...b?{minimum_amount:ne,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...v?{max_redemptions:Number(v)}:{},...x==="repeating"?{duration_in_months:Number(B)}:{}},R(Z)}y.current=!0,S(!0);try{await t(Z)}catch(q){M(Js(q)),q instanceof Ot&&q.status>=400&&q.status<500&&q.details?.retryable!==!0&&R(null)}finally{y.current=!1,S(!1)}}let V=(G,Z,q,ne={})=>He("label",{className:"af-grid af-gap-1 af-text-sm",children:[G,Ie(ge,{"aria-label":G,value:Z,onChange:W=>q(W.target.value),...ne})]}),ce="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return He("form",{onSubmit:K,className:"af-max-w-xl af-space-y-4","aria-label":a?"Replace promo code":"Create promo code",children:[Ie("h3",{className:"af-text-lg af-font-semibold",children:a?`Replace ${a.code}`:"Create promo code"}),a&&Ie("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."}),He("fieldset",{disabled:A||!!N,className:"af-grid af-gap-4",children:[V("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),V("Name",o,d,{required:!0,maxLength:40}),He("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",He("select",{"aria-label":"Discount type",className:ce,value:f,onChange:G=>u(G.target.value),children:[Ie("option",{value:"percent",children:"Percentage"}),He("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),V("Discount",r,p,{type:"number",required:!0,min:f==="percent"?"0.01":O,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":O}),V("Minimum order amount",b,g,{type:"number",min:O,step:O,placeholder:e?.toUpperCase()}),He("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."]}),V("Expires at (local time)",c,l,{type:"datetime-local",step:1}),V("Maximum redemptions",v,h,{type:"number",min:1,max:1e6,step:1}),He("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",He("select",{"aria-label":"Subscription duration",className:ce,value:x,onChange:G=>D(G.target.value),children:[Ie("option",{value:"once",children:"First invoice only"}),Ie("option",{value:"forever",children:"Every invoice"}),Ie("option",{value:"repeating",children:"Number of months"})]})]}),x==="repeating"&&V("Months",B,m,{type:"number",required:!0,min:1,max:36,step:1})]}),k&&Ie("p",{role:"alert",className:"af-text-sm af-text-destructive",children:k}),N&&!A&&He("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",Ie("span",{className:"af-break-all",children:N.request_id})]}),He("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{type:"submit",disabled:A,children:A?"Saving\u2026":N?"Retry same request":a?"Create replacement":"Create code"}),Ie(w,{type:"button",variant:"ghost",disabled:A||!!N,onClick:s,children:"Cancel"})]})]})}import*as Os from"react";import{ArrowLeft as ju,FileText as Gu,Package as Wu,Receipt as Ku,Settings as Zu,Users as Ju}from"lucide-react";import*as Rn from"react";import{Package as Sc,Pencil as _c,Plus as Ei,Trash2 as Rc}from"lucide-react";import{jsx as $e,jsxs as Ft}from"react/jsx-runtime";function Pc(e){if(e.allow_custom_amount){let a=e.min_amount!==null?j(e.min_amount,e.currency):"?",s=e.max_amount!==null?j(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":j(e.unit_amount,e.currency)}function Cc(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Pn({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:d}=e,[f,u]=Rn.useState(null),[r,p]=Rn.useState(!1),[b,g]=Rn.useState(null),c=async()=>{if(f)try{p(!0),g(null),await d(f.id),u(null)}catch(l){g(l instanceof Error?l.message:"Failed to delete product")}finally{p(!1)}};return i?$e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:$e("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?$e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Ft("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Ft("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[$e(Sc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ft("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",$e("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Ft(w,{variant:"outline",onClick:()=>s?.(),children:[$e(Ei,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Ft("div",{className:t,children:[$e("div",{className:"af-flex af-justify-end af-mb-4",children:Ft(w,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[$e(Ei,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Ft(Be,{children:[$e(Fe,{children:Ft(pe,{children:[$e($,{children:"Name"}),$e($,{children:"Price"}),$e($,{children:"Fulfillment"}),$e($,{children:"Status"}),$e($,{className:"af-text-right",children:"Actions"})]})}),$e(Me,{children:n.map(l=>Ft(pe,{children:[$e(U,{className:"af-font-medium",children:l.name}),$e(U,{children:Pc(l)}),$e(U,{className:"af-text-muted-foreground",children:Cc(l)}),$e(U,{children:$e(te,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),$e(U,{className:"af-text-right",children:Ft("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ft(w,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[$e(_c,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Ft(w,{variant:"ghost",size:"sm",onClick:()=>{g(null),u(l)},children:[$e(Rc,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),$e(Ba,{open:!!f,onOpenChange:l=>{!l&&!r&&u(null)},children:Ft(_a,{children:[Ft(Ra,{children:[$e(Ca,{children:"Delete product?"}),Ft(Ta,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),b&&$e("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),Ft(Pa,{children:[$e(w,{variant:"outline",onClick:()=>u(null),disabled:r,children:"Cancel"}),$e(w,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as Je from"react";import{FileText as kc,Link2 as Ec,Loader2 as Di,Plus as Ac,Upload as Ic,X as Dc}from"lucide-react";import*as vt from"react";import{Loader2 as Ai,Plus as Rr,Trash2 as Ii,X as Tc}from"lucide-react";import{jsx as Y,jsxs as de}from"react/jsx-runtime";function Pr(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function Cn({productId:e,currency:a,className:s}){let{api:t}=se(),n=va(a)?"1":"0.01",[i,o]=vt.useState(null),[d,f]=vt.useState(!0),[u,r]=vt.useState(null),[p,b]=vt.useState(null),[g,c]=vt.useState(!1),l=vt.useRef(!0);vt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let v=vt.useCallback(async()=>{try{let P=await t.getProduct(e);if(!l.current)return;o(P)}catch(P){if(!l.current)return;r(P instanceof Error?P.message:"Failed to load product")}finally{l.current&&f(!1)}},[t,e]);vt.useEffect(()=>{v()},[v]);let h=async P=>{b(null),c(!0);try{await P(),await v()}catch(L){l.current&&b(L instanceof Error?L.message:"Something went wrong")}finally{l.current&&c(!1)}},[x,D]=vt.useState(""),[B,m]=vt.useState(""),[N,R]=vt.useState({}),A=()=>h(async()=>{let P=x.trim(),L=B.split(",").map(I=>I.trim()).filter(Boolean);if(!P)throw new Error("Option name is required");if(L.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:P,values:L}),l.current&&(D(""),m(""))}),S=P=>h(async()=>{let L=(N[P.id]??"").trim();if(!L)throw new Error("Enter a value");await t.updateOption(P.id,{add_values:[L]}),l.current&&R(I=>({...I,[P.id]:""}))}),k=(P,L)=>h(()=>t.updateOption(P.id,{remove_values:[L]})),M=P=>h(()=>t.deleteOption(P.id)),[y,O]=vt.useState(null),[K,V]=vt.useState(null),[ce,G]=vt.useState(!1),[Z,q]=vt.useState(null),ne=i?.options??[],W=i?.variants??[],he=()=>{V(null),O({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ne.map(P=>[P.id,P.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Ze=P=>{V(null);let L=P.inventory?.on_hand??0,I=L<0?"":String(L);O({variant:P,title:P.title??"",sku:P.sku??"",unitAmount:P.unit_amount!=null?String(gt(P.unit_amount,a)):"",compareAt:P.compare_at_amount!=null?String(gt(P.compare_at_amount,a)):"",active:P.active,optionValues:{},tracked:P.inventory?.tracked??!1,onHand:I,initialOnHand:I,allowBackorder:P.inventory?.allow_backorder??!1})},it=async()=>{if(!y)return;V(null);let P=y.variant?.allow_custom_amount??!1,L=null,I=null;if(!P){if(L=Zt(y.unitAmount,a),L===null||L<=0){V("Enter a valid price");return}if(y.compareAt.trim()&&(I=Zt(y.compareAt,a),I===null||I<=L)){V("Compare-at price must be greater than the price");return}}let ue=y.onHand.trim()!==y.initialOnHand.trim(),me=parseInt(y.onHand,10);if(y.tracked&&ue&&(!Number.isFinite(me)||me<0)){V("On-hand quantity must be zero or more");return}try{if(G(!0),y.variant)await t.updateVariant(y.variant.id,{title:y.title.trim()||null,sku:y.sku.trim()||null,...P?{}:{unit_amount:L,compare_at_amount:I},active:y.active}),await t.setVariantInventory(y.variant.id,{tracked:y.tracked,on_hand:y.tracked&&ue?me:void 0,allow_backorder:y.allowBackorder});else{let _e={};for(let Te of ne){let tt=y.optionValues[Te.id];if(!tt){V(`Choose a ${Te.title}`),G(!1);return}_e[Te.title]=tt}await t.createVariant(e,{title:y.title.trim()||null,sku:y.sku.trim()||null,unit_amount:L,compare_at_amount:I,active:y.active,option_values:ne.length>0?_e:void 0,inventory:y.tracked?{tracked:!0,on_hand:me,allow_backorder:y.allowBackorder}:{tracked:!1,allow_backorder:y.allowBackorder}})}await v(),l.current&&O(null)}catch(_e){if(l.current&&V(_e instanceof Error?_e.message:"Failed to save variant"),y.variant)try{let Te=await t.getProduct(e);l.current&&o(Te)}catch{}}finally{l.current&&G(!1)}},Pe=()=>h(async()=>{Z&&(await t.deleteVariant(Z.id),l.current&&q(null))}),je=y?.variant?.allow_custom_amount??!1,et=y?.variant!=null&&y.variant.option_values.length===0&&ne.length>0&&!y.variant.active,xe=y?.variant?.inventory!=null&&y.variant.inventory.on_hand<0?-y.variant.inventory.on_hand:null;function Et(P){let L=P.inventory;if(!L||!L.tracked)return Y("span",{className:"af-text-muted-foreground",children:"Unlimited"});let I=L.available??L.on_hand;return I<0?de("span",{children:[-I," backordered"]}):de("span",{children:[I," in stock",L.allow_backorder&&Y("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return d?Y("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:Y(Ai,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):u?Y("div",{className:s,children:Y("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})}):de("div",{className:`af-space-y-6 ${s||""}`,children:[de("div",{className:"af-space-y-3",children:[de("div",{children:[Y(ve,{children:"Options"}),Y("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."})]}),ne.length>0&&Y("div",{className:"af-space-y-3",children:ne.map(P=>de("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[de("div",{className:"af-flex af-items-center af-justify-between",children:[Y("span",{className:"af-text-sm af-font-medium",children:P.title}),Y(w,{variant:"ghost",size:"sm",onClick:()=>M(P),disabled:g,children:Y(Ii,{className:"af-h-4 af-w-4"})})]}),Y("div",{className:"af-flex af-flex-wrap af-gap-2",children:P.values.map(L=>de(te,{variant:"secondary",className:"af-gap-1",children:[L.value,Y("button",{type:"button",onClick:()=>k(P,L.value),className:"af-ml-1 hover:af-text-destructive",disabled:g,title:"Remove value",children:Y(Tc,{className:"af-h-3 af-w-3"})})]},L.id))}),de("div",{className:"af-flex af-gap-2",children:[Y(ge,{value:N[P.id]??"",onChange:L=>R(I=>({...I,[P.id]:L.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),S(P))},disabled:g}),Y(w,{type:"button",variant:"outline",size:"sm",onClick:()=>S(P),disabled:g||!(N[P.id]??"").trim(),children:Y(Rr,{className:"af-h-4 af-w-4"})})]})]},P.id))}),de("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[de("div",{className:"af-space-y-1",children:[Y(ve,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),Y(ge,{id:"new-option-title",value:x,onChange:P=>D(P.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:g})]}),de("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[Y(ve,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),Y(ge,{id:"new-option-values",value:B,onChange:P=>m(P.target.value),placeholder:"S, M, L",disabled:g})]}),de(w,{type:"button",variant:"outline",onClick:A,disabled:g||!x.trim()||!B.trim(),children:[Y(Rr,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),de("div",{className:"af-space-y-3",children:[de("div",{className:"af-flex af-items-center af-justify-between",children:[Y(ve,{children:"Variants"}),de(w,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:g||ne.length===0,children:[Y(Rr,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ne.length===0&&Y("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),W.length===0?Y("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):de(Be,{children:[Y(Fe,{children:de(pe,{children:[Y($,{children:"Variant"}),Y($,{children:"SKU"}),Y($,{children:"Price"}),Y($,{children:"Stock"}),Y($,{children:"Status"}),Y($,{className:"af-text-right",children:"Actions"})]})}),Y(Me,{children:W.map(P=>de(pe,{children:[Y(U,{className:"af-font-medium",children:Pr(P)}),Y(U,{className:"af-text-muted-foreground",children:P.sku||"-"}),Y(U,{children:P.unit_amount!=null?de("span",{children:[P.compare_at_amount!=null&&Y("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(P.compare_at_amount,P.currency)}),j(P.unit_amount,P.currency)]}):P.allow_custom_amount?Y("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),Y(U,{children:Et(P)}),Y(U,{children:Y(te,{variant:P.active?"success":"secondary",children:P.active?"Active":"Inactive"})}),Y(U,{className:"af-text-right",children:de("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[Y(w,{variant:"ghost",size:"sm",onClick:()=>Ze(P),disabled:g,children:"Edit"}),Y(w,{variant:"ghost",size:"icon",onClick:()=>q(P),disabled:g,title:"Delete variant",children:Y(Ii,{className:"af-h-4 af-w-4"})})]})})]},P.id))})]})]}),p&&Y("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),Y(Ba,{open:y!==null,onOpenChange:P=>{!P&&!ce&&O(null)},children:de(_a,{children:[de(Ra,{children:[Y(Ca,{children:y?.variant?"Edit variant":"Add variant"}),Y(Ta,{children:"Price, markdown, and stock live on the variant."})]}),y&&de("div",{className:"af-space-y-3",children:[y.variant?y.variant.option_values.length>0&&de("div",{className:"af-text-sm",children:[Y("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Pr(y.variant)]}):ne.map(P=>de("div",{className:"af-space-y-1",children:[Y(ve,{className:"af-text-xs af-text-muted-foreground",children:P.title}),de(da,{value:y.optionValues[P.id]??"",onValueChange:L=>O(I=>I&&{...I,optionValues:{...I.optionValues,[P.id]:L}}),children:[Y(na,{children:Y(fa,{placeholder:`Choose ${P.title}`})}),Y(ra,{children:P.values.map(L=>Y(Ke,{value:L.value,children:L.value},L.id))})]})]},P.id)),je?de("div",{className:"af-space-y-1",children:[Y(ve,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),Y("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):de("div",{className:"af-flex af-gap-3",children:[de("div",{className:"af-space-y-1",children:[de(ve,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),Y(ge,{id:"variant-price",type:"number",min:"0",step:n,value:y.unitAmount,onChange:P=>O(L=>L&&{...L,unitAmount:P.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),de("div",{className:"af-space-y-1",children:[Y(ve,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),Y(ge,{id:"variant-compare",type:"number",min:"0",step:n,value:y.compareAt,onChange:P=>O(L=>L&&{...L,compareAt:P.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),de("div",{className:"af-space-y-1",children:[Y(ve,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),Y(ge,{id:"variant-sku",value:y.sku,onChange:P=>O(L=>L&&{...L,sku:P.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),de("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Y("input",{type:"checkbox",checked:y.tracked,onChange:P=>O(L=>L&&{...L,tracked:P.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),y.tracked&&de("div",{className:"af-space-y-1 af-pl-6",children:[de("div",{className:"af-flex af-items-end af-gap-3",children:[de("div",{className:"af-space-y-1",children:[Y(ve,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),Y(ge,{id:"variant-onhand",type:"number",min:"0",step:"1",value:y.onHand,onChange:P=>O(L=>L&&{...L,onHand:P.target.value}),placeholder:xe!=null?"0":void 0,className:"af-w-[100px]"})]}),de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[Y("input",{type:"checkbox",checked:y.allowBackorder,onChange:P=>O(L=>L&&{...L,allowBackorder:P.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),xe!=null&&de("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",xe," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),de("div",{className:"af-space-y-1",children:[de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Y("input",{type:"checkbox",checked:y.active,onChange:P=>O(L=>L&&{...L,active:P.target.checked}),className:"af-h-4 af-w-4",disabled:et}),"Active (buyers can purchase this variant)"]}),et&&Y("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),K&&Y("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:K})]}),de(Pa,{children:[Y(w,{variant:"outline",onClick:()=>O(null),disabled:ce,children:"Cancel"}),de(w,{onClick:it,disabled:ce,children:[ce?Y(Ai,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?.variant?"Save":"Add variant"]})]})]})}),Y(Ba,{open:Z!==null,onOpenChange:P=>{!P&&!g&&q(null)},children:de(_a,{children:[de(Ra,{children:[Y(Ca,{children:"Delete variant?"}),Y(Ta,{children:Z&&`"${Pr(Z)}" will no longer be purchasable. Past orders are unaffected.`})]}),de(Pa,{children:[Y(w,{variant:"outline",onClick:()=>q(null),disabled:g,children:"Cancel"}),Y(w,{variant:"destructive",onClick:Pe,disabled:g,children:"Delete"})]})]})})]})}import{Fragment as Oc,jsx as fe,jsxs as Re}from"react/jsx-runtime";function Lc(e){if(e===0)return"0 B";let a=1024,s=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(a));return`${parseFloat((e/Math.pow(a,t)).toFixed(1))} ${s[t]}`}function Tn({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:d,attachProductFileFromUrl:f}=e,u=!!a,r=a?.currency??s,p=va(r)?"1":"0.01",b=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[g,c]=Je.useState(!1),[l,v]=Je.useState(null),h=Je.useRef(!0);Je.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);let[x,D]=Je.useState(a?.name??""),[B,m]=Je.useState(a?.description??""),[N,R]=Je.useState(a?.allow_custom_amount?"custom":"fixed"),[A,S]=Je.useState(a?.unit_amount!=null?String(gt(a.unit_amount,r)):""),[k,M]=Je.useState(a?.min_amount!=null?String(gt(a.min_amount,r)):""),[y,O]=Je.useState(a?.max_amount!=null?String(gt(a.max_amount,r)):""),[K,V]=Je.useState(String(a?.max_quantity??10)),ce=Je.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(gt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(gt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(gt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[G,Z]=Je.useState(a?.collect_shipping_address??!1),[q,ne]=Je.useState(a?.active??!0),[W,he]=Je.useState(a?.images??[]),[Ze,it]=Je.useState(""),[Pe,je]=Je.useState(a?.fulfillment??null),[et,xe]=Je.useState(!1),[Et,P]=Je.useState(""),[L,I]=Je.useState(null),ue=Je.useRef(null),me=g||et,_e=()=>{let ie=Ze.trim();if(ie){if(W.includes(ie)){v("This image URL is already added");return}he(Ee=>[...Ee,ie]),it(""),v(null)}},Te=ie=>{he(Ee=>Ee.filter(ot=>ot!==ie))},tt=async()=>{if(v(null),!x.trim()){v("Product name is required");return}let ie=null,Ee=null,ot=null,sa=!u||N!==ce.pricingMode||(N==="fixed"?A!==ce.unitAmount:k!==ce.minAmount||y!==ce.maxAmount),xt=!u||K!==ce.maxQuantity,At=b||N==="fixed";if(!(b||!sa))if(N==="fixed"){if(ie=Zt(A,r),ie===null||ie<=0){v("Enter a valid price");return}}else{if(Ee=Zt(k,r),ot=Zt(y,r),Ee===null||ot===null){v("Enter valid minimum and maximum amounts");return}if(ot<Ee){v("Maximum amount must be at least the minimum amount");return}}let qt=parseInt(K,10);if(At&&xt&&(!Number.isFinite(qt)||qt<1)){v("Max quantity must be at least 1");return}try{c(!0);let Ve;if(u&&a){let at={name:x.trim(),description:B.trim()||null,images:W,collect_shipping_address:G,active:q};!b&&sa&&(at.allow_custom_amount=N==="custom",N==="fixed"?at.unit_amount=ie:(at.min_amount=Ee,at.max_amount=ot)),At&&xt&&(at.max_quantity=qt),Ve=await o(a.id,at),ce.pricingMode=Ve.allow_custom_amount?"custom":"fixed",ce.unitAmount=Ve.unit_amount!=null?String(gt(Ve.unit_amount,r)):"",ce.minAmount=Ve.min_amount!=null?String(gt(Ve.min_amount,r)):"",ce.maxAmount=Ve.max_amount!=null?String(gt(Ve.max_amount,r)):"",ce.maxQuantity=String(Ve.max_quantity)}else{let at={name:x.trim(),allow_custom_amount:N==="custom",collect_shipping_address:G,active:q};B.trim()&&(at.description=B.trim()),W.length>0&&(at.images=W),N==="fixed"?(at.unit_amount=ie,at.max_quantity=qt):(at.min_amount=Ee,at.max_amount=ot),Ve=await i(at)}if(!h.current)return;je(Ve.fulfillment),t?.(Ve)}catch(Ve){if(!h.current)return;v(Ve instanceof Error?Ve.message:"Failed to save product")}finally{h.current&&c(!1)}},Ue=async ie=>{let Ee=ie.target.files?.[0];if(!(!Ee||!a))try{xe(!0),I(null);let ot=await d(a.id,Ee);if(!h.current)return;je(ot.fulfillment),t?.(ot)}catch(ot){if(!h.current)return;I(ot instanceof Error?ot.message:"Failed to upload file")}finally{h.current&&(xe(!1),ue.current&&(ue.current.value=""))}},Ge=async()=>{let ie=Et.trim();if(!(!ie||!a))try{xe(!0),I(null);let Ee=await f(a.id,ie);if(!h.current)return;je(Ee.fulfillment),P(""),t?.(Ee)}catch(Ee){if(!h.current)return;I(Ee instanceof Error?Ee.message:"Failed to fetch file")}finally{h.current&&xe(!1)}};return Re("div",{className:`af-space-y-6 ${n||""}`,children:[Re("div",{className:"af-space-y-2",children:[fe(ve,{htmlFor:"product-name",children:"Name"}),fe(ge,{id:"product-name",value:x,onChange:ie=>D(ie.target.value),placeholder:"My product"})]}),Re("div",{className:"af-space-y-2",children:[fe(ve,{htmlFor:"product-description",children:"Description"}),fe("textarea",{id:"product-description",value:B,onChange:ie=>m(ie.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"})]}),Re("div",{className:"af-space-y-2",children:[fe(ve,{children:"Pricing"}),b?fe("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Re(Oc,{children:[Re(da,{value:N,onValueChange:ie=>R(ie),children:[fe(na,{className:"af-w-[260px]",children:fe(fa,{})}),Re(ra,{children:[fe(Ke,{value:"fixed",children:"Fixed price"}),fe(Ke,{value:"custom",children:"Buyer chooses the amount"})]})]}),N==="fixed"?fe("div",{className:"af-flex af-items-end af-gap-3",children:Re("div",{className:"af-space-y-1",children:[Re(ve,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),fe(ge,{id:"product-price",type:"number",min:"0",step:p,value:A,onChange:ie=>S(ie.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Re("div",{className:"af-space-y-1",children:[Re("div",{className:"af-flex af-items-end af-gap-3",children:[Re("div",{className:"af-space-y-1",children:[Re(ve,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),fe(ge,{id:"product-min-amount",type:"number",min:"0",step:p,value:k,onChange:ie=>M(ie.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Re("div",{className:"af-space-y-1",children:[Re(ve,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),fe(ge,{id:"product-max-amount",type:"number",min:"0",step:p,value:y,onChange:ie=>O(ie.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),fe("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."})]}),Re("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",r.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||N==="fixed")&&Re("div",{className:"af-space-y-1",children:[fe(ve,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),fe(ge,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:K,onChange:ie=>V(ie.target.value),className:"af-w-[140px]"})]})]}),Re("div",{className:"af-space-y-2",children:[fe(ve,{children:"Images"}),fe("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Re("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[W.map(ie=>Re(te,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[fe("span",{className:"af-truncate",children:ie}),fe("button",{type:"button",onClick:()=>Te(ie),className:"af-ml-1 hover:af-text-destructive",disabled:g,children:fe(Dc,{className:"af-h-3 af-w-3"})})]},ie)),W.length===0&&fe("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Re("div",{className:"af-flex af-gap-2",children:[fe(ge,{type:"url",value:Ze,onChange:ie=>it(ie.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),_e())},disabled:g}),fe(w,{type:"button",variant:"outline",onClick:_e,disabled:!Ze.trim()||g,children:fe(Ac,{className:"af-h-4 af-w-4"})})]})]}),Re("div",{className:"af-space-y-2",children:[fe(ve,{children:"Digital File"}),fe("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?Re("div",{className:"af-space-y-3",children:[Pe?.type==="download"&&Re("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[fe(kc,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),fe("span",{className:"af-text-sm",children:Pe.filename}),Pe.size!=null&&Re("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Lc(Pe.size),")"]})]}),Pe?.type==="redirect"&&Pe.url&&Re("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[fe(Ec,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Re("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Pe.url]})]}),Re("div",{className:"af-flex af-items-center af-gap-2",children:[fe("input",{ref:ue,type:"file",onChange:Ue,className:"af-hidden",disabled:me}),Re(w,{type:"button",variant:"outline",size:"sm",onClick:()=>ue.current?.click(),disabled:me,children:[et?fe(Di,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):fe(Ic,{className:"af-h-4 af-w-4 af-mr-1"}),Pe?.type==="download"?"Replace file":"Upload file"]}),fe("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),fe(ge,{type:"url",value:Et,onChange:ie=>P(ie.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:et}),fe(w,{type:"button",variant:"outline",size:"sm",onClick:Ge,disabled:!Et.trim()||me,children:"Fetch from URL"})]}),L&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:L})]}):fe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Re("div",{className:"af-space-y-2",children:[fe(ve,{children:"Settings"}),Re("div",{className:"af-space-y-2",children:[Re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[fe("input",{type:"checkbox",checked:G,onChange:ie=>Z(ie.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Re("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[fe("input",{type:"checkbox",checked:q,onChange:ie=>ne(ie.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),u&&a&&Re("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[fe(ve,{children:"Options & Variants"}),fe(Cn,{productId:a.id,currency:r})]}),l&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),fe("div",{className:"af-flex af-items-center af-gap-2",children:Re(w,{type:"button",onClick:tt,disabled:me,children:[g?fe(Di,{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 ru,ChevronRight as qi,Loader2 as iu,Receipt as ou,Search as lu,SlidersHorizontal as cu}from"lucide-react";import*as lt from"react";var Bc=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function kn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=se(),[t,n]=lt.useState([]),[i,o]=lt.useState(0),[d,f]=lt.useState(!0),[u,r]=lt.useState(null),[p,b]=lt.useState(0),[g,c]=lt.useState(e),[l,v]=lt.useState(void 0),[h,x]=lt.useState(""),[D,B]=lt.useState(""),[m,N]=lt.useState(""),[R,A]=lt.useState(!1),[S,k]=lt.useState(!1),[M,y]=lt.useState(void 0),O=M?M.join(","):"",K=lt.useMemo(()=>{if(!O)return;let Z=new Set(O.split(","));return Bc.filter(q=>!Z.has(q))},[O]),V=lt.useRef(0),ce=lt.useCallback(async()=>{let Z=++V.current;try{f(!0),r(null);let q={limit:g,offset:p*g};l?q.status=l:K?q.excludeStatus=K:R||(q.excludeStatus=["pending","expired"]),h.trim()&&(q.customerEmail=h.trim()),D.trim()&&(q.from=D.trim()),m.trim()&&(q.to=m.trim()),S&&(q.unfulfilledOnly=!0);let ne=await s.getOrders(q);if(Z!==V.current)return;n(ne.orders),o(ne.total)}catch(q){if(Z!==V.current)return;r(q instanceof Error?q:new Error("Failed to fetch orders"))}finally{Z===V.current&&f(!1)}},[s,p,g,l,K,R,S,h,D,m,a]);lt.useEffect(()=>{ce()},[ce]);let G=Math.ceil(i/g);return{orders:t,total:i,isLoading:d,error:u,page:p,pageSize:g,hasNextPage:p<G-1,hasPreviousPage:p>0,setPage:b,setPageSize:Z=>{c(Z),b(0)},status:l,setStatus:Z=>{v(Z),b(0)},statusIn:M,setStatusIn:Z=>{y(Z&&Z.length>0?Z:void 0),b(0)},customerEmail:h,setCustomerEmail:Z=>{x(Z),b(0)},from:D,setFrom:Z=>{B(Z),b(0)},to:m,setTo:Z=>{N(Z),b(0)},showAbandoned:R,setShowAbandoned:Z=>{A(Z),b(0)},unfulfilledOnly:S,setUnfulfilledOnly:Z=>{k(Z),b(0)},clearFilters:()=>{v(void 0),y(void 0),A(!1),k(!1),x(""),B(""),N(""),b(0)},refetch:ce}}import*as dt from"react";import{ArrowLeft as $c,Check as Bi,ChevronLeft as Uc,ChevronRight as Vc,ClipboardCopy as Hc,Copy as zc,Download as qc,Loader2 as Dn,Mail as Fi,MoreHorizontal as jc,Package as Gc,RotateCcw as Wc,Truck as Kc,Undo2 as Mi}from"lucide-react";import*as Li from"react";import*as $a from"@radix-ui/react-popover";import{jsx as Cr}from"react/jsx-runtime";var En=$a.Root,An=$a.Trigger;var Ys=Li.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>Cr($a.Portal,{children:Cr("div",{className:"aifeatures-admin",children:Cr($a.Content,{ref:n,align:a,sideOffset:s,className:J("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...t})})}));Ys.displayName=$a.Content.displayName;import{jsx as In}from"react/jsx-runtime";var Fc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Mc(e){return Fc[e]??e}function Oi(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 bs({status:e,className:a}){return In(te,{variant:Oi(e),className:a,children:Mc(e)})}function ys({status:e}){return In(bs,{status:e})}function Ts({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?In(te,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?In(te,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Xa(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as au,jsx as C,jsxs as X}from"react/jsx-runtime";var Hi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",hs="af-text-xs af-text-muted-foreground";function Tr(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Zc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zi(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 Ln=24,Jc=["paid","partially_refunded"],Yc=["paid","partially_refunded","disputed"],Qc=/^[A-Za-z0-9 _-]*$/,$i=100;function Ar(e,a,s,t,n){let i=Jc.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="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."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${Ln} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Ln} tries used). Nothing is being retried while the order is ${t.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:a==="failed_final"?s<Ln&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<Ln&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:a==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${t==="refunded"?"because the order was refunded":t==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:a==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(a),variant:"secondary",detail:null}}function Ui({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:d}){if(d)return X("div",{children:[C(Oa,{deliveries:[d]}),o&&C("div",{className:"af-mt-2",children:o})]});let f=Ar(n,s,t,i,a);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:[C("div",{className:"af-text-sm",children:e}),a&&C("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:a})]}),C(te,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&C("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),o&&C("div",{className:"af-mt-2",children:o})]})}function Vi(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=Zc(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&a.push(i)}let t=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");t&&a.push(t),typeof s.country=="string"&&s.country&&a.push(s.country)}return a.length>0?a:Object.entries(e).map(([t,n])=>`${t}: ${zi(n)}`)}function Xc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ir({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=dt.useState(!1);if(!Xc())return null;let d=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},f=i?C(Bi,{className:"af-h-3 af-w-3"}):C(zc,{className:"af-h-3 af-w-3"});return n==="icon"?C(w,{variant:"ghost",size:"icon",className:J("af-h-6 af-w-6 af-shrink-0",t),onClick:d,title:a,"aria-label":a,children:f}):X(w,{variant:"outline",size:"sm",className:t,onClick:d,"aria-label":a,children:[i?C(Bi,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):C(Hc,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function kr({label:e,value:a}){return X("div",{children:[C("div",{className:hs,children:e}),X("div",{className:"af-flex af-items-center af-gap-1",children:[C("code",{className:"af-text-xs af-font-mono af-break-all",children:a}),C(Ir,{value:a,label:`Copy ${e}`})]})]})}function eu({src:e}){let[a,s]=dt.useState(!1);return!e||a?C("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:C(Gc,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):C("img",{src:e,alt:"","aria-hidden":"true",onError:()=>s(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Ua({title:e,action:a,children:s,className:t}){return X("section",{className:J("af-rounded-lg af-border af-p-4",t),children:[X("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[C("h4",{className:Hi,children:e}),a]}),C("div",{className:"af-mt-3",children:s})]})}function Jt({label:e,emphasis:a,divider:s,children:t}){return X("div",{className:J("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[C("span",{className:a?"af-text-base af-font-semibold":hs,children:e}),C("span",{className:J("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Er({onSelect:e,disabled:a,icon:s,children:t}){return X(w,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:a,children:[C("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),t]})}function tu(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?a.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${j(_n(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),t=s?vn(s):Ar("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);a.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),t=s?vn(s):Ar("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);a.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&a.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&&a.push({key:"refunded",text:`Refunded ${j(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&a.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),a}function On({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:d=!1,hasNextOrder:f=!1}){let{api:u}=se(),[r,p]=dt.useState(e),[b,g]=dt.useState(null),[c,l]=dt.useState(null),[v,h]=dt.useState(!1),[x,D]=dt.useState(!1),[B,m]=dt.useState(!1),[N,R]=dt.useState(!1),[A,S]=dt.useState(""),[k,M]=dt.useState(!1),[y,O]=dt.useState(null),[K,V]=dt.useState(!1),[ce,G]=dt.useState(""),[Z,q]=dt.useState([]),[ne,W]=dt.useState(!1),[he,Ze]=dt.useState(!1),[it,Pe]=dt.useState(null);dt.useEffect(()=>{p(e)},[e]);let je=E=>{let Ae=E.id===r.id&&E.email_deliveries===void 0?{...E,email_deliveries:r.email_deliveries}:E;p(Ae),t?.(Ae)},et=Object.entries(r.metadata??{}),xe=Math.max(0,_n(r)-r.amount_refunded),Et=(r.status==="paid"||r.status==="partially_refunded")&&xe>0,P=r.exclusive_tax_total!=null,L=E=>typeof E.amountNet=="number"?E.amountNet+(E.exclusiveTax??0):(typeof E.unitAmount=="number"?E.unitAmount:0)*(typeof E.quantity=="number"&&E.quantity>0?E.quantity:1),I=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),ue=Z.reduce((E,Ae)=>E+L(r.line_items[Ae]??{}),0)+(ne?I:0),me=r.tax_total??0,_e=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((E,Ae)=>E+(Ae.exclusiveTax??0),0)),Te=P?ne&&I>0?_e:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&me>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,me-(r.tax_refunded??0)),Math.round(me*ue/(r.amount_total+(r.shipping_total??0)))):0,tt=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(ue+Te,xe):ue+Te,Ue=Z.length>0||ne,Ge=Ue?tt:Zt(ce,r.currency),ie=va(r.currency)?"1":"0.01",Ee=async()=>{try{h(!0),g(null),l(null),await u.resendOrderReceipt(r.id);let E=await u.getOrder(r.id);je(E),l("Receipt email queued.")}catch(E){g(E instanceof Error?E.message:"Failed to resend receipt")}finally{h(!1)}},ot=async()=>{try{D(!0),g(null),l(null);let E=await u.resetOrderDownloads(r.id);je(E),m(!1),l("Download count reset.")}catch(E){g(E instanceof Error?E.message:"Failed to reset downloads")}finally{D(!1)}},sa=r.line_items.some(E=>E.collectShippingAddress===!0&&!E.refunded&&!E.unavailableReason),xt=typeof r.merchant_fulfilled_at=="string",At=Yc.includes(r.status)||r.status==="refunded"&&r.line_items.some(E=>E.collectShippingAddress===!0&&E.amountNet===0&&!E.refunded&&!E.unavailableReason),qt=A.trim(),Ve=Qc.test(qt)&&qt.length<=$i,at=async E=>{try{M(!0),O(null),l(null);let Ae=await u.setOrderFulfillment(r.id,{fulfilled:E,...E&&qt?{trackingNumber:qt}:{}});je(Ae),S(""),l(E?"Marked as shipped.":"Marked as not shipped.")}catch(Ae){Ae instanceof Ot&&Ae.status===409?O(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):O(Ae instanceof Error?Ae.message:"Failed to update the order")}finally{M(!1)}},as=()=>{Pe(null),G(String(gt(xe,r.currency))),q([]),W(!1),V(!0)},Hs=E=>q(Ae=>Ae.includes(E)?Ae.filter(Gt=>Gt!==E):[...Ae,E]),Lt=async(E,Ae)=>{if(s)try{Ze(!0),Pe(null),await s(r,E,Ae);let Gt=await u.getOrder(r.id);je(Gt),V(!1),l("Refund issued.")}catch(Gt){Pe(Gt instanceof Error?Gt.message:"Refund failed")}finally{Ze(!1)}},un=async()=>{if(Ue){if(tt<=0){Pe("The lines you picked were charged nothing");return}if(tt>xe){Pe(`That selection exceeds the refundable remainder (${j(xe,r.currency)})`);return}await Lt(tt,{...Z.length>0?{line_items:[...Z].sort((Ae,Gt)=>Ae-Gt)}:{},...ne?{shipping:!0}:{}});return}let E=Zt(ce,r.currency);if(E===null||E<=0){Pe("Enter a valid refund amount");return}if(E>xe){Pe(`Amount exceeds the refundable remainder (${j(xe,r.currency)})`);return}await Lt(E,{amount:E})},H=()=>Lt(xe,{full:!0}),We=!r.subscription_history_only&&r.fulfillment_type==="download",z=!r.subscription_history_only&&n&&sa,jt=tu(r),cl=r.shipping_address?Vi(r.shipping_address).join(`
|
|
4
|
+
`):"",ci=r.shipping_total!=null,mr=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),ui=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-mr):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,di=mr>0,ul=ui>0,fi=r.amount_subtotal!=null||ci||di||(r.discount_total??0)>0,zs=[];return r.subscription_history_only||zs.push(C(Er,{icon:v?C(Dn,{className:"af-h-4 af-w-4 af-animate-spin"}):C(Fi,{className:"af-h-4 af-w-4"}),disabled:v||r.fulfillment_status!=="fulfilled",onSelect:()=>{R(!1),Ee()},children:"Resend receipt"},"resend")),We&&zs.push(C(Er,{icon:C(Wc,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{R(!1),m(!0)},children:"Reset download count"},"reset")),Et&&zs.push(X("div",{children:[C(Er,{icon:C(Mi,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{R(!1),as()},children:"Refund\u2026"}),!s&&C("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:a,className:"af-mb-2 af--ml-2",children:[C($c,{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:[C("h3",{className:"af-text-xl af-font-semibold",children:Xa(r)}),C(bs,{status:r.status}),n&&!r.subscription_history_only&&C(Ts,{order:r}),r.is_test&&C(te,{variant:"outline",children:"Test"})]}),X("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Tr(r.created_at)]}),r.is_test&&C("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:[(i||o)&&X("div",{className:"af-flex af-items-center",children:[C(w,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!d,"aria-label":"Previous order",children:C(Uc,{className:"af-h-4 af-w-4"})}),C(w,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!f,"aria-label":"Next order",children:C(Vc,{className:"af-h-4 af-w-4"})})]}),z&&(xt?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",r.merchant_fulfilled_at?` \xB7 ${Tr(r.merchant_fulfilled_at)}`:""]}),At&&X(w,{variant:"ghost",size:"sm",onClick:()=>at(!1),disabled:k,children:[k?C(Dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):C(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):At?X("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[C(ge,{value:A,onChange:E=>S(E.target.value),placeholder:"Tracking number (optional)",maxLength:$i,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),X(w,{variant:"default",className:"af-shrink-0",onClick:()=>at(!0),disabled:k||!Ve,children:[k?C(Dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):C(Kc,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),zs.length>0&&X(En,{open:N,onOpenChange:R,children:[C(An,{asChild:!0,children:C(w,{variant:"outline",size:"icon","aria-label":"More actions",children:C(jc,{className:"af-h-4 af-w-4"})})}),C(Ys,{children:C("div",{className:"af-space-y-0.5",children:zs})})]})]})]}),z&&!xt&&!Ve&&C("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."}),y&&C("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:y}),c&&C("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&&C("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:[r.line_items.length>0&&C(Ua,{title:"Items",children:C("ul",{className:"af-space-y-3",children:r.line_items.map((E,Ae)=>{let Gt=typeof E.name=="string"&&E.name?E.name:"Item",mi=typeof E.quantity=="number"&&E.quantity>0?E.quantity:1,pi=typeof E.unitAmount=="number";return X("li",{className:"af-flex af-items-start af-gap-3",children:[C(eu,{src:typeof E.imageUrl=="string"&&E.imageUrl?E.imageUrl:void 0}),X("div",{className:"af-min-w-0 af-flex-1",children:[X("div",{className:"af-text-sm af-font-medium",children:[Gt,typeof E.variantTitle=="string"&&E.variantTitle&&X("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",E.variantTitle]})]}),X("div",{className:hs,children:[mi," \xD7"," ",pi?j(E.unitAmount,r.currency):"\u2014"]}),E.unavailableReason==="oversold"&&!E.refunded&&C(te,{variant:"secondary",className:"af-mt-1",children:E.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),E.refunded===!0&&C(te,{variant:"secondary",className:"af-mt-1",children:E.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),C("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof E.amountNet=="number"||pi?j(E.amountNet??E.unitAmount*mi,r.currency):"\u2014"})]},Ae)})})}),et.length>0&&C(Ua,{title:"Order details",children:C("dl",{className:"af-space-y-2",children:et.map(([E,Ae])=>X("div",{children:[C("dt",{className:J(hs,"af-capitalize"),children:E.replace(/_/g," ")}),C("dd",{className:"af-text-sm af-break-words",children:zi(Ae)})]},E))})}),C(Ua,{title:"Totals",children:X("div",{className:"af-w-full",children:[fi&&C(Jt,{label:"Subtotal",children:j(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&X(Jt,{label:"Discount",children:["\u2212",j(r.discount_total,r.currency)]}),ci&&C(Jt,{label:"Shipping",children:r.shipping_total===0?"Free":j(r.shipping_total??0,r.currency)}),di&&C(Jt,{label:"Tax",children:j(mr,r.currency)}),C(Jt,{label:"Total",emphasis:!0,divider:fi,children:j(Qa(r),r.currency)}),(r.credit_applied??0)>0&&X(Jt,{label:"Credit applied",children:["\u2212",j(r.credit_applied,r.currency)]}),r.amount_paid!=null&&C(Jt,{label:"Amount paid",children:j(r.amount_paid,r.currency)}),ul&&C(Jt,{label:"incl. tax",children:j(ui,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&X(Jt,{label:"Your price",children:[j(r.base_amount_total,r.base_currency),X("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&X(au,{children:[X(Jt,{label:"Refunded",children:["\u2212",j(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&X("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",j(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),C(Jt,{label:"Net",children:C("span",{className:"af-font-medium",children:j(Math.max(0,_n(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&X(Ua,{title:"Platform fee",children:[r.application_fee_original!=null&&C(Jt,{label:"Collected",children:j(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&C(Jt,{label:"Returned",children:j(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&C(Jt,{label:"Retained",children:j(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&C("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:r.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),C(Ua,{title:"Timeline",children:C("ol",{className:"af-space-y-3",children:jt.map(E=>X("li",{className:"af-flex af-gap-3",children:[C("span",{"aria-hidden":"true",className:J("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",E.tone==="destructive"?"af-bg-destructive":E.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),X("div",{className:"af-min-w-0",children:[C("div",{className:"af-text-sm af-break-words",children:E.text}),E.at&&C("div",{className:"af-text-xs af-text-muted-foreground",children:Tr(E.at)})]})]},E.key))})})]}),X("div",{className:"af-space-y-6",children:[C(Ua,{title:"Customer",children:X("div",{className:"af-space-y-2",children:[X("div",{children:[C("div",{className:hs,children:"Email"}),X("div",{className:"af-flex af-items-center af-gap-1",children:[C("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||C("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&C(Ir,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&X("div",{children:[C("div",{className:hs,children:"Name"}),C("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&X("div",{children:[C("div",{className:hs,children:"Customer record"}),X("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[C("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),C(te,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&C(Ua,{title:"Ship to",action:C(Ir,{value:cl,label:"Copy address",size:"sm",children:"Copy address"}),children:C("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Vi(r.shipping_address).map((E,Ae)=>C("div",{children:E},Ae))})}),r.subscription_history_only?C(Ua,{title:"Subscription history",children:C("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(Ua,{title:"Emails",children:[C(Oa,{deliveries:r.email_deliveries?.filter(E=>!["purchase_receipt","merchant_sale"].includes(E.kind)),problemsOnly:!0,className:"af-mb-4"}),X("div",{className:"af-space-y-4",children:[C(Ui,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(E=>E.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:X(w,{variant:"outline",size:"sm",onClick:Ee,disabled:v||r.fulfillment_status!=="fulfilled",children:[v?C(Dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):C(Fi,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),C(Ui,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(E=>E.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),We&&C(Ua,{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:[C(qc,{className:"af-h-4 af-w-4"}),X("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&C("a",{href:r.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:[C("summary",{className:J(Hi,"af-cursor-pointer af-select-none"),children:"Technical details"}),X("div",{className:"af-mt-3 af-space-y-2",children:[C(kr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&C(kr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&C(kr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),C(Ba,{open:B,onOpenChange:E=>{!E&&!x&&m(!1)},children:X(_a,{children:[X(Ra,{children:[C(Ca,{children:"Reset download count?"}),C(Ta,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),X(Pa,{children:[C(w,{variant:"outline",onClick:()=>m(!1),disabled:x,children:"Cancel"}),C(w,{onClick:ot,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),C(Ba,{open:K,onOpenChange:E=>{!E&&!he&&V(!1)},children:X(_a,{children:[X(Ra,{children:[C(Ca,{children:"Refund order"}),X(Ta,{children:["Refund up to ",j(xe,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),X("div",{className:"af-space-y-4",children:[(r.line_items.length>0||I>0)&&X("div",{className:"af-space-y-2",children:[C(ve,{children:"Items"}),X("div",{className:"af-space-y-2",children:[r.line_items.map((E,Ae)=>{let Gt=E.refunded===!0;return X("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[C("input",{type:"checkbox",checked:Z.includes(Ae),onChange:()=>Hs(Ae),disabled:he||Gt||!!E.unavailableReason||L(E)<=0,className:"af-h-4 af-w-4"}),X("span",{className:Gt?"af-text-muted-foreground af-line-through":void 0,children:[typeof E.name=="string"&&E.name?E.name:"Item",typeof E.variantTitle=="string"&&E.variantTitle?` \u2014 ${E.variantTitle}`:"",typeof E.quantity=="number"&&E.quantity>1?` \xD7 ${E.quantity}`:""]}),C("span",{className:"af-ml-auto af-text-muted-foreground",children:Gt?"Refunded":j(L(E),r.currency)})]},Ae)}),I>0&&X("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[C("input",{type:"checkbox",checked:ne,onChange:E=>W(E.target.checked),disabled:he,className:"af-h-4 af-w-4"}),C("span",{children:"Shipping"}),C("span",{className:"af-ml-auto af-text-muted-foreground",children:j(I,r.currency)})]})]})]}),X("div",{className:"af-space-y-2",children:[X(ve,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),C(ge,{id:"refund-amount",type:"number",min:"0",step:ie,value:Ue?String(gt(tt,r.currency)):ce,onChange:E=>G(E.target.value),disabled:he||Ue}),Ue&&C("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),it&&C("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:it}),X(Pa,{children:[C(w,{variant:"outline",onClick:()=>V(!1),disabled:he,children:"Cancel"}),C(w,{variant:"outline",onClick:H,disabled:he,children:"Refund everything"}),C(w,{variant:"destructive",onClick:un,disabled:he,children:he?"Refunding...":Ge!==null&&Ge>0?`Refund ${j(Ge,r.currency)}`:"Refund"})]})]})})]})}import*as Bn from"react";import{ArrowLeft as su,RefreshCw as nu}from"lucide-react";import{jsx as Yt,jsxs as os}from"react/jsx-runtime";function Nt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=Bn.useRef(null);return Bn.useEffect(()=>{i.current?.focus()},[]),os("div",{className:J("af-bg-background",n),children:[os("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:[Yt("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&os(w,{type:"button",variant:"outline",size:"sm",onClick:a,className:"af-order-first af-shrink-0",children:[Yt(su,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Yt("div",{className:"af-p-4",children:t})]})}function ae({className:e}){return Yt("div",{"aria-hidden":"true",className:J("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function st({label:e,children:a,detail:s,valueClassName:t}){return os("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Yt("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Yt("div",{className:J("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&Yt("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function la({message:e,onRetry:a}){return os("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Yt("span",{children:e}),os(w,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[Yt(nu,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ea({icon:e,children:a}){return os("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Yt("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}function ks({icon:e,heading:a,body:s,action:t,className:n,children:i}){return os("div",{className:J("af-px-6 af-py-10 af-text-center",n),children:[Yt(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),Yt("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:a}),Yt("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),t&&Yt(w,{type:"button",className:"af-mt-4",onClick:t.onClick,children:t.label}),i]})}import{jsx as F,jsxs as ye}from"react/jsx-runtime";var uu={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},ji={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Gi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Wi(e){let a=Array.isArray(e.line_items)?e.line_items:[],s=a[0];if(!s)return"\u2014";let t=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${t} \xD7${n}`:t;return a.length>1?`${i} +${a.length-1} more`:i}function Fn(e){return e.customer?.name||e.customer_name||null}function du({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o,maxRows:d,onViewAll:f}){let u=typeof d=="number",{api:r}=se(),p=kn({refreshKey:s}),{orders:b,total:g,isLoading:c,error:l,page:v,pageSize:h,hasNextPage:x,hasPreviousPage:D,setPage:B,setPageSize:m,customerEmail:N,setCustomerEmail:R,setStatusIn:A,from:S,setFrom:k,to:M,setTo:y,showAbandoned:O,setShowAbandoned:K,setUnfulfilledOnly:V,refetch:ce}=p,[G,Z]=Rt.useState("list"),[q,ne]=Rt.useState(null),[W,he]=Rt.useState(""),[Ze,it]=Rt.useState(""),[Pe,je]=Rt.useState(!u&&n?"needs_shipping":"all"),[et,xe]=Rt.useState(!1),[Et,P]=Rt.useState(!!t&&!u),[L,I]=Rt.useState(null);Rt.useEffect(()=>{if(!t||u)return;let z=!1;return P(!0),I(null),r.getOrder(t).then(jt=>{z||(ne(jt),Z("detail"))}).catch(()=>{z||I("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{z||P(!1)}),()=>{z=!0}},[r,t,u]);let ue=Rt.useCallback(z=>{je(z);let jt=ji[z];A(jt.statusIn),V(jt.unfulfilledOnly)},[A,V]);Rt.useEffect(()=>{n&&!u&&V(!0)},[]);let me=Rt.useRef(!n);Rt.useEffect(()=>{me.current||c||(me.current=!0,b.length===0&&ue("all"))},[c,b.length,ue]);let _e=G==="detail"&&!!q;Rt.useEffect(()=>{o?.(_e)},[_e,o]);let Te=(S?1:0)+(M?1:0)+(O?1:0),tt=Te>0||!!N||!!Ze,Ue=!!S&&!!M&&S>M,Ge=!u||!!f,ie=z=>{if(u){f?.();return}ne(z),Z("detail")},Ee=()=>{Z("list"),ne(null),ce()},ot=z=>{let jt=z.trim();if(!jt){it(""),N&&R("");return}if(jt.startsWith("#")||/^\d+$/.test(jt)){it(jt),N&&R("");return}it(""),R(jt)},sa=()=>{he(""),it(""),R(""),k(""),y(""),K(!1),xe(!1)},xt=Ze.replace(/^#/,"").toLowerCase(),At=xt?b.filter(z=>String(z.order_number??"")===xt||z.id.toLowerCase().startsWith(xt)):b,qt=u?At.slice(0,d):At,Ve=q?b.findIndex(z=>z.id===q.id):-1,at=Ve>0,as=Ve>=0&&Ve<b.length-1;if(Et)return F("div",{className:a,children:F("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:F(iu,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(G==="detail"&&q)return F("div",{className:a,children:F(On,{order:q,onBack:Ee,onRefund:e,onOrderUpdated:z=>ne(z),allowFulfillment:n,onPrevOrder:at?()=>ne(b[Ve-1]):void 0,onNextOrder:as?()=>ne(b[Ve+1]):void 0,hasPrevOrder:at,hasNextOrder:as},q.id)});let Lt=ye("div",{className:"af-mb-4 af-space-y-3",children:[L&&F("p",{className:"af-text-xs af-text-muted-foreground",children:L}),ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[F("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(n?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(z=>F("button",{type:"button","aria-pressed":Pe===z,onClick:()=>ue(z),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Pe===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:uu[z]},z))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[F(lu,{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"}),F(ge,{type:"text",value:W,onChange:z=>he(z.target.value),onBlur:()=>ot(W),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),ot(W))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),ye(w,{type:"button",variant:Te>0?"secondary":"ghost",size:"sm",onClick:()=>xe(z=>!z),"aria-expanded":et,children:[F(cu,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Te>0&&F(te,{variant:"secondary",className:"af-ml-2",children:Te})]}),tt&&F(w,{type:"button",variant:"ghost",size:"sm",onClick:sa,children:"Clear filters"})]}),(et||!!S||!!M)&&ye("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:[F(ve,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),F(ge,{id:"orders-from",type:"date",value:S,max:M||void 0,onChange:z=>k(z.target.value),className:"af-w-[170px]"}),F(ve,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),F(ge,{id:"orders-to",type:"date",value:M,min:S||void 0,onChange:z=>y(z.target.value),className:"af-w-[170px]"}),!ji[Pe].statusIn&&F(w,{type:"button",variant:O?"secondary":"ghost",size:"sm",onClick:()=>K(!O),"aria-pressed":O,children:O?"Hide abandoned":"Show abandoned"})]}),Ue&&F("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(c)return ye("div",{className:a,children:[u?null:Lt,F("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(z=>ye("div",{className:"af-rounded-md af-border af-p-3",children:[ye("div",{className:"af-flex af-items-center af-justify-between",children:[F(ae,{className:"af-h-4 af-w-16"}),F(ae,{className:"af-h-4 af-w-14"})]}),F(ae,{className:"af-mt-2 af-h-3 af-w-40"}),F(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},z))}),F("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[F(Fe,{children:ye(pe,{children:[F($,{children:"Order"}),F($,{children:"Date"}),F($,{children:"Customer"}),F($,{children:"Items"}),F($,{className:"af-text-right",children:"Total"}),F($,{children:"Status"}),F($,{className:"af-w-8"})]})}),F(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(z=>ye(pe,{children:[F(U,{children:F(ae,{className:"af-h-4 af-w-14"})}),F(U,{children:F(ae,{className:"af-h-4 af-w-24"})}),F(U,{children:F(ae,{className:"af-h-4 af-w-40"})}),F(U,{children:F(ae,{className:"af-h-4 af-w-32"})}),F(U,{children:F(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),F(U,{children:F(ae,{className:"af-h-5 af-w-16"})}),F(U,{})]},z))})]})}),F("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return ye("div",{className:a,children:[u?null:Lt,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[F("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),F(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let un=Pe!=="all";if(At.length===0&&v===0)return tt||un?ye("div",{className:a,children:[!u&&Lt,F(Ea,{children:"No orders match these filters."})]}):F("div",{className:a,children:F(ks,{icon:ou,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!u&&F(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>K(!0),children:"Show abandoned checkouts"})})});let H=v*h+1,We=Math.min((v+1)*h,g);return ye("div",{className:a,children:[u?null:Lt,F("div",{className:"af-space-y-3 lg:af-hidden",children:qt.map(z=>ye("button",{type:"button",onClick:()=>ie(z),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[ye("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[F("span",{className:"af-font-medium",children:Xa(z)}),F("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(Qa(z),z.currency)})]}),ye("div",{className:"af-mt-1 af-min-w-0",children:[ye("div",{className:"af-truncate af-text-sm",children:[z.customer_email||F("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Fn(z)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Fn(z)]})]}),F("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Wi(z)}),z.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(z.amount_refunded,z.currency)," refunded"]})]}),ye("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[F(bs,{status:z.status}),F(Ws,{deliveries:z.email_deliveries}),z.is_test&&F(te,{variant:"outline",children:"Test"}),n&&F(Ts,{order:z}),F("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Gi(z.created_at)})]})]},z.id))}),F("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[F(Fe,{children:ye(pe,{children:[F($,{children:"Order"}),F($,{children:"Date"}),F($,{children:"Customer"}),F($,{children:"Items"}),F($,{className:"af-text-right",children:"Total"}),F($,{children:"Status"}),F($,{className:"af-w-8"})]})}),F(Me,{children:qt.map(z=>ye(pe,{onClick:Ge?()=>ie(z):void 0,className:Ge?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[ye(U,{className:"af-whitespace-nowrap af-font-medium",children:[F("button",{type:"button",onClick:jt=>{jt.stopPropagation(),ie(z)},disabled:!Ge,"aria-label":`Open order ${Xa(z)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,children:Xa(z)}),z.is_test&&F(te,{variant:"outline",className:"af-ml-2",children:"Test"})]}),F(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Gi(z.created_at)}),ye(U,{className:"af-max-w-[220px]",children:[F("div",{className:"af-truncate",children:z.customer_email||F("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Fn(z)&&F("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Fn(z)})]}),F(U,{className:"af-max-w-[220px]",children:F("div",{className:"af-truncate af-text-muted-foreground",children:Wi(z)})}),ye(U,{className:"af-whitespace-nowrap af-text-right",children:[F("div",{className:"af-font-medium af-tabular-nums",children:j(Qa(z),z.currency)}),z.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(z.amount_refunded,z.currency)," ","refunded"]})]}),F(U,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[F(bs,{status:z.status}),F(Ws,{deliveries:z.email_deliveries}),n&&F(Ts,{order:z})]})}),F(U,{className:"af-w-8 af-text-right",children:F(qi,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},z.id))})]})}),u?null:ye("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[ye("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[F("span",{children:xt?`${At.length} matching this page`:`Showing ${H}-${We} of ${g}`}),ye(da,{value:String(h),onValueChange:z=>m(Number(z)),children:[F(na,{className:"af-w-[70px] af-h-8",children:F(fa,{})}),ye(ra,{children:[F(Ke,{value:"10",children:"10"}),F(Ke,{value:"25",children:"25"}),F(Ke,{value:"50",children:"50"}),F(Ke,{value:"100",children:"100"})]})]}),F("span",{children:"per page"})]}),ye("div",{className:"af-flex af-items-center af-gap-2",children:[ye(w,{variant:"outline",size:"sm",onClick:()=>B(v-1),disabled:!D,children:[F(ru,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ye(w,{variant:"outline",size:"sm",onClick:()=>B(v+1),disabled:!x,children:["Next",F(qi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function ls(e){return F(du,{...e},e.maxRows==null?"full":"compact")}import*as Un from"react";import{ChevronLeft as gu,ChevronRight as vu,Eye as bu,Search as yu,Users as hu}from"lucide-react";import*as Qt from"react";function Mn({initialPageSize:e=25}={}){let{api:a}=se(),[s,t]=Qt.useState([]),[n,i]=Qt.useState(0),[o,d]=Qt.useState(!0),[f,u]=Qt.useState(null),[r,p]=Qt.useState(0),[b,g]=Qt.useState(e),[c,l]=Qt.useState(""),v=Qt.useRef(0),h=Qt.useCallback(async()=>{let D=++v.current;try{d(!0),u(null);let B={limit:b,offset:r*b};c.trim()&&(B.email=c.trim());let m=await a.getCustomers(B);if(D!==v.current)return;t(m.customers),i(m.total)}catch(B){if(D!==v.current)return;u(B instanceof Error?B:new Error("Failed to fetch customers"))}finally{D===v.current&&d(!1)}},[a,r,b,c]);Qt.useEffect(()=>{h()},[h]);let x=Math.ceil(n/b);return{customers:s,total:n,isLoading:o,error:f,page:r,pageSize:b,hasNextPage:r<x-1,hasPreviousPage:r>0,setPage:p,setPageSize:D=>{g(D),p(0)},email:c,setEmail:D=>{l(D),p(0)},refetch:h}}import*as xs from"react";import{ArrowLeft as fu,Loader2 as mu}from"lucide-react";import{jsx as De,jsxs as It}from"react/jsx-runtime";function Ki(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function pu(e){let a=[];e.name&&a.push(e.name),a.push(e.line1),e.line2&&a.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&a.push(s),e.country&&a.push(e.country),a}function $n({customer:e,onBack:a,className:s}){let{api:t}=se(),[n,i]=xs.useState(null),[o,d]=xs.useState([]),[f,u]=xs.useState(!0),[r,p]=xs.useState(null);xs.useEffect(()=>{let c=!1;return u(!0),p(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,v])=>{c||(i(l),d(v.orders))}).catch(l=>{c||p(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{c||u(!1)}),()=>{c=!0}},[t,e.id,e.email]);let b=n?.addresses??[],g=n?.order_count??o.length;return It("div",{className:s,children:[It("div",{className:"af-mb-6",children:[It(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[De(fu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),De("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),It("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Ki(e.created_at)]})]}),f?De("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:De(mu,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?De("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):It("div",{className:"af-space-y-6",children:[De(Oa,{deliveries:n?.email_deliveries}),It("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),It("div",{className:"af-space-y-1 af-text-sm",children:[It("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),De("span",{children:e.email})]}),e.name&&It("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),De("span",{children:e.name})]}),e.phone&&It("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),De("span",{children:e.phone})]}),It("div",{className:"af-flex af-gap-2",children:[De("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),De("span",{children:g})]})]})]}),b.length>0&&It("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),De("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(c=>It("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&De(te,{variant:"secondary",className:"af-mb-1",children:"Default"}),pu(c).map((l,v)=>De("div",{children:l},v))]},c.id))})]}),It("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?De("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):It(Be,{children:[De(Fe,{children:It(pe,{children:[De($,{children:"Date"}),De($,{children:"Amount"}),De($,{children:"Status"})]})}),De(Me,{children:o.map(c=>It(pe,{children:[De(U,{className:"af-text-muted-foreground",children:Ki(c.created_at)}),De(U,{children:j(Qa(c),c.currency)}),De(U,{children:De(ys,{status:c.status})})]},c.id))})]})]})]})]})}import{Fragment as wu,jsx as Ce,jsxs as bt}from"react/jsx-runtime";function xu(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Vn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:d,hasPreviousPage:f,setPage:u,setPageSize:r,email:p,setEmail:b,refetch:g}=Mn(),[c,l]=Un.useState("list"),[v,h]=Un.useState(null),[x,D]=Un.useState(""),B=S=>{h(S),l("detail")},m=()=>{l("list"),h(null),g()};if(c==="detail"&&v)return Ce("div",{className:e,children:Ce($n,{customer:v,onBack:m})});let N=bt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Ce(ge,{type:"email",value:x,onChange:S=>D(S.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),b(x.trim()))}}),bt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>b(x.trim()),children:[Ce(yu,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),p&&Ce(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{D(""),b("")},children:"Clear"})]});if(t)return bt("div",{className:e,children:[N,Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ce("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return bt("div",{className:e,children:[N,Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:bt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return bt("div",{className:e,children:[p&&N,bt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Ce(hu,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ce("p",{className:"af-text-muted-foreground af-text-center",children:p?"No customers match that email.":bt(wu,{children:["No customers yet.",Ce("br",{}),"Customers appear here after their first purchase."]})})]})]});let R=i*o+1,A=Math.min((i+1)*o,s);return bt("div",{className:e,children:[N,bt(Be,{children:[Ce(Fe,{children:bt(pe,{children:[Ce($,{children:"Email"}),Ce($,{children:"Name"}),Ce($,{children:"Customer since"}),Ce($,{className:"af-text-right",children:"Actions"})]})}),Ce(Me,{children:a.map(S=>bt(pe,{children:[Ce(U,{className:"af-font-medium",children:S.email}),Ce(U,{children:S.name||Ce("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ce(U,{className:"af-text-muted-foreground",children:xu(S.created_at)}),Ce(U,{className:"af-text-right",children:Ce(w,{variant:"ghost",size:"icon",onClick:()=>B(S),title:"View customer",children:Ce(bu,{className:"af-h-4 af-w-4"})})})]},S.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 ",R,"-",A," of ",s]}),bt(da,{value:String(o),onValueChange:S=>r(Number(S)),children:[Ce(na,{className:"af-w-[70px] af-h-8",children:Ce(fa,{})}),bt(ra,{children:[Ce(Ke,{value:"10",children:"10"}),Ce(Ke,{value:"25",children:"25"}),Ce(Ke,{value:"50",children:"50"}),Ce(Ke,{value:"100",children:"100"})]})]}),Ce("span",{children:"per page"})]}),bt("div",{className:"af-flex af-items-center af-gap-2",children:[bt(w,{variant:"outline",size:"sm",onClick:()=>u(i-1),disabled:!f,children:[Ce(gu,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),bt(w,{variant:"outline",size:"sm",onClick:()=>u(i+1),disabled:!d,children:["Next",Ce(vu,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Se from"react";import{ArrowLeft as Nu,ChevronLeft as Su,ChevronRight as Zi,Copy as _u,Download as Ru,ExternalLink as Pu,FileText as Qi,Loader2 as Cu,Search as Tu}from"lucide-react";import*as yt from"react";function Es({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=se(),[n,i]=yt.useState([]),[o,d]=yt.useState(0),[f,u]=yt.useState(null),[r,p]=yt.useState(!0),[b,g]=yt.useState(null),[c,l]=yt.useState(0),[v,h]=yt.useState(e),[x,D]=yt.useState(void 0),[B,m]=yt.useState(""),[N,R]=yt.useState(""),[A,S]=yt.useState(""),[k,M]=yt.useState(""),[y,O]=yt.useState(""),K=x?x.join(","):"",V=yt.useRef(0),ce=yt.useCallback(async()=>{let Z=++V.current;p(!0),g(null);try{let q={labels:K?K.split(","):void 0,customerEmail:B||void 0,q:N||void 0,from:A||void 0,to:k||void 0,retainerId:y||void 0,includeAggregates:s,limit:v,offset:c*v},ne=await t.getInvoices(q);if(Z!==V.current)return;if(c>0&&c*v>=ne.total){l(Math.max(0,Math.ceil(ne.total/v)-1));return}i(ne.invoices),d(ne.total),s&&u(ne.aggregates??null)}catch(q){if(Z!==V.current)return;g(q instanceof Error?q:new Error("Failed to fetch invoices"))}finally{Z===V.current&&p(!1)}},[t,K,B,N,A,k,y,c,v,s]);yt.useEffect(()=>{ce()},[ce,a]);let G=Z=>q=>{l(0),Z(q)};return{invoices:n,total:o,aggregates:f,isLoading:r,error:b,page:c,pageSize:v,hasNextPage:(c+1)*v<o,hasPreviousPage:c>0,setPage:l,setPageSize:G(h),labels:x,setLabels:G(D),customerEmail:B,setCustomerEmail:G(m),q:N,setQ:G(R),from:A,setFrom:G(S),to:k,setTo:G(M),retainerId:y,setRetainerId:G(O),clearFilters:()=>{l(0),D(void 0),m(""),R(""),S(""),M(""),O("")},refetch:ce}}import{Fragment as Bu,jsx as T,jsxs as Q}from"react/jsx-runtime";var ku={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 Br(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:ku[e.label]??e.label}function Eu(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 Or={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Au={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Qs({invoice:e,className:a}){return Q("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[T(te,{variant:Eu(e.label),className:a,children:Br(e)}),e.collection_method==="charge_automatically"&&T(te,{variant:"secondary",children:"Managed in Stripe"})]})}function qn({delivery:e,className:a}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return T(te,{variant:s,className:a,children:Or[e.state]??e.state})}function As(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ya(e){if(!e)return"\u2014";let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Ji={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Hn={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0};function Iu(e){let a=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(a),t=s?`'${a}`:a;return s||/[",;\r\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}var Dr=100,Lr=5e3;async function Du(e,a){let s=[],t=0;for(let n=0;n<Lr;n+=Dr){let i=await e.getInvoices({...a,limit:Dr,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<Dr||s.length>=t)break}return{invoices:s.slice(0,Lr),total:t,truncated:t>s.length||t>Lr}}function Xi(e){let a=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(t=>[t.id,As(t),Br(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),j(t.amount_subtotal,t.currency),j(t.tax_total,t.currency),j(t.amount_total,t.currency),t.amount_due===null?"":j(t.amount_due,t.currency),t.amount_paid===null?"":j(t.amount_paid,t.currency),j(t.amount_refunded,t.currency),t.payment_method??"",t.pay_url??"",t.retainer_id??"",t.replaces_order_id??"",t.replaced_by_order_id??"",t.tax_behavior??"",t.discount_total===void 0?"":j(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(Iu).join(",")).join(`
|
|
5
|
+
`)}function Lu(e){if(typeof document>"u")return;let a=new Blob([Xi(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(a),t=document.createElement("a");t.href=s,t.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(s)}function Ou({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:d=null,onClearRetainerFilter:f,maxRows:u,onViewAll:r}){let p=typeof u=="number",{api:b}=se(),{invoices:g,total:c,isLoading:l,error:v,page:h,pageSize:x,hasNextPage:D,hasPreviousPage:B,setPage:m,labels:N,setLabels:R,customerEmail:A,setCustomerEmail:S,q:k,setQ:M,from:y,setFrom:O,to:K,setTo:V,retainerId:ce,setRetainerId:G,refetch:Z}=Es({refreshKey:a}),[q,ne]=Se.useState(typeof u=="number"?"all":"open"),[W,he]=Se.useState(""),[Ze,it]=Se.useState(null),Pe=Se.useRef(0),je=!p||!!r,et=Se.useCallback(H=>{if(p){r?.();return}Pe.current++,Et(!1),it(H)},[p,r]),[xe,Et]=Se.useState(!1),[P,L]=Se.useState(0),[I,ue]=Se.useState(null),[me,_e]=Se.useState(!1),[Te,tt]=Se.useState(0);Se.useEffect(()=>{it(H=>{if(!H)return H;let We=g.find(z=>z.id===H.id);return We&&We!==H?We:H})},[g]);let[Ue,Ge]=Se.useState(!1),[ie,Ee]=Se.useState(null),ot=async()=>{if(!Ue){Ge(!0),Ee(null);try{let{invoices:H,total:We,truncated:z}=await Du(b,{labels:N,customerEmail:A,q:k,from:y,to:K,retainerId:ce});Lu(H),Ee(z?`Exported the first ${H.length.toLocaleString()} of ${We.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ee("Couldn't export \u2014 try again.")}finally{Ge(!1)}}},sa=!A&&!k&&!y&&!K&&!ce,[xt,At]=Se.useState(null);Se.useEffect(()=>{if(l||c>0||!sa||q!=="open")return;let H=!1;return b.getInvoices({limit:1}).then(We=>{H||At(We.total>0)}).catch(()=>{H||At(!0)}),()=>{H=!0}},[b,l,c,sa,q,a]),Se.useEffect(()=>{R(p?Hn.all:Hn.open)},[]),Se.useEffect(()=>{let H=d?.id??"";H!==ce&&(G(H),H&&(ne("all"),R(Hn.all),S(""),M(""),he(""),O(""),V("")))},[d?.id]),Se.useEffect(()=>{let H=!1;return _e(!1),b.getInvoiceSettings().then(We=>{H||ue({payments_active:We.payments_active,blocked:We.blocked})}).catch(()=>{H||_e(!0)}),()=>{H=!0}},[b,a,Te]),Se.useEffect(()=>{if(!s||p)return;let H=!1,We=Pe.current;return Et(!1),b.getInvoice(s).then(z=>{!H&&We===Pe.current&&it(z)}).catch(()=>{!H&&We===Pe.current&&Et(!0)}),()=>{H=!0}},[b,s,P,p]),Se.useEffect(()=>{t?.(Ze!==null)},[Ze,t]);let qt=H=>{ne(H),R(Hn[H])},Ve=H=>{let We=H.trim();if(!We){k&&M(""),A&&S("");return}if(We.includes("@")){k&&M(""),S(We);return}A&&S(""),M(We.replace(/^#/,""))},at=g,as=p?at.slice(0,u):at,Hs=xe&&Q("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. ",T(w,{type:"button",variant:"link",size:"sm",onClick:()=>L(H=>H+1),children:"Retry opening invoice"})]});if(Ze)return Q("div",{className:e,children:[Hs,T(Fr,{invoice:Ze,refreshKey:a,onBack:()=>{et(null),Z()}},Ze.id)]});let Lt=Q("div",{className:"af-mb-4 af-space-y-3",children:[me&&Q("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",T(w,{type:"button",variant:"link",size:"sm",onClick:()=>tt(H=>H+1),children:"Retry setup check"})]}),Hs,I?.blocked&&Q("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",I.blocked.reason?`: ${I.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),d&&Q("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[Q(te,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",d.label]}),f&&T(w,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),Q("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[T("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(Ji).map(H=>T("button",{type:"button","aria-pressed":q===H,onClick:()=>qt(H),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",q===H?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ji[H]},H))}),Q("div",{className:"af-relative af-w-full af-max-w-xs",children:[T(Tu,{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(ge,{type:"text",value:W,onChange:H=>he(H.target.value),onBlur:()=>Ve(W),onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),Ve(W))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),Q("div",{className:"af-flex af-items-center af-gap-2",children:[T(ve,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),T(ge,{id:"invoices-from",type:"date",value:y,max:K||void 0,onChange:H=>O(H.target.value),className:"af-invoice-date af-w-[150px]"})]}),Q("div",{className:"af-flex af-items-center af-gap-2",children:[T(ve,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),T(ge,{id:"invoices-to",type:"date",value:K,min:y||void 0,onChange:H=>V(H.target.value),className:"af-invoice-date af-w-[150px]"})]}),Q(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ot(),disabled:Ue||l||!!v||c===0,"aria-busy":Ue,children:[T(Ru,{className:"af-h-4 af-w-4 af-mr-1"}),Ue?"Exporting\u2026":"Export CSV (all matching)"]})]}),ie&&T("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:ie})]});return l?Q("div",{className:e,children:[p?null:Lt,T("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(H=>Q("div",{className:"af-rounded-md af-border af-p-3",children:[Q("div",{className:"af-flex af-items-center af-justify-between",children:[T(ae,{className:"af-h-4 af-w-20"}),T(ae,{className:"af-h-4 af-w-16"})]}),T(ae,{className:"af-mt-2 af-h-3 af-w-40"})]},H))})]}):v?Q("div",{className:e,children:[p?null:Lt,Q("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",T(w,{type:"button",variant:"link",size:"sm",onClick:()=>void Z(),children:"Retry"})]})]}):c===0&&sa&&(q==="all"||xt===!1)&&(q==="open"||q==="all")?I?.blocked?Q("div",{className:e,children:[p?null:Lt,T(zn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?Q("div",{className:e,children:[p?null:Lt,T(zn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):I&&!I.payments_active?Q("div",{className:e,children:[p?null:Lt,T(zn,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):Q("div",{className:e,children:[p?null:Lt,T(zn,{heading:"No invoices yet",body:!I||me?"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."})]}):Q("div",{className:e,children:[p?null:Lt,as.length===0?T("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."}):Q(Bu,{children:[T("div",{className:"af-space-y-3 lg:af-hidden",children:as.map(H=>Q("button",{type:"button",onClick:()=>et(H),disabled:!je,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${je?" hover:af-bg-muted/50":""}`,children:[Q("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[T("span",{className:"af-font-medium",children:As(H)}),T(Qs,{invoice:H})]}),T("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:H.customer_name??H.customer_email??"\u2014"}),H.delivery&&T("div",{className:"af-mt-1",children:T(qn,{delivery:H.delivery})}),Q("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[T("span",{children:H.collection_method==="charge_automatically"?"Automatic collection":H.due_at?`Due ${ya(H.due_at)}`:"Due on receipt"}),T("span",{className:"af-font-medium af-tabular-nums",children:j(H.amount_due??H.amount_total,H.currency)})]})]},H.id))}),T("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Q(Be,{children:[T(Fe,{children:Q(pe,{children:[T($,{children:"Invoice"}),T($,{children:"Created"}),T($,{children:"Customer"}),T($,{children:"Due"}),T($,{className:"af-text-right",children:"Amount"}),T($,{children:"Status"}),T($,{children:"Delivery"}),T($,{className:"af-w-8"})]})}),T(Me,{children:as.map(H=>Q(pe,{className:je?"af-cursor-pointer":void 0,onClick:je?()=>et(H):void 0,children:[T(U,{className:"af-font-medium",children:T("button",{type:"button",disabled:!je,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${je?" hover:af-underline":""}`,onClick:We=>{We.stopPropagation(),et(H)},"aria-label":`Open invoice ${As(H)}`,children:As(H)})}),T(U,{children:ya(H.created_at)}),Q(U,{children:[T("div",{children:H.customer_name??"\u2014"}),T("div",{className:"af-text-xs af-text-muted-foreground",children:H.customer_email})]}),T(U,{children:H.collection_method==="charge_automatically"?"Automatic":H.due_at?ya(H.due_at):"On receipt"}),T(U,{className:"af-text-right af-tabular-nums",children:j(H.amount_due??H.amount_total,H.currency)}),T(U,{children:T(Qs,{invoice:H})}),T(U,{children:T(qn,{delivery:H.delivery})}),T(U,{children:T(Zi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},H.id))})]})}),p?null:Q("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[Q("span",{children:[c," invoice",c===1?"":"s"]}),Q("div",{className:"af-flex af-items-center af-gap-1",children:[T(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>m(h-1),disabled:!B,"aria-label":"Previous page",children:T(Su,{className:"af-h-4 af-w-4"})}),Q("span",{className:"af-tabular-nums",children:[h*x+1,"\u2013",Math.min((h+1)*x,c)]}),T(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>m(h+1),disabled:!D,"aria-label":"Next page",children:T(Zi,{className:"af-h-4 af-w-4"})})]})]})]})]})}function zn({heading:e,body:a,action:s}){return T(ks,{icon:Qi,heading:e,body:a,action:s})}function us(e){return T(Ou,{...e},e.maxRows==null?"full":"compact")}var es="af-text-xs af-text-muted-foreground";function Yi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Fr({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=se(),i=Se.useRef(null);Se.useEffect(()=>{i.current?.focus()},[e.id]);let[o,d]=Se.useState(!1),[f,u]=Se.useState(null),[r,p]=Se.useState(!1),[b,g]=Se.useState(!1),c=Se.useRef(0),[l,v]=Se.useState(null),[h,x]=Se.useState(!1),[D,B]=Se.useState(0);Se.useEffect(()=>{let y=!1;return x(!1),n.getInvoice(e.id).then(O=>{y||v({source:e,value:O})}).catch(()=>{y||x(!0)}),()=>{y=!0}},[n,e,s,D]);let m=l?.source===e?l.value:e,N=m.collection_method==="charge_automatically";Se.useEffect(()=>(c.current++,u(null),p(!1),g(!1),d(!1),()=>{c.current++}),[n,m,s]);let R=y=>y==null?"\u2014":j(y,m.currency),A=async()=>{if(!(!m.pay_url||!Yi()))try{await navigator.clipboard.writeText(m.pay_url),d(!0),setTimeout(()=>d(!1),1500)}catch{}},S=async()=>{if(f){u(null);return}let y=++c.current;g(!1),p(!0);try{let O=await n.getInvoicePreview(m.id);y===c.current&&u(O)}catch{y===c.current&&g(!0)}finally{y===c.current&&p(!1)}},k=m.bill_to,M=k?[k.company,k.name,k.address?.line1,k.address?.line2,[k.address?.city,k.address?.state,k.address?.postal_code].filter(Boolean).join(", "),k.address?.country,k.tax_id?`${k.tax_id.value}`:null,k.po_number?`PO ${k.po_number}`:null,k.service_period?`Service period: ${k.service_period}`:null].filter(y=>!!y&&y.length>0):[];return Q("div",{className:t,children:[Q("div",{className:"af-mb-4",children:[Q(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[T(Nu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),Q("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Q("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",As(m)]}),T(Qs,{invoice:m}),T(qn,{delivery:m.delivery})]}),Q("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[m.customer_name??m.customer_email,m.customer_name&&m.customer_email?` \xB7 ${m.customer_email}`:""]})]}),h&&Q("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. ",T(w,{type:"button",variant:"link",size:"sm",onClick:()=>B(y=>y+1),children:"Retry details"})]}),m.label==="failed"&&T("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."}),m.label==="creating"&&T("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."}),Q("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[Q("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[Q("section",{className:"af-rounded-md af-border af-p-4",children:[Q(Be,{children:[T(Fe,{children:Q(pe,{children:[T($,{children:"Description"}),T($,{className:"af-text-right",children:"Qty"}),T($,{className:"af-text-right",children:"Amount"})]})}),T(Me,{children:m.line_items.map((y,O)=>Q(pe,{children:[T(U,{style:{overflowWrap:"anywhere"},children:y.description}),T(U,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:y.quantity}),T(U,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:R(y.amount)})]},O))})]}),Q("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[T(cs,{label:"Subtotal",value:R(m.amount_subtotal)}),(m.discount_total??0)>0&&T(cs,{label:"Discount",value:`-${R(m.discount_total)}`}),m.tax_total>0&&T(cs,{label:m.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:R(m.tax_total)}),T(cs,{label:"Total",value:R(m.amount_total),strong:!0}),m.credit_applied>0&&T(cs,{label:"Credit applied",value:`-${R(m.credit_applied)}`}),m.amount_due!==null&&m.amount_due!==m.amount_total&&T(cs,{label:"Amount due",value:R(m.amount_due),strong:!0}),m.amount_paid!==null&&m.amount_paid>0&&T(cs,{label:"Amount paid",value:R(m.amount_paid)}),m.amount_refunded>0&&T(cs,{label:"Refunded",value:R(m.amount_refunded)})]}),m.credit_notes?.length>0&&Q("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[T("div",{className:es,children:"Credit notes"}),m.credit_notes.map(y=>Q("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[Q("span",{className:"af-text-muted-foreground",children:[ya(y.created_at)," \xB7 ",y.origin==="dashboard"?"issued in Stripe":"refund",y.stripe_credit_note_id?"":" \xB7 being created"]}),Q("span",{className:"af-tabular-nums",children:["-",j(y.amount,y.currency)]})]},y.id))]})]}),(m.note||m.footer)&&Q("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[m.note&&Q("div",{children:[T("div",{className:es,children:"Note"}),T("div",{className:"af-whitespace-pre-wrap af-break-words",children:m.note})]}),m.footer&&Q("div",{children:[T("div",{className:es,children:"Footer"}),T("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:m.footer})]})]}),f&&!N&&Q("section",{className:"af-rounded-md af-border af-p-4",children:[Q("div",{className:J(es,"af-break-words"),children:["Email preview \u2014 ",f.subject]}),T("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),T("iframe",{title:"Invoice email preview",srcDoc:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),Q("div",{className:"af-min-w-0 af-space-y-4",children:[Q("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[T(ba,{label:"Created",value:ya(m.created_at)}),T(ba,{label:"Due",value:m.collection_method==="charge_automatically"?"Managed in Stripe":m.due_at?ya(m.due_at):"On receipt"}),m.paid_at&&T(ba,{label:"Paid",value:ya(m.paid_at)}),m.payment_method&&T(ba,{label:"Paid by",value:m.paid_out_of_band?`${m.payment_method} (recorded outside Stripe)`:m.payment_method}),m.payment_state!=="none"&&T(ba,{label:"Payment",value:m.payment_state==="processing"?"Processing":m.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),m.delivery&&T(ba,{label:"Delivery",value:`${Or[m.delivery.state]} \xB7 ${m.delivery.recipient}`}),m.marked_uncollectible_at&&T(ba,{label:"Written off",value:ya(m.marked_uncollectible_at)}),m.correction_reason&&T(ba,{label:"Correction",value:m.correction_reason}),m.replaced_by_order_id&&T(ba,{label:"Replaced by",value:m.replaced_by_order_id}),m.collection_method==="charge_automatically"?T(ba,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):m.retainer_id&&T(ba,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),m.replaces_order_id&&T(ba,{label:"Replaces",value:m.replaces_order_id})]}),Q("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[T("div",{className:es,children:"Reminders"}),N?T("div",{children:"View automatic payment reminders in Stripe."}):m.reminders.disabled?T("div",{children:"Off for this invoice."}):m.reminders.paused_until?Q("div",{children:["Paused until ",ya(m.reminders.paused_until),"."]}):m.reminders.next_at?Q("div",{children:["Next on ",ya(m.reminders.next_at),"."]}):m.reminders.final_sent_at?Q("div",{children:["Final reminder sent ",ya(m.reminders.final_sent_at),"."]}):T("div",{children:"None scheduled."}),!N&&Q("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",m.reminders.schedule.length===0?"none":m.reminders.schedule.map(y=>y<0?`${-y}d before`:y===0?"due day":`${y}d after`).join(", ")]})]}),m.communications&&m.communications.length>0&&Q("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[T("div",{className:es,children:"Email delivery history"}),m.communications.map(y=>Q("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[Q("span",{className:"af-min-w-0 af-break-words",children:[Au[y.kind]??y.kind,y.kind==="reminder"&&y.slot!==null?` #${y.slot}`:"",Q("span",{className:"af-text-muted-foreground",children:[" \xB7 ",y.recipient]})]}),Q("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Or[y.state]??y.state," \xB7 ",ya(y.state_at??y.created_at)]})]},y.id))]}),M.length>0&&Q("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[T("div",{className:es,children:"Bill to"}),M.map((y,O)=>T("div",{className:"af-break-words",children:y},O))]}),Q("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[m.pay_url&&Q(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void A(),disabled:!Yi(),children:[T(_u,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":N?"Copy invoice link":"Copy pay link"]}),m.pdf_url&&T(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:Q("a",{href:m.pdf_url,target:"_blank",rel:"noreferrer",children:[T(Pu,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!N&&Q(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void S(),disabled:r,children:[r?T(Cu,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):T(Qi,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!N&&T("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),m.pay_url&&T("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:m.pay_url}),T("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 ba({label:e,value:a}){return Q("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[T("span",{className:J(es,"af-shrink-0"),children:e}),T("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function cs({label:e,value:a,strong:s}){return Q("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[T("dt",{className:J(es,s&&"af-font-medium af-text-foreground"),children:e}),T("dd",{className:J("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as Fu}from"lucide-react";import{jsx as ht,jsxs as Aa}from"react/jsx-runtime";var Mu={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},eo={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function $u(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 to(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>eo[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>eo[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Mu[e.status]}function ao(e){let a=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${a}`}function Uu(e){return e.status==="canceled"?`Ended ${jn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${jn(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 ${jn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${jn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function jn(e){if(!e)return"\u2014";let a=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(a);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Mr({retainer:e,className:a}){return ht(te,{variant:$u(e.status),className:J("af-max-w-full af-whitespace-normal af-break-words",a),children:to(e)})}function Is({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:d=0,isLoadingMore:f=!1,onLoadMore:u,includeEnded:r=!1,onIncludeEndedChange:p,className:b}){let g=!!p;if(!a&&!s&&e.length===0&&!(g&&(r||d>0)))return null;let c=o!==void 0?Math.max(0,o-e.length):0;return Aa("section",{className:J("af-mb-6",b),"aria-label":"Recurring invoices",children:[Aa("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[ht(Fu,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),ht("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),ht("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."}),g&&ht(w,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>p?.(!r),children:r?"Hide ended recurring invoices":d>0&&e.length===0?`Show ended recurring invoices (${d})`:"Show ended recurring invoices"})]}),s?Aa("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",ht(w,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?ht("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>Aa("div",{className:"af-rounded-md af-border af-p-3",children:[ht(ae,{className:"af-h-4 af-w-48"}),ht(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?ht("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:r?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):ht("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let v=i===l.id;return Aa("li",{className:J("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[Aa("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Aa("div",{className:"af-min-w-0",children:[ht("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),ht("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),ht(Mr,{retainer:l})]}),l.collection_method==="charge_automatically"?Aa("div",{className:"af-mt-2 af-space-y-1",children:[ht(te,{variant:"secondary",children:"Managed in Stripe"}),ht("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."})]}):ht("div",{className:"af-mt-2 af-text-sm",children:ao(l)}),Aa("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:[Aa("span",{children:[Uu(l)," \xB7 ",l.cycles.count===0?"no invoices yet":`${l.cycles.paid} paid${l.cycles.open>0?`, ${l.cycles.open} open`:""}`]}),l.cycles.count>0&&ht(w,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&Aa("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!a&&!s&&c>0&&u&&ht("div",{className:"af-mt-2",children:ht(w,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:f,children:f?"Loading\u2026":`Load more (${c} more)`})})]})}import*as no from"react";import{AlertTriangle as so,CheckCircle2 as Vu,CreditCard as $r,Loader2 as Hu,RefreshCw as zu}from"lucide-react";import{jsx as nt,jsxs as Pt}from"react/jsx-runtime";function Gn({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=is(),[d,f]=no.useState(!1),u=async()=>{f(!0);try{await o()}finally{f(!1)}};return n&&!t?nt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:nt("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?nt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Pt("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?nt("div",{className:s,children:Pt("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:[nt(Vu,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Pt("div",{children:[nt("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),Pt("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",t.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):Pt("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&Pt("div",{className:"af-space-y-3",children:[Pt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[nt($r,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Pt("div",{children:[nt("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),nt("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?Pt(w,{onClick:e,children:[nt($r,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):nt("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),t.reason==="needs_paid_plan"&&Pt("div",{className:"af-space-y-3",children:[Pt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[nt(so,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Pt("div",{children:[nt("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),nt("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."})]})]}),a?nt(w,{onClick:a,children:"Upgrade plan"}):nt("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&Pt("div",{className:"af-space-y-3",children:[Pt("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:[nt(so,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Pt("div",{children:[nt("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?nt("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."}):nt("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."})]})]}),Pt("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&Pt(w,{onClick:e,children:[nt($r,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Pt(w,{variant:"outline",onClick:u,disabled:d,children:[d?nt(Hu,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):nt(zu,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as $t from"react";function Ur(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function Ds({includeStats:e=!1,refreshKey:a}={}){let{api:s}=se(),[t,n]=$t.useState([]),[i,o]=$t.useState(!0),[d,f]=$t.useState(null),u=$t.useRef(0),r=$t.useCallback(async()=>{let v=++u.current;try{o(!0),f(null);let h=await s.getProducts(e?{include:"stats"}:{});if(v!==u.current)return;n(h)}catch(h){if(v!==u.current)return;f(h instanceof Error?h:new Error("Failed to fetch products"))}finally{v===u.current&&o(!1)}},[s,e,a]);$t.useEffect(()=>{r()},[r]);let p=$t.useCallback(async v=>{let h=await s.createProduct(v);return n(x=>[h,...x]),h},[s]),b=$t.useCallback(async(v,h)=>{let x=await s.updateProduct(v,h);return n(D=>Ur(D,v,x)),x},[s]),g=$t.useCallback(async v=>{await s.deleteProduct(v),n(h=>h.filter(x=>x.id!==v))},[s]),c=$t.useCallback(async(v,h)=>{let x=await s.attachProductFile(v,h);return n(D=>Ur(D,v,x)),x},[s]),l=$t.useCallback(async(v,h)=>{let x=await s.attachProductFileFromUrl(v,h);return n(D=>Ur(D,v,x)),x},[s]);return{products:t,isLoading:i,error:d,refetch:r,createProduct:p,updateProduct:b,deleteProduct:g,attachProductFile:c,attachProductFileFromUrl:l}}import*as Ut from"react";var ro=["creating","active","paused","canceling"],qu=["canceled","failed"];function Ls({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=se(),[n,i]=Ut.useState([]),[o,d]=Ut.useState(0),[f,u]=Ut.useState(0),[r,p]=Ut.useState(!0),[b,g]=Ut.useState(!1),[c,l]=Ut.useState(null),[v,h]=Ut.useState(a),x=Ut.useRef(0),D=Ut.useCallback(async()=>{let m=++x.current;p(!0),g(!1),l(null);try{let N=await t.getRetainers({statuses:v?void 0:ro,limit:s,offset:0});if(m!==x.current)return;if(i(N.retainers),d(N.total),!v&&N.total===0){let R=await t.getRetainers({statuses:qu,limit:1,offset:0});if(m!==x.current)return;u(R.total)}else u(0)}catch(N){if(m!==x.current)return;l(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{m===x.current&&p(!1)}},[t,v,s]);Ut.useEffect(()=>{D()},[D,e]);let B=Ut.useCallback(async()=>{if(r||b||n.length>=o)return;let m=x.current;g(!0);try{let N=await t.getRetainers({statuses:v?void 0:ro,limit:s,offset:n.length});if(m!==x.current)return;i(R=>{let A=new Set(R.map(S=>S.id));return[...R,...N.retainers.filter(S=>!A.has(S.id))]}),d(N.total)}catch(N){if(m!==x.current)return;l(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{m===x.current&&g(!1)}},[t,v,s,r,b,n.length,o]);return{retainers:n,total:o,endedTotal:f,hasMore:n.length<o,isLoading:r,isLoadingMore:b,error:c,includeEnded:v,setIncludeEnded:h,loadMore:B,refetch:D}}import{Fragment as Qu,jsx as ze,jsxs as Xt}from"react/jsx-runtime";function io({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=Os.useState(a),[d,f]=Os.useState("list"),[u,r]=Os.useState(null),p=Ds(),{status:b,error:g}=is(),c=b?.currency,l=D=>{r(D),f("edit")},v=()=>{r(null),f("create")},h=()=>{f("list"),r(null)},x=D=>{r(D),f("edit")};return Xt("div",{className:e,children:[Xt("div",{className:"af-mb-6",children:[ze("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),ze("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Xt(mn,{value:i,onValueChange:D=>o(D),children:[Xt(Gs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Xt(wa,{value:"products",className:"af-gap-2",children:[ze(Wu,{className:"af-h-4 af-w-4"}),"Products"]}),Xt(wa,{value:"orders",className:"af-gap-2",children:[ze(Ku,{className:"af-h-4 af-w-4"}),"Orders"]}),Xt(wa,{value:"invoices",className:"af-gap-2",children:[ze(Gu,{className:"af-h-4 af-w-4"}),"Invoices"]}),Xt(wa,{value:"customers",className:"af-gap-2",children:[ze(Ju,{className:"af-h-4 af-w-4"}),"Customers"]}),ze(wa,{value:"promos",children:"Promo codes"}),Xt(wa,{value:"setup",className:"af-gap-2",children:[ze(Zu,{className:"af-h-4 af-w-4"}),"Setup"]})]}),ze(Na,{value:"products",children:d==="list"?ze(Pn,{productsState:p,onSelectProduct:l,onCreateProduct:v}):Xt("div",{children:[Xt("div",{className:"af-mb-6",children:[Xt(w,{variant:"ghost",size:"sm",onClick:h,className:"af-mb-2 af--ml-2",children:[ze(ju,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),ze("h3",{className:"af-text-lg af-font-semibold",children:d==="create"?"New Product":u?.name})]}),d==="create"&&!c?ze("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:g?Xt("div",{className:"af-text-destructive",children:["Error: ",g.message]}):ze("div",{className:"af-text-muted-foreground",children:"Loading..."})}):ze(Tn,{productsState:p,product:d==="edit"?u:null,currency:c??"usd",onSaved:x},d==="edit"?u?.id??"edit":"new")]})}),ze(Na,{value:"orders",children:ze(ls,{onRefund:t})}),ze(Na,{value:"invoices",children:ze(Yu,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),ze(Na,{value:"customers",children:ze(Vn,{})}),ze(Na,{value:"promos",children:ze(Cs,{})}),ze(Na,{value:"setup",children:ze(Gn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Yu({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=Ls(),[n,i]=Os.useState(null),[o,d]=Os.useState(!1);return Xt(Qu,{children:[!o&&ze(Is,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>i(u=>u?.id===f.id?null:f),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),ze(us,{onDetailOpenChange:d,onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}import*as lo from"react";import*as Va from"react";function Bs({refreshKey:e}={}){let{api:a}=se(),[s,t]=Va.useState(null),[n,i]=Va.useState(!0),[o,d]=Va.useState(null),f=Va.useRef(0),u=Va.useCallback(async()=>{let r=++f.current;try{i(!0),d(null);let p=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==f.current)return;t(p)}catch(p){if(r!==f.current)return;d(p instanceof Error?p:new Error("Failed to fetch summary"))}finally{r===f.current&&i(!1)}},[a,e]);return Va.useEffect(()=>{u()},[u]),{summary:s,isLoading:n,error:o,refetch:u}}import{Fragment as Vr,jsx as Ct,jsxs as Hr}from"react/jsx-runtime";function oo(e,a){if(e.settled.complete)return{headline:j(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:j(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${j(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:j(0,a),extra:[]}}function co({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:d,error:f,refetch:u}=Bs({refreshKey:e}),[r,p]=lo.useState(!1),b=Ct("div",{className:"af-mb-6",children:f&&!o?Ct(la,{message:"Couldn't load your revenue summary.",onRetry:()=>u()}):Ct("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!o?Hr(Vr,{children:[Ct(st,{label:"This week",children:Ct(ae,{className:"af-h-6 af-w-24"})}),Ct(st,{label:"Today",children:Ct(ae,{className:"af-h-6 af-w-24"})}),Ct(st,{label:"Needs attention",children:Ct(ae,{className:"af-h-6 af-w-10"})})]}):Ct(Vr,{children:(()=>{let g=oo(o.revenue.d7,o.currency),c=oo(o.revenue.today,o.currency);return Hr(Vr,{children:[Ct(st,{label:"This week",detail:g.extra.length>0?Ct("div",{children:g.extra.map(l=>Ct("div",{children:l},l))}):void 0,children:g.headline}),Ct(st,{label:"Today",detail:c.extra.length>0?Ct("div",{children:c.extra.map(l=>Ct("div",{children:l},l))}):void 0,children:c.headline}),Ct(st,{label:"Needs attention",valueClassName:o.needs_attention.count>0?"af-text-2xl af-font-semibold af-tabular-nums af-text-destructive":"af-text-2xl af-font-semibold af-tabular-nums af-text-muted-foreground",detail:o.needs_attention.count===0?"All clear":o.needs_attention.items[0]?.title??void 0,children:o.needs_attention.count})]})})()})})});return Hr(Nt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[b,Ct(ls,{refreshKey:e,initialOrderId:a,onDetailOpenChange:p,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as za from"react";import{ImageOff as sd,Package as nd,Search as rd}from"lucide-react";import*as Ha from"react";import{ArrowLeft as td,ImageOff as ad}from"lucide-react";import{jsx as Ia,jsxs as Xs}from"react/jsx-runtime";var uo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ds="af-text-xs af-text-muted-foreground",Wn="af-text-sm af-font-medium af-tabular-nums",Xu=3;function ed(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let f=e.min_amount??a?.min_amount??null,u=e.max_amount??a?.max_amount??null;return f!==null&&u!==null?{text:`Buyer chooses (${j(f,s)} \u2013 ${j(u,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=a?.min_amount??e.unit_amount,i=a?.max_amount??e.unit_amount;if(n===null||i===null)return{text:"Varies by variant",compareAt:null};let o=n===i?j(n,s):`${j(n,s)} \u2013 ${j(i,s)}`,d=a?.compare_at_amount??null;return{text:o,compareAt:d!==null&&d>i?j(d,s):null}}function Kn({product:e,className:a}){let s=ed(e);return Xs("div",{className:a,children:[Ia("span",{className:Wn,children:s.text}),s.compareAt&&Ia("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Zn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?Ia(te,{variant:"destructive",children:"Out of stock"}):a.low_stock?Xs(te,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?Ia(te,{variant:"secondary",children:"Backorder"}):a.available===null?null:Xs(te,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?Ia(te,{variant:"warning",children:"Low stock"}):null}function Jn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Yn(e){return e.map(a=>j(a.amount,a.currency)).join(" + ")}function fo(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 mo({variant:e}){let a=e.inventory;if(!a||!a.tracked)return Ia("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?Xs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Ia("span",{className:"af-tabular-nums",children:Math.max(0,s)}),Ia(te,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?Ia(te,{variant:"destructive",children:"Out of stock"}):Xs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Ia("span",{className:"af-tabular-nums",children:s}),s<=Xu&&Ia(te,{variant:"warning",children:"Low"})]})}import{jsx as le,jsxs as Ye}from"react/jsx-runtime";function en({title:e,children:a,className:s}){return Ye("section",{className:J("af-rounded-lg af-border af-p-4",s),children:[le("h4",{className:uo,children:e}),le("div",{className:"af-mt-3",children:a})]})}function po({src:e,className:a}){let[s,t]=Ha.useState(!1);return Ha.useEffect(()=>t(!1),[e]),!e||s?le("div",{"aria-hidden":"true",className:J("af-flex af-items-center af-justify-center af-bg-muted",a),children:le(ad,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):le("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:J("af-object-cover",a)})}function go({product:e,showStats:a=!1,onBack:s}){let{api:t}=se(),[n,i]=Ha.useState(null),[o,d]=Ha.useState(!0),[f,u]=Ha.useState(null),[r,p]=Ha.useState(0),[b,g]=Ha.useState(0);Ha.useEffect(()=>{let m=!1;return d(!0),u(null),t.getProduct(e.id).then(N=>{m||i(N)}).catch(N=>{m||u(N instanceof Error?N:new Error("Failed to load product"))}).finally(()=>{m||d(!1)}),()=>{m=!0}},[t,e.id,r]);let c=n?{...e,...n}:e,l=c.images.length>0?c.images:e.images,v=l[b]??l[0],h=Jn(c),x=a?c.stats:void 0,D=n?.variants??[],B=D.length>1;return Ye("div",{children:[Ye("div",{className:"af-mb-6",children:[Ye(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[le(td,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),Ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[le("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),le(te,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),le(Zn,{product:c})]}),le(Kn,{product:c,className:"af-mt-1"}),!c.active&&le("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),Ye("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[Ye("div",{className:"af-space-y-2",children:[le(po,{src:v,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&le("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((m,N)=>le("button",{type:"button",onClick:()=>g(N),"aria-label":`Show photo ${N+1} of ${l.length}`,"aria-pressed":N===b,className:J("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:le(po,{src:m,className:"af-h-12 af-w-12 af-rounded-md"})},`${m}-${N}`))})]}),Ye("div",{className:"af-space-y-6",children:[c.description&&le(en,{title:"Description",children:le("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?Ye(en,{title:"Variants",children:[le("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(m=>Ye("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[le(ae,{className:"af-h-4 af-w-28"}),le(ae,{className:"af-h-4 af-w-20"}),le(ae,{className:"af-h-4 af-w-16"})]},m))}),le("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?le(la,{message:"Couldn't load this product's variants.",onRetry:()=>p(m=>m+1)}):B?le(en,{title:`Variants \xB7 ${D.length}`,children:le("div",{className:"af-overflow-x-auto",children:Ye(Be,{children:[le(Fe,{children:Ye(pe,{children:[le($,{children:"Variant"}),le($,{children:"SKU"}),le($,{className:"af-text-right",children:"Price"}),le($,{children:"Stock"})]})}),le(Me,{children:D.map(m=>Ye(pe,{children:[Ye(U,{className:"af-font-medium",children:[m.title||m.option_values.map(N=>N.value).join(" / ")||"\u2014",!m.active&&le(te,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),le(U,{className:"af-text-muted-foreground",children:m.sku?le("code",{className:"af-font-mono af-text-xs af-break-all",children:m.sku}):"\u2014"}),Ye(U,{className:"af-whitespace-nowrap af-text-right",children:[le("div",{className:Wn,children:fo(m)}),m.compare_at_amount!==null&&m.unit_amount!==null&&m.compare_at_amount>m.unit_amount&&le("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(m.compare_at_amount,m.currency)})]}),le(U,{className:"af-text-sm",children:le(mo,{variant:m})})]},m.id))})]})})}):null,le(en,{title:"Details",children:Ye("dl",{className:"af-space-y-2",children:[Ye("div",{children:[le("dt",{className:ds,children:"Delivery"}),le("dd",{className:"af-text-sm",children:h==="Digital download"?c.fulfillment.filename??"Digital download":h??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&Ye("div",{children:[le("dt",{className:ds,children:"Sends buyers to"}),le("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),Ye("div",{children:[le("dt",{className:ds,children:"Shipping address"}),le("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),Ye("div",{children:[le("dt",{className:ds,children:"Most one buyer can order"}),le("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),x&&le(en,{title:"Last 30 days",children:Ye("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[Ye("div",{children:[le("dt",{className:ds,children:"Units sold"}),le("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.units_sold})]}),Ye("div",{children:[le("dt",{className:ds,children:"Orders"}),le("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:x.orders})]}),Ye("div",{children:[le("dt",{className:ds,children:"Gross"}),le("dd",{className:Wn,children:x.gross.length>0?Yn(x.gross):"\u2014"})]})]})}),le("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 fs,jsx as re,jsxs as Qe}from"react/jsx-runtime";var id={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},od=["all","active","draft","low_stock","out_of_stock"];function vo(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function bo(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function ld(e){return e.inventory?.out_of_stock??!1}function cd(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return bo(e);case"out_of_stock":return ld(e);default:return!0}}function ud({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Jn(e),o=e.variant_count??0;return Qe("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[t?re("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):re("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:re(sd,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Qe("div",{className:"af-space-y-2 af-p-3",children:[Qe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Qe("div",{className:"af-min-w-0",children:[re("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),re(Kn,{product:e,className:"af-mt-0.5"})]}),!e.active&&re(te,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Qe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[re(Zn,{product:e}),o>1&&Qe(te,{variant:"outline",children:[o," variants"]}),i&&re(te,{variant:"outline",children:i})]}),n&&Qe("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${Yn(n.gross)}`:""," ",re("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function dd(){return re("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=>Qe("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[re("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Qe("div",{className:"af-space-y-2 af-p-3",children:[re(ae,{className:"af-w-32"}),re(ae,{className:"af-w-16"}),re(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function yo({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:d}=Ds({includeStats:a,refreshKey:e}),[f,u]=za.useState(!1),[r,p]=za.useState(null),[b,g]=za.useState("all"),[c,l]=za.useState(""),[v,h]=za.useState("newest"),x=za.useMemo(()=>{if(!a)return null;let y=null;for(let O of n)!O.stats||O.stats.units_sold===0||(!y||O.stats.units_sold>(y.stats?.units_sold??0))&&(y=O);return y},[n,a]),D=za.useMemo(()=>n.filter(bo).length,[n]),B=c.trim().toLowerCase(),m=za.useMemo(()=>{let O=[...n.filter(K=>cd(K,b)&&(!B||K.name.toLowerCase().includes(B)))];return v==="name"?O.sort((K,V)=>K.name.localeCompare(V.name)):v==="best_selling"?O.sort((K,V)=>(V.stats?.units_sold??0)-(K.stats?.units_sold??0)):O.sort((K,V)=>vo(V.created_at)-vo(K.created_at)),O},[n,b,B,v]),N=b!=="all"||!!B,R=()=>{g("all"),l("")},A=i||o!==null&&n.length===0,S=re("div",{className:"af-mb-6",children:re("div",{className:J("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:A?Qe(fs,{children:[re(st,{label:"Products",children:re(ae,{className:"af-h-6 af-w-10"})}),a?Qe(fs,{children:[re(st,{label:"Best seller",children:re(ae,{className:"af-h-6 af-w-28"})}),re(st,{label:"Low stock",children:re(ae,{className:"af-h-6 af-w-10"})})]}):re(st,{label:"Active",children:re(ae,{className:"af-h-6 af-w-10"})})]}):Qe(fs,{children:[re(st,{label:"Products",children:n.length}),a?Qe(fs,{children:[re(st,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:x?`${x.stats?.units_sold??0} sold, last 30 days`:void 0,children:x?re("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:x.name}):re("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),re(st,{label:"Low stock",children:D})]}):re(st,{label:"Active",children:n.filter(y=>y.active).length})]})})}),k=Qe("div",{className:"af-mb-4 af-space-y-3",children:[Qe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[re("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:od.map(y=>re("button",{type:"button","aria-pressed":b===y,onClick:()=>g(y),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===y?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:id[y]},y))}),Qe("div",{className:"af-relative af-w-full af-max-w-xs",children:[re(rd,{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"}),re(ge,{type:"text",value:c,onChange:y=>l(y.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Qe(da,{value:v,onValueChange:y=>h(y),children:[re(na,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:re(fa,{})}),Qe(ra,{children:[re(Ke,{value:"newest",children:"Newest"}),re(Ke,{value:"name",children:"Name A\u2013Z"}),a&&re(Ke,{value:"best_selling",children:"Best selling"})]})]}),N&&re(w,{type:"button",variant:"ghost",size:"sm",onClick:R,children:"Clear filters"})]}),i&&n.length===0?re(ae,{className:"af-h-4 af-w-28"}):re("p",{className:"af-text-sm af-text-muted-foreground",children:N?`${m.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${D>0?` \xB7 ${D} low stock`:""}`})]}),M;return r?M=re(go,{product:r,showStats:a,onBack:()=>{p(null),d()}},r.id):i&&n.length===0?M=Qe(fs,{children:[k,re(dd,{}),re("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?M=re("div",{className:"af-flex af-justify-center af-py-8",children:re(la,{message:"Couldn't load your products.",onRetry:()=>d()})}):n.length===0?M=Qe(Ea,{icon:re(nd,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",re("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):M=Qe(fs,{children:[k,o&&re("div",{className:"af-mb-4",children:re(la,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>d()})}),m.length===0?Qe(Ea,{children:["No products match these filters.",re("br",{}),re(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:R,children:"Show all products"})]}):re("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:m.map(y=>re(ud,{product:y,showStats:a,onOpen:()=>p(y)},y.id))})]}),re(Nt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:f?Qe(fs,{children:[re(w,{variant:"ghost",onClick:()=>u(!1),children:"Back to products"}),re(Cs,{})]}):Qe(fs,{children:[!r&&re("div",{className:"af-mb-4 af-flex af-justify-end",children:re(w,{variant:"outline",onClick:()=>u(!0),children:"Promo codes"})}),!r&&S,M]})})}import*as Da from"react";import{ArrowLeft as So,Check as fd,ChevronLeft as ho,ChevronRight as xo,ClipboardCopy as md,Mail as qr,Search as pd,Users as gd}from"lucide-react";import*as ca from"react";function Qn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=se(),[t,n]=ca.useState([]),[i,o]=ca.useState(!0),[d,f]=ca.useState(null),[u,r]=ca.useState(0),[p]=ca.useState(e),[b,g]=ca.useState(""),c=ca.useRef(0),l=ca.useCallback(async()=>{let v=++c.current;try{o(!0),f(null);let h={limit:p,offset:u*p};b.trim()&&(h.q=b.trim());let x=await s.getPeople(h);if(v!==c.current)return;n(x.people)}catch(h){if(v!==c.current)return;f(h instanceof Error?h:new Error("Failed to fetch people"))}finally{v===c.current&&o(!1)}},[s,u,p,b,a]);return ca.useEffect(()=>{l()},[l]),{people:t,isLoading:i,error:d,page:u,pageSize:p,hasNextPage:t.length===p,hasPreviousPage:u>0,setPage:r,q:b,setQ:v=>{g(v),r(0)},refetch:l}}import*as qa from"react";function Xn(e,{refreshKey:a}={}){let{api:s}=se(),[t,n]=qa.useState(null),[i,o]=qa.useState(e!==null),[d,f]=qa.useState(null),u=qa.useRef(0),r=qa.useCallback(async()=>{if(e===null){n(null),o(!1),f(null);return}let p=++u.current;try{o(!0),f(null);let b=await s.getPerson(e);if(p!==u.current)return;n(b)}catch(b){if(p!==u.current)return;f(b instanceof Error?b:new Error("Failed to fetch person"))}finally{p===u.current&&o(!1)}},[s,e,a]);return qa.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:d,refetch:r}}import{jsx as _,jsxs as oe}from"react/jsx-runtime";var zr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",vd="af-text-xs af-text-muted-foreground";function Fs(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function jr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function bd(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function yd({value:e,label:a}){let[s,t]=Da.useState(!1);return bd()?oe(w,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),t(!0),setTimeout(()=>t(!1),1500)}catch{}},"aria-label":a,className:"af-shrink-0",children:[s?_(fd,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):_(md,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function wo(e){return oe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&oe(te,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&_(te,{variant:"secondary",children:"Contact form"})]})}function No(e){return e.name?e.name:e.email?e.email:_("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var hd=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,xd=40;function wd(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>hd.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=xd).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return t?{message:String(t[1]),rest:a.filter(([n])=>n!==t[0])}:{message:null,rest:a}}function Nd(e){return e.replace(/_/g," ")}function Sd(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function _d({data:e}){let{message:a,rest:s}=wd(e);return a===null&&s.length===0?_("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):oe("div",{className:"af-space-y-3",children:[a!==null&&_("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&_("dl",{className:"af-space-y-1",children:s.map(([t,n])=>oe("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[_("dt",{className:J(vd,"af-w-28 af-shrink-0 af-capitalize"),children:Nd(t)}),_("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Sd(n)})]},t))})]})}function _o({formName:e,createdAt:a,data:s}){return oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[_(te,{variant:"outline",children:"Form submission (unverified)"}),e&&_("span",{className:"af-text-xs af-text-muted-foreground",children:e}),_("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Fs(a)})]}),_(_d,{data:s})]})}function Rd(e){return e.charged_total??e.amount_total}function Pd({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=Xn(e,{refreshKey:a}),d=jr(e,t?.submissions[0]?.form_name);return oe("div",{children:[oe("div",{className:"af-mb-6",children:[oe(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[_(So,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),oe("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[oe("div",{className:"af-min-w-0",children:[n?_(ae,{className:"af-h-7 af-w-48"}):_("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),oe("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[_("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),_(yd,{value:e,label:"Copy email address"})]})]}),_(w,{asChild:!0,children:oe("a",{href:d,children:[_(qr,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?oe("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[_(ae,{className:"af-w-40"}),_(ae,{className:"af-mt-2 af-w-64"})]},f)),_("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?_("div",{className:"af-flex af-justify-center af-py-8",children:_(la,{message:"Couldn't load this person.",onRetry:()=>o()})}):oe("div",{className:"af-space-y-6",children:[t.customer&&oe("div",{children:[_("h4",{className:J(zr,"af-mb-3"),children:"Customer"}),oe("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&oe("div",{className:"af-flex af-gap-2",children:[_("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),_("dd",{children:t.customer.name})]}),t.customer.phone&&oe("div",{className:"af-flex af-gap-2",children:[_("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),_("dd",{children:t.customer.phone})]}),oe("div",{className:"af-flex af-gap-2",children:[_("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),_("dd",{children:Fs(t.customer.created_at)})]})]})]}),t.orders.length>0&&oe("div",{children:[_("h4",{className:J(zr,"af-mb-3"),children:"Purchases"}),_("div",{className:"af-overflow-x-auto",children:oe(Be,{children:[_(Fe,{children:oe(pe,{children:[_($,{children:"Order"}),_($,{children:"Date"}),_($,{className:"af-text-right",children:"Total"}),_($,{children:"Status"})]})}),_(Me,{children:t.orders.map(f=>oe(pe,{children:[_(U,{className:"af-whitespace-nowrap af-font-medium",children:Xa(f)}),_(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Fs(f.created_at)}),_(U,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(Rd(f),f.currency)}),_(U,{children:_(ys,{status:f.status})})]},f.id))})]})}),_("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."})]}),t.submissions.length>0&&oe("div",{children:[_("h4",{className:J(zr,"af-mb-3"),children:"Messages"}),_("div",{className:"af-space-y-3",children:t.submissions.map(f=>_(_o,{formName:f.form_name,createdAt:f.created_at,data:f.data},f.id))})]})]})]})}function Cd({submissionId:e,onBack:a}){let{api:s}=se(),[t,n]=Da.useState(null),[i,o]=Da.useState(!0),[d,f]=Da.useState(null),[u,r]=Da.useState(0);return Da.useEffect(()=>{let p=!1;return o(!0),f(null),s.getSubmission(e).then(b=>{p||n(b)}).catch(b=>{p||f(b instanceof Error?b:new Error("Failed to load submission"))}).finally(()=>{p||o(!1)}),()=>{p=!0}},[s,e,u]),oe("div",{children:[oe("div",{className:"af-mb-6",children:[oe(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[_(So,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),_("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?_(ae,{className:"af-mt-1 af-h-4 af-w-32"}):t&&_("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Fs(t.metadata.submitted_at)})]}),i?oe("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[_(ae,{className:"af-w-40"}),_(ae,{className:"af-mt-2 af-w-64"}),_(ae,{className:"af-mt-2 af-w-52"}),_("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!t?_("div",{className:"af-flex af-justify-center af-py-8",children:_(la,{message:"Couldn't load this submission.",onRetry:()=>r(p=>p+1)})}):oe("div",{className:"af-space-y-3",children:[_(_o,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),_("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 Td={all:"All",customers:"Customers",leads:"Leads"},kd=["all","customers","leads"];function Ed(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function Ad({refreshKey:e,onBackToWebsite:a,className:s,maxRows:t,onViewAll:n}){let i=typeof t=="number",{people:o,isLoading:d,error:f,page:u,pageSize:r,hasNextPage:p,hasPreviousPage:b,setPage:g,q:c,setQ:l,refetch:v}=Qn({refreshKey:e}),[h,x]=Da.useState({kind:"list"}),[D,B]=Da.useState(""),[m,N]=Da.useState("all"),R=!i||!!n,A=K=>{if(i){n?.();return}K.email?x({kind:"person",email:K.email}):K.submission_id&&x({kind:"submission",submissionId:K.submission_id})},S=()=>{x({kind:"list"}),v()},k=K=>{let V=K.trim();V!==c&&l(V)},M=o.filter(K=>Ed(K,m)),y=i?M.slice(0,t):M,O;if(h.kind==="person")O=_(Pd,{email:h.email,refreshKey:e,onBack:S});else if(h.kind==="submission")O=_(Cd,{submissionId:h.submissionId,onBack:S});else{let K=oe("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[_("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:kd.map(V=>_("button",{type:"button","aria-pressed":m===V,onClick:()=>N(V),className:J("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",m===V?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Td[V]},V))}),oe("div",{className:"af-relative af-w-full af-max-w-xs",children:[_(pd,{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"}),_(ge,{type:"text",value:D,onChange:V=>B(V.target.value),onBlur:()=>k(D),onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),k(D))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&_(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{B(""),l("")},children:"Clear search"})]});if(d)O=oe("div",{children:[i?null:K,_("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(V=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-flex af-items-center af-justify-between",children:[_(ae,{className:"af-h-4 af-w-32"}),_(ae,{className:"af-h-4 af-w-16"})]}),_(ae,{className:"af-mt-2 af-h-5 af-w-28"}),_(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},V))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[_(Fe,{children:oe(pe,{children:[_($,{children:"Person"}),_($,{children:"Came from"}),_($,{children:"Latest message"}),_($,{children:"Last activity"}),_($,{className:"af-w-8"}),_($,{className:"af-w-8"})]})}),_(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(V=>oe(pe,{children:[_(U,{children:_(ae,{className:"af-h-4 af-w-40"})}),_(U,{children:_(ae,{className:"af-h-5 af-w-24"})}),_(U,{children:_(ae,{className:"af-h-4 af-w-56"})}),_(U,{children:_(ae,{className:"af-h-4 af-w-24"})}),_(U,{}),_(U,{})]},V))})]})}),_("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(f)O=oe("div",{children:[i?null:K,_("div",{className:"af-flex af-justify-center af-py-8",children:_(la,{message:"Couldn't load your leads.",onRetry:()=>v()})})]});else if(y.length===0&&u===0){let V=!!c||m!=="all";O=oe("div",{children:[V&&K,V?_(Ea,{children:c?"Nobody matches that search.":m==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):_(ks,{icon:gd,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)O=oe("div",{children:[i?null:K,_(Ea,{children:"No more results."}),_("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:oe(w,{variant:"outline",size:"sm",onClick:()=>g(u-1),children:[_(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let V=u*r+1,ce=u*r+o.length;O=oe("div",{children:[i?null:K,_("div",{className:"af-space-y-3 lg:af-hidden",children:y.map((G,Z)=>oe("div",{onClick:R?()=>A(G):void 0,className:`af-rounded-md af-border af-p-3${R?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[oe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[oe("div",{className:"af-min-w-0",children:[_("button",{type:"button",onClick:q=>{q.stopPropagation(),A(G)},disabled:!R,"aria-label":`Open ${G.name||G.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${R?" hover:af-underline":""}`,children:No(G)}),G.name&&G.email&&_("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:G.email})]}),oe("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[_("span",{className:"af-text-xs af-text-muted-foreground",children:Fs(G.last_activity_at)}),G.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:jr(G.email),onClick:q=>q.stopPropagation(),"aria-label":`Email ${G.email}`,children:_(qr,{className:"af-h-4 af-w-4"})})})]})]}),_("div",{className:"af-mt-2",children:wo(G)}),G.latest_message_excerpt&&_("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:G.latest_message_excerpt})]},G.email??G.submission_id??Z))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[_(Fe,{children:oe(pe,{children:[_($,{children:"Person"}),_($,{children:"Came from"}),_($,{children:"Latest message"}),_($,{children:"Last activity"}),_($,{className:"af-w-8",children:_("span",{className:"af-sr-only",children:"Reply"})}),_($,{className:"af-w-8"})]})}),_(Me,{children:y.map((G,Z)=>oe(pe,{onClick:R?()=>A(G):void 0,className:R?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[oe(U,{className:"af-max-w-[260px] af-font-medium",children:[_("button",{type:"button",onClick:q=>{q.stopPropagation(),A(G)},disabled:!R,"aria-label":`Open ${G.name||G.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${R?" hover:af-underline":""}`,children:No(G)}),G.name&&G.email&&_("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:G.email})]}),_(U,{children:wo(G)}),_(U,{className:"af-max-w-[320px]",children:G.latest_message_excerpt?_("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:G.latest_message_excerpt}):_("span",{className:"af-text-muted-foreground",children:"\u2014"})}),_(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Fs(G.last_activity_at)}),_(U,{className:"af-w-8",children:G.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:jr(G.email),onClick:q=>q.stopPropagation(),"aria-label":`Email ${G.email}`,children:_(qr,{className:"af-h-4 af-w-4"})})})}),_(U,{className:"af-w-8 af-text-right",children:_(xo,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},G.email??G.submission_id??Z))})]})}),!i&&oe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[_("span",{className:"af-text-sm af-text-muted-foreground",children:m==="all"?`Showing ${V}-${ce}`:`${y.length} of ${o.length} on this page`}),oe("div",{className:"af-flex af-items-center af-gap-2",children:[oe(w,{variant:"outline",size:"sm",onClick:()=>g(u-1),disabled:!b,children:[_(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),oe(w,{variant:"outline",size:"sm",onClick:()=>g(u+1),disabled:!p,children:["Next",_(xo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?_("div",{className:s,children:O}):_(Nt,{title:"Leads",onBackToWebsite:a,hideBackButton:h.kind!=="list",className:s,children:O})}function er(e){return _(Ad,{...e},e.maxRows==null?"full":"compact")}import{ChevronLeft as Ro,ChevronRight as Id,Repeat as Dd}from"lucide-react";import*as ea from"react";function tr({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=se(),[t,n]=ea.useState([]),[i,o]=ea.useState(0),[d,f]=ea.useState(!0),[u,r]=ea.useState(null),[p,b]=ea.useState(0),[g,c]=ea.useState(e),[l,v]=ea.useState(void 0),h=ea.useRef(0),x=ea.useCallback(async()=>{let B=++h.current;try{f(!0),r(null);let m={limit:g,offset:p*g};l&&(m.status=l);let N=await s.getSubscriptions(m);if(B!==h.current)return;n(N.subscriptions),o(N.total)}catch(m){if(B!==h.current)return;r(m instanceof Error?m:new Error("Failed to fetch subscriptions"))}finally{B===h.current&&f(!1)}},[s,p,g,l,a]);ea.useEffect(()=>{x()},[x]);let D=Math.ceil(i/g);return{subscriptions:t,total:i,isLoading:d,error:u,page:p,pageSize:g,hasNextPage:p<D-1,hasPreviousPage:p>0,setPage:b,setPageSize:B=>{c(B),b(0)},status:l,setStatus:B=>{v(B),b(0)},refetch:x}}import{jsx as ee,jsxs as Xe}from"react/jsx-runtime";function Po(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Co({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 Ld(e,a){let s=j(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function To({sub:e}){let a=e.current_amount!==e.plan_amount;return Xe("div",{children:[ee("div",{className:"af-font-medium af-tabular-nums",children:Ld(e,e.current_amount)}),a&&Xe("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function ko(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Po(e.current_period_end)}`:"Ends at period end":e.current_period_end?Po(e.current_period_end):"\u2014"}function Eo({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:d,pageSize:f,hasNextPage:u,hasPreviousPage:r,setPage:p,refetch:b}=tr({refreshKey:e}),g;if(i)g=Xe("div",{children:[ee("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(c=>Xe("div",{className:"af-rounded-md af-border af-p-3",children:[Xe("div",{className:"af-flex af-items-center af-justify-between",children:[ee(ae,{className:"af-h-4 af-w-40"}),ee(ae,{className:"af-h-4 af-w-20"})]}),ee(ae,{className:"af-mt-2 af-h-3 af-w-32"}),ee(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},c))}),ee("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Xe(Be,{children:[ee(Fe,{children:Xe(pe,{children:[ee($,{children:"Subscriber"}),ee($,{children:"Plan"}),ee($,{className:"af-text-right",children:"Amount"}),ee($,{children:"Renews"}),ee($,{children:"Status"})]})}),ee(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(c=>Xe(pe,{children:[ee(U,{children:ee(ae,{className:"af-h-4 af-w-44"})}),ee(U,{children:ee(ae,{className:"af-h-4 af-w-32"})}),ee(U,{className:"af-text-right",children:ee(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),ee(U,{children:ee(ae,{className:"af-h-4 af-w-24"})}),ee(U,{children:ee(ae,{className:"af-h-5 af-w-20"})})]},c))})]})}),ee("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)g=ee("div",{className:"af-flex af-justify-center af-py-8",children:ee(la,{message:"Couldn't load your subscriptions.",onRetry:()=>b()})});else if(t.length===0&&d===0)g=ee(Ea,{icon:ee(Dd,{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(t.length===0)g=Xe("div",{children:[ee(Ea,{children:"No more results."}),ee("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Xe(w,{variant:"outline",size:"sm",onClick:()=>p(d-1),children:[ee(Ro,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=d*f+1,l=d*f+t.length;g=Xe("div",{children:[ee("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(v=>Xe("div",{className:"af-rounded-md af-border af-p-3",children:[Xe("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Xe("div",{className:"af-min-w-0",children:[ee("div",{className:"af-truncate af-text-sm af-font-medium",children:v.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:v.plan_title||"Untitled plan"})]}),ee("div",{className:"af-shrink-0 af-text-right",children:ee(To,{sub:v})})]}),Xe("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(Co,{sub:v}),v.is_test&&ee(te,{variant:"outline",children:"Test"}),ee("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ko(v)})]}),ee(Oa,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},v.id))}),ee("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Xe(Be,{children:[ee(Fe,{children:Xe(pe,{children:[ee($,{children:"Subscriber"}),ee($,{children:"Plan"}),ee($,{className:"af-text-right",children:"Amount"}),ee($,{children:"Renews"}),ee($,{children:"Status"})]})}),ee(Me,{children:t.map(v=>Xe(pe,{children:[ee(U,{className:"af-max-w-[240px]",children:ee("div",{className:"af-truncate af-font-medium",children:v.customer_email||ee("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),ee(U,{className:"af-max-w-[220px]",children:ee("div",{className:"af-truncate",children:v.plan_title||ee("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),ee(U,{className:"af-whitespace-nowrap af-text-right",children:ee(To,{sub:v})}),ee(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ko(v)}),Xe(U,{children:[Xe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(Co,{sub:v}),v.is_test&&ee(te,{variant:"outline",children:"Test"})]}),ee(Oa,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},v.id))})]})}),Xe("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 ${c}-${l} of ${n}`}),Xe("div",{className:"af-flex af-items-center af-gap-2",children:[Xe(w,{variant:"outline",size:"sm",onClick:()=>p(d-1),disabled:!r,children:[ee(Ro,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Xe(w,{variant:"outline",size:"sm",onClick:()=>p(d+1),disabled:!u,children:["Next",ee(Id,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ee(Nt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:g})}import*as Gr from"react";import{Fragment as Ao,jsx as ua,jsxs as ar}from"react/jsx-runtime";function Io({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:d,isLoading:f,error:u,refetch:r}=Es({refreshKey:e,initialPageSize:1,includeAggregates:!0}),p=Ls({refreshKey:e}),[b,g]=Gr.useState(!1),[c,l]=Gr.useState(null),v=ua("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!f&&!d?ar("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. ",ua(w,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):f||!d?ar(Ao,{children:[ua(st,{label:"Outstanding",children:ua(ae,{className:"af-h-6 af-w-24"})}),ua(st,{label:"Overdue",children:ua(ae,{className:"af-h-6 af-w-24"})}),ua(st,{label:"Paid this month",children:ua(ae,{className:"af-h-6 af-w-24"})})]}):ar(Ao,{children:[ua(st,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:j(d.outstanding.amount,d.currency)}),ua(st,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:j(d.overdue.amount,d.currency)}),ua(st,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:j(d.paid_this_month.amount,d.currency)})]})});return ar(Nt,{title:"Invoices",onBackToWebsite:s,hideBackButton:b,className:o,children:[v,!b&&ua(Is,{retainers:p.retainers,isLoading:p.isLoading,error:p.error,onRetry:()=>void p.refetch(),activeRetainerId:c?.id??null,onShowCycles:h=>l(x=>x?.id===h.id?null:h),total:p.total,endedTotal:p.endedTotal,isLoadingMore:p.isLoadingMore,onLoadMore:()=>void p.loadMore(),includeEnded:p.includeEnded,onIncludeEndedChange:p.setIncludeEnded}),ua(us,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:g,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:c?{id:c.id,label:`${c.customer_name??c.customer_email??"Recurring invoices"} \u2014 ${c.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}import*as St from"react";var Od=2e3,Dt=()=>({data:null,error:null,isLoading:!0});function Ms(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=se(),[i,o]=St.useState(Dt),[d,f]=St.useState(Dt),[u,r]=St.useState(Dt),[p,b]=St.useState(Dt),[g,c]=St.useState(Dt),l=q=>Object.fromEntries(q.map(ne=>[ne,Dt()])),[v,h]=St.useState(()=>l(s)),x=St.useRef(0),D=St.useRef(0),B=St.useRef("idle"),m=s.join(","),N=ss()??"",R=JSON.stringify(t),A=`${e}:${m}:${R}:${N}`,[S,k]=St.useState({api:n,fetchIdentity:A});(S.api!==n||S.fetchIdentity!==A)&&(k({api:n,fetchIdentity:A}),x.current+=1,o(Dt),f(Dt),r(Dt),b(Dt),h(l(m?m.split(","):[])));let M=`${e}:${String(a??"")}:${N}`,[y,O]=St.useState({api:n,conversionsIdentity:M});(y.api!==n||y.conversionsIdentity!==M)&&(O({api:n,conversionsIdentity:M}),D.current+=1,B.current="idle",c(Dt));let K=St.useCallback(async q=>{let ne=++x.current,W=m?m.split(","):[];o(Dt),f(Dt),r(Dt),b(Dt),h(Object.fromEntries(W.map(P=>[P,Dt()])));let he=B.current!=="pending"&&(q?.force===!0||B.current==="idle"),Ze=(P,L)=>L.then(I=>{ne===x.current&&P({data:I,error:null,isLoading:!1})},I=>{ne===x.current&&P({data:null,error:I instanceof Error?I:new Error("Failed to fetch report"),isLoading:!1})}),it=n.getAnalyticsStatus(),Pe=Ze(o,it),je=Symbol("status-timeout"),et,xe=await Promise.race([it.then(P=>P,()=>null),new Promise(P=>{et=setTimeout(()=>P(je),Od)})]);if(clearTimeout(et),ne!==x.current)return;if(xe===je&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),xe!==null&&xe!==je&&(xe.collecting!==!0||xe.first_seen===null&&!xe.first_seen_unavailable||xe.first_seen!==null&&xe.first_seen_in_reports===!1)){let P={data:null,error:null,isLoading:!1};f(P),r(P),b(P),h(Object.fromEntries(W.map(L=>[L,{...P}]))),he&&(c(P),B.current="done"),await Pe;return}await Promise.all([xe===je?Promise.resolve():Pe,Ze(f,n.getAnalyticsSummary(e,t)),Ze(r,n.getAnalyticsTimeseries(e,t)),Ze(b,n.getAnalyticsChannels(e,t)),he?(()=>{B.current="pending";let P=++D.current;return c(Dt),n.getAnalyticsConversions(e).then(L=>{P===D.current&&(c({data:L,error:null,isLoading:!1}),B.current="done")},L=>{P===D.current&&(c({data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1}),B.current="done")})})():Promise.resolve(),...W.map(P=>n.getAnalyticsBreakdown(P,e,t).then(L=>{ne===x.current&&h(I=>({...I,[P]:{data:L,error:null,isLoading:!1}}))},L=>{ne===x.current&&h(I=>({...I,[P]:{data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,m,R,M,N]),V=St.useCallback(async()=>{let q=x.current;try{let ne=await n.getAnalyticsStatus();if(q!==x.current)return;o({data:ne,error:null,isLoading:!1})}catch(ne){if(q!==x.current)return;o(W=>({data:W.data,error:ne instanceof Error?ne:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ce=St.useCallback(()=>K({force:!0}),[K]);St.useEffect(()=>{K()},[K,a]);let G=i.isLoading||d.isLoading||u.isLoading||p.isLoading||g.isLoading||Object.values(v).some(q=>q.isLoading),Z=[u,d,p,g,...Object.values(v)].map(q=>q.data?.status==="ok"?q.data.timezone:void 0).find(q=>q!==void 0);return{status:i,summary:d,timeseries:u,channels:p,conversions:g,breakdowns:v,reportedZone:Z,isLoading:G,refetch:ce,refetchStatus:V}}import*as _t from"react";var Wr=3e4,Kr=3;function sr(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=se(),[o,d]=_t.useState(null),[f,u]=_t.useState(null),[r,p]=_t.useState(!1),[b,g]=_t.useState(null),[c,l]=_t.useState(!1),[v,h]=_t.useState(!0),[x,D]=_t.useState(0),B=_t.useRef(0),m=_t.useRef(0),N=_t.useRef(void 0);s!==void 0&&(N.current=s);let R=a?N.current===!0||N.current===void 0&&t:!0,[A,S]=_t.useState({api:i,identity:n}),k=n!==void 0&&n!==A.identity;(A.api!==i||k)&&(N.current=void 0,S({api:i,identity:n}),m.current+=1,B.current=0,d(null),u(null),p(!1),g(null),l(!1),h(!0),D(0));let M=_t.useRef(()=>{}),y=_t.useRef(null),O=_t.useCallback(async()=>{if(y.current!==null&&y.current===m.current)return;let K=++m.current;y.current=K;try{let V=await i.getAnalyticsRealtime();if(K!==m.current)return;if(V.status==="unreachable"){l(!0),p(!0),h(!1),D(ce=>ce+1);return}B.current=0,l(!1),d(V.data.current_visitors),u(V.as_of),p(!1),g(null),h(!1),D(ce=>ce+1)}catch(V){if(K!==m.current)return;B.current+=1,h(!1),D(ce=>ce+1),p(!0),B.current>=Kr&&g(V instanceof Error?V:new Error("Realtime unavailable"))}finally{y.current===K&&(y.current=null)}},[i]);return M.current=()=>void O(),_t.useEffect(()=>{let K,V=()=>{K===void 0&&(K=setInterval(()=>M.current(),Wr))},ce=()=>{K!==void 0&&(clearInterval(K),K=void 0)},G=()=>{typeof document<"u"&&document.hidden?ce():(M.current(),V())};return R?((typeof document>"u"||!document.hidden)&&(M.current(),V()),document?.addEventListener("visibilitychange",G),()=>{ce(),document?.removeEventListener("visibilitychange",G),m.current+=1}):()=>{document?.removeEventListener("visibilitychange",G)}},[A.api,A.identity,R]),{currentVisitors:o,asOf:f,isStale:r,error:b,isUnreachable:c,isInitialLoad:v,polls:x}}import*as rt from"react";import*as Lo from"react";import{jsx as Zr,jsxs as Do}from"react/jsx-runtime";function Bd(){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 Jr({value:e,chosen:a,onChange:s}){let t=qs(),n=a===null&&t!==null&&e===t,i=Lo.useMemo(()=>{let o=Bd();return o.includes(e)?o:[e,...o]},[e]);return Do("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[Zr("span",{className:"af-sr-only",children:"Reporting timezone"}),Do("select",{value:n?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[Zr("option",{value:"",children:t?`${t.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),i.map(o=>Zr("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var nr=(e,{published:a}={})=>{let s=a===!1,t=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),n=!t&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,i=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=n||i;return{notCollecting:t,awaitingFirstVisit:n,firstVisitTooRecent:i,holdingForFirstData:o,nothingToReport:t||o}};import*as tn from"react";var Fd=3e4;function rr({status:e,holdingForFirstData:a,refetchStatus:s,refetch:t}){tn.useEffect(()=>{if(!a)return;let i,o=()=>{i===void 0&&(i=setInterval(()=>void s(),Fd))},d=()=>{i!==void 0&&(clearInterval(i),i=void 0)},f=()=>{typeof document<"u"&&document.hidden?d():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",f),()=>{d(),document?.removeEventListener("visibilitychange",f)}},[a,s]);let n=tn.useRef(void 0);tn.useEffect(()=>{if(!e){n.current=void 0;return}let i=n.current;n.current=a,i===!0&&!a&&t()},[e,a,t])}import*as Ns from"react";var Md=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vt(e){let a=Math.abs(e);if(a<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[t,n]of s)if(a>=t){let i=e/t,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&t!==1e9?Vt(o*t):`${o}${n}`}return String(e)}function $s(e){return`${(e*100).toFixed(1)}%`}function an(e){let a=Math.max(0,Math.round(e));if(a<60)return`${a}s`;let s=Math.floor(a/60);return s<60?`${s}m ${a%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Bo(e){let a=Math.max(0,Math.round(e));return a>=3600&&a%3600===0?`${a/3600}h`:a>=60&&a%60===0?`${a/60}m`:an(a)}function Fo(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function Mo(e,a){if(!(!Number.isFinite(e)||e<=0))for(let s of a){let t=Math.ceil(e/s);if(t<=5)return Array.from({length:t+1},(n,i)=>Number((i*s).toPrecision(12)))}}function sn(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function $o(e){let a=new Date(e);return Number.isNaN(a.getTime())?"as of an unknown time":`as of ${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}function Yr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${Md[a-1]} ${s}`}function Oo(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function $d(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Uo(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=Oo(e.to,s);for(let o=Oo(e.from,s);o<i;o=$d(o))n.push(t.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Vo(e){let a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=new Date(`${e}T00:00:00Z`);if(Number.isNaN(t.getTime()))return e;let n=String(t.getUTCDate()).padStart(2,"0");return`${a[t.getUTCDay()]}, ${n} ${s[t.getUTCMonth()]}`}import{Fragment as Vd,jsx as ms,jsxs as Ud}from"react/jsx-runtime";function Ho({what:e="This report",onRetry:a,collecting:s}){return Ud("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:[ms("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),ms("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:s===!0?`${e} is temporarily unavailable. Your data is still being collected \u2014 this is not zero traffic.`:`${e} is temporarily unavailable, so we can\u2019t show it right now. This is not a report of zero traffic.`}),a?ms("button",{type:"button",onClick:a,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 ir({what:e="No data"}){return ms("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 ts({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?ms("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?ms(Ho,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?ms(Ho,{what:t,onRetry:n,collecting:i}):ms(Vd,{children:o(e.data)})}import{Fragment as Hd,jsx as ta,jsxs as ws}from"react/jsx-runtime";function Qr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:d,maxRows:f=9}){let[u,r]=Ns.useState(!1);if(e.length===0)return ta(ir,{what:i});let p=e.reduce((c,l)=>Math.max(c,Number(l[s]??0)),0)||1,b=Math.max(0,e.length-f),g=u?e:e.slice(0,f);return ws(Hd,{children:[ws("table",{className:"af-w-full af-text-sm",children:[ta("thead",{children:ws("tr",{className:"af-text-xs af-text-muted-foreground",children:[ta("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),ta("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),ta("tbody",{children:g.map((c,l)=>{let v=Number(c[s]??0),h=c[a]??null,x=sn(h),D=n?c[n]:null,B=h!==null&&(d?d(h,D):!0);return ws("tr",{className:"af-border-t af-border-border",children:[ws("td",{className:"af-relative af-py-1.5 af-pr-2",children:[ta("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,v/p*100)}%`}}),h!==null&&o&&B?ta("button",{type:"button",onClick:()=>o(h,D),title:`Filter by ${x}`,"aria-label":`Filter by ${x}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:x}):ta("span",{className:"af-relative af-break-words af-text-foreground",children:x}),D?ta("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:D}):null]}),ta("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(v)})]},`${x}-${D??""}-${l}`)})})]}),b>0?ta("button",{type:"button",onClick:()=>r(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:u?"Show fewer":`Show all ${e.length}`}):null]})}function nn({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=Ns.useState(s),o=a.find(g=>g.id===n)??a[0],d=Ns.useId(),f=g=>`${d}-tab-${g}`,u=g=>`${d}-panel-${g}`,r=Ns.useRef(null),p=(g,c)=>{g.preventDefault();let l=(c+a.length)%a.length;i(a[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return ws("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[ws("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:[ta("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:g=>{let c=a.findIndex(l=>l.id===n);g.key==="ArrowRight"&&p(g,c+1),g.key==="ArrowLeft"&&p(g,c-1),g.key==="Home"&&p(g,0),g.key==="End"&&p(g,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(g=>ta("button",{id:f(g.id),role:"tab",type:"button","aria-selected":g.id===n,"aria-controls":u(g.id),tabIndex:g.id===n?0:-1,onClick:()=>i(g.id),className:g.id===n?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:g.label},g.id))}),t]}),o?ta("div",{id:u(o.id),role:"tabpanel","aria-labelledby":f(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as aa from"react";import*as ps from"@radix-ui/react-popover";var Us=3,Vs=100;import{jsx as ft,jsxs as ja}from"react/jsx-runtime";var rn={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"},zd=Object.keys(rn);function zo(e){let a=rn[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>sn(n)).join(" or ");return`${a} ${s} ${t}`}function Xr(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function qd(e,a){let s={};for(let[t,n]of Object.entries(a)){let i=e.get(t)??new Set;for(let o of n)i.add(o);e.set(t,i),s[t]=[...i]}return s}function qo(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));return s>=0?e.map((t,n)=>n===s?a:t):a.values.length>100||e.length>=3?e:[...e,a]}function jd(e){return{dimension:e,operator:"is",search:"",picked:[]}}function jo(e,a,s,t={}){if(e.api!==a.api||e.period!==a.period)return e.api=a.api,e.period=a.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=qd(e.byDimension,s);for(let[i,o]of Object.entries(t)){let d=e.foldsByLabel.get(i)??new Set;for(let f of o)d.add(f);e.foldsByLabel.set(i,d)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Go(e){let{filters:a,onChange:s}=e,t=a.length>=3;return aa.useEffect(()=>{if(a.length===0)return;let n=i=>{let o=i.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||i.key==="Escape"&&s([])};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[a.length,s]),ja("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>ja("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:[ft("span",{className:"af-text-foreground",children:zo(n)}),ft("button",{type:"button","aria-label":`Remove filter ${zo(n)}`,onClick:()=>s(a.filter((o,d)=>d!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),ft(Gd,{...e,disabled:t}),a.length>0?ft("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Gd({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,d]=aa.useState(!1),f=aa.useRef(null),[u,r]=aa.useState(null);aa.useEffect(()=>{r(f.current?.closest(".aifeatures-admin")??null)},[]);let[p,b]=aa.useState(null),[g,c]=aa.useState("is"),[l,v]=aa.useState(""),[h,x]=aa.useState([]);aa.useEffect(()=>{o||(b(null),c("is"),v(""),x([]))},[o]);let D=aa.useRef(t);D.current!==t&&(D.current=t,o&&d(!1),p!==null&&b(null),h.length>0&&x([]),l!==""&&v(""),g!=="is"&&c("is"));let B=k=>{let M=jd(k);b(M.dimension),x(M.picked),v(M.search),c(M.operator)},N=(p?s[p]??[]:[]).filter(k=>k.toLowerCase().includes(l.trim().toLowerCase())),R=p===null||h.length===0?null:Xr(e,{dimension:p,operator:g,values:i?i(p,h):h}),A=R!==null&&R!==e,S=()=>{let k=R;!k||k===e||(a(k),d(!1))};return ja(ps.Root,{open:o,onOpenChange:d,children:[ft(ps.Trigger,{asChild:!0,children:ft("button",{ref:f,type:"button",disabled:!1,title:n?`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"})}),ft(ps.Portal,{container:u,children:ft(ps.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:p===null?ja("div",{children:[ft("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),ft("div",{className:"af-max-h-96 af-overflow-y-auto",children:zd.filter(k=>s[k]!==void 0).map(k=>{let M=s[k]?.length??0,y=!e.some(O=>O.dimension===k)&&e.length>=3;return ja("button",{type:"button",onClick:()=>B(k),disabled:M===0||y,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:[ft("span",{children:rn[k]}),ft("span",{className:"af-text-muted-foreground",children:M===0?"no data":y?"no room":M})]},k)})})]}):ja("div",{children:[ja("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[ft("button",{type:"button",onClick:()=>B(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),ft("span",{className:"af-text-xs af-font-medium af-text-foreground",children:rn[p]}),ja("select",{"aria-label":"Operator",value:g,onChange:k=>c(k.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[ft("option",{value:"is",children:"is"}),ft("option",{value:"is_not",children:"is not"})]})]}),ft("input",{type:"text",value:l,onChange:k=>v(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${rn[p]}`,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"}),ft("div",{className:"af-max-h-48 af-overflow-y-auto",children:N.length===0?ja("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):N.map(k=>ja("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:[ft("input",{type:"checkbox",checked:h.includes(k),disabled:!h.includes(k)&&h.length>=100,onChange:M=>x(y=>M.target.checked?[...y,k]:y.filter(O=>O!==k))}),ft("span",{className:"af-break-all",children:sn(k)})]},k))}),ft("button",{type:"button",onClick:S,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:h.length<=1?"Apply filter":h.length>=100?`Apply filter (${h.length} values \u2014 the maximum)`:`Apply filter (${h.length} values)`})]})})})]})}import{Fragment as Zd,jsx as Ht,jsxs as or}from"react/jsx-runtime";var Wd=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Vt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Vt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Vt,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:$s,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:an,chart:"visit_duration_seconds"}];function Kd({current:e,previous:a,downIsGood:s}){if(a===0)return null;let t=(e-a)/a;if(Math.abs(t)<5e-4)return null;let n=t>0,i=s?!n:n,o=`${n?"+":""}${(t*100).toFixed(1)}%`;return Ht("span",{className:i?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function Wo({summary:e,selected:a,onSelect:s}){return Ht("div",{className:"af-@container",children:Ht("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Wd.map(t=>{let n=t.chart===a,i=s!==void 0,o=or(Zd,{children:[Ht("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),or("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Ht("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?Ht(Kd,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?Ht("button",{type:"button","aria-pressed":n,onClick:()=>s(t.chart),className:n?"af-rounded-lg af-border af-border-border af-bg-muted af-p-3 af-text-left":"af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-text-left hover:af-bg-muted/50",children:o},t.key):Ht("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function ei({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return or("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:[Ht("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Ht("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return Ht("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?$o(a):"freshness unknown",d=i?" across the whole site, not the current filter,":"",f=s?`${e} current visitors${d} ${o} (not updating)`:`${e} current visitors${d} ${o}`;return or("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:f,children:[Ht("span",{"aria-hidden":"true",className:s?"af-h-2 af-w-2 af-rounded-full af-bg-muted-foreground":"af-h-2 af-w-2 af-rounded-full af-bg-emerald-500"}),Ht("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Ht("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),Ht("span",{className:"af-sr-only",children:f})]})}import*as Zo from"react";import{Star as Jd}from"lucide-react";import{Fragment as Ko,jsx as Tt,jsxs as Ss}from"react/jsx-runtime";function lr(e,a){return!a||e.goal!==a.goal?!1:a.implicit===void 0||e.implicit===a.implicit}function cr({rows:e,denominator:a,windowPrecedesCollection:s=!1,coverageUnknown:t=!1,emptyCopy:n="No conversions in this period",maxRows:i=9,primaryConversion:o}){let[d,f]=Zo.useState(!1),u=e.filter(v=>!v.implicit||v.visitors>0||v.events>0||lr(v,o)),r=s?Tt("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."}):t?Tt("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 Ss(Ko,{children:[Tt(ir,{what:n}),r]});let p=u.slice(0,i),b=o?u.find(v=>lr(v,o)):void 0,g=b&&!p.includes(b)?u.filter(v=>p.includes(v)||v===b).slice(0,Math.max(0,i-1)).concat(b):p,c=d?e:g,l=Math.max(0,e.length-g.length);return Ss(Ko,{children:[Ss("table",{className:"af-w-full af-text-sm",children:[Tt("thead",{children:Ss("tr",{className:"af-text-xs af-text-muted-foreground",children:[Tt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),Tt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),Tt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),Tt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),Tt("tbody",{children:c.map((v,h)=>Ss("tr",{className:"af-border-t af-border-border","aria-current":lr(v,o)?"true":void 0,children:[Tt("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:lr(v,o)?Ss("span",{className:"af-flex af-items-center af-gap-1.5",children:[Tt(Jd,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),Tt("span",{className:"af-font-medium af-text-foreground",children:v.goal}),Tt("span",{className:"af-sr-only",children:"(your main conversion)"})]}):v.goal}),Tt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(v.visitors)}),Tt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(v.events)}),Tt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:v.conversion_rate===null?Tt("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):$s(v.conversion_rate)})]},`${v.goal}-${h}`))})]}),l>0?Tt("button",{type:"button",onClick:()=>f(v=>!v),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,Ss("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Vt(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),r]})}import{Area as Yd,AreaChart as Qd,CartesianGrid as Xd,ResponsiveContainer as ef,Tooltip as tf,XAxis as af,YAxis as sf}from"recharts";import{jsx as zt,jsxs as on}from"react/jsx-runtime";var ur={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},ai={visitors:Vt,visits:Vt,pageviews:Vt,views_per_visit:e=>e.toFixed(2),bounce_rate:$s,visit_duration_seconds:an},nf=31,rf=new Set(["visitors","visits","pageviews"]),of={...ai,bounce_rate:Fo,visit_duration_seconds:Bo},ti=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],lf=[5,10,15,30,60,120,300,600,900,1800,3600,7200],cf=[.01,.02,.05,.1,.2,.25,.5,1],uf=[.25,.5,1,2,5,10,25,50],df={visitors:ti,visits:ti,pageviews:ti,views_per_visit:uf,bounce_rate:cf,visit_duration_seconds:lf};function ff({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return on("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:[zt("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:ur[t]}),on("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[zt("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),zt("span",{className:"af-text-muted-foreground",children:Vo(String(s))}),zt("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:ai[t](Number(n[t]??0))})]})]})}function dr({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=Uo(a,e,t),o=ai[s],d=of[s],f=Mo(i.reduce((r,p)=>Math.max(r,Number(p[s]??0)),0),df[s]),u=`${ur[s]} by day: ${i.map(r=>`${Yr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return on("figure",{"aria-label":`${ur[s]} over time`,className:"af-m-0",children:[zt(ef,{width:"100%",height:n,children:on(Qd,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[zt("defs",{children:on("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[zt("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),zt("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),zt(Xd,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),zt(af,{dataKey:"date",tickFormatter:Yr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),zt(sf,{allowDecimals:!rf.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:r=>d(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),zt(tf,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:zt(ff,{metric:s})}),zt(Yd,{type:"linear",dataKey:s,name:ur[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=nf?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),zt("figcaption",{className:"af-sr-only",children:u})]})}import{Fragment as si,jsx as be,jsxs as Mt}from"react/jsx-runtime";var mf="2026-08-13",pf=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],gf=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function vf({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,primaryConversion:n,className:i,published:o,lastPublishedAt:d}){let[f,u]=rt.useState(30),[r,p]=rt.useState(()=>vr()),b=e!==void 0&&a!==void 0,[g,c]=rt.useState(e??[]),{api:l}=se(),[v,h]=rt.useState(l);v!==l&&(h(l),!b&&g.length>0&&c([]));let x=b?e:g,D=rt.useCallback(I=>{a&&a(I),b||c(I)},[a,b]),B=rt.useCallback((I,ue,me)=>{let _e=Array.isArray(ue)?ue:[ue];if(_e.length===0)return null;let Te=Xr(x,{dimension:I,operator:"is",values:_e});if(me&&(!me.value||(Te=qo(Te,{dimension:me.dimension,operator:"is",values:[me.value]}),!Te.find(Ge=>Ge.dimension===me.dimension&&Ge.operator!=="is_not")?.values.includes(me.value))))return null;let tt=Te.find(Ue=>Ue.dimension===I&&Ue.operator!=="is_not");return _e.every(Ue=>tt?.values.includes(Ue))?JSON.stringify(Te)===JSON.stringify(x)?null:Te:null},[x]),m=rt.useCallback((I,ue,me)=>B(I,ue,me)!==null,[B]),N=rt.useCallback((I,ue,me)=>{let _e=B(I,ue,me);_e&&D(_e)},[B,D]),[R,A]=rt.useState("visitors"),S=Ms(f,{refreshKey:s,breakdowns:gf,filters:x}),k=S.status.data,M=S.reportedZone??k?.timezone,y=M??r??qs()??"UTC",{notCollecting:O,awaitingFirstVisit:K,firstVisitTooRecent:V,holdingForFirstData:ce}=nr(k,{published:o}),G=o===!1,Z=sr({collecting:K||O?!1:k?.collecting,statusFailed:S.status.error!=null,identity:k?.analytics_id}),q=rt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),ne=rt.useMemo(()=>{let I=S.breakdowns.sources?.data,ue={};if(!I||I.status!=="ok")return ue;for(let me of I.data){let _e=me.source,Te=me.sources;typeof _e=="string"&&Array.isArray(Te)&&Te.length>0&&(ue[_e]=Te)}return ue},[S.breakdowns.sources?.data]),W=rt.useMemo(()=>{let I=(_e,Te)=>{let tt=S.breakdowns[_e]?.data;return!tt||tt.status!=="ok"?[]:[...new Set(tt.data.map(Ue=>Ue[Te]).filter(Ue=>typeof Ue=="string"&&Ue!==""))]};return{channel:S.channels.data?.status==="ok"?[...new Set(S.channels.data.data.map(_e=>_e.channel))]:[],source:I("sources","source"),campaign:I("utm/campaign","campaign"),page:I("pages","pathname"),entry_page:I("entry-pages","pathname"),exit_page:I("exit-pages","pathname"),country:I("countries","country"),browser:I("browsers","browser"),os:I("operating-systems","os"),device:I("devices","device")}},[S.breakdowns,S.channels.data]),[he,Ze]=rt.useState({}),it=JSON.stringify(W),[Pe,je]=rt.useState(new Map),et=JSON.stringify(ne);rt.useEffect(()=>{let{suggestions:I,folds:ue}=jo(q.current,{api:l,period:f},JSON.parse(it),JSON.parse(et));Ze(I),je(ue)},[it,et,l,f]);let xe=rt.useCallback((I,ue)=>I!=="source"?ue:[...new Set(ue.flatMap(me=>{let _e=[...Pe.get(me)??[],...ne[me]??[]];return _e.length>0?_e:[me]}))],[Pe,ne]),Et=rt.useMemo(()=>{let I=S.conversions.error;return I instanceof Ot&&I.details?.code==="goals_exceed_report_budget"?I.message:null},[S.conversions.error]),P=rt.useMemo(()=>{let I=[S.summary,S.timeseries,S.channels,...Object.values(S.breakdowns)];for(let ue of I){let me=ue?.error;if(me instanceof Ot&&me.details?.code==="filter_unsupported")return me.message}return null},[S.summary,S.timeseries,S.channels,S.breakdowns]),L=(I,ue,me,_e,Te,tt,Ue,Ge,ie)=>()=>{let Ee=S.breakdowns[I];return be(ts,{sourced:Ee?.data??null,error:Ee?.error,isLoading:Ee?.isLoading,what:ue,collecting:k?.collecting,onRetry:S.refetch,children:ot=>{let sa=xt=>Ge?xe(Ge,[xt]):xt;return be(Qr,{rows:ot,dimension:me,metric:_e,metricLabel:Te,secondary:tt,emptyCopy:x.length>0?"No data for this filter":Ue,canFilter:Ge?(xt,At)=>m(Ge,sa(xt),ie?{dimension:ie,value:At}:void 0):()=>!1,onFilter:Ge?(xt,At)=>N(Ge,sa(xt),ie?{dimension:ie,value:At}:void 0):void 0})}})};if(rr({status:k,holdingForFirstData:ce,refetchStatus:S.refetchStatus,refetch:S.refetch}),O){let I=!!d&&String(d).slice(0,10)<mf;return be(Nt,{title:"Analytics",onBackToWebsite:t,className:i,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),be("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:G?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":I?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return K?be(Nt,{title:"Analytics",onBackToWebsite:t,className:i,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),be("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."})]})}):V?Mt(Nt,{title:"Analytics",onBackToWebsite:t,className:i,children:[be("div",{className:"af-mb-3 af-flex af-justify-end",children:be(Jr,{value:y,chosen:r,onChange:I=>{br(I),p(I)}})}),Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Mt("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",k?.timezone?` ${k.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),be("div",{className:"af-mt-4 af-flex af-justify-center",children:be(ei,{currentVisitors:Z.currentVisitors,asOf:Z.asOf,isStale:Z.isStale,isUnreachable:Z.isUnreachable||Z.error!==null,isInitialLoad:Z.isInitialLoad})})]})]}):be(Nt,{title:"Analytics",onBackToWebsite:t,className:i,children:Mt("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Mt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[be("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:pf.map(I=>be("button",{type:"button","aria-pressed":I.value===f,onClick:()=>u(I.value),className:I.value===f?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:I.label},I.value))}),be(Jr,{value:y,chosen:r,onChange:I=>{br(I),p(I)}}),be(ei,{currentVisitors:Z.currentVisitors,asOf:Z.asOf,isStale:Z.isStale,isUnreachable:Z.isUnreachable||Z.error!==null,isInitialLoad:Z.isInitialLoad,scopeIsSiteWide:x.length>0})]}),be(Go,{filters:x,onChange:D,suggestions:he,expandValues:xe,resetKey:l}),P?Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),be("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:P}),be("button",{type:"button",onClick:()=>D([]),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,!P&&k?.timezone_defaulted?be("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,P?null:Mt(si,{children:[be(ts,{sourced:S.summary.data,error:S.summary.error,isLoading:S.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:S.refetch,children:I=>Mt(si,{children:[be(Wo,{summary:I,selected:R,onSelect:A}),I.previous_unavailable?Mt("p",{className:"af-text-xs af-text-muted-foreground",children:[I.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]})}),be("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:be(ts,{sourced:S.timeseries.data,error:S.timeseries.error,isLoading:S.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:S.refetch,children:I=>{let ue=S.timeseries.data?.status==="ok"?S.timeseries.data.window:{from:"",to:""};return be(dr,{rows:I,window:ue,metric:R,timeZone:M??"UTC"})}})}),Mt("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[be(nn,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>be(ts,{sourced:S.channels.data,error:S.channels.error,isLoading:S.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:S.refetch,children:I=>be(Qr,{rows:I,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:ue=>m("channel",ue),onFilter:ue=>N("channel",ue)})})},{id:"sources",label:"Sources",render:L("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:L("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),be(nn,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:L("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:L("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:L("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),be(nn,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:L("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:L("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:L("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),be(nn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:L("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:L("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:L("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Mt("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[be("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:be("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Mt("div",{className:"af-px-3 af-py-2",children:[x.length>0?Mt("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",x.length===1?"filter":"filters"," above."]}):null,Et!==null?Mt("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:[be("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),be("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Et})]}):be(ts,{sourced:S.conversions.data,error:S.conversions.error,isLoading:S.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:S.refetch,children:I=>{let ue=S.conversions.data?.status==="ok"?S.conversions.data:null;return be(si,{children:be(cr,{rows:I,primaryConversion:n,denominator:ue?.denominator??0,windowPrecedesCollection:ue?.window_precedes_collection??!1,coverageUnknown:ue?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import*as nl from"react";import{Phone as tl,Mail as ri,ShoppingBag as xf,ExternalLink as wf,MessageCircle as Nf,Download as Sf,Target as rl}from"lucide-react";import*as ha from"react";import{Check as ni,ChevronLeft as bf,Loader2 as Jo}from"lucide-react";import{jsx as qe,jsxs as kt}from"react/jsx-runtime";var Yo=90,Qo=100;function yf(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Xo(e){return!!e.label&&e.label!==e.target}function hf(e,a,s){if(!a)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:t,with_a_value:n}=a;return t===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<t?s?`These cover ${n.toLocaleString()} of ${t.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${t.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function ln(e,a){return e.goal!==a.goal?!1:a.implicit===void 0||e.implicit===a.implicit}function el({current:e,onChange:a,onClose:s}){let{api:t}=se(),[n,i]=ha.useState(null),[o,d]=ha.useState(!1),[f,u]=ha.useState({at:"goals"}),[r,p]=ha.useState(null),[b,g]=ha.useState(null),[c,l]=ha.useState(!1),[v,h]=ha.useState(null),x=ha.useRef(0);ha.useEffect(()=>{let N=!0;return i(null),d(!1),u({at:"goals"}),p(null),g(null),l(!1),h(null),x.current+=1,t.getAnalyticsConversions(Yo).then(R=>{if(N){if(R.status!=="ok"){d(!0);return}i(R.data)}}).catch(()=>{N&&d(!0)}),()=>{N=!1}},[t]);let D=N=>{u({at:"targets",row:N}),p(null),g(null),l(!1),h(null);let R=++x.current;t.getAnalyticsGoalTargets(N.goal,Yo,Qo).then(A=>{if(R===x.current){if(A.status!=="ok"){g("failed");return}p(A.data),l(A.truncated===!0),h(A.coverage??null)}}).catch(A=>{if(R!==x.current)return;let S=A instanceof Ot?A.details?.code:void 0;g(S==="goal_has_no_targets"?"no-values":"failed")})},B=N=>{a(N),s()};if(o)return qe("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return kt("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[qe(Jo,{className:"af-h-4 af-w-4 af-animate-spin"}),qe("span",{children:"Loading your conversions\u2026"})]});if(f.at==="targets"){let N=f.row,R=new Map;for(let A of r??[])R.set(A.label,(R.get(A.label)??0)+1);return kt("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:[qe("header",{className:"af-flex af-items-center af-gap-1",children:kt(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({at:"goals"}),children:[qe(bf,{className:"af-h-4 af-w-4"}),qe("span",{children:"All conversions"})]})}),kt("button",{type:"button","aria-current":e&&ln(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:()=>B({goal:N.goal,implicit:N.implicit}),children:[e&&ln(N,e)&&!e.target&&qe(ni,{className:"af-h-4 af-w-4 af-shrink-0"}),kt("span",{children:["Any ",N.goal.toLowerCase()]})]}),b==="no-values"&&qe("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"&&kt("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[qe("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),qe(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>D(N),children:"Try again"})]}),!r&&b===null&&kt("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:[qe(Jo,{className:"af-h-4 af-w-4 af-animate-spin"}),qe("span",{children:"Loading\u2026"})]}),r&&qe("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:hf(r.length,v,c)}),c&&kt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Qo,". If what you want isn\u2019t here, pick the conversion itself instead."]}),r?.some(Xo)&&qe("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."}),r?.map(A=>{let S=!!(e&&ln(N,e)&&e.target===A.target),k=R.get(A.label)>1;return Xo(A)?kt("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:[kt("span",{className:"af-min-w-0",children:[qe("span",{className:"af-block af-truncate",children:A.label}),k&&qe("span",{className:"af-block af-truncate af-text-xs",children:A.target})]}),qe("span",{className:"af-shrink-0 af-text-xs",children:A.visitors.toLocaleString()})]},A.target):kt("button",{type:"button","aria-current":S?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>B({goal:N.goal,implicit:N.implicit,target:A.target,...A.label&&A.label!==A.target?{label:A.label}:{}}),children:[kt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[S&&qe(ni,{className:"af-h-4 af-w-4 af-shrink-0"}),kt("span",{className:"af-min-w-0",children:[qe("span",{className:"af-block af-truncate",children:A.label}),k&&qe("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:A.target})]})]}),qe("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:A.visitors.toLocaleString()})]},A.target)})]})}let m=e?.goal&&!n.some(N=>ln(N,e));return kt("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:[m&&kt("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&qe("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(N=>{let R=e?ln(N,e):!1;return kt("div",{className:"af-flex af-items-center af-gap-1",children:[kt("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:()=>B({goal:N.goal,implicit:N.implicit}),children:[kt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[R&&qe(ni,{className:"af-h-4 af-w-4 af-shrink-0"}),qe("span",{className:"af-truncate",children:N.goal})]}),qe("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:N.visitors.toLocaleString()})]}),yf(N)&&qe(w,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${N.goal}`,onClick:()=>D(N),children:"Narrow"})]},N.goal)}),e?.goal&&qe("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:()=>B(null),children:"No main conversion"})]})}import{Fragment as Cf,jsx as _s,jsxs as sl}from"react/jsx-runtime";function _f(e){let a=[e];e.startsWith("//")?a.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||a.push(`https://${e}`);for(let s of a)try{let{hostname:t}=new URL(s);if(t)return t.toLowerCase().replace(/^www\./,"")}catch{}return null}function Rf(e){if(ii(e,"whatsapp"))return!0;let a=_f(e);return a===null?!1:["wa.me","whatsapp.com"].some(s=>a===s||a.endsWith(`.${s}`))}function ii(e,a){return e.slice(0,a.length+1).toLowerCase()===`${a}:`}var al=[{goal:"Contact",target:e=>ii(e,"tel"),icon:tl,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>ii(e,"mailto"),icon:ri,line:"This site is set up to get you emails."},{goal:"Contact",icon:tl,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Rf(e),icon:Nf,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:wf,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:ri,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:ri,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:xf,line:"This site is set up to sell."},{goal:"File Download",icon:Sf,line:"This site is set up to get your file downloaded."}];function il(e){let{goal:a,target:s}=e;return e.implicit!==!0?null:(s?al.find(n=>n.goal===a&&n.target?.(s)):void 0)??al.find(n=>n.goal===a&&!n.target)??null}function Pf(e){return il(e)?.icon??rl}function ol({primaryConversion:e,onChange:a}){let[s,t]=nl.useState(!1);if(!!!e?.goal&&!a)return null;let i=e?il(e):null,o=e?.label?.trim(),d=e?Pf(e):rl,f=e?.goal?o?`Your main conversion is ${o}.`:i?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",u=sl(Cf,{children:[_s(d,{className:"af-h-4 af-w-4 af-shrink-0"}),_s("span",{children:f})]});return a?sl(En,{open:s,onOpenChange:t,children:[_s(An,{asChild:!0,children:_s("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})}),_s(Ys,{align:"start",className:"af-w-80 af-p-1",children:s&&_s(el,{current:e,onChange:a,onClose:()=>t(!1)})})]}):_s("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:u})}import{Fragment as Tf,jsx as gs,jsxs as fr}from"react/jsx-runtime";function ll({refreshKey:e,onViewAll:a,primaryConversion:s}){let t=Ms(7,{refreshKey:e,breakdowns:[]}),n=t.status.data??void 0,{nothingToReport:i,notCollecting:o,holdingForFirstData:d}=nr(n);return rr({status:n,holdingForFirstData:d,refetchStatus:t.refetchStatus,refetch:t.refetch}),fr("section",{className:"af-rounded-md af-border af-p-3",children:[fr("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[gs("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),a&&gs(w,{type:"button",variant:"ghost",size:"sm",onClick:a,children:"View all analytics"})]}),i?gs("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."}):fr(Tf,{children:[gs(ts,{sourced:t.timeseries.data,error:t.timeseries.error,isLoading:t.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:t.refetch,children:f=>{let u=t.timeseries.data?.status==="ok"?t.timeseries.data:null;return gs(dr,{rows:f,window:u?.window??{from:"",to:""},metric:"visitors",timeZone:u?.timezone,height:140})}}),fr("div",{className:"af-mt-3",children:[gs("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),gs(ts,{sourced:t.conversions.data,error:t.conversions.error,isLoading:t.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:t.refetch,children:f=>{let u=t.conversions.data?.status==="ok"?t.conversions.data:null;return gs(cr,{rows:f,primaryConversion:s,denominator:u?.denominator??0,windowPrecedesCollection:u?.window_precedes_collection??!1,coverageUnknown:u?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as La,jsxs as cn}from"react/jsx-runtime";var oi=5;function li({title:e,viewAllLabel:a,onViewAll:s}){return cn("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[La("h3",{className:"af-text-sm af-font-medium",children:e}),s&&La(w,{type:"button",variant:"ghost",size:"sm",onClick:s,children:a})]})}function kf({refreshKey:e,onBackToWebsite:a,primaryConversion:s,onChangePrimaryConversion:t,onOpenSurface:n,needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:d}){let f=Bs({refreshKey:e}),u=(f.summary?.products.count??0)>0||(f.summary?.commerce?.storefront_orders??!1),r=u||(f.summary?.commerce?.invoicing??!1);return La(Nt,{title:"Dashboard",onBackToWebsite:a,children:cn("div",{className:"af-flex af-flex-col af-gap-4",children:[La(ol,{primaryConversion:s,onChange:t}),La(ll,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:s}),cn("section",{className:"af-rounded-md af-border af-p-3",children:[La(li,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),La(er,{refreshKey:e,maxRows:oi,onViewAll:n&&(()=>n("leads"))})]}),u&&cn("section",{className:"af-rounded-md af-border af-p-3",children:[La(li,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),La(ls,{refreshKey:e,maxRows:oi,onViewAll:n&&(()=>n("orders"))})]}),r&&cn("section",{className:"af-rounded-md af-border af-p-3",children:[La(li,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),La(us,{refreshKey:e,maxRows:oi,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:d})]})]})})}export{Ot as AifeaturesApiError,fl as AifeaturesProvider,vf as AnalyticsView,$n as CustomerDetail,Vn as CustomersList,kf as DashboardView,Sn as FormSettings,hn as FormSubmissions,Ti as FormsDashboard,pn as FormsList,Fr as InvoiceDetail,Qs as InvoiceLabelBadge,us as InvoicesList,Io as InvoicesView,er as LeadsView,Us as MAX_ANALYTICS_FILTERS,Vs as MAX_ANALYTICS_FILTER_VALUES,On as OrderDetail,ys as OrderStatusBadge,ls as OrdersList,co as OrdersView,io as PaymentsDashboard,Gn as PaymentsSetup,Tn as ProductSettings,Pn as ProductsList,yo as ProductsView,Cs as PromosPanel,Kr as REALTIME_FAILURES_BEFORE_ERROR,Wr as REALTIME_POLL_MS,Mr as RetainerStatusBadge,Is as RetainersPanel,yn as SubmissionDetail,Eo as SubscriptionsView,Cn as VariantsEditor,Nt as ViewShell,wn as WebhookDeliveries,Nn as WebhookSettings,Qa as chargedTotal,hr as createApiClient,j as formatPrice,va as isZeroDecimalCurrency,gt as toMajorUnits,Zt as toMinorUnits,se as useAifeatures,se as useAifeaturesContext,Ms as useAnalytics,Bs as useBusinessSummary,Mn as useCustomers,xn as useEventDestinations,Rs as useForms,Es as useInvoices,kn as useOrders,is as usePaymentsStatus,Qn as usePeople,Xn as usePerson,Ds as useProducts,sr as useRealtimeVisitors,Ls as useRetainers,bn as useSubmissions,tr as useSubscriptions};
|