@aifeatures/admin-react 0.16.0 → 0.18.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 +207 -35
- package/dist/index.d.ts +207 -35
- package/dist/index.js +4 -4
- package/dist/styles.css +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import*as Xa from"react";var rr="aifeatures:analytics:timezone",ir;function Us(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function ni(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function fs(){return or()??Us()}function or(){if(ir!==void 0)return ir;try{let e=window.localStorage.getItem(rr);return ni(e)?e:null}catch{return null}}function lr(e){if(!(e!==null&&!ni(e))){ir=e;try{e===null?window.localStorage.removeItem(rr):window.localStorage.setItem(rr,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 Gt=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function cr(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 ur(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 f;try{f=await o.json()}catch{}throw new Gt(cr(f?.error,o.status),o.status,f)}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(),f=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(f)},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,f=i.id??i.name,d=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(f)}`,p=await fetch(d,{headers:{Authorization:`Bearer ${e}`}});if(!p.ok){let m;try{m=await p.json()}catch{}throw new Gt(cr(m?.error,p.status),p.status,m)}let r=await p.blob(),g=URL.createObjectURL(r),y=document.createElement("a");y.href=g,y.download=o,document.body.appendChild(y),y.click(),document.body.removeChild(y),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 f;try{f=await o.json()}catch{}throw new Gt(cr(f?.error,o.status),o.status,f)}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 Ko}from"react/jsx-runtime";var ri=Xa.createContext(null);function Go(e){return e?e.startsWith("sk_")?"Invalid token type: You passed an organization API key (sk_xxx) but AifeaturesProvider requires a site token (st_xxx). Site tokens are returned when you create a site via the API.":e.startsWith("st_")?null:`Invalid token format: Expected a site token starting with "st_" but got "${e.slice(0,10)}...". Site tokens are returned when you create a site via the API.`:"No siteToken provided to AifeaturesProvider"}function Wo({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Xa.useMemo(()=>Go(e),[e]),o=Xa.useMemo(()=>ur(e,a),[e,a]),f=Xa.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?Vs("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:Ko("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(ri.Provider,{value:f,children:Vs("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function re(){let e=Xa.useContext(ri);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as ts from"react";import{ArrowLeft as Zl,Settings as Jl,Inbox as Yl}from"lucide-react";import*as rn from"react";import*as ba from"@radix-ui/react-tabs";import{clsx as Zo}from"clsx";import{extendTailwindMerge as Jo}from"tailwind-merge";var Yo=Jo({prefix:"af-"});function K(...e){return Yo(Zo(e))}import{jsx as dr}from"react/jsx-runtime";var on=ba.Root,$s=rn.forwardRef(({className:e,...a},s)=>dr(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)=>dr(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)=>dr(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 ii from"react";import{Slot as Qo}from"@radix-ui/react-slot";import{cva as Xo}from"class-variance-authority";import{jsx as tl}from"react/jsx-runtime";var el=Xo("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=ii.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>tl(t?Qo:"button",{className:K(el({variant:a,size:s,className:e})),ref:i,...n}));w.displayName="Button";import{Inbox as oi,Settings as nl}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 al=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}));al.displayName="TableFooter";var fe=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}));fe.displayName="TableRow";var M=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}));M.displayName="TableHead";var U=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}));U.displayName="TableCell";var sl=qa.forwardRef(({className:e,...a},s)=>za("caption",{ref:s,className:K("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));sl.displayName="TableCaption";import*as xa from"react";function xs(){let{api:e}=re(),[a,s]=xa.useState([]),[t,n]=xa.useState(!0),[i,o]=xa.useState(null),f=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(()=>{f()},[f]);let d=xa.useCallback(async g=>{let y=await e.createForm(g);return s(m=>[...m,y]),y},[e]),p=xa.useCallback(async(g,y)=>{let m=await e.updateForm(g,y);return s(c=>c.map(l=>l.id===g?m:l)),m},[e]),r=xa.useCallback(async g=>{await e.deleteForm(g),s(y=>y.filter(m=>m.id!==g))},[e]);return{forms:a,isLoading:t,error:i,refetch:f,createForm:d,updateForm:p,deleteForm:r}}import{jsx as Tt,jsxs as ja}from"react/jsx-runtime";function ln({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=xs();return t?Tt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Tt("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?Tt("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:[Tt(oi,{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.",Tt("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):Tt("div",{className:a,children:ja(Be,{children:[Tt(Fe,{children:ja(fe,{children:[Tt(M,{children:"Name"}),Tt(M,{children:"Endpoint"}),Tt(M,{className:"af-text-right",children:"Actions"})]})}),Tt(Me,{children:s.map(i=>ja(fe,{children:[Tt(U,{className:"af-font-medium",children:i.name}),Tt(U,{children:Tt("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","")})}),Tt(U,{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:[Tt(oi,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),ja(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[Tt(nl,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as ll}from"lucide-react";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-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function ee({className:e,variant:a,...s}){return ol("div",{className:K(il({variant:a}),e),...s})}import{jsx as ms,jsxs as cn}from"react/jsx-runtime";var cl={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 fr(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function ul(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 fr(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(ll,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function Aa({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||fr([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=ul(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:cl[n.kind]??"Email notification"}),ms(ee,{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&&fr([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 _l,ChevronRight as Rl,Eye as Pl,Inbox as Cl,Paperclip as Tl}from"lucide-react";import*as es from"react";import*as we from"@radix-ui/react-select";import{Check as dl,ChevronDown as li,ChevronUp as fl}from"lucide-react";import{jsx as Dt,jsxs as mr}from"react/jsx-runtime";var ca=we.Root;var ua=we.Value,aa=es.forwardRef(({className:e,children:a,...s},t)=>mr(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,Dt(we.Icon,{asChild:!0,children:Dt(li,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));aa.displayName=we.Trigger.displayName;var ci=es.forwardRef(({className:e,...a},s)=>Dt(we.ScrollUpButton,{ref:s,className:K("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Dt(fl,{className:"af-h-4 af-w-4"})}));ci.displayName=we.ScrollUpButton.displayName;var ui=es.forwardRef(({className:e,...a},s)=>Dt(we.ScrollDownButton,{ref:s,className:K("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Dt(li,{className:"af-h-4 af-w-4"})}));ui.displayName=we.ScrollDownButton.displayName;var sa=es.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>Dt(we.Portal,{children:mr(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:[Dt(ci,{}),Dt(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}),Dt(ui,{})]})}));sa.displayName=we.Content.displayName;var ml=es.forwardRef(({className:e,...a},s)=>Dt(we.Label,{ref:s,className:K("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));ml.displayName=we.Label.displayName;var We=es.forwardRef(({className:e,children:a,...s},t)=>mr(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:[Dt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:Dt(we.ItemIndicator,{children:Dt(dl,{className:"af-h-4 af-w-4"})})}),Dt(we.ItemText,{children:a})]}));We.displayName=we.Item.displayName;var pl=es.forwardRef(({className:e,...a},s)=>Dt(we.Separator,{ref:s,className:K("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));pl.displayName=we.Separator.displayName;import*as da from"react";function dn({formId:e,initialPageSize:a=25}){let{api:s}=re(),[t,n]=da.useState([]),[i,o]=da.useState(0),[f,d]=da.useState(!0),[p,r]=da.useState(null),[g,y]=da.useState(0),[m,c]=da.useState(a),l=da.useCallback(async()=>{if(e)try{d(!0),r(null);let N={limit:m,offset:g*m},E=await s.getSubmissions(e,N);n(E.submissions),o(E.total)}catch(N){r(N instanceof Error?N:new Error("Failed to fetch submissions"))}finally{d(!1)}},[s,e,g,m]);da.useEffect(()=>{l()},[l]);let v=da.useCallback(async N=>{await s.deleteSubmission(N),n(E=>E.filter(B=>B.id!==N)),o(E=>E-1)},[s]),h=Math.ceil(i/m);return{submissions:t,total:i,isLoading:f,error:p,page:g,pageSize:m,hasNextPage:g<h-1,hasPreviousPage:g>0,setPage:y,setPageSize:N=>{c(N),y(0)},refetch:l,deleteSubmission:v}}import*as fi from"react";import{ArrowLeft as gl,Download as vl,Globe as bl,Clock as yl,FileText as hl,Loader2 as xl,Monitor as wl,Mail as Nl}from"lucide-react";import{jsx as ot,jsxs as lt}from"react/jsx-runtime";function di(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Sl(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}=re(),[t,n]=fi.useState(null),i=d=>d.id??d.name,o=async d=>{n(i(d));try{await s.downloadAttachment(e.id,d)}catch(p){console.error("Download failed:",p)}finally{n(null)}},f=Object.entries(e.data).filter(([d])=>!d.startsWith("_"));return lt("div",{children:[lt("div",{className:"af-mb-6",children:[lt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[ot(gl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),ot("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),lt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",di(e.metadata.submitted_at)]})]}),lt("div",{className:"af-space-y-6",children:[ot(Aa,{deliveries:e.email_deliveries}),lt("div",{children:[ot("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),lt("div",{className:"af-space-y-3",children:[f.map(([d,p])=>lt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[ot("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:d.replace(/_/g," ")}),ot("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof p=="string"&&p.includes(`
|
|
3
|
-
`)?ot("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:p}):String(p)})]},d)),f.length===0&&ot("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&<("div",{children:[ot("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),ot("div",{className:"af-space-y-2",children:e.attachments.map((d,p)=>lt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[lt("div",{className:"af-flex af-items-center af-gap-2",children:[ot(hl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ot("span",{className:"af-text-sm",children:d.name}),lt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Sl(d.size),")"]})]}),lt(w,{variant:"ghost",size:"sm",onClick:()=>o(d),disabled:t===i(d),children:[t===i(d)?ot(xl,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):ot(vl,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(d)?"Downloading...":"Download"]})]},p))})]}),lt("div",{children:[ot("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),lt("div",{className:"af-space-y-2 af-text-sm",children:[lt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ot(yl,{className:"af-h-4 af-w-4"}),ot("span",{children:di(e.metadata.submitted_at)})]}),e.metadata.ip_address&<("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ot(bl,{className:"af-h-4 af-w-4"}),lt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&<("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[ot(wl,{className:"af-h-4 af-w-4 af-mt-0.5"}),ot("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&<("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[ot(Nl,{className:"af-h-4 af-w-4"}),lt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as Pe,jsxs as St}from"react/jsx-runtime";function kl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function El(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 Il(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:f,pageSize:d,hasNextPage:p,hasPreviousPage:r,setPage:g,setPageSize:y}=dn({formId:e}),[m,c]=zs.useState("list"),[l,v]=zs.useState(null);zs.useEffect(()=>{if(s&&t.length>0){let u=t.find(k=>k.id===s);u&&(v(u),c("detail"))}},[s,t]);let h=u=>{v(u),c("detail")},N=()=>{c("list"),v(null)};if(m==="detail"&&l)return Pe("div",{className:a,children:Pe(fn,{submission:l,onBack:N})});if(i)return Pe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Pe("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return Pe("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&&f===0)return St("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Pe(Cl,{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.",Pe("br",{}),"Submissions will appear here when visitors use your form."]})]});let E=f*d+1,B=Math.min((f+1)*d,n);return St("div",{className:a,children:[St(Be,{children:[Pe(Fe,{children:St(fe,{children:[Pe(M,{children:"Email"}),Pe(M,{children:"Preview"}),Pe(M,{children:"Date"}),Pe(M,{className:"af-text-right",children:"Actions"})]})}),Pe(Me,{children:t.map(u=>{let k=El(u.data),I=Il(u.data);return St(fe,{children:[St(U,{className:"af-font-medium",children:[St("div",{className:"af-flex af-items-center af-gap-2",children:[k||Pe("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),u.attachments.length>0&&St("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${u.attachments.length} attachment(s)`,children:[Pe(Tl,{className:"af-h-3 af-w-3"}),Pe("span",{className:"af-text-xs",children:u.attachments.length})]})]}),Pe(Hs,{deliveries:u.email_deliveries,label:"Notification email needs attention"})]}),Pe(U,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:I||Pe("span",{className:"af-italic",children:"No preview available"})}),Pe(U,{className:"af-text-muted-foreground",children:kl(u.metadata.submitted_at)}),Pe(U,{className:"af-text-right",children:Pe(w,{variant:"ghost",size:"icon",onClick:()=>h(u),title:"View details",children:Pe(Pl,{className:"af-h-4 af-w-4"})})})]},u.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 ",E,"-",B," of ",n]}),St(ca,{value:String(d),onValueChange:u=>y(Number(u)),children:[Pe(aa,{className:"af-w-[70px] af-h-8",children:Pe(ua,{})}),St(sa,{children:[Pe(We,{value:"10",children:"10"}),Pe(We,{value:"25",children:"25"}),Pe(We,{value:"50",children:"50"}),Pe(We,{value:"100",children:"100"})]})]}),Pe("span",{children:"per page"})]}),St("div",{className:"af-flex af-items-center af-gap-2",children:[St(w,{variant:"outline",size:"sm",onClick:()=>g(f-1),disabled:!r,children:[Pe(_l,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),St(w,{variant:"outline",size:"sm",onClick:()=>g(f+1),disabled:!p,children:["Next",Pe(Rl,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as ra from"react";import{Plus as jl,X as Gl,Loader2 as Wl,Check as Kl}from"lucide-react";import*as mi from"react";import{jsx as Al}from"react/jsx-runtime";var me=mi.forwardRef(({className:e,type:a,...s},t)=>Al("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}));me.displayName="Input";import*as pi from"react";import{cva as Dl}from"class-variance-authority";import{jsx as Ol}from"react/jsx-runtime";var Ll=Dl("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ge=pi.forwardRef(({className:e,...a},s)=>Ol("label",{ref:s,className:K(Ll(),e),...a}));ge.displayName="Label";import*as ma from"react";import{Plus as Ul,Loader2 as gr,Copy as Vl,Check as $l,Trash2 as Hl,RefreshCw as zl,AlertTriangle as ql}from"lucide-react";import*as qs from"react";import*as ht from"@radix-ui/react-dialog";import{X as Bl}from"lucide-react";import{jsx as Ga,jsxs as pr}from"react/jsx-runtime";var Da=ht.Root;var Fl=ht.Portal;var gi=qs.forwardRef(({className:e,...a},s)=>Ga(ht.Overlay,{ref:s,className:K("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));gi.displayName=ht.Overlay.displayName;var wa=qs.forwardRef(({className:e,children:a,...s},t)=>Ga(Fl,{children:pr("div",{className:"aifeatures-admin",children:[Ga(gi,{}),pr(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,pr(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:[Ga(Bl,{className:"af-h-4 af-w-4"}),Ga("span",{className:"af-sr-only",children:"Close"})]})]})]})}));wa.displayName=ht.Content.displayName;var Na=({className:e,...a})=>Ga("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})=>Ga("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)=>Ga(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)=>Ga(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}=re(),[a,s]=na.useState([]),[t,n]=na.useState(!0),[i,o]=na.useState(null),f=na.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(m){o(m instanceof Error?m:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);na.useEffect(()=>{f()},[f]);let d=na.useCallback(async m=>{let c=await e.createEventDestination(m);return s(l=>[c,...l]),c},[e]),p=na.useCallback(async(m,c)=>{let l=await e.updateEventDestination(m,c);return s(v=>v.map(h=>h.id===m?l:h)),l},[e]),r=na.useCallback(async m=>{await e.deleteEventDestination(m),s(c=>c.filter(l=>l.id!==m))},[e]),g=na.useCallback(async m=>{let c=await e.rotateEventDestinationSecret(m);return s(l=>l.map(v=>v.id===m?c:v)),c},[e]),y=na.useCallback(m=>e.getEventDestinationSecret(m),[e]);return{destinations:a,isLoading:t,error:i,refetch:f,createDestination:d,updateDestination:p,deleteDestination:r,rotateSecret:g,getSecret:y}}import*as Wa from"react";import{Loader2 as vi,RotateCw as Ml}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}=re(),[n,i]=Wa.useState([]),[o,f]=Wa.useState(!0),[d,p]=Wa.useState(null),[r,g]=Wa.useState(null),y=Wa.useCallback(async()=>{try{f(!0),p(null),i(await t.getEventDeliveries(e,a))}catch(c){p(c instanceof Error?c.message:"Failed to load deliveries")}finally{f(!1)}},[t,e,a]);Wa.useEffect(()=>{y()},[y]);let m=async c=>{try{g(c.id),p(null);let l=await t.retryEventDelivery(e,c.id);i(v=>v.map(h=>h.id===c.id?l:h))}catch(l){p(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(vi,{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(c=>{let l=c.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(ee,{variant:"secondary",children:c.last_status??200}):fa(ee,{variant:"destructive",children:c.last_status??"failed"}),fa("span",{className:"af-text-sm af-truncate",children:c.type})]}),js("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&&fa("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),fa(w,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===c.id,onClick:()=>m(c),children:r===c.id?fa(vi,{className:"af-h-4 af-w-4 af-animate-spin"}):fa(Ml,{className:"af-h-4 af-w-4"})})]},c.id)})})})}import{jsx as Ce,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:f,updateDestination:d,deleteDestination:p,rotateSecret:r,getSecret:g}=pn(),[y,m]=ma.useState(""),[c,l]=ma.useState(!1),[v,h]=ma.useState(null),[N,E]=ma.useState(null),[B,u]=ma.useState(null),[k,I]=ma.useState(!1),[C,D]=ma.useState(null),[A,F]=ma.useState(null),[b,G]=ma.useState(null),Q=ma.useMemo(()=>n.filter(W=>W.form_id===e),[n,e]),z=async()=>{let W=y.trim();if(W){if(!W.startsWith("https://")){h("Webhook URLs must start with https://");return}try{l(!0),h(null),await f({url:W,form_id:e,...a&&a.length>0?{topics:a}:{}}),m("")}catch(he){h(he instanceof Error?he.message:"Failed to add webhook")}finally{l(!1)}}},ce=async W=>{try{F(W.id),h(null),await r(W.id),I(!1),u(await g(W.id))}catch(he){h(he instanceof Error?he.message:"Failed to rotate secret")}finally{F(null)}},O=async W=>{try{F(W.id),h(null),await d(W.id,{status:"active"})}catch(he){h(he instanceof Error?he.message:"Failed to re-enable")}finally{F(null)}},te=async()=>{if(C)try{F(C.id),await p(C.id),D(null)}catch(W){h(W instanceof Error?W.message:"Failed to delete")}finally{F(null)}},H=async W=>{if(N===W.id){E(null),u(null);return}try{F(W.id),h(null),I(!1),E(W.id),u(await g(W.id))}catch(he){E(null),h(he instanceof Error?he.message:"Failed to read secret")}finally{F(null)}},ne=async()=>{if(B)try{await navigator.clipboard.writeText(B),I(!0)}catch{}};return ft("div",{className:t,children:[ft("div",{className:"af-space-y-1",children:[Ce(ge,{children:"Webhooks"}),Ce("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:[Ce(me,{value:y,placeholder:"https://hooks.zapier.com/...",onChange:W=>m(W.target.value),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),z())},disabled:c}),ft(w,{onClick:z,disabled:c||!y.trim(),children:[c?Ce(gr,{className:"af-h-4 af-w-4 af-animate-spin"}):Ce(Ul,{className:"af-h-4 af-w-4"}),Ce("span",{className:"af-ml-1",children:"Add"})]})]}),(v||o)&&Ce("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:v||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:[Ce(gr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&Q.length===0&&Ce("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:[Ce("span",{className:"af-font-mono af-text-sm af-truncate",children:W.url}),W.status==="disabled"?Ce(ee,{variant:"destructive",children:"Disabled"}):Ce(ee,{variant:"secondary",children:"Active"})]}),Ce("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:[Ce(w,{variant:"ghost",size:"sm",onClick:()=>G(b===W.id?null:W.id),children:b===W.id?"Hide log":"Deliveries"}),Ce(w,{variant:"ghost",size:"sm",onClick:()=>H(W),disabled:A===W.id,children:N===W.id?"Hide secret":"Show secret"}),Ce(w,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:A===W.id,onClick:()=>D(W),children:Ce(Hl,{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:[Ce(ql,{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]}),Ce(w,{variant:"outline",size:"sm",className:"af-mt-2",disabled:A===W.id,onClick:()=>O(W),children:"Re-enable"})]})]}),N===W.id&&B&&ft("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Ce("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:[Ce(me,{readOnly:!0,value:B,className:"af-font-mono"}),Ce(w,{variant:"outline",title:"Copy signing secret",onClick:ne,children:k?Ce($l,{className:"af-h-4 af-w-4"}):Ce(Vl,{className:"af-h-4 af-w-4"})}),Ce(w,{variant:"outline",title:"Rotate signing secret",disabled:A===W.id,onClick:()=>ce(W),children:A===W.id?Ce(gr,{className:"af-h-4 af-w-4 af-animate-spin"}):Ce(zl,{className:"af-h-4 af-w-4"})})]})]}),b===W.id&&Ce(gn,{destinationId:W.id})]},W.id))]}),Ce(Da,{open:!!C,onOpenChange:W=>{!W&&!A&&D(null)},children:ft(wa,{children:[ft(Na,{children:[Ce(_a,{children:"Delete this webhook?"}),ft(Ra,{children:["New submissions will stop being sent to ",C?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),ft(Sa,{children:[Ce(w,{variant:"outline",onClick:()=>D(null),disabled:!!A,children:"Cancel"}),Ce(w,{variant:"destructive",onClick:te,disabled:!!A,children:A?"Deleting...":"Delete"})]})]})})]})}import{jsx as De,jsxs as Pa}from"react/jsx-runtime";function bn({form:e,onSaved:a,className:s}){let{updateForm:t}=xs(),[n,i]=ra.useState(!1),[o,f]=ra.useState(null),[d,p]=ra.useState(null),[r,g]=ra.useState(e.name),[y,m]=ra.useState(e.redirect_url||""),[c,l]=ra.useState(e.email_recipients),[v,h]=ra.useState("");ra.useEffect(()=>{g(e.name),m(e.redirect_url||""),l(e.email_recipients),p(null)},[e]);let N=ra.useCallback(async I=>{try{i(!0),p(null);let C=await t(e.id,I);f(new Date),a?.(C)}catch(C){p(C instanceof Error?C.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);ra.useEffect(()=>{if(o){let I=setTimeout(()=>f(null),2e3);return()=>clearTimeout(I)}},[o]);let E=async()=>{let I=v.trim().toLowerCase();if(!I)return;if(!I.includes("@")){p("Please enter a valid email address");return}if(c.includes(I)){p("This email is already added");return}let C=[...c,I];l(C),h(""),p(null),await N({email_recipients:C})},B=async I=>{let C=c.filter(D=>D!==I);l(C),await N({email_recipients:C})},u=async()=>{r!==e.name&&await N({name:r})},k=async()=>{let I=y||null;I!==e.redirect_url&&await N({redirect_url:I})};return Pa("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&De("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:[De(Wl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),De("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:[De(Kl,{className:"af-h-4 af-w-4 af-text-green-600"}),De("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),Pa("div",{className:"af-space-y-2",children:[De(ge,{htmlFor:"form-name",children:"Form Name"}),De(me,{id:"form-name",value:r,onChange:I=>g(I.target.value),onBlur:u,placeholder:"Contact Form"}),De("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:[De(ge,{children:"Email Recipients"}),De("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:[c.map(I=>Pa(ee,{variant:"secondary",className:"af-gap-1",children:[I,De("button",{type:"button",onClick:()=>B(I),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:De(Gl,{className:"af-h-3 af-w-3"})})]},I)),c.length===0&&De("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),Pa("div",{className:"af-flex af-gap-2",children:[De(me,{type:"email",value:v,onChange:I=>h(I.target.value),placeholder:"Add email address",onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),E())},disabled:n}),De(w,{type:"button",variant:"outline",onClick:E,disabled:!v.trim()||n,children:De(jl,{className:"af-h-4 af-w-4"})})]})]}),Pa("div",{className:"af-space-y-2",children:[De(ge,{htmlFor:"redirect-url",children:"Redirect URL"}),De(me,{id:"redirect-url",value:y,onChange:I=>m(I.target.value),onBlur:k,placeholder:"/thank-you"}),De("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:[De(ge,{children:"Form Endpoint"}),De("div",{className:"af-flex af-items-center af-gap-2",children:De("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})}),De("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:[De(ge,{children:"Captcha Protection"}),De("div",{className:"af-flex af-items-center af-gap-2",children:De(ee,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),De("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),De(vn,{formId:e.id}),d&&De("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 Bt,jsxs as La}from"react/jsx-runtime";function bi({className:e,submissionId:a}){let{api:s}=re(),[t,n]=ts.useState("list"),[i,o]=ts.useState(null),[f,d]=ts.useState("submissions"),[p,r]=ts.useState(a),[g,y]=ts.useState(!!a);ts.useEffect(()=>{if(!a)return;async function v(){try{let h=await s.getSubmission(a),N=await s.getForm(h.form_id);o(N),n("detail"),d("submissions"),r(a)}catch(h){console.error("Failed to load submission for deep link:",h)}finally{y(!1)}}v()},[a,s]);let m=(v,h)=>{o(v),n("detail"),d(h),r(void 0)},c=()=>{n("list"),o(null),r(void 0)},l=v=>{o(v)};return g?Bt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Bt("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:[Bt("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Bt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Bt(ln,{onSelectForm:m})]}),t==="detail"&&i&&La("div",{children:[La("div",{className:"af-mb-6",children:[La(w,{variant:"ghost",size:"sm",onClick:c,className:"af-mb-2 af--ml-2",children:[Bt(Zl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),Bt("h2",{className:"af-text-lg af-font-semibold",children:i.name}),Bt("p",{className:"af-text-sm af-text-muted-foreground",children:Bt("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:f,onValueChange:v=>d(v),children:[La($s,{className:"af-mb-4",children:[La(ya,{value:"submissions",className:"af-gap-2",children:[Bt(Yl,{className:"af-h-4 af-w-4"}),"Submissions"]}),La(ya,{value:"settings",className:"af-gap-2",children:[Bt(Jl,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Bt(ha,{value:"submissions",children:Bt(mn,{formId:i.id,defaultSubmissionId:p})}),Bt(ha,{value:"settings",children:Bt(bn,{form:i,onSaved:l})})]})]})]})}import*as Le from"react";import*as Oa from"react";function as(){let{api:e}=re(),[a,s]=Oa.useState(null),[t,n]=Oa.useState(!0),[i,o]=Oa.useState(null),f=Oa.useRef(0),d=Oa.useCallback(async()=>{let p=++f.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(p!==f.current)return;s(r)}catch(r){if(p!==f.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{p===f.current&&n(!1)}},[e]);return Oa.useEffect(()=>{d()},[d]),{status:a,isLoading:t,error:i,refetch:d}}var Ql=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function pa(e){return Ql.has(e.toLowerCase())}function j(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 Wt(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 tc,jsx as Ee,jsxs as He}from"react/jsx-runtime";function Gs(e){return e instanceof Gt&&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 yi(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 ws(){let{api:e,siteToken:a}=re();return Ee(Xl,{api:e},a)}function Xl({api:e}){let{status:a,error:s}=as(),[t,n]=Le.useState([]),[i,o]=Le.useState(null),[f,d]=Le.useState(null),[p,r]=Le.useState(!1),[g,y]=Le.useState(!1),[m,c]=Le.useState(""),[l,v]=Le.useState(null),[h,N]=Le.useState(null),[E,B]=Le.useState(!1),u=Le.useRef(0),k=Le.useCallback(async D=>{let A=++u.current;r(!0),c("");try{let F=await e.getPromos(D);if(A!==u.current)return;n(b=>D?[...b,...F.promos.filter(G=>!b.some(Q=>Q.id===G.id))]:F.promos),o(F.next_cursor),d(F.checkout_enabled)}catch(F){A===u.current&&c(Gs(F))}finally{A===u.current&&r(!1)}},[e]);Le.useEffect(()=>(k(),()=>{u.current++}),[k]);async function I(D){let A=++u.current;r(!0),c(""),B(!1);try{let F=await e.getPromo(D);A===u.current&&v(F)}catch(F){A===u.current&&c(Gs(F))}finally{A===u.current&&r(!1)}}async function C(){if(l){y(!0),r(!0),c("");try{let D=await e.disablePromo(l.id);if(v(D),!["inactive","expired","exhausted"].includes(D.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");B(!1),await k()}catch(D){c(Gs(D))}finally{y(!1),r(!1)}}}return h?Ee(ec,{currency:a?.currency??void 0,replaces:h.replaces,onCancel:()=>N(null),onSave:async D=>{let A=h.replaces?await e.replacePromo(h.replaces.id,D):await e.createPromo(D),F=await e.getPromo(A.id);if(F.status==="pending"||F.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");v(F),N(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:[Ee("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),Ee(w,{disabled:p||!a?.currency,onClick:()=>{c(""),N({})},children:"Create promo code"})]}),Ee("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."}),f===!1&&Ee("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&&Ee("p",{className:"af-text-sm",children:s?Gs(s):"Connect Stripe and set the payment currency before creating codes."}),m&&He("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[m," ",Ee(w,{variant:"outline",disabled:p,onClick:()=>l?void I(l.id):void k(),children:"Refresh"})]}),l?He("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Ee(w,{variant:"ghost",disabled:g,onClick:()=>{v(null),B(!1),k()},children:"Back to codes"}),He("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),He("p",{children:[yi(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."]}),Ee("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:[Ee(w,{variant:"outline",disabled:p,onClick:()=>void I(l.id),children:"Refresh details"}),Ee(w,{variant:"outline",disabled:p||l.status==="pending"||l.status==="unavailable"||!a?.currency,onClick:()=>N({replaces:l}),children:"Replace with new code"}),Ee(w,{variant:"outline",disabled:p||!["active","pending","unavailable"].includes(l.status),onClick:()=>B(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),E&&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."]}),Ee(w,{disabled:p,onClick:()=>void C(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Ee(w,{variant:"ghost",disabled:p,onClick:()=>B(!1),children:"Cancel"})]})]}):He(tc,{children:[t.map(D=>He("button",{type:"button",disabled:p,onClick:()=>void I(D.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:[Ee("span",{className:"af-font-semibold af-break-all",children:D.code}),Ee("span",{className:"af-text-sm",children:D.status})]}),He("div",{className:"af-text-sm",children:[yi(D)," \xB7"," ",D.times_redeemed==null?"Usage unavailable":`${D.times_redeemed} redemptions`]})]},D.id)),!p&&!m&&t.length===0&&Ee("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),p&&Ee("p",{role:"status",children:"Loading promo codes\u2026"}),i&&Ee(w,{variant:"outline",disabled:p,onClick:()=>void k(i),children:"Load more"})]})]})}function ec({currency:e,replaces:a,onCancel:s,onSave:t}){let[n,i]=Le.useState(""),[o,f]=Le.useState(a?.name??""),[d,p]=Le.useState(a?.amount_off!=null?"fixed":"percent"),[r,g]=Le.useState(a?.percent_off?.toString()??(a?.amount_off!=null&&e?String(mt(a.amount_off,e)):"")),[y,m]=Le.useState(a?.minimum_amount!=null&&e?String(mt(a.minimum_amount,e)):""),[c,l]=Le.useState(()=>{if(!a?.expires_at)return"";let O=new Date(a.expires_at);return Number.isFinite(O.getTime())?new Date(O.getTime()-O.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[v,h]=Le.useState(a?.max_redemptions?.toString()??""),[N,E]=Le.useState(a?.duration??"once"),[B,u]=Le.useState(a?.duration_in_months?.toString()??"3"),[k,I]=Le.useState(null),[C,D]=Le.useState(!1),[A,F]=Le.useState(""),b=Le.useRef(!1),G=e&&pa(e)?"1":"0.01";async function Q(O){if(O.preventDefault(),b.current)return;F("");let te=k;if(!te){if(!e){F("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){F("Choose a different code for the replacement.");return}let H=Wt(r,e),ne=y?Wt(y,e):null;if(d==="fixed"&&(!H||H>999999999999)||y&&(!ne||ne>999999999999)){F("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){F("Choose a future expiry.");return}te={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:N,...d==="percent"?{percent_off:Number(r)}:{amount_off:H,currency:e},...y?{minimum_amount:ne,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...v?{max_redemptions:Number(v)}:{},...N==="repeating"?{duration_in_months:Number(B)}:{}},I(te)}b.current=!0,D(!0);try{await t(te)}catch(H){F(Gs(H)),H instanceof Gt&&H.status>=400&&H.status<500&&H.details?.retryable!==!0&&I(null)}finally{b.current=!1,D(!1)}}let z=(O,te,H,ne={})=>He("label",{className:"af-grid af-gap-1 af-text-sm",children:[O,Ee(me,{"aria-label":O,value:te,onChange:W=>H(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:Q,className:"af-max-w-xl af-space-y-4","aria-label":a?"Replace promo code":"Create promo code",children:[Ee("h3",{className:"af-text-lg af-font-semibold",children:a?`Replace ${a.code}`:"Create promo code"}),a&&Ee("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:C||!!k,className:"af-grid af-gap-4",children:[z("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),z("Name",o,f,{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:O=>p(O.target.value),children:[Ee("option",{value:"percent",children:"Percentage"}),He("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),z("Discount",r,g,{type:"number",required:!0,min:d==="percent"?"0.01":G,max:d==="percent"?"100":void 0,step:d==="percent"?"0.01":G}),z("Minimum order amount",y,m,{type:"number",min:G,step:G,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."]}),z("Expires at (local time)",c,l,{type:"datetime-local",step:1}),z("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:N,onChange:O=>E(O.target.value),children:[Ee("option",{value:"once",children:"First invoice only"}),Ee("option",{value:"forever",children:"Every invoice"}),Ee("option",{value:"repeating",children:"Number of months"})]})]}),N==="repeating"&&z("Months",B,u,{type:"number",required:!0,min:1,max:36,step:1})]}),A&&Ee("p",{role:"alert",className:"af-text-sm af-text-destructive",children:A}),k&&!C&&He("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",Ee("span",{className:"af-break-all",children:k.request_id})]}),He("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ee(w,{type:"submit",disabled:C,children:C?"Saving\u2026":k?"Retry same request":a?"Create replacement":"Create code"}),Ee(w,{type:"button",variant:"ghost",disabled:C||!!k,onClick:s,children:"Cancel"})]})]})}import*as ks from"react";import{ArrowLeft as _u,FileText as Ru,Package as Pu,Receipt as Cu,Settings as Tu,Users as ku}from"lucide-react";import*as hn from"react";import{Package as ac,Pencil as sc,Plus as hi,Trash2 as nc}from"lucide-react";import{jsx as Ue,jsxs as Lt}from"react/jsx-runtime";function rc(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 ic(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:f}=e,[d,p]=hn.useState(null),[r,g]=hn.useState(!1),[y,m]=hn.useState(null),c=async()=>{if(d)try{g(!0),m(null),await f(d.id),p(null)}catch(l){m(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:Lt("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Lt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ue(ac,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Lt("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."]}),Lt(w,{variant:"outline",onClick:()=>s?.(),children:[Ue(hi,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Lt("div",{className:t,children:[Ue("div",{className:"af-flex af-justify-end af-mb-4",children:Lt(w,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Ue(hi,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Lt(Be,{children:[Ue(Fe,{children:Lt(fe,{children:[Ue(M,{children:"Name"}),Ue(M,{children:"Price"}),Ue(M,{children:"Fulfillment"}),Ue(M,{children:"Status"}),Ue(M,{className:"af-text-right",children:"Actions"})]})}),Ue(Me,{children:n.map(l=>Lt(fe,{children:[Ue(U,{className:"af-font-medium",children:l.name}),Ue(U,{children:rc(l)}),Ue(U,{className:"af-text-muted-foreground",children:ic(l)}),Ue(U,{children:Ue(ee,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),Ue(U,{className:"af-text-right",children:Lt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Lt(w,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[Ue(sc,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Lt(w,{variant:"ghost",size:"sm",onClick:()=>{m(null),p(l)},children:[Ue(nc,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),Ue(Da,{open:!!d,onOpenChange:l=>{!l&&!r&&p(null)},children:Lt(wa,{children:[Lt(Na,{children:[Ue(_a,{children:"Delete product?"}),Lt(Ra,{children:['"',d?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),y&&Ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y}),Lt(Sa,{children:[Ue(w,{variant:"outline",onClick:()=>p(null),disabled:r,children:"Cancel"}),Ue(w,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as Ze from"react";import{FileText as lc,Link2 as cc,Loader2 as Ni,Plus as uc,Upload as dc,X as fc}from"lucide-react";import*as pt from"react";import{Loader2 as xi,Plus as vr,Trash2 as wi,X as oc}from"lucide-react";import{jsx as Z,jsxs as ue}from"react/jsx-runtime";function br(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}=re(),n=pa(a)?"1":"0.01",[i,o]=pt.useState(null),[f,d]=pt.useState(!0),[p,r]=pt.useState(null),[g,y]=pt.useState(null),[m,c]=pt.useState(!1),l=pt.useRef(!0);pt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let v=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(()=>{v()},[v]);let h=async _=>{y(null),c(!0);try{await _(),await v()}catch(x){l.current&&y(x instanceof Error?x.message:"Something went wrong")}finally{l.current&&c(!1)}},[N,E]=pt.useState(""),[B,u]=pt.useState(""),[k,I]=pt.useState({}),C=()=>h(async()=>{let _=N.trim(),x=B.split(",").map(q=>q.trim()).filter(Boolean);if(!_)throw new Error("Option name is required");if(x.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:_,values:x}),l.current&&(E(""),u(""))}),D=_=>h(async()=>{let x=(k[_.id]??"").trim();if(!x)throw new Error("Enter a value");await t.updateOption(_.id,{add_values:[x]}),l.current&&I(q=>({...q,[_.id]:""}))}),A=(_,x)=>h(()=>t.updateOption(_.id,{remove_values:[x]})),F=_=>h(()=>t.deleteOption(_.id)),[b,G]=pt.useState(null),[Q,z]=pt.useState(null),[ce,O]=pt.useState(!1),[te,H]=pt.useState(null),ne=i?.options??[],W=i?.variants??[],he=()=>{z(null),G({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ne.map(_=>[_.id,_.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},qe=_=>{z(null);let x=_.inventory?.on_hand??0,q=x<0?"":String(x);G({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:q,initialOnHand:q,allowBackorder:_.inventory?.allow_backorder??!1})},rt=async()=>{if(!b)return;z(null);let _=b.variant?.allow_custom_amount??!1,x=null,q=null;if(!_){if(x=Wt(b.unitAmount,a),x===null||x<=0){z("Enter a valid price");return}if(b.compareAt.trim()&&(q=Wt(b.compareAt,a),q===null||q<=x)){z("Compare-at price must be greater than the price");return}}let pe=b.onHand.trim()!==b.initialOnHand.trim(),be=parseInt(b.onHand,10);if(b.tracked&&pe&&(!Number.isFinite(be)||be<0)){z("On-hand quantity must be zero or more");return}try{if(O(!0),b.variant)await t.updateVariant(b.variant.id,{title:b.title.trim()||null,sku:b.sku.trim()||null,..._?{}:{unit_amount:x,compare_at_amount:q},active:b.active}),await t.setVariantInventory(b.variant.id,{tracked:b.tracked,on_hand:b.tracked&&pe?be:void 0,allow_backorder:b.allowBackorder});else{let Te={};for(let je of ne){let Oe=b.optionValues[je.id];if(!Oe){z(`Choose a ${je.title}`),O(!1);return}Te[je.title]=Oe}await t.createVariant(e,{title:b.title.trim()||null,sku:b.sku.trim()||null,unit_amount:x,compare_at_amount:q,active:b.active,option_values:ne.length>0?Te:void 0,inventory:b.tracked?{tracked:!0,on_hand:be,allow_backorder:b.allowBackorder}:{tracked:!1,allow_backorder:b.allowBackorder}})}await v(),l.current&&G(null)}catch(Te){if(l.current&&z(Te instanceof Error?Te.message:"Failed to save variant"),b.variant)try{let je=await t.getProduct(e);l.current&&o(je)}catch{}}finally{l.current&&O(!1)}},_e=()=>h(async()=>{te&&(await t.deleteVariant(te.id),l.current&&H(null))}),Ve=b?.variant?.allow_custom_amount??!1,Xe=b?.variant!=null&&b.variant.option_values.length===0&&ne.length>0&&!b.variant.active,xe=b?.variant?.inventory!=null&&b.variant.inventory.on_hand<0?-b.variant.inventory.on_hand:null;function yt(_){let x=_.inventory;if(!x||!x.tracked)return Z("span",{className:"af-text-muted-foreground",children:"Unlimited"});let q=x.available??x.on_hand;return q<0?ue("span",{children:[-q," backordered"]}):ue("span",{children:[q," in stock",x.allow_backorder&&Z("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return f?Z("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:Z(xi,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):p?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:p})}):ue("div",{className:`af-space-y-6 ${s||""}`,children:[ue("div",{className:"af-space-y-3",children:[ue("div",{children:[Z(ge,{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."})]}),ne.length>0&&Z("div",{className:"af-space-y-3",children:ne.map(_=>ue("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[ue("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:()=>F(_),disabled:m,children:Z(wi,{className:"af-h-4 af-w-4"})})]}),Z("div",{className:"af-flex af-flex-wrap af-gap-2",children:_.values.map(x=>ue(ee,{variant:"secondary",className:"af-gap-1",children:[x.value,Z("button",{type:"button",onClick:()=>A(_,x.value),className:"af-ml-1 hover:af-text-destructive",disabled:m,title:"Remove value",children:Z(oc,{className:"af-h-3 af-w-3"})})]},x.id))}),ue("div",{className:"af-flex af-gap-2",children:[Z(me,{value:k[_.id]??"",onChange:x=>I(q=>({...q,[_.id]:x.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),D(_))},disabled:m}),Z(w,{type:"button",variant:"outline",size:"sm",onClick:()=>D(_),disabled:m||!(k[_.id]??"").trim(),children:Z(vr,{className:"af-h-4 af-w-4"})})]})]},_.id))}),ue("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[ue("div",{className:"af-space-y-1",children:[Z(ge,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),Z(me,{id:"new-option-title",value:N,onChange:_=>E(_.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:m})]}),ue("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[Z(ge,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),Z(me,{id:"new-option-values",value:B,onChange:_=>u(_.target.value),placeholder:"S, M, L",disabled:m})]}),ue(w,{type:"button",variant:"outline",onClick:C,disabled:m||!N.trim()||!B.trim(),children:[Z(vr,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),ue("div",{className:"af-space-y-3",children:[ue("div",{className:"af-flex af-items-center af-justify-between",children:[Z(ge,{children:"Variants"}),ue(w,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:m||ne.length===0,children:[Z(vr,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ne.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."}):ue(Be,{children:[Z(Fe,{children:ue(fe,{children:[Z(M,{children:"Variant"}),Z(M,{children:"SKU"}),Z(M,{children:"Price"}),Z(M,{children:"Stock"}),Z(M,{children:"Status"}),Z(M,{className:"af-text-right",children:"Actions"})]})}),Z(Me,{children:W.map(_=>ue(fe,{children:[Z(U,{className:"af-font-medium",children:br(_)}),Z(U,{className:"af-text-muted-foreground",children:_.sku||"-"}),Z(U,{children:_.unit_amount!=null?ue("span",{children:[_.compare_at_amount!=null&&Z("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(_.compare_at_amount,_.currency)}),j(_.unit_amount,_.currency)]}):_.allow_custom_amount?Z("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),Z(U,{children:yt(_)}),Z(U,{children:Z(ee,{variant:_.active?"success":"secondary",children:_.active?"Active":"Inactive"})}),Z(U,{className:"af-text-right",children:ue("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[Z(w,{variant:"ghost",size:"sm",onClick:()=>qe(_),disabled:m,children:"Edit"}),Z(w,{variant:"ghost",size:"icon",onClick:()=>H(_),disabled:m,title:"Delete variant",children:Z(wi,{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:b!==null,onOpenChange:_=>{!_&&!ce&&G(null)},children:ue(wa,{children:[ue(Na,{children:[Z(_a,{children:b?.variant?"Edit variant":"Add variant"}),Z(Ra,{children:"Price, markdown, and stock live on the variant."})]}),b&&ue("div",{className:"af-space-y-3",children:[b.variant?b.variant.option_values.length>0&&ue("div",{className:"af-text-sm",children:[Z("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),br(b.variant)]}):ne.map(_=>ue("div",{className:"af-space-y-1",children:[Z(ge,{className:"af-text-xs af-text-muted-foreground",children:_.title}),ue(ca,{value:b.optionValues[_.id]??"",onValueChange:x=>G(q=>q&&{...q,optionValues:{...q.optionValues,[_.id]:x}}),children:[Z(aa,{children:Z(ua,{placeholder:`Choose ${_.title}`})}),Z(sa,{children:_.values.map(x=>Z(We,{value:x.value,children:x.value},x.id))})]})]},_.id)),Ve?ue("div",{className:"af-space-y-1",children:[Z(ge,{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."})]}):ue("div",{className:"af-flex af-gap-3",children:[ue("div",{className:"af-space-y-1",children:[ue(ge,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),Z(me,{id:"variant-price",type:"number",min:"0",step:n,value:b.unitAmount,onChange:_=>G(x=>x&&{...x,unitAmount:_.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),ue("div",{className:"af-space-y-1",children:[Z(ge,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),Z(me,{id:"variant-compare",type:"number",min:"0",step:n,value:b.compareAt,onChange:_=>G(x=>x&&{...x,compareAt:_.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),ue("div",{className:"af-space-y-1",children:[Z(ge,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),Z(me,{id:"variant-sku",value:b.sku,onChange:_=>G(x=>x&&{...x,sku:_.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),ue("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[ue("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Z("input",{type:"checkbox",checked:b.tracked,onChange:_=>G(x=>x&&{...x,tracked:_.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),b.tracked&&ue("div",{className:"af-space-y-1 af-pl-6",children:[ue("div",{className:"af-flex af-items-end af-gap-3",children:[ue("div",{className:"af-space-y-1",children:[Z(ge,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),Z(me,{id:"variant-onhand",type:"number",min:"0",step:"1",value:b.onHand,onChange:_=>G(x=>x&&{...x,onHand:_.target.value}),placeholder:xe!=null?"0":void 0,className:"af-w-[100px]"})]}),ue("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[Z("input",{type:"checkbox",checked:b.allowBackorder,onChange:_=>G(x=>x&&{...x,allowBackorder:_.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),xe!=null&&ue("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."]})]})]}),ue("div",{className:"af-space-y-1",children:[ue("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[Z("input",{type:"checkbox",checked:b.active,onChange:_=>G(x=>x&&{...x,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})]}),ue(Sa,{children:[Z(w,{variant:"outline",onClick:()=>G(null),disabled:ce,children:"Cancel"}),ue(w,{onClick:rt,disabled:ce,children:[ce?Z(xi,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,b?.variant?"Save":"Add variant"]})]})]})}),Z(Da,{open:te!==null,onOpenChange:_=>{!_&&!m&&H(null)},children:ue(wa,{children:[ue(Na,{children:[Z(_a,{children:"Delete variant?"}),Z(Ra,{children:te&&`"${br(te)}" will no longer be purchasable. Past orders are unaffected.`})]}),ue(Sa,{children:[Z(w,{variant:"outline",onClick:()=>H(null),disabled:m,children:"Cancel"}),Z(w,{variant:"destructive",onClick:_e,disabled:m,children:"Delete"})]})]})})]})}import{Fragment as pc,jsx as de,jsxs as Se}from"react/jsx-runtime";function mc(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:f,attachProductFileFromUrl:d}=e,p=!!a,r=a?.currency??s,g=pa(r)?"1":"0.01",y=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[m,c]=Ze.useState(!1),[l,v]=Ze.useState(null),h=Ze.useRef(!0);Ze.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);let[N,E]=Ze.useState(a?.name??""),[B,u]=Ze.useState(a?.description??""),[k,I]=Ze.useState(a?.allow_custom_amount?"custom":"fixed"),[C,D]=Ze.useState(a?.unit_amount!=null?String(mt(a.unit_amount,r)):""),[A,F]=Ze.useState(a?.min_amount!=null?String(mt(a.min_amount,r)):""),[b,G]=Ze.useState(a?.max_amount!=null?String(mt(a.max_amount,r)):""),[Q,z]=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,[O,te]=Ze.useState(a?.collect_shipping_address??!1),[H,ne]=Ze.useState(a?.active??!0),[W,he]=Ze.useState(a?.images??[]),[qe,rt]=Ze.useState(""),[_e,Ve]=Ze.useState(a?.fulfillment??null),[Xe,xe]=Ze.useState(!1),[yt,_]=Ze.useState(""),[x,q]=Ze.useState(null),pe=Ze.useRef(null),be=m||Xe,Te=()=>{let ie=qe.trim();if(ie){if(W.includes(ie)){v("This image URL is already added");return}he(Ae=>[...Ae,ie]),rt(""),v(null)}},je=ie=>{he(Ae=>Ae.filter(et=>et!==ie))},Oe=async()=>{if(v(null),!N.trim()){v("Product name is required");return}let ie=null,Ae=null,et=null,Ct=!p||k!==ce.pricingMode||(k==="fixed"?C!==ce.unitAmount:A!==ce.minAmount||b!==ce.maxAmount),It=!p||Q!==ce.maxQuantity,ta=y||k==="fixed";if(!(y||!Ct))if(k==="fixed"){if(ie=Wt(C,r),ie===null||ie<=0){v("Enter a valid price");return}}else{if(Ae=Wt(A,r),et=Wt(b,r),Ae===null||et===null){v("Enter valid minimum and maximum amounts");return}if(et<Ae){v("Maximum amount must be at least the minimum amount");return}}let zt=parseInt(Q,10);if(ta&&It&&(!Number.isFinite(zt)||zt<1)){v("Max quantity must be at least 1");return}try{c(!0);let $e;if(p&&a){let tt={name:N.trim(),description:B.trim()||null,images:W,collect_shipping_address:O,active:H};!y&&Ct&&(tt.allow_custom_amount=k==="custom",k==="fixed"?tt.unit_amount=ie:(tt.min_amount=Ae,tt.max_amount=et)),ta&&It&&(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:N.trim(),allow_custom_amount:k==="custom",collect_shipping_address:O,active:H};B.trim()&&(tt.description=B.trim()),W.length>0&&(tt.images=W),k==="fixed"?(tt.unit_amount=ie,tt.max_quantity=zt):(tt.min_amount=Ae,tt.max_amount=et),$e=await i(tt)}if(!h.current)return;Ve($e.fulfillment),t?.($e)}catch($e){if(!h.current)return;v($e instanceof Error?$e.message:"Failed to save product")}finally{h.current&&c(!1)}},Ke=async ie=>{let Ae=ie.target.files?.[0];if(!(!Ae||!a))try{xe(!0),q(null);let et=await f(a.id,Ae);if(!h.current)return;Ve(et.fulfillment),t?.(et)}catch(et){if(!h.current)return;q(et instanceof Error?et.message:"Failed to upload file")}finally{h.current&&(xe(!1),pe.current&&(pe.current.value=""))}},dt=async()=>{let ie=yt.trim();if(!(!ie||!a))try{xe(!0),q(null);let Ae=await d(a.id,ie);if(!h.current)return;Ve(Ae.fulfillment),_(""),t?.(Ae)}catch(Ae){if(!h.current)return;q(Ae instanceof Error?Ae.message:"Failed to fetch file")}finally{h.current&&xe(!1)}};return Se("div",{className:`af-space-y-6 ${n||""}`,children:[Se("div",{className:"af-space-y-2",children:[de(ge,{htmlFor:"product-name",children:"Name"}),de(me,{id:"product-name",value:N,onChange:ie=>E(ie.target.value),placeholder:"My product"})]}),Se("div",{className:"af-space-y-2",children:[de(ge,{htmlFor:"product-description",children:"Description"}),de("textarea",{id:"product-description",value:B,onChange:ie=>u(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"})]}),Se("div",{className:"af-space-y-2",children:[de(ge,{children:"Pricing"}),y?de("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Se(pc,{children:[Se(ca,{value:k,onValueChange:ie=>I(ie),children:[de(aa,{className:"af-w-[260px]",children:de(ua,{})}),Se(sa,{children:[de(We,{value:"fixed",children:"Fixed price"}),de(We,{value:"custom",children:"Buyer chooses the amount"})]})]}),k==="fixed"?de("div",{className:"af-flex af-items-end af-gap-3",children:Se("div",{className:"af-space-y-1",children:[Se(ge,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),de(me,{id:"product-price",type:"number",min:"0",step:g,value:C,onChange:ie=>D(ie.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Se("div",{className:"af-space-y-1",children:[Se("div",{className:"af-flex af-items-end af-gap-3",children:[Se("div",{className:"af-space-y-1",children:[Se(ge,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),de(me,{id:"product-min-amount",type:"number",min:"0",step:g,value:A,onChange:ie=>F(ie.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Se("div",{className:"af-space-y-1",children:[Se(ge,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),de(me,{id:"product-max-amount",type:"number",min:"0",step:g,value:b,onChange:ie=>G(ie.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),de("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."})]}),Se("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."]})]}),(y||k==="fixed")&&Se("div",{className:"af-space-y-1",children:[de(ge,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),de(me,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:Q,onChange:ie=>z(ie.target.value),className:"af-w-[140px]"})]})]}),Se("div",{className:"af-space-y-2",children:[de(ge,{children:"Images"}),de("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Se("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[W.map(ie=>Se(ee,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[de("span",{className:"af-truncate",children:ie}),de("button",{type:"button",onClick:()=>je(ie),className:"af-ml-1 hover:af-text-destructive",disabled:m,children:de(fc,{className:"af-h-3 af-w-3"})})]},ie)),W.length===0&&de("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Se("div",{className:"af-flex af-gap-2",children:[de(me,{type:"url",value:qe,onChange:ie=>rt(ie.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),Te())},disabled:m}),de(w,{type:"button",variant:"outline",onClick:Te,disabled:!qe.trim()||m,children:de(uc,{className:"af-h-4 af-w-4"})})]})]}),Se("div",{className:"af-space-y-2",children:[de(ge,{children:"Digital File"}),de("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."}),p?Se("div",{className:"af-space-y-3",children:[_e?.type==="download"&&Se("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[de(lc,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),de("span",{className:"af-text-sm",children:_e.filename}),_e.size!=null&&Se("span",{className:"af-text-xs af-text-muted-foreground",children:["(",mc(_e.size),")"]})]}),_e?.type==="redirect"&&_e.url&&Se("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[de(cc,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Se("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",_e.url]})]}),Se("div",{className:"af-flex af-items-center af-gap-2",children:[de("input",{ref:pe,type:"file",onChange:Ke,className:"af-hidden",disabled:be}),Se(w,{type:"button",variant:"outline",size:"sm",onClick:()=>pe.current?.click(),disabled:be,children:[Xe?de(Ni,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):de(dc,{className:"af-h-4 af-w-4 af-mr-1"}),_e?.type==="download"?"Replace file":"Upload file"]}),de("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),de(me,{type:"url",value:yt,onChange:ie=>_(ie.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Xe}),de(w,{type:"button",variant:"outline",size:"sm",onClick:dt,disabled:!yt.trim()||be,children:"Fetch from URL"})]}),x&&de("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x})]}):de("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Se("div",{className:"af-space-y-2",children:[de(ge,{children:"Settings"}),Se("div",{className:"af-space-y-2",children:[Se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[de("input",{type:"checkbox",checked:O,onChange:ie=>te(ie.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[de("input",{type:"checkbox",checked:H,onChange:ie=>ne(ie.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),p&&a&&Se("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[de(ge,{children:"Options & Variants"}),de(wn,{productId:a.id,currency:r})]}),l&&de("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),de("div",{className:"af-flex af-items-center af-gap-2",children:Se(w,{type:"button",onClick:Oe,disabled:be,children:[m?de(Ni,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,p?"Save changes":"Create product"]})})]})}import*as _t from"react";import{ChevronLeft as Mc,ChevronRight as Oi,Loader2 as Uc,Receipt as Vc,Search as $c,SlidersHorizontal as Hc}from"lucide-react";import*as it from"react";var gc=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Sn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=re(),[t,n]=it.useState([]),[i,o]=it.useState(0),[f,d]=it.useState(!0),[p,r]=it.useState(null),[g,y]=it.useState(0),[m,c]=it.useState(e),[l,v]=it.useState(void 0),[h,N]=it.useState(""),[E,B]=it.useState(""),[u,k]=it.useState(""),[I,C]=it.useState(!1),[D,A]=it.useState(!1),[F,b]=it.useState(void 0),G=F?F.join(","):"",Q=it.useMemo(()=>{if(!G)return;let te=new Set(G.split(","));return gc.filter(H=>!te.has(H))},[G]),z=it.useRef(0),ce=it.useCallback(async()=>{let te=++z.current;try{d(!0),r(null);let H={limit:m,offset:g*m};l?H.status=l:Q?H.excludeStatus=Q:I||(H.excludeStatus=["pending","expired"]),h.trim()&&(H.customerEmail=h.trim()),E.trim()&&(H.from=E.trim()),u.trim()&&(H.to=u.trim()),D&&(H.unfulfilledOnly=!0);let ne=await s.getOrders(H);if(te!==z.current)return;n(ne.orders),o(ne.total)}catch(H){if(te!==z.current)return;r(H instanceof Error?H:new Error("Failed to fetch orders"))}finally{te===z.current&&d(!1)}},[s,g,m,l,Q,I,D,h,E,u,a]);it.useEffect(()=>{ce()},[ce]);let O=Math.ceil(i/m);return{orders:t,total:i,isLoading:f,error:p,page:g,pageSize:m,hasNextPage:g<O-1,hasPreviousPage:g>0,setPage:y,setPageSize:te=>{c(te),y(0)},status:l,setStatus:te=>{v(te),y(0)},statusIn:F,setStatusIn:te=>{b(te&&te.length>0?te:void 0),y(0)},customerEmail:h,setCustomerEmail:te=>{N(te),y(0)},from:E,setFrom:te=>{B(te),y(0)},to:u,setTo:te=>{k(te),y(0)},showAbandoned:I,setShowAbandoned:te=>{C(te),y(0)},unfulfilledOnly:D,setUnfulfilledOnly:te=>{A(te),y(0)},clearFilters:()=>{v(void 0),b(void 0),C(!1),A(!1),N(""),B(""),k(""),y(0)},refetch:ce}}import*as ct from"react";import{ArrowLeft as yc,Check as Ci,ChevronLeft as hc,ChevronRight as xc,ClipboardCopy as wc,Copy as Nc,Download as Sc,Loader2 as Rn,Mail as Ti,MoreHorizontal as _c,Package as Rc,RotateCcw as Pc,Truck as Cc,Undo2 as ki}from"lucide-react";import*as Si from"react";import*as Ba from"@radix-ui/react-popover";import{jsx as yr}from"react/jsx-runtime";var _i=Ba.Root,Ri=Ba.Trigger;var hr=Si.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>yr(Ba.Portal,{children:yr("div",{className:"aifeatures-admin",children:yr(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})})}));hr.displayName=Ba.Content.displayName;import{jsx as _n}from"react/jsx-runtime";var vc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function bc(e){return vc[e]??e}function Pi(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(ee,{variant:Pi(e),className:a,children:bc(e)})}function gs({status:e}){return _n(ps,{status:e})}function Ns({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?_n(ee,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?_n(ee,{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 Oc,jsx as R,jsxs as Y}from"react/jsx-runtime";var Di="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",vs="af-text-xs af-text-muted-foreground";function xr(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 Tc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Li(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,kc=["paid","partially_refunded"],Ec=["paid","partially_refunded","disputed"],Ic=/^[A-Za-z0-9 _-]*$/,Ei=100;function Sr(e,a,s,t,n){let i=kc.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 Ii({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:f}){if(f)return Y("div",{children:[R(Aa,{deliveries:[f]}),o&&R("div",{className:"af-mt-2",children:o})]});let d=Sr(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(ee,{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 Ai(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=Tc(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}: ${Li(n)}`)}function Ac(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _r({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=ct.useState(!1);if(!Ac())return null;let f=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},d=i?R(Ci,{className:"af-h-3 af-w-3"}):R(Nc,{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:f,title:a,"aria-label":a,children:d}):Y(w,{variant:"outline",size:"sm",className:t,onClick:f,"aria-label":a,children:[i?R(Ci,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):R(wc,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function wr({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(_r,{value:a,label:`Copy ${e}`})]})]})}function Dc({src:e}){let[a,s]=ct.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(Rc,{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:Di,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 Nr({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 Lc(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(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):Sr("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):Sr("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 Cn({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:f=!1,hasNextOrder:d=!1}){let{api:p}=re(),[r,g]=ct.useState(e),[y,m]=ct.useState(null),[c,l]=ct.useState(null),[v,h]=ct.useState(!1),[N,E]=ct.useState(!1),[B,u]=ct.useState(!1),[k,I]=ct.useState(!1),[C,D]=ct.useState(""),[A,F]=ct.useState(!1),[b,G]=ct.useState(null),[Q,z]=ct.useState(!1),[ce,O]=ct.useState(""),[te,H]=ct.useState([]),[ne,W]=ct.useState(!1),[he,qe]=ct.useState(!1),[rt,_e]=ct.useState(null);ct.useEffect(()=>{g(e)},[e]);let Ve=T=>{let ke=T.id===r.id&&T.email_deliveries===void 0?{...T,email_deliveries:r.email_deliveries}:T;g(ke),t?.(ke)},Xe=Object.entries(r.metadata??{}),xe=Math.max(0,yn(r)-r.amount_refunded),yt=(r.status==="paid"||r.status==="partially_refunded")&&xe>0,_=r.exclusive_tax_total!=null,x=T=>typeof T.amountNet=="number"?T.amountNet+(T.exclusiveTax??0):(typeof T.unitAmount=="number"?T.unitAmount:0)*(typeof T.quantity=="number"&&T.quantity>0?T.quantity:1),q=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),pe=te.reduce((T,ke)=>T+x(r.line_items[ke]??{}),0)+(ne?q:0),be=r.tax_total??0,Te=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((T,ke)=>T+(ke.exclusiveTax??0),0)),je=_?ne&&q>0?Te:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&be>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,be-(r.tax_refunded??0)),Math.round(be*pe/(r.amount_total+(r.shipping_total??0)))):0,Oe=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(pe+je,xe):pe+je,Ke=te.length>0||ne,dt=Ke?Oe:Wt(ce,r.currency),ie=pa(r.currency)?"1":"0.01",Ae=async()=>{try{h(!0),m(null),l(null),await p.resendOrderReceipt(r.id);let T=await p.getOrder(r.id);Ve(T),l("Receipt email queued.")}catch(T){m(T instanceof Error?T.message:"Failed to resend receipt")}finally{h(!1)}},et=async()=>{try{E(!0),m(null),l(null);let T=await p.resetOrderDownloads(r.id);Ve(T),u(!1),l("Download count reset.")}catch(T){m(T instanceof Error?T.message:"Failed to reset downloads")}finally{E(!1)}},Ct=r.line_items.some(T=>T.collectShippingAddress===!0&&!T.refunded&&!T.unavailableReason),It=typeof r.merchant_fulfilled_at=="string",ta=Ec.includes(r.status)||r.status==="refunded"&&r.line_items.some(T=>T.collectShippingAddress===!0&&T.amountNet===0&&!T.refunded&&!T.unavailableReason),zt=C.trim(),$e=Ic.test(zt)&&zt.length<=Ei,tt=async T=>{try{F(!0),G(null),l(null);let ke=await p.setOrderFulfillment(r.id,{fulfilled:T,...T&&zt?{trackingNumber:zt}:{}});Ve(ke),D(""),l(T?"Marked as shipped.":"Marked as not shipped.")}catch(ke){ke instanceof Gt&&ke.status===409?G(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):G(ke instanceof Error?ke.message:"Failed to update the order")}finally{F(!1)}},Qa=()=>{_e(null),O(String(mt(xe,r.currency))),H([]),W(!1),z(!0)},Fs=T=>H(ke=>ke.includes(T)?ke.filter(jt=>jt!==T):[...ke,T]),At=async(T,ke)=>{if(s)try{qe(!0),_e(null),await s(r,T,ke);let jt=await p.getOrder(r.id);Ve(jt),z(!1),l("Refund issued.")}catch(jt){_e(jt instanceof Error?jt.message:"Refund failed")}finally{qe(!1)}},sn=async()=>{if(Ke){if(Oe<=0){_e("The lines you picked were charged nothing");return}if(Oe>xe){_e(`That selection exceeds the refundable remainder (${j(xe,r.currency)})`);return}await At(Oe,{...te.length>0?{line_items:[...te].sort((ke,jt)=>ke-jt)}:{},...ne?{shipping:!0}:{}});return}let T=Wt(ce,r.currency);if(T===null||T<=0){_e("Enter a valid refund amount");return}if(T>xe){_e(`Amount exceeds the refundable remainder (${j(xe,r.currency)})`);return}await At(T,{amount:T})},V=()=>At(xe,{full:!0}),Ge=!r.subscription_history_only&&r.fulfillment_type==="download",$=!r.subscription_history_only&&n&&Ct,qt=Lc(r),qo=r.shipping_address?Ai(r.shipping_address).join(`
|
|
4
|
-
`):"",Qr=r.shipping_total!=null,nr=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),Xr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-nr):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,ei=nr>0,jo=Xr>0,ti=r.amount_subtotal!=null||Qr||ei||(r.discount_total??0)>0,Ms=[];return r.subscription_history_only||Ms.push(R(Nr,{icon:v?R(Rn,{className:"af-h-4 af-w-4 af-animate-spin"}):R(Ti,{className:"af-h-4 af-w-4"}),disabled:v||r.fulfillment_status!=="fulfilled",onSelect:()=>{I(!1),Ae()},children:"Resend receipt"},"resend")),Ge&&Ms.push(R(Nr,{icon:R(Pc,{className:"af-h-4 af-w-4"}),disabled:N,onSelect:()=>{I(!1),u(!0)},children:"Reset download count"},"reset")),yt&&Ms.push(Y("div",{children:[R(Nr,{icon:R(ki,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{I(!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(yc,{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(Ns,{order:r}),r.is_test&&R(ee,{variant:"outline",children:"Test"})]}),Y("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",xr(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:!f,"aria-label":"Previous order",children:R(hc,{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(xc,{className:"af-h-4 af-w-4"})})]}),$&&(It?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 ${xr(r.merchant_fulfilled_at)}`:""]}),ta&&Y(w,{variant:"ghost",size:"sm",onClick:()=>tt(!1),disabled:A,children:[A?R(Rn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(ki,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):ta?Y("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[R(me,{value:C,onChange:T=>D(T.target.value),placeholder:"Tracking number (optional)",maxLength:Ei,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:A}),Y(w,{variant:"default",className:"af-shrink-0",onClick:()=>tt(!0),disabled:A||!$e,children:[A?R(Rn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(Cc,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ms.length>0&&Y(_i,{open:k,onOpenChange:I,children:[R(Ri,{asChild:!0,children:R(w,{variant:"outline",size:"icon","aria-label":"More actions",children:R(_c,{className:"af-h-4 af-w-4"})})}),R(hr,{children:R("div",{className:"af-space-y-0.5",children:Ms})})]})]})]}),$&&!It&&!$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."}),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}),c&&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:c}),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})]}),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((T,ke)=>{let jt=typeof T.name=="string"&&T.name?T.name:"Item",ai=typeof T.quantity=="number"&&T.quantity>0?T.quantity:1,si=typeof T.unitAmount=="number";return Y("li",{className:"af-flex af-items-start af-gap-3",children:[R(Dc,{src:typeof T.imageUrl=="string"&&T.imageUrl?T.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 T.variantTitle=="string"&&T.variantTitle&&Y("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",T.variantTitle]})]}),Y("div",{className:vs,children:[ai," \xD7"," ",si?j(T.unitAmount,r.currency):"\u2014"]}),T.unavailableReason==="oversold"&&!T.refunded&&R(ee,{variant:"secondary",className:"af-mt-1",children:T.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),T.refunded===!0&&R(ee,{variant:"secondary",className:"af-mt-1",children:T.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),R("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof T.amountNet=="number"||si?j(T.amountNet??T.unitAmount*ai,r.currency):"\u2014"})]},ke)})})}),Xe.length>0&&R(Fa,{title:"Order details",children:R("dl",{className:"af-space-y-2",children:Xe.map(([T,ke])=>Y("div",{children:[R("dt",{className:K(vs,"af-capitalize"),children:T.replace(/_/g," ")}),R("dd",{className:"af-text-sm af-break-words",children:Li(ke)})]},T))})}),R(Fa,{title:"Totals",children:Y("div",{className:"af-w-full",children:[ti&&R(Kt,{label:"Subtotal",children:j(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&Y(Kt,{label:"Discount",children:["\u2212",j(r.discount_total,r.currency)]}),Qr&&R(Kt,{label:"Shipping",children:r.shipping_total===0?"Free":j(r.shipping_total??0,r.currency)}),ei&&R(Kt,{label:"Tax",children:j(nr,r.currency)}),R(Kt,{label:"Total",emphasis:!0,divider:ti,children:j(Ka(r),r.currency)}),(r.credit_applied??0)>0&&Y(Kt,{label:"Credit applied",children:["\u2212",j(r.credit_applied,r.currency)]}),r.amount_paid!=null&&R(Kt,{label:"Amount paid",children:j(r.amount_paid,r.currency)}),jo&&R(Kt,{label:"incl. tax",children:j(Xr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&Y(Kt,{label:"Your price",children:[j(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(Oc,{children:[Y(Kt,{label:"Refunded",children:["\u2212",j(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&Y("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",j(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),R(Kt,{label:"Net",children:R("span",{className:"af-font-medium",children:j(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:j(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&R(Kt,{label:"Returned",children:j(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&R(Kt,{label:"Retained",children:j(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(T=>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",T.tone==="destructive"?"af-bg-destructive":T.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:T.text}),T.at&&R("div",{className:"af-text-xs af-text-muted-foreground",children:xr(T.at)})]})]},T.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(_r,{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(ee,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&R(Fa,{title:"Ship to",action:R(_r,{value:qo,label:"Copy address",size:"sm",children:"Copy address"}),children:R("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Ai(r.shipping_address).map((T,ke)=>R("div",{children:T},ke))})}),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(Aa,{deliveries:r.email_deliveries?.filter(T=>!["purchase_receipt","merchant_sale"].includes(T.kind)),problemsOnly:!0,className:"af-mb-4"}),Y("div",{className:"af-space-y-4",children:[R(Ii,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(T=>T.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:Ae,disabled:v||r.fulfillment_status!=="fulfilled",children:[v?R(Rn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(Ti,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),R(Ii,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(T=>T.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),Ge&&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(Sc,{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(Di,"af-cursor-pointer af-select-none"),children:"Technical details"}),Y("div",{className:"af-mt-3 af-space-y-2",children:[R(wr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&R(wr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&R(wr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),R(Da,{open:B,onOpenChange:T=>{!T&&!N&&u(!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:()=>u(!1),disabled:N,children:"Cancel"}),R(w,{onClick:et,disabled:N,children:N?"Resetting...":"Reset"})]})]})}),R(Da,{open:Q,onOpenChange:T=>{!T&&!he&&z(!1)},children:Y(wa,{children:[Y(Na,{children:[R(_a,{children:"Refund order"}),Y(Ra,{children:["Refund up to ",j(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||q>0)&&Y("div",{className:"af-space-y-2",children:[R(ge,{children:"Items"}),Y("div",{className:"af-space-y-2",children:[r.line_items.map((T,ke)=>{let jt=T.refunded===!0;return Y("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[R("input",{type:"checkbox",checked:te.includes(ke),onChange:()=>Fs(ke),disabled:he||jt||!!T.unavailableReason||x(T)<=0,className:"af-h-4 af-w-4"}),Y("span",{className:jt?"af-text-muted-foreground af-line-through":void 0,children:[typeof T.name=="string"&&T.name?T.name:"Item",typeof T.variantTitle=="string"&&T.variantTitle?` \u2014 ${T.variantTitle}`:"",typeof T.quantity=="number"&&T.quantity>1?` \xD7 ${T.quantity}`:""]}),R("span",{className:"af-ml-auto af-text-muted-foreground",children:jt?"Refunded":j(x(T),r.currency)})]},ke)}),q>0&&Y("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[R("input",{type:"checkbox",checked:ne,onChange:T=>W(T.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:j(q,r.currency)})]})]})]}),Y("div",{className:"af-space-y-2",children:[Y(ge,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),R(me,{id:"refund-amount",type:"number",min:"0",step:ie,value:Ke?String(mt(Oe,r.currency)):ce,onChange:T=>O(T.target.value),disabled:he||Ke}),Ke&&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:()=>z(!1),disabled:he,children:"Cancel"}),R(w,{variant:"outline",onClick:V,disabled:he,children:"Refund everything"}),R(w,{variant:"destructive",onClick:sn,disabled:he,children:he?"Refunding...":dt!==null&&dt>0?`Refund ${j(dt,r.currency)}`:"Refund"})]})]})})]})}import*as Tn from"react";import{ArrowLeft as Bc,RefreshCw as Fc}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(Bc,{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(Fc,{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 Ss({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"},Bi={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Fi(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 Mi(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 qc({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o,maxRows:f,onViewAll:d}){let p=typeof f=="number",{api:r}=re(),g=Sn({refreshKey:s}),{orders:y,total:m,isLoading:c,error:l,page:v,pageSize:h,hasNextPage:N,hasPreviousPage:E,setPage:B,setPageSize:u,customerEmail:k,setCustomerEmail:I,setStatusIn:C,from:D,setFrom:A,to:F,setTo:b,showAbandoned:G,setShowAbandoned:Q,setUnfulfilledOnly:z,refetch:ce}=g,[O,te]=_t.useState("list"),[H,ne]=_t.useState(null),[W,he]=_t.useState(""),[qe,rt]=_t.useState(""),[_e,Ve]=_t.useState(!p&&n?"needs_shipping":"all"),[Xe,xe]=_t.useState(!1),[yt,_]=_t.useState(!!t&&!p),[x,q]=_t.useState(null);_t.useEffect(()=>{if(!t||p)return;let $=!1;return _(!0),q(null),r.getOrder(t).then(qt=>{$||(ne(qt),te("detail"))}).catch(()=>{$||q("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{$||_(!1)}),()=>{$=!0}},[r,t,p]);let pe=_t.useCallback($=>{Ve($);let qt=Bi[$];C(qt.statusIn),z(qt.unfulfilledOnly)},[C,z]);_t.useEffect(()=>{n&&!p&&z(!0)},[]);let be=_t.useRef(!n);_t.useEffect(()=>{be.current||c||(be.current=!0,y.length===0&&pe("all"))},[c,y.length,pe]);let Te=O==="detail"&&!!H;_t.useEffect(()=>{o?.(Te)},[Te,o]);let je=(D?1:0)+(F?1:0)+(G?1:0),Oe=je>0||!!k||!!qe,Ke=!!D&&!!F&&D>F,dt=!p||!!d,ie=$=>{if(p){d?.();return}ne($),te("detail")},Ae=()=>{te("list"),ne(null),ce()},et=$=>{let qt=$.trim();if(!qt){rt(""),k&&I("");return}if(qt.startsWith("#")||/^\d+$/.test(qt)){rt(qt),k&&I("");return}rt(""),I(qt)},Ct=()=>{he(""),rt(""),I(""),A(""),b(""),Q(!1),xe(!1)},It=qe.replace(/^#/,"").toLowerCase(),ta=It?y.filter($=>String($.order_number??"")===It||$.id.toLowerCase().startsWith(It)):y,zt=p?ta.slice(0,f):ta,$e=H?y.findIndex($=>$.id===H.id):-1,tt=$e>0,Qa=$e>=0&&$e<y.length-1;if(yt)return L("div",{className:a,children:L("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:L(Uc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(O==="detail"&&H)return L("div",{className:a,children:L(Cn,{order:H,onBack:Ae,onRefund:e,onOrderUpdated:$=>ne($),allowFulfillment:n,onPrevOrder:tt?()=>ne(y[$e-1]):void 0,onNextOrder:Qa?()=>ne(y[$e+1]):void 0,hasPrevOrder:tt,hasNextOrder:Qa},H.id)});let At=ye("div",{className:"af-mb-4 af-space-y-3",children:[x&&L("p",{className:"af-text-xs af-text-muted-foreground",children:x}),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($=>L("button",{type:"button","aria-pressed":_e===$,onClick:()=>pe($),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",_e===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:zc[$]},$))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[L($c,{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(me,{type:"text",value:W,onChange:$=>he($.target.value),onBlur:()=>et(W),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),et(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:je>0?"secondary":"ghost",size:"sm",onClick:()=>xe($=>!$),"aria-expanded":Xe,children:[L(Hc,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",je>0&&L(ee,{variant:"secondary",className:"af-ml-2",children:je})]}),Oe&&L(w,{type:"button",variant:"ghost",size:"sm",onClick:Ct,children:"Clear filters"})]}),(Xe||!!D||!!F)&&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(ge,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),L(me,{id:"orders-from",type:"date",value:D,max:F||void 0,onChange:$=>A($.target.value),className:"af-w-[170px]"}),L(ge,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),L(me,{id:"orders-to",type:"date",value:F,min:D||void 0,onChange:$=>b($.target.value),className:"af-w-[170px]"}),!Bi[_e].statusIn&&L(w,{type:"button",variant:G?"secondary":"ghost",size:"sm",onClick:()=>Q(!G),"aria-pressed":G,children:G?"Hide abandoned":"Show abandoned"})]}),Ke&&L("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:[p?null:At,L("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map($=>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"})]},$))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[L(Fe,{children:ye(fe,{children:[L(M,{children:"Order"}),L(M,{children:"Date"}),L(M,{children:"Customer"}),L(M,{children:"Items"}),L(M,{className:"af-text-right",children:"Total"}),L(M,{children:"Status"}),L(M,{className:"af-w-8"})]})}),L(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map($=>ye(fe,{children:[L(U,{children:L(ae,{className:"af-h-4 af-w-14"})}),L(U,{children:L(ae,{className:"af-h-4 af-w-24"})}),L(U,{children:L(ae,{className:"af-h-4 af-w-40"})}),L(U,{children:L(ae,{className:"af-h-4 af-w-32"})}),L(U,{children:L(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),L(U,{children:L(ae,{className:"af-h-5 af-w-16"})}),L(U,{})]},$))})]})}),L("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return ye("div",{className:a,children:[p?null:At,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=_e!=="all";if(ta.length===0&&v===0)return Oe||sn?ye("div",{className:a,children:[!p&&At,L(Ca,{children:"No orders match these filters."})]}):L("div",{className:a,children:L(Ss,{icon:Vc,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!p&&L(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>Q(!0),children:"Show abandoned checkouts"})})});let V=v*h+1,Ge=Math.min((v+1)*h,m);return ye("div",{className:a,children:[p?null:At,L("div",{className:"af-space-y-3 lg:af-hidden",children:zt.map($=>ye("button",{type:"button",onClick:()=>ie($),disabled:!dt,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${dt?" 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($)}),L("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(Ka($),$.currency)})]}),ye("div",{className:"af-mt-1 af-min-w-0",children:[ye("div",{className:"af-truncate af-text-sm",children:[$.customer_email||L("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),kn($)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",kn($)]})]}),L("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Mi($)}),$.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j($.amount_refunded,$.currency)," refunded"]})]}),ye("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[L(ps,{status:$.status}),L(Hs,{deliveries:$.email_deliveries}),$.is_test&&L(ee,{variant:"outline",children:"Test"}),n&&L(Ns,{order:$}),L("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Fi($.created_at)})]})]},$.id))}),L("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[L(Fe,{children:ye(fe,{children:[L(M,{children:"Order"}),L(M,{children:"Date"}),L(M,{children:"Customer"}),L(M,{children:"Items"}),L(M,{className:"af-text-right",children:"Total"}),L(M,{children:"Status"}),L(M,{className:"af-w-8"})]})}),L(Me,{children:zt.map($=>ye(fe,{onClick:dt?()=>ie($):void 0,className:dt?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[ye(U,{className:"af-whitespace-nowrap af-font-medium",children:[L("button",{type:"button",onClick:qt=>{qt.stopPropagation(),ie($)},disabled:!dt,"aria-label":`Open order ${Za($)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${dt?" hover:af-underline":""}`,children:Za($)}),$.is_test&&L(ee,{variant:"outline",className:"af-ml-2",children:"Test"})]}),L(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Fi($.created_at)}),ye(U,{className:"af-max-w-[220px]",children:[L("div",{className:"af-truncate",children:$.customer_email||L("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),kn($)&&L("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:kn($)})]}),L(U,{className:"af-max-w-[220px]",children:L("div",{className:"af-truncate af-text-muted-foreground",children:Mi($)})}),ye(U,{className:"af-whitespace-nowrap af-text-right",children:[L("div",{className:"af-font-medium af-tabular-nums",children:j(Ka($),$.currency)}),$.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j($.amount_refunded,$.currency)," ","refunded"]})]}),L(U,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[L(ps,{status:$.status}),L(Hs,{deliveries:$.email_deliveries}),n&&L(Ns,{order:$})]})}),L(U,{className:"af-w-8 af-text-right",children:L(Oi,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},$.id))})]})}),p?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:It?`${ta.length} matching this page`:`Showing ${V}-${Ge} of ${m}`}),ye(ca,{value:String(h),onValueChange:$=>u(Number($)),children:[L(aa,{className:"af-w-[70px] af-h-8",children:L(ua,{})}),ye(sa,{children:[L(We,{value:"10",children:"10"}),L(We,{value:"25",children:"25"}),L(We,{value:"50",children:"50"}),L(We,{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:()=>B(v-1),disabled:!E,children:[L(Mc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ye(w,{variant:"outline",size:"sm",onClick:()=>B(v+1),disabled:!N,children:["Next",L(Oi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function ns(e){return L(qc,{...e},e.maxRows==null?"full":"compact")}import*as An from"react";import{ChevronLeft as Kc,ChevronRight as Zc,Eye as Jc,Search as Yc,Users as Qc}from"lucide-react";import*as Jt from"react";function En({initialPageSize:e=25}={}){let{api:a}=re(),[s,t]=Jt.useState([]),[n,i]=Jt.useState(0),[o,f]=Jt.useState(!0),[d,p]=Jt.useState(null),[r,g]=Jt.useState(0),[y,m]=Jt.useState(e),[c,l]=Jt.useState(""),v=Jt.useRef(0),h=Jt.useCallback(async()=>{let E=++v.current;try{f(!0),p(null);let B={limit:y,offset:r*y};c.trim()&&(B.email=c.trim());let u=await a.getCustomers(B);if(E!==v.current)return;t(u.customers),i(u.total)}catch(B){if(E!==v.current)return;p(B instanceof Error?B:new Error("Failed to fetch customers"))}finally{E===v.current&&f(!1)}},[a,r,y,c]);Jt.useEffect(()=>{h()},[h]);let N=Math.ceil(n/y);return{customers:s,total:n,isLoading:o,error:d,page:r,pageSize:y,hasNextPage:r<N-1,hasPreviousPage:r>0,setPage:g,setPageSize:E=>{m(E),g(0)},email:c,setEmail:E=>{l(E),g(0)},refetch:h}}import*as bs from"react";import{ArrowLeft as jc,Loader2 as Gc}from"lucide-react";import{jsx as Ie,jsxs as kt}from"react/jsx-runtime";function Ui(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 Wc(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 In({customer:e,onBack:a,className:s}){let{api:t}=re(),[n,i]=bs.useState(null),[o,f]=bs.useState([]),[d,p]=bs.useState(!0),[r,g]=bs.useState(null);bs.useEffect(()=>{let c=!1;return p(!0),g(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,v])=>{c||(i(l),f(v.orders))}).catch(l=>{c||g(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{c||p(!1)}),()=>{c=!0}},[t,e.id,e.email]);let y=n?.addresses??[],m=n?.order_count??o.length;return kt("div",{className:s,children:[kt("div",{className:"af-mb-6",children:[kt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[Ie(jc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Ie("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),kt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Ui(e.created_at)]})]}),d?Ie("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ie(Gc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?Ie("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):kt("div",{className:"af-space-y-6",children:[Ie(Aa,{deliveries:n?.email_deliveries}),kt("div",{children:[Ie("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),kt("div",{className:"af-space-y-1 af-text-sm",children:[kt("div",{className:"af-flex af-gap-2",children:[Ie("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Ie("span",{children:e.email})]}),e.name&&kt("div",{className:"af-flex af-gap-2",children:[Ie("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Ie("span",{children:e.name})]}),e.phone&&kt("div",{className:"af-flex af-gap-2",children:[Ie("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Ie("span",{children:e.phone})]}),kt("div",{className:"af-flex af-gap-2",children:[Ie("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Ie("span",{children:m})]})]})]}),y.length>0&&kt("div",{children:[Ie("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Ie("div",{className:"af-flex af-flex-wrap af-gap-3",children:y.map(c=>kt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&Ie(ee,{variant:"secondary",className:"af-mb-1",children:"Default"}),Wc(c).map((l,v)=>Ie("div",{children:l},v))]},c.id))})]}),kt("div",{children:[Ie("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Ie("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):kt(Be,{children:[Ie(Fe,{children:kt(fe,{children:[Ie(M,{children:"Date"}),Ie(M,{children:"Amount"}),Ie(M,{children:"Status"})]})}),Ie(Me,{children:o.map(c=>kt(fe,{children:[Ie(U,{className:"af-text-muted-foreground",children:Ui(c.created_at)}),Ie(U,{children:j(Ka(c),c.currency)}),Ie(U,{children:Ie(gs,{status:c.status})})]},c.id))})]})]})]})]})}import{Fragment as eu,jsx as Re,jsxs as gt}from"react/jsx-runtime";function Xc(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:f,hasPreviousPage:d,setPage:p,setPageSize:r,email:g,setEmail:y,refetch:m}=En(),[c,l]=An.useState("list"),[v,h]=An.useState(null),[N,E]=An.useState(""),B=D=>{h(D),l("detail")},u=()=>{l("list"),h(null),m()};if(c==="detail"&&v)return Re("div",{className:e,children:Re(In,{customer:v,onBack:u})});let k=gt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Re(me,{type:"email",value:N,onChange:D=>E(D.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),y(N.trim()))}}),gt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>y(N.trim()),children:[Re(Yc,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&Re(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{E(""),y("")},children:"Clear"})]});if(t)return gt("div",{className:e,children:[k,Re("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Re("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return gt("div",{className:e,children:[k,Re("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:[Re(Qc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Re("p",{className:"af-text-muted-foreground af-text-center",children:g?"No customers match that email.":gt(eu,{children:["No customers yet.",Re("br",{}),"Customers appear here after their first purchase."]})})]})]});let I=i*o+1,C=Math.min((i+1)*o,s);return gt("div",{className:e,children:[k,gt(Be,{children:[Re(Fe,{children:gt(fe,{children:[Re(M,{children:"Email"}),Re(M,{children:"Name"}),Re(M,{children:"Customer since"}),Re(M,{className:"af-text-right",children:"Actions"})]})}),Re(Me,{children:a.map(D=>gt(fe,{children:[Re(U,{className:"af-font-medium",children:D.email}),Re(U,{children:D.name||Re("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Re(U,{className:"af-text-muted-foreground",children:Xc(D.created_at)}),Re(U,{className:"af-text-right",children:Re(w,{variant:"ghost",size:"icon",onClick:()=>B(D),title:"View customer",children:Re(Jc,{className:"af-h-4 af-w-4"})})})]},D.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 ",I,"-",C," of ",s]}),gt(ca,{value:String(o),onValueChange:D=>r(Number(D)),children:[Re(aa,{className:"af-w-[70px] af-h-8",children:Re(ua,{})}),gt(sa,{children:[Re(We,{value:"10",children:"10"}),Re(We,{value:"25",children:"25"}),Re(We,{value:"50",children:"50"}),Re(We,{value:"100",children:"100"})]})]}),Re("span",{children:"per page"})]}),gt("div",{className:"af-flex af-items-center af-gap-2",children:[gt(w,{variant:"outline",size:"sm",onClick:()=>p(i-1),disabled:!d,children:[Re(Kc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),gt(w,{variant:"outline",size:"sm",onClick:()=>p(i+1),disabled:!f,children:["Next",Re(Zc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ne from"react";import{ArrowLeft as tu,ChevronLeft as au,ChevronRight as Vi,Copy as su,Download as nu,ExternalLink as ru,FileText as zi,Loader2 as iu,Search as ou}from"lucide-react";import*as vt from"react";function _s({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=re(),[n,i]=vt.useState([]),[o,f]=vt.useState(0),[d,p]=vt.useState(null),[r,g]=vt.useState(!0),[y,m]=vt.useState(null),[c,l]=vt.useState(0),[v,h]=vt.useState(e),[N,E]=vt.useState(void 0),[B,u]=vt.useState(""),[k,I]=vt.useState(""),[C,D]=vt.useState(""),[A,F]=vt.useState(""),[b,G]=vt.useState(""),Q=N?N.join(","):"",z=vt.useRef(0),ce=vt.useCallback(async()=>{let te=++z.current;g(!0),m(null);try{let H={labels:Q?Q.split(","):void 0,customerEmail:B||void 0,q:k||void 0,from:C||void 0,to:A||void 0,retainerId:b||void 0,includeAggregates:s,limit:v,offset:c*v},ne=await t.getInvoices(H);if(te!==z.current)return;if(c>0&&c*v>=ne.total){l(Math.max(0,Math.ceil(ne.total/v)-1));return}i(ne.invoices),f(ne.total),s&&p(ne.aggregates??null)}catch(H){if(te!==z.current)return;m(H instanceof Error?H:new Error("Failed to fetch invoices"))}finally{te===z.current&&g(!1)}},[t,Q,B,k,C,A,b,c,v,s]);vt.useEffect(()=>{ce()},[ce,a]);let O=te=>H=>{l(0),te(H)};return{invoices:n,total:o,aggregates:d,isLoading:r,error:y,page:c,pageSize:v,hasNextPage:(c+1)*v<o,hasPreviousPage:c>0,setPage:l,setPageSize:O(h),labels:N,setLabels:O(E),customerEmail:B,setCustomerEmail:O(u),q:k,setQ:O(I),from:C,setFrom:O(D),to:A,setTo:O(F),retainerId:b,setRetainerId:O(G),clearFilters:()=>{l(0),E(void 0),u(""),I(""),D(""),F(""),G("")},refetch:ce}}import{Fragment as gu,jsx as P,jsxs as J}from"react/jsx-runtime";var lu={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 Tr(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:lu[e.label]??e.label}function cu(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 Cr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},uu={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ws({invoice:e,className:a}){return J("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[P(ee,{variant:cu(e.label),className:a,children:Tr(e)}),e.collection_method==="charge_automatically"&&P(ee,{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(ee,{variant:s,className:a,children:Cr[e.state]??e.state})}function Rs(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 $i={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 du(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 Rr=100,Pr=5e3;async function fu(e,a){let s=[],t=0;for(let n=0;n<Pr;n+=Rr){let i=await e.getInvoices({...a,limit:Rr,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<Rr||s.length>=t)break}return{invoices:s.slice(0,Pr),total:t,truncated:t>s.length||t>Pr}}function qi(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,Rs(t),Tr(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(du).join(",")).join(`
|
|
5
|
-
`)}function mu(e){if(typeof document>"u")return;let a=new Blob([qi(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 pu({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:f=null,onClearRetainerFilter:d,maxRows:p,onViewAll:r}){let g=typeof p=="number",{api:y}=re(),{invoices:m,total:c,isLoading:l,error:v,page:h,pageSize:N,hasNextPage:E,hasPreviousPage:B,setPage:u,labels:k,setLabels:I,customerEmail:C,setCustomerEmail:D,q:A,setQ:F,from:b,setFrom:G,to:Q,setTo:z,retainerId:ce,setRetainerId:O,refetch:te}=_s({refreshKey:a}),[H,ne]=Ne.useState(typeof p=="number"?"all":"open"),[W,he]=Ne.useState(""),[qe,rt]=Ne.useState(null),_e=Ne.useRef(0),Ve=!g||!!r,Xe=Ne.useCallback(V=>{if(g){r?.();return}_e.current++,yt(!1),rt(V)},[g,r]),[xe,yt]=Ne.useState(!1),[_,x]=Ne.useState(0),[q,pe]=Ne.useState(null),[be,Te]=Ne.useState(!1),[je,Oe]=Ne.useState(0);Ne.useEffect(()=>{rt(V=>{if(!V)return V;let Ge=m.find($=>$.id===V.id);return Ge&&Ge!==V?Ge:V})},[m]);let[Ke,dt]=Ne.useState(!1),[ie,Ae]=Ne.useState(null),et=async()=>{if(!Ke){dt(!0),Ae(null);try{let{invoices:V,total:Ge,truncated:$}=await fu(y,{labels:k,customerEmail:C,q:A,from:b,to:Q,retainerId:ce});mu(V),Ae($?`Exported the first ${V.length.toLocaleString()} of ${Ge.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ae("Couldn't export \u2014 try again.")}finally{dt(!1)}}},Ct=!C&&!A&&!b&&!Q&&!ce,[It,ta]=Ne.useState(null);Ne.useEffect(()=>{if(l||c>0||!Ct||H!=="open")return;let V=!1;return y.getInvoices({limit:1}).then(Ge=>{V||ta(Ge.total>0)}).catch(()=>{V||ta(!0)}),()=>{V=!0}},[y,l,c,Ct,H,a]),Ne.useEffect(()=>{I(g?Ln.all:Ln.open)},[]),Ne.useEffect(()=>{let V=f?.id??"";V!==ce&&(O(V),V&&(ne("all"),I(Ln.all),D(""),F(""),he(""),G(""),z("")))},[f?.id]),Ne.useEffect(()=>{let V=!1;return Te(!1),y.getInvoiceSettings().then(Ge=>{V||pe({payments_active:Ge.payments_active,blocked:Ge.blocked})}).catch(()=>{V||Te(!0)}),()=>{V=!0}},[y,a,je]),Ne.useEffect(()=>{if(!s||g)return;let V=!1,Ge=_e.current;return yt(!1),y.getInvoice(s).then($=>{!V&&Ge===_e.current&&rt($)}).catch(()=>{!V&&Ge===_e.current&&yt(!0)}),()=>{V=!0}},[y,s,_,g]),Ne.useEffect(()=>{t?.(qe!==null)},[qe,t]);let zt=V=>{ne(V),I(Ln[V])},$e=V=>{let Ge=V.trim();if(!Ge){A&&F(""),C&&D("");return}if(Ge.includes("@")){A&&F(""),D(Ge);return}C&&D(""),F(Ge.replace(/^#/,""))},tt=m,Qa=g?tt.slice(0,p):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:()=>x(V=>V+1),children:"Retry opening invoice"})]});if(qe)return J("div",{className:e,children:[Fs,P(kr,{invoice:qe,refreshKey:a,onBack:()=>{Xe(null),te()}},qe.id)]});let At=J("div",{className:"af-mb-4 af-space-y-3",children:[be&&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:()=>Oe(V=>V+1),children:"Retry setup check"})]}),Fs,q?.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",q.blocked.reason?`: ${q.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),f&&J("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[J(ee,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",f.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($i).map(V=>P("button",{type:"button","aria-pressed":H===V,onClick:()=>zt(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",H===V?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:$i[V]},V))}),J("div",{className:"af-relative af-w-full af-max-w-xs",children:[P(ou,{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(me,{type:"text",value:W,onChange:V=>he(V.target.value),onBlur:()=>$e(W),onKeyDown:V=>{V.key==="Enter"&&(V.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(ge,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),P(me,{id:"invoices-from",type:"date",value:b,max:Q||void 0,onChange:V=>G(V.target.value),className:"af-invoice-date af-w-[150px]"})]}),J("div",{className:"af-flex af-items-center af-gap-2",children:[P(ge,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),P(me,{id:"invoices-to",type:"date",value:Q,min:b||void 0,onChange:V=>z(V.target.value),className:"af-invoice-date af-w-[150px]"})]}),J(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void et(),disabled:Ke||l||!!v||c===0,"aria-busy":Ke,children:[P(nu,{className:"af-h-4 af-w-4 af-mr-1"}),Ke?"Exporting\u2026":"Export CSV (all matching)"]})]}),ie&&P("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:ie})]});return l?J("div",{className:e,children:[g?null:At,P("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(V=>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"})]},V))})]}):v?J("div",{className:e,children:[g?null:At,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 te(),children:"Retry"})]})]}):c===0&&Ct&&(H==="all"||It===!1)&&(H==="open"||H==="all")?q?.blocked?J("div",{className:e,children:[g?null:At,P(On,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?J("div",{className:e,children:[g?null:At,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})]}):q&&!q.payments_active?J("div",{className:e,children:[g?null:At,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:At,P(On,{heading:"No invoices yet",body:!q||be?"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:At,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(gu,{children:[P("div",{className:"af-space-y-3 lg:af-hidden",children:Qa.map(V=>J("button",{type:"button",onClick:()=>Xe(V),disabled:!Ve,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ve?" 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:Rs(V)}),P(Ws,{invoice:V})]}),P("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:V.customer_name??V.customer_email??"\u2014"}),V.delivery&&P("div",{className:"af-mt-1",children:P(Bn,{delivery:V.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:V.collection_method==="charge_automatically"?"Automatic collection":V.due_at?`Due ${va(V.due_at)}`:"Due on receipt"}),P("span",{className:"af-font-medium af-tabular-nums",children:j(V.amount_due??V.amount_total,V.currency)})]})]},V.id))}),P("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:J(Be,{children:[P(Fe,{children:J(fe,{children:[P(M,{children:"Invoice"}),P(M,{children:"Created"}),P(M,{children:"Customer"}),P(M,{children:"Due"}),P(M,{className:"af-text-right",children:"Amount"}),P(M,{children:"Status"}),P(M,{children:"Delivery"}),P(M,{className:"af-w-8"})]})}),P(Me,{children:Qa.map(V=>J(fe,{className:Ve?"af-cursor-pointer":void 0,onClick:Ve?()=>Xe(V):void 0,children:[P(U,{className:"af-font-medium",children:P("button",{type:"button",disabled:!Ve,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ve?" hover:af-underline":""}`,onClick:Ge=>{Ge.stopPropagation(),Xe(V)},"aria-label":`Open invoice ${Rs(V)}`,children:Rs(V)})}),P(U,{children:va(V.created_at)}),J(U,{children:[P("div",{children:V.customer_name??"\u2014"}),P("div",{className:"af-text-xs af-text-muted-foreground",children:V.customer_email})]}),P(U,{children:V.collection_method==="charge_automatically"?"Automatic":V.due_at?va(V.due_at):"On receipt"}),P(U,{className:"af-text-right af-tabular-nums",children:j(V.amount_due??V.amount_total,V.currency)}),P(U,{children:P(Ws,{invoice:V})}),P(U,{children:P(Bn,{delivery:V.delivery})}),P(U,{children:P(Vi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},V.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:[c," invoice",c===1?"":"s"]}),J("div",{className:"af-flex af-items-center af-gap-1",children:[P(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(h-1),disabled:!B,"aria-label":"Previous page",children:P(au,{className:"af-h-4 af-w-4"})}),J("span",{className:"af-tabular-nums",children:[h*N+1,"\u2013",Math.min((h+1)*N,c)]}),P(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(h+1),disabled:!E,"aria-label":"Next page",children:P(Vi,{className:"af-h-4 af-w-4"})})]})]})]})]})}function On({heading:e,body:a,action:s}){return P(Ss,{icon:zi,heading:e,body:a,action:s})}function is(e){return P(pu,{...e},e.maxRows==null?"full":"compact")}var Ja="af-text-xs af-text-muted-foreground";function Hi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function kr({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=re(),i=Ne.useRef(null);Ne.useEffect(()=>{i.current?.focus()},[e.id]);let[o,f]=Ne.useState(!1),[d,p]=Ne.useState(null),[r,g]=Ne.useState(!1),[y,m]=Ne.useState(!1),c=Ne.useRef(0),[l,v]=Ne.useState(null),[h,N]=Ne.useState(!1),[E,B]=Ne.useState(0);Ne.useEffect(()=>{let b=!1;return N(!1),n.getInvoice(e.id).then(G=>{b||v({source:e,value:G})}).catch(()=>{b||N(!0)}),()=>{b=!0}},[n,e,s,E]);let u=l?.source===e?l.value:e,k=u.collection_method==="charge_automatically";Ne.useEffect(()=>(c.current++,p(null),g(!1),m(!1),f(!1),()=>{c.current++}),[n,u,s]);let I=b=>b==null?"\u2014":j(b,u.currency),C=async()=>{if(!(!u.pay_url||!Hi()))try{await navigator.clipboard.writeText(u.pay_url),f(!0),setTimeout(()=>f(!1),1500)}catch{}},D=async()=>{if(d){p(null);return}let b=++c.current;m(!1),g(!0);try{let G=await n.getInvoicePreview(u.id);b===c.current&&p(G)}catch{b===c.current&&m(!0)}finally{b===c.current&&g(!1)}},A=u.bill_to,F=A?[A.company,A.name,A.address?.line1,A.address?.line2,[A.address?.city,A.address?.state,A.address?.postal_code].filter(Boolean).join(", "),A.address?.country,A.tax_id?`${A.tax_id.value}`:null,A.po_number?`PO ${A.po_number}`:null,A.service_period?`Service period: ${A.service_period}`:null].filter(b=>!!b&&b.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(tu,{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 ",Rs(u)]}),P(Ws,{invoice:u}),P(Bn,{delivery:u.delivery})]}),J("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[u.customer_name??u.customer_email,u.customer_name&&u.customer_email?` \xB7 ${u.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:()=>B(b=>b+1),children:"Retry details"})]}),u.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."}),u.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(fe,{children:[P(M,{children:"Description"}),P(M,{className:"af-text-right",children:"Qty"}),P(M,{className:"af-text-right",children:"Amount"})]})}),P(Me,{children:u.line_items.map((b,G)=>J(fe,{children:[P(U,{style:{overflowWrap:"anywhere"},children:b.description}),P(U,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:b.quantity}),P(U,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:I(b.amount)})]},G))})]}),J("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[P(rs,{label:"Subtotal",value:I(u.amount_subtotal)}),(u.discount_total??0)>0&&P(rs,{label:"Discount",value:`-${I(u.discount_total)}`}),u.tax_total>0&&P(rs,{label:u.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:I(u.tax_total)}),P(rs,{label:"Total",value:I(u.amount_total),strong:!0}),u.credit_applied>0&&P(rs,{label:"Credit applied",value:`-${I(u.credit_applied)}`}),u.amount_due!==null&&u.amount_due!==u.amount_total&&P(rs,{label:"Amount due",value:I(u.amount_due),strong:!0}),u.amount_paid!==null&&u.amount_paid>0&&P(rs,{label:"Amount paid",value:I(u.amount_paid)}),u.amount_refunded>0&&P(rs,{label:"Refunded",value:I(u.amount_refunded)})]}),u.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"}),u.credit_notes.map(b=>J("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[J("span",{className:"af-text-muted-foreground",children:[va(b.created_at)," \xB7 ",b.origin==="dashboard"?"issued in Stripe":"refund",b.stripe_credit_note_id?"":" \xB7 being created"]}),J("span",{className:"af-tabular-nums",children:["-",j(b.amount,b.currency)]})]},b.id))]})]}),(u.note||u.footer)&&J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[u.note&&J("div",{children:[P("div",{className:Ja,children:"Note"}),P("div",{className:"af-whitespace-pre-wrap af-break-words",children:u.note})]}),u.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:u.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(u.created_at)}),P(ga,{label:"Due",value:u.collection_method==="charge_automatically"?"Managed in Stripe":u.due_at?va(u.due_at):"On receipt"}),u.paid_at&&P(ga,{label:"Paid",value:va(u.paid_at)}),u.payment_method&&P(ga,{label:"Paid by",value:u.paid_out_of_band?`${u.payment_method} (recorded outside Stripe)`:u.payment_method}),u.payment_state!=="none"&&P(ga,{label:"Payment",value:u.payment_state==="processing"?"Processing":u.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),u.delivery&&P(ga,{label:"Delivery",value:`${Cr[u.delivery.state]} \xB7 ${u.delivery.recipient}`}),u.marked_uncollectible_at&&P(ga,{label:"Written off",value:va(u.marked_uncollectible_at)}),u.correction_reason&&P(ga,{label:"Correction",value:u.correction_reason}),u.replaced_by_order_id&&P(ga,{label:"Replaced by",value:u.replaced_by_order_id}),u.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."}):u.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"}),u.replaces_order_id&&P(ga,{label:"Replaces",value:u.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."}):u.reminders.disabled?P("div",{children:"Off for this invoice."}):u.reminders.paused_until?J("div",{children:["Paused until ",va(u.reminders.paused_until),"."]}):u.reminders.next_at?J("div",{children:["Next on ",va(u.reminders.next_at),"."]}):u.reminders.final_sent_at?J("div",{children:["Final reminder sent ",va(u.reminders.final_sent_at),"."]}):P("div",{children:"None scheduled."}),!k&&J("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",u.reminders.schedule.length===0?"none":u.reminders.schedule.map(b=>b<0?`${-b}d before`:b===0?"due day":`${b}d after`).join(", ")]})]}),u.communications&&u.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"}),u.communications.map(b=>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:[uu[b.kind]??b.kind,b.kind==="reminder"&&b.slot!==null?` #${b.slot}`:"",J("span",{className:"af-text-muted-foreground",children:[" \xB7 ",b.recipient]})]}),J("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Cr[b.state]??b.state," \xB7 ",va(b.state_at??b.created_at)]})]},b.id))]}),F.length>0&&J("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[P("div",{className:Ja,children:"Bill to"}),F.map((b,G)=>P("div",{className:"af-break-words",children:b},G))]}),J("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[u.pay_url&&J(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void C(),disabled:!Hi(),children:[P(su,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":k?"Copy invoice link":"Copy pay link"]}),u.pdf_url&&P(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:J("a",{href:u.pdf_url,target:"_blank",rel:"noreferrer",children:[P(ru,{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 D(),disabled:r,children:[r?P(iu,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(zi,{className:"af-h-4 af-w-4 af-mr-1"}),d?"Hide email preview":y?"Retry email preview":"Show email preview"]}),y&&!k&&P("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),u.pay_url&&P("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:u.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 vu}from"lucide-react";import{jsx as bt,jsxs as Ta}from"react/jsx-runtime";var bu={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},ji={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function yu(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 Gi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>ji[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>ji[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":bu[e.status]}function Wi(e){let a=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${a}`}function hu(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 Er({retainer:e,className:a}){return bt(ee,{variant:yu(e.status),className:K("af-max-w-full af-whitespace-normal af-break-words",a),children:Gi(e)})}function Ps({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:f=0,isLoadingMore:d=!1,onLoadMore:p,includeEnded:r=!1,onIncludeEndedChange:g,className:y}){let m=!!g;if(!a&&!s&&e.length===0&&!(m&&(r||f>0)))return null;let c=o!==void 0?Math.max(0,o-e.length):0;return Ta("section",{className:K("af-mb-6",y),"aria-label":"Recurring invoices",children:[Ta("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[bt(vu,{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."}),m&&bt(w,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>g?.(!r),children:r?"Hide ended recurring invoices":f>0&&e.length===0?`Show ended recurring invoices (${f})`:"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 v=i===l.id;return Ta("li",{className:K("af-rounded-md af-border af-p-3",v&&"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(Er,{retainer:l})]}),l.collection_method==="charge_automatically"?Ta("div",{className:"af-mt-2 af-space-y-1",children:[bt(ee,{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:Wi(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:[hu(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:v?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":v,children:v?"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&&c>0&&p&&bt("div",{className:"af-mt-2",children:bt(w,{type:"button",variant:"outline",size:"sm",onClick:p,disabled:d,children:d?"Loading\u2026":`Load more (${c} more)`})})]})}import*as Zi from"react";import{AlertTriangle as Ki,CheckCircle2 as xu,CreditCard as Ir,Loader2 as wu,RefreshCw as Nu}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(),[f,d]=Zi.useState(!1),p=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(xu,{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(Ki,{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(Ki,{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:p,disabled:f,children:[f?st(wu,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):st(Nu,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Ft from"react";function Ar(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function Cs({includeStats:e=!1,refreshKey:a}={}){let{api:s}=re(),[t,n]=Ft.useState([]),[i,o]=Ft.useState(!0),[f,d]=Ft.useState(null),p=Ft.useRef(0),r=Ft.useCallback(async()=>{let v=++p.current;try{o(!0),d(null);let h=await s.getProducts(e?{include:"stats"}:{});if(v!==p.current)return;n(h)}catch(h){if(v!==p.current)return;d(h instanceof Error?h:new Error("Failed to fetch products"))}finally{v===p.current&&o(!1)}},[s,e,a]);Ft.useEffect(()=>{r()},[r]);let g=Ft.useCallback(async v=>{let h=await s.createProduct(v);return n(N=>[h,...N]),h},[s]),y=Ft.useCallback(async(v,h)=>{let N=await s.updateProduct(v,h);return n(E=>Ar(E,v,N)),N},[s]),m=Ft.useCallback(async v=>{await s.deleteProduct(v),n(h=>h.filter(N=>N.id!==v))},[s]),c=Ft.useCallback(async(v,h)=>{let N=await s.attachProductFile(v,h);return n(E=>Ar(E,v,N)),N},[s]),l=Ft.useCallback(async(v,h)=>{let N=await s.attachProductFileFromUrl(v,h);return n(E=>Ar(E,v,N)),N},[s]);return{products:t,isLoading:i,error:f,refetch:r,createProduct:g,updateProduct:y,deleteProduct:m,attachProductFile:c,attachProductFileFromUrl:l}}import*as Mt from"react";var Ji=["creating","active","paused","canceling"],Su=["canceled","failed"];function Ts({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=re(),[n,i]=Mt.useState([]),[o,f]=Mt.useState(0),[d,p]=Mt.useState(0),[r,g]=Mt.useState(!0),[y,m]=Mt.useState(!1),[c,l]=Mt.useState(null),[v,h]=Mt.useState(a),N=Mt.useRef(0),E=Mt.useCallback(async()=>{let u=++N.current;g(!0),m(!1),l(null);try{let k=await t.getRetainers({statuses:v?void 0:Ji,limit:s,offset:0});if(u!==N.current)return;if(i(k.retainers),f(k.total),!v&&k.total===0){let I=await t.getRetainers({statuses:Su,limit:1,offset:0});if(u!==N.current)return;p(I.total)}else p(0)}catch(k){if(u!==N.current)return;l(k instanceof Error?k:new Error("Failed to fetch retainers"))}finally{u===N.current&&g(!1)}},[t,v,s]);Mt.useEffect(()=>{E()},[E,e]);let B=Mt.useCallback(async()=>{if(r||y||n.length>=o)return;let u=N.current;m(!0);try{let k=await t.getRetainers({statuses:v?void 0:Ji,limit:s,offset:n.length});if(u!==N.current)return;i(I=>{let C=new Set(I.map(D=>D.id));return[...I,...k.retainers.filter(D=>!C.has(D.id))]}),f(k.total)}catch(k){if(u!==N.current)return;l(k instanceof Error?k:new Error("Failed to fetch retainers"))}finally{u===N.current&&m(!1)}},[t,v,s,r,y,n.length,o]);return{retainers:n,total:o,endedTotal:d,hasMore:n.length<o,isLoading:r,isLoadingMore:y,error:c,includeEnded:v,setIncludeEnded:h,loadMore:B,refetch:E}}import{Fragment as Iu,jsx as ze,jsxs as Yt}from"react/jsx-runtime";function Yi({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=ks.useState(a),[f,d]=ks.useState("list"),[p,r]=ks.useState(null),g=Cs(),{status:y,error:m}=as(),c=y?.currency,l=E=>{r(E),d("edit")},v=()=>{r(null),d("create")},h=()=>{d("list"),r(null)},N=E=>{r(E),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:E=>o(E),children:[Yt($s,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Yt(ya,{value:"products",className:"af-gap-2",children:[ze(Pu,{className:"af-h-4 af-w-4"}),"Products"]}),Yt(ya,{value:"orders",className:"af-gap-2",children:[ze(Cu,{className:"af-h-4 af-w-4"}),"Orders"]}),Yt(ya,{value:"invoices",className:"af-gap-2",children:[ze(Ru,{className:"af-h-4 af-w-4"}),"Invoices"]}),Yt(ya,{value:"customers",className:"af-gap-2",children:[ze(ku,{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(Tu,{className:"af-h-4 af-w-4"}),"Setup"]})]}),ze(ha,{value:"products",children:f==="list"?ze(xn,{productsState:g,onSelectProduct:l,onCreateProduct:v}):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(_u,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),ze("h3",{className:"af-text-lg af-font-semibold",children:f==="create"?"New Product":p?.name})]}),f==="create"&&!c?ze("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:m?Yt("div",{className:"af-text-destructive",children:["Error: ",m.message]}):ze("div",{className:"af-text-muted-foreground",children:"Loading..."})}):ze(Nn,{productsState:g,product:f==="edit"?p:null,currency:c??"usd",onSaved:N},f==="edit"?p?.id??"edit":"new")]})}),ze(ha,{value:"orders",children:ze(ns,{onRefund:t})}),ze(ha,{value:"invoices",children:ze(Eu,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:y?.reason==="needs_paid_plan"})}),ze(ha,{value:"customers",children:ze(Dn,{})}),ze(ha,{value:"promos",children:ze(ws,{})}),ze(ha,{value:"setup",children:ze(Mn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Eu({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=Ts(),[n,i]=ks.useState(null),[o,f]=ks.useState(!1);return Yt(Iu,{children:[!o&&ze(Ps,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:d=>i(p=>p?.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:f,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 Xi from"react";import*as Ma from"react";function Es({refreshKey:e}={}){let{api:a}=re(),[s,t]=Ma.useState(null),[n,i]=Ma.useState(!0),[o,f]=Ma.useState(null),d=Ma.useRef(0),p=Ma.useCallback(async()=>{let r=++d.current;try{i(!0),f(null);let g=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==d.current)return;t(g)}catch(g){if(r!==d.current)return;f(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{r===d.current&&i(!1)}},[a,e]);return Ma.useEffect(()=>{p()},[p]),{summary:s,isLoading:n,error:o,refetch:p}}import{Fragment as Dr,jsx as Pt,jsxs as Lr}from"react/jsx-runtime";function Qi(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 eo({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:f,error:d,refetch:p}=Es({refreshKey:e}),[r,g]=Xi.useState(!1),y=Pt("div",{className:"af-mb-6",children:d&&!o?Pt(ia,{message:"Couldn't load your revenue summary.",onRetry:()=>p()}):Pt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!o?Lr(Dr,{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(Dr,{children:(()=>{let m=Qi(o.revenue.d7,o.currency),c=Qi(o.revenue.today,o.currency);return Lr(Dr,{children:[Pt(at,{label:"This week",detail:m.extra.length>0?Pt("div",{children:m.extra.map(l=>Pt("div",{children:l},l))}):void 0,children:m.headline}),Pt(at,{label:"Today",detail:c.extra.length>0?Pt("div",{children:c.extra.map(l=>Pt("div",{children:l},l))}):void 0,children:c.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 Lr(xt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[y,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 Bu,Package as Fu,Search as Mu}from"lucide-react";import*as Ua from"react";import{ArrowLeft as Lu,ImageOff as Ou}from"lucide-react";import{jsx as ka,jsxs as Ks}from"react/jsx-runtime";var to="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",Au=3;function Du(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,p=e.max_amount??a?.max_amount??null;return d!==null&&p!==null?{text:`Buyer chooses (${j(d,s)} \u2013 ${j(p,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)}`,f=a?.compare_at_amount??null;return{text:o,compareAt:f!==null&&f>i?j(f,s):null}}function Vn({product:e,className:a}){let s=Du(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(ee,{variant:"destructive",children:"Out of stock"}):a.low_stock?Ks(ee,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?ka(ee,{variant:"secondary",children:"Backorder"}):a.available===null?null:Ks(ee,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?ka(ee,{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=>j(a.amount,a.currency)).join(" + ")}function ao(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 so({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(ee,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?ka(ee,{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<=Au&&ka(ee,{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:to,children:e}),le("div",{className:"af-mt-3",children:a})]})}function no({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(Ou,{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 ro({product:e,showStats:a=!1,onBack:s}){let{api:t}=re(),[n,i]=Ua.useState(null),[o,f]=Ua.useState(!0),[d,p]=Ua.useState(null),[r,g]=Ua.useState(0),[y,m]=Ua.useState(0);Ua.useEffect(()=>{let u=!1;return f(!0),p(null),t.getProduct(e.id).then(k=>{u||i(k)}).catch(k=>{u||p(k instanceof Error?k:new Error("Failed to load product"))}).finally(()=>{u||f(!1)}),()=>{u=!0}},[t,e.id,r]);let c=n?{...e,...n}:e,l=c.images.length>0?c.images:e.images,v=l[y]??l[0],h=Hn(c),N=a?c.stats:void 0,E=n?.variants??[],B=E.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(Lu,{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:c.name}),le(ee,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),le($n,{product:c})]}),le(Vn,{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."})]}),Je("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[Je("div",{className:"af-space-y-2",children:[le(no,{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((u,k)=>le("button",{type:"button",onClick:()=>m(k),"aria-label":`Show photo ${k+1} of ${l.length}`,"aria-pressed":k===y,className:K("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",k===y?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:le(no,{src:u,className:"af-h-12 af-w-12 af-rounded-md"})},`${u}-${k}`))})]}),Je("div",{className:"af-space-y-6",children:[c.description&&le(Zs,{title:"Description",children:le("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?Je(Zs,{title:"Variants",children:[le("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(u=>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"})]},u))}),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(u=>u+1)}):B?le(Zs,{title:`Variants \xB7 ${E.length}`,children:le("div",{className:"af-overflow-x-auto",children:Je(Be,{children:[le(Fe,{children:Je(fe,{children:[le(M,{children:"Variant"}),le(M,{children:"SKU"}),le(M,{className:"af-text-right",children:"Price"}),le(M,{children:"Stock"})]})}),le(Me,{children:E.map(u=>Je(fe,{children:[Je(U,{className:"af-font-medium",children:[u.title||u.option_values.map(k=>k.value).join(" / ")||"\u2014",!u.active&&le(ee,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),le(U,{className:"af-text-muted-foreground",children:u.sku?le("code",{className:"af-font-mono af-text-xs af-break-all",children:u.sku}):"\u2014"}),Je(U,{className:"af-whitespace-nowrap af-text-right",children:[le("div",{className:Un,children:ao(u)}),u.compare_at_amount!==null&&u.unit_amount!==null&&u.compare_at_amount>u.unit_amount&&le("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(u.compare_at_amount,u.currency)})]}),le(U,{className:"af-text-sm",children:le(so,{variant:u})})]},u.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"?c.fulfillment.filename??"Digital download":h??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&Je("div",{children:[le("dt",{className:os,children:"Sends buyers to"}),le("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),Je("div",{children:[le("dt",{className:os,children:"Shipping address"}),le("dd",{className:"af-text-sm",children:c.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:c.max_quantity})]})]})}),N&&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:N.units_sold})]}),Je("div",{children:[le("dt",{className:os,children:"Orders"}),le("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:N.orders})]}),Je("div",{children:[le("dt",{className:os,children:"Gross"}),le("dd",{className:Un,children:N.gross.length>0?zn(N.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 se,jsxs as Ye}from"react/jsx-runtime";var Uu={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Vu=["all","active","draft","low_stock","out_of_stock"];function io(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function oo(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function $u(e){return e.inventory?.out_of_stock??!1}function Hu(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return oo(e);case"out_of_stock":return $u(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?se("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):se("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:se(Bu,{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:[se("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),se(Vn,{product:e,className:"af-mt-0.5"})]}),!e.active&&se(ee,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[se($n,{product:e}),o>1&&Ye(ee,{variant:"outline",children:[o," variants"]}),i&&se(ee,{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)}`:""," ",se("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function qu(){return se("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:[se("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:[se(ae,{className:"af-w-32"}),se(ae,{className:"af-w-16"}),se(ae,{className:"af-h-5 af-w-24"})]})]},e))})}function lo({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:f}=Cs({includeStats:a,refreshKey:e}),[d,p]=Va.useState(!1),[r,g]=Va.useState(null),[y,m]=Va.useState("all"),[c,l]=Va.useState(""),[v,h]=Va.useState("newest"),N=Va.useMemo(()=>{if(!a)return null;let b=null;for(let G of n)!G.stats||G.stats.units_sold===0||(!b||G.stats.units_sold>(b.stats?.units_sold??0))&&(b=G);return b},[n,a]),E=Va.useMemo(()=>n.filter(oo).length,[n]),B=c.trim().toLowerCase(),u=Va.useMemo(()=>{let G=[...n.filter(Q=>Hu(Q,y)&&(!B||Q.name.toLowerCase().includes(B)))];return v==="name"?G.sort((Q,z)=>Q.name.localeCompare(z.name)):v==="best_selling"?G.sort((Q,z)=>(z.stats?.units_sold??0)-(Q.stats?.units_sold??0)):G.sort((Q,z)=>io(z.created_at)-io(Q.created_at)),G},[n,y,B,v]),k=y!=="all"||!!B,I=()=>{m("all"),l("")},C=i||o!==null&&n.length===0,D=se("div",{className:"af-mb-6",children:se("div",{className:K("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:C?Ye(ls,{children:[se(at,{label:"Products",children:se(ae,{className:"af-h-6 af-w-10"})}),a?Ye(ls,{children:[se(at,{label:"Best seller",children:se(ae,{className:"af-h-6 af-w-28"})}),se(at,{label:"Low stock",children:se(ae,{className:"af-h-6 af-w-10"})})]}):se(at,{label:"Active",children:se(ae,{className:"af-h-6 af-w-10"})})]}):Ye(ls,{children:[se(at,{label:"Products",children:n.length}),a?Ye(ls,{children:[se(at,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:N?`${N.stats?.units_sold??0} sold, last 30 days`:void 0,children:N?se("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:N.name}):se("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),se(at,{label:"Low stock",children:E})]}):se(at,{label:"Active",children:n.filter(b=>b.active).length})]})})}),A=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:[se("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:Vu.map(b=>se("button",{type:"button","aria-pressed":y===b,onClick:()=>m(b),className:K("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",y===b?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Uu[b]},b))}),Ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[se(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"}),se(me,{type:"text",value:c,onChange:b=>l(b.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ye(ca,{value:v,onValueChange:b=>h(b),children:[se(aa,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:se(ua,{})}),Ye(sa,{children:[se(We,{value:"newest",children:"Newest"}),se(We,{value:"name",children:"Name A\u2013Z"}),a&&se(We,{value:"best_selling",children:"Best selling"})]})]}),k&&se(w,{type:"button",variant:"ghost",size:"sm",onClick:I,children:"Clear filters"})]}),i&&n.length===0?se(ae,{className:"af-h-4 af-w-28"}):se("p",{className:"af-text-sm af-text-muted-foreground",children:k?`${u.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${E>0?` \xB7 ${E} low stock`:""}`})]}),F;return r?F=se(ro,{product:r,showStats:a,onBack:()=>{g(null),f()}},r.id):i&&n.length===0?F=Ye(ls,{children:[A,se(qu,{}),se("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?F=se("div",{className:"af-flex af-justify-center af-py-8",children:se(ia,{message:"Couldn't load your products.",onRetry:()=>f()})}):n.length===0?F=Ye(Ca,{icon:se(Fu,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",se("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):F=Ye(ls,{children:[A,o&&se("div",{className:"af-mb-4",children:se(ia,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>f()})}),u.length===0?Ye(Ca,{children:["No products match these filters.",se("br",{}),se(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:I,children:"Show all products"})]}):se("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:u.map(b=>se(zu,{product:b,showStats:a,onOpen:()=>g(b)},b.id))})]}),se(xt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:d?Ye(ls,{children:[se(w,{variant:"ghost",onClick:()=>p(!1),children:"Back to products"}),se(ws,{})]}):Ye(ls,{children:[!r&&se("div",{className:"af-mb-4 af-flex af-justify-end",children:se(w,{variant:"outline",onClick:()=>p(!0),children:"Promo codes"})}),!r&&D,F]})})}import*as Ea from"react";import{ArrowLeft as po,Check as ju,ChevronLeft as co,ChevronRight as uo,ClipboardCopy as Gu,Mail as Br,Search as Wu,Users as Ku}from"lucide-react";import*as oa from"react";function qn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=re(),[t,n]=oa.useState([]),[i,o]=oa.useState(!0),[f,d]=oa.useState(null),[p,r]=oa.useState(0),[g]=oa.useState(e),[y,m]=oa.useState(""),c=oa.useRef(0),l=oa.useCallback(async()=>{let v=++c.current;try{o(!0),d(null);let h={limit:g,offset:p*g};y.trim()&&(h.q=y.trim());let N=await s.getPeople(h);if(v!==c.current)return;n(N.people)}catch(h){if(v!==c.current)return;d(h instanceof Error?h:new Error("Failed to fetch people"))}finally{v===c.current&&o(!1)}},[s,p,g,y,a]);return oa.useEffect(()=>{l()},[l]),{people:t,isLoading:i,error:f,page:p,pageSize:g,hasNextPage:t.length===g,hasPreviousPage:p>0,setPage:r,q:y,setQ:v=>{m(v),r(0)},refetch:l}}import*as $a from"react";function jn(e,{refreshKey:a}={}){let{api:s}=re(),[t,n]=$a.useState(null),[i,o]=$a.useState(e!==null),[f,d]=$a.useState(null),p=$a.useRef(0),r=$a.useCallback(async()=>{if(e===null){n(null),o(!1),d(null);return}let g=++p.current;try{o(!0),d(null);let y=await s.getPerson(e);if(g!==p.current)return;n(y)}catch(y){if(g!==p.current)return;d(y instanceof Error?y:new Error("Failed to fetch person"))}finally{g===p.current&&o(!1)}},[s,e,a]);return $a.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:f,refetch:r}}import{jsx as S,jsxs as oe}from"react/jsx-runtime";var Or="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Zu="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 Fr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Ju(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Yu({value:e,label:a}){let[s,t]=Ea.useState(!1);return Ju()?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?S(ju,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):S(Gu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function fo(e){return oe("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&oe(ee,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&S(ee,{variant:"secondary",children:"Contact form"})]})}function mo(e){return e.name?e.name:e.email?e.email:S("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Qu=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Xu=40;function ed(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>Qu.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=Xu).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 td(e){return e.replace(/_/g," ")}function ad(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function sd({data:e}){let{message:a,rest:s}=ed(e);return a===null&&s.length===0?S("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):oe("div",{className:"af-space-y-3",children:[a!==null&&S("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&S("dl",{className:"af-space-y-1",children:s.map(([t,n])=>oe("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[S("dt",{className:K(Zu,"af-w-28 af-shrink-0 af-capitalize"),children:td(t)}),S("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ad(n)})]},t))})]})}function go({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:[S(ee,{variant:"outline",children:"Form submission (unverified)"}),e&&S("span",{className:"af-text-xs af-text-muted-foreground",children:e}),S("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Is(a)})]}),S(sd,{data:s})]})}function nd(e){return e.charged_total??e.amount_total}function rd({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=jn(e,{refreshKey:a}),f=Fr(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:[S(po,{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?S(ae,{className:"af-h-7 af-w-48"}):S("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:[S("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),S(Yu,{value:e,label:"Copy email address"})]})]}),S(w,{asChild:!0,children:oe("a",{href:f,children:[S(Br,{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:[S(ae,{className:"af-w-40"}),S(ae,{className:"af-mt-2 af-w-64"})]},d)),S("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?S("div",{className:"af-flex af-justify-center af-py-8",children:S(ia,{message:"Couldn't load this person.",onRetry:()=>o()})}):oe("div",{className:"af-space-y-6",children:[t.customer&&oe("div",{children:[S("h4",{className:K(Or,"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:[S("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),S("dd",{children:t.customer.name})]}),t.customer.phone&&oe("div",{className:"af-flex af-gap-2",children:[S("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),S("dd",{children:t.customer.phone})]}),oe("div",{className:"af-flex af-gap-2",children:[S("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),S("dd",{children:Is(t.customer.created_at)})]})]})]}),t.orders.length>0&&oe("div",{children:[S("h4",{className:K(Or,"af-mb-3"),children:"Purchases"}),S("div",{className:"af-overflow-x-auto",children:oe(Be,{children:[S(Fe,{children:oe(fe,{children:[S(M,{children:"Order"}),S(M,{children:"Date"}),S(M,{className:"af-text-right",children:"Total"}),S(M,{children:"Status"})]})}),S(Me,{children:t.orders.map(d=>oe(fe,{children:[S(U,{className:"af-whitespace-nowrap af-font-medium",children:Za(d)}),S(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Is(d.created_at)}),S(U,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(nd(d),d.currency)}),S(U,{children:S(gs,{status:d.status})})]},d.id))})]})}),S("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:[S("h4",{className:K(Or,"af-mb-3"),children:"Messages"}),S("div",{className:"af-space-y-3",children:t.submissions.map(d=>S(go,{formName:d.form_name,createdAt:d.created_at,data:d.data},d.id))})]})]})]})}function id({submissionId:e,onBack:a}){let{api:s}=re(),[t,n]=Ea.useState(null),[i,o]=Ea.useState(!0),[f,d]=Ea.useState(null),[p,r]=Ea.useState(0);return Ea.useEffect(()=>{let g=!1;return o(!0),d(null),s.getSubmission(e).then(y=>{g||n(y)}).catch(y=>{g||d(y instanceof Error?y:new Error("Failed to load submission"))}).finally(()=>{g||o(!1)}),()=>{g=!0}},[s,e,p]),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:[S(po,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),S("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?S(ae,{className:"af-mt-1 af-h-4 af-w-32"}):t&&S("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:[S(ae,{className:"af-w-40"}),S(ae,{className:"af-mt-2 af-w-64"}),S(ae,{className:"af-mt-2 af-w-52"}),S("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):f||!t?S("div",{className:"af-flex af-justify-center af-py-8",children:S(ia,{message:"Couldn't load this submission.",onRetry:()=>r(g=>g+1)})}):oe("div",{className:"af-space-y-3",children:[S(go,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),S("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 od={all:"All",customers:"Customers",leads:"Leads"},ld=["all","customers","leads"];function cd(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function ud({refreshKey:e,onBackToWebsite:a,className:s,maxRows:t,onViewAll:n}){let i=typeof t=="number",{people:o,isLoading:f,error:d,page:p,pageSize:r,hasNextPage:g,hasPreviousPage:y,setPage:m,q:c,setQ:l,refetch:v}=qn({refreshKey:e}),[h,N]=Ea.useState({kind:"list"}),[E,B]=Ea.useState(""),[u,k]=Ea.useState("all"),I=!i||!!n,C=Q=>{if(i){n?.();return}Q.email?N({kind:"person",email:Q.email}):Q.submission_id&&N({kind:"submission",submissionId:Q.submission_id})},D=()=>{N({kind:"list"}),v()},A=Q=>{let z=Q.trim();z!==c&&l(z)},F=o.filter(Q=>cd(Q,u)),b=i?F.slice(0,t):F,G;if(h.kind==="person")G=S(rd,{email:h.email,refreshKey:e,onBack:D});else if(h.kind==="submission")G=S(id,{submissionId:h.submissionId,onBack:D});else{let Q=oe("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[S("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:ld.map(z=>S("button",{type:"button","aria-pressed":u===z,onClick:()=>k(z),className:K("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",u===z?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:od[z]},z))}),oe("div",{className:"af-relative af-w-full af-max-w-xs",children:[S(Wu,{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"}),S(me,{type:"text",value:E,onChange:z=>B(z.target.value),onBlur:()=>A(E),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),A(E))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&S(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{B(""),l("")},children:"Clear search"})]});if(f)G=oe("div",{children:[i?null:Q,S("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(z=>oe("div",{className:"af-rounded-md af-border af-p-3",children:[oe("div",{className:"af-flex af-items-center af-justify-between",children:[S(ae,{className:"af-h-4 af-w-32"}),S(ae,{className:"af-h-4 af-w-16"})]}),S(ae,{className:"af-mt-2 af-h-5 af-w-28"}),S(ae,{className:"af-mt-2 af-h-3 af-w-56"})]},z))}),S("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[S(Fe,{children:oe(fe,{children:[S(M,{children:"Person"}),S(M,{children:"Came from"}),S(M,{children:"Latest message"}),S(M,{children:"Last activity"}),S(M,{className:"af-w-8"}),S(M,{className:"af-w-8"})]})}),S(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(z=>oe(fe,{children:[S(U,{children:S(ae,{className:"af-h-4 af-w-40"})}),S(U,{children:S(ae,{className:"af-h-5 af-w-24"})}),S(U,{children:S(ae,{className:"af-h-4 af-w-56"})}),S(U,{children:S(ae,{className:"af-h-4 af-w-24"})}),S(U,{}),S(U,{})]},z))})]})}),S("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(d)G=oe("div",{children:[i?null:Q,S("div",{className:"af-flex af-justify-center af-py-8",children:S(ia,{message:"Couldn't load your leads.",onRetry:()=>v()})})]});else if(b.length===0&&p===0){let z=!!c||u!=="all";G=oe("div",{children:[z&&Q,z?S(Ca,{children:c?"Nobody matches that search.":u==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):S(Ss,{icon:Ku,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)G=oe("div",{children:[i?null:Q,S(Ca,{children:"No more results."}),S("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:oe(w,{variant:"outline",size:"sm",onClick:()=>m(p-1),children:[S(co,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let z=p*r+1,ce=p*r+o.length;G=oe("div",{children:[i?null:Q,S("div",{className:"af-space-y-3 lg:af-hidden",children:b.map((O,te)=>oe("div",{onClick:I?()=>C(O):void 0,className:`af-rounded-md af-border af-p-3${I?" 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:[S("button",{type:"button",onClick:H=>{H.stopPropagation(),C(O)},disabled:!I,"aria-label":`Open ${O.name||O.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${I?" hover:af-underline":""}`,children:mo(O)}),O.name&&O.email&&S("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:O.email})]}),oe("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[S("span",{className:"af-text-xs af-text-muted-foreground",children:Is(O.last_activity_at)}),O.email&&S(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:S("a",{href:Fr(O.email),onClick:H=>H.stopPropagation(),"aria-label":`Email ${O.email}`,children:S(Br,{className:"af-h-4 af-w-4"})})})]})]}),S("div",{className:"af-mt-2",children:fo(O)}),O.latest_message_excerpt&&S("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:O.latest_message_excerpt})]},O.email??O.submission_id??te))}),S("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[S(Fe,{children:oe(fe,{children:[S(M,{children:"Person"}),S(M,{children:"Came from"}),S(M,{children:"Latest message"}),S(M,{children:"Last activity"}),S(M,{className:"af-w-8",children:S("span",{className:"af-sr-only",children:"Reply"})}),S(M,{className:"af-w-8"})]})}),S(Me,{children:b.map((O,te)=>oe(fe,{onClick:I?()=>C(O):void 0,className:I?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[oe(U,{className:"af-max-w-[260px] af-font-medium",children:[S("button",{type:"button",onClick:H=>{H.stopPropagation(),C(O)},disabled:!I,"aria-label":`Open ${O.name||O.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${I?" hover:af-underline":""}`,children:mo(O)}),O.name&&O.email&&S("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:O.email})]}),S(U,{children:fo(O)}),S(U,{className:"af-max-w-[320px]",children:O.latest_message_excerpt?S("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:O.latest_message_excerpt}):S("span",{className:"af-text-muted-foreground",children:"\u2014"})}),S(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Is(O.last_activity_at)}),S(U,{className:"af-w-8",children:O.email&&S(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:S("a",{href:Fr(O.email),onClick:H=>H.stopPropagation(),"aria-label":`Email ${O.email}`,children:S(Br,{className:"af-h-4 af-w-4"})})})}),S(U,{className:"af-w-8 af-text-right",children:S(uo,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},O.email??O.submission_id??te))})]})}),!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:[S("span",{className:"af-text-sm af-text-muted-foreground",children:u==="all"?`Showing ${z}-${ce}`:`${b.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:()=>m(p-1),disabled:!y,children:[S(co,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),oe(w,{variant:"outline",size:"sm",onClick:()=>m(p+1),disabled:!g,children:["Next",S(uo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?S("div",{className:s,children:G}):S(xt,{title:"Leads",onBackToWebsite:a,hideBackButton:h.kind!=="list",className:s,children:G})}function Gn(e){return S(ud,{...e},e.maxRows==null?"full":"compact")}import{ChevronLeft as vo,ChevronRight as dd,Repeat as fd}from"lucide-react";import*as Qt from"react";function Wn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=re(),[t,n]=Qt.useState([]),[i,o]=Qt.useState(0),[f,d]=Qt.useState(!0),[p,r]=Qt.useState(null),[g,y]=Qt.useState(0),[m,c]=Qt.useState(e),[l,v]=Qt.useState(void 0),h=Qt.useRef(0),N=Qt.useCallback(async()=>{let B=++h.current;try{d(!0),r(null);let u={limit:m,offset:g*m};l&&(u.status=l);let k=await s.getSubscriptions(u);if(B!==h.current)return;n(k.subscriptions),o(k.total)}catch(u){if(B!==h.current)return;r(u instanceof Error?u:new Error("Failed to fetch subscriptions"))}finally{B===h.current&&d(!1)}},[s,g,m,l,a]);Qt.useEffect(()=>{N()},[N]);let E=Math.ceil(i/m);return{subscriptions:t,total:i,isLoading:f,error:p,page:g,pageSize:m,hasNextPage:g<E-1,hasPreviousPage:g>0,setPage:y,setPageSize:B=>{c(B),y(0)},status:l,setStatus:B=>{v(B),y(0)},refetch:N}}import{jsx as X,jsxs as Qe}from"react/jsx-runtime";function bo(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 yo({sub:e}){return e.status==="canceled"?X(ee,{variant:"outline",children:"Canceled"}):e.status==="past_due"?X(ee,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?X(ee,{variant:"warning",children:"Scheduled to cancel"}):X(ee,{variant:"success",children:"Active"}):X(ee,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function md(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 ho({sub:e}){let a=e.current_amount!==e.plan_amount;return Qe("div",{children:[X("div",{className:"af-font-medium af-tabular-nums",children:md(e,e.current_amount)}),a&&Qe("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function xo(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${bo(e.current_period_end)}`:"Ends at period end":e.current_period_end?bo(e.current_period_end):"\u2014"}function wo({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:f,pageSize:d,hasNextPage:p,hasPreviousPage:r,setPage:g,refetch:y}=Wn({refreshKey:e}),m;if(i)m=Qe("div",{children:[X("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(c=>Qe("div",{className:"af-rounded-md af-border af-p-3",children:[Qe("div",{className:"af-flex af-items-center af-justify-between",children:[X(ae,{className:"af-h-4 af-w-40"}),X(ae,{className:"af-h-4 af-w-20"})]}),X(ae,{className:"af-mt-2 af-h-3 af-w-32"}),X(ae,{className:"af-mt-2 af-h-5 af-w-24"})]},c))}),X("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Qe(Be,{children:[X(Fe,{children:Qe(fe,{children:[X(M,{children:"Subscriber"}),X(M,{children:"Plan"}),X(M,{className:"af-text-right",children:"Amount"}),X(M,{children:"Renews"}),X(M,{children:"Status"})]})}),X(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(c=>Qe(fe,{children:[X(U,{children:X(ae,{className:"af-h-4 af-w-44"})}),X(U,{children:X(ae,{className:"af-h-4 af-w-32"})}),X(U,{className:"af-text-right",children:X(ae,{className:"af-ml-auto af-h-4 af-w-24"})}),X(U,{children:X(ae,{className:"af-h-4 af-w-24"})}),X(U,{children:X(ae,{className:"af-h-5 af-w-20"})})]},c))})]})}),X("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)m=X("div",{className:"af-flex af-justify-center af-py-8",children:X(ia,{message:"Couldn't load your subscriptions.",onRetry:()=>y()})});else if(t.length===0&&f===0)m=X(Ca,{icon:X(fd,{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)m=Qe("div",{children:[X(Ca,{children:"No more results."}),X("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Qe(w,{variant:"outline",size:"sm",onClick:()=>g(f-1),children:[X(vo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=f*d+1,l=f*d+t.length;m=Qe("div",{children:[X("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(v=>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:[X("div",{className:"af-truncate af-text-sm af-font-medium",children:v.customer_email||X("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),X("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:v.plan_title||"Untitled plan"})]}),X("div",{className:"af-shrink-0 af-text-right",children:X(ho,{sub:v})})]}),Qe("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[X(yo,{sub:v}),v.is_test&&X(ee,{variant:"outline",children:"Test"}),X("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:xo(v)})]}),X(Aa,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},v.id))}),X("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Qe(Be,{children:[X(Fe,{children:Qe(fe,{children:[X(M,{children:"Subscriber"}),X(M,{children:"Plan"}),X(M,{className:"af-text-right",children:"Amount"}),X(M,{children:"Renews"}),X(M,{children:"Status"})]})}),X(Me,{children:t.map(v=>Qe(fe,{children:[X(U,{className:"af-max-w-[240px]",children:X("div",{className:"af-truncate af-font-medium",children:v.customer_email||X("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),X(U,{className:"af-max-w-[220px]",children:X("div",{className:"af-truncate",children:v.plan_title||X("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),X(U,{className:"af-whitespace-nowrap af-text-right",children:X(ho,{sub:v})}),X(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:xo(v)}),Qe(U,{children:[Qe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[X(yo,{sub:v}),v.is_test&&X(ee,{variant:"outline",children:"Test"})]}),X(Aa,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},v.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:[X("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${c}-${l} of ${n}`}),Qe("div",{className:"af-flex af-items-center af-gap-2",children:[Qe(w,{variant:"outline",size:"sm",onClick:()=>g(f-1),disabled:!r,children:[X(vo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Qe(w,{variant:"outline",size:"sm",onClick:()=>g(f+1),disabled:!p,children:["Next",X(dd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return X(xt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:m})}import*as Mr from"react";import{Fragment as No,jsx as la,jsxs as Kn}from"react/jsx-runtime";function So({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:f,isLoading:d,error:p,refetch:r}=_s({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ts({refreshKey:e}),[y,m]=Mr.useState(!1),[c,l]=Mr.useState(null),v=la("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:p||!d&&!f?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||!f?Kn(No,{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(No,{children:[la(at,{label:"Outstanding",detail:`${f.outstanding.count} open`,children:j(f.outstanding.amount,f.currency)}),la(at,{label:"Overdue",detail:f.overdue.count===0?"Nothing overdue":`${f.overdue.count} overdue`,valueClassName:f.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:j(f.overdue.amount,f.currency)}),la(at,{label:"Paid this month",detail:`${f.paid_this_month.count} paid`,children:j(f.paid_this_month.amount,f.currency)})]})});return Kn(xt,{title:"Invoices",onBackToWebsite:s,hideBackButton:y,className:o,children:[v,!y&&la(Ps,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:c?.id??null,onShowCycles:h=>l(N=>N?.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:m,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 wt from"react";var pd=2e3,Et=()=>({data:null,error:null,isLoading:!0});function As(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=re(),[i,o]=wt.useState(Et),[f,d]=wt.useState(Et),[p,r]=wt.useState(Et),[g,y]=wt.useState(Et),[m,c]=wt.useState(Et),l=H=>Object.fromEntries(H.map(ne=>[ne,Et()])),[v,h]=wt.useState(()=>l(s)),N=wt.useRef(0),E=wt.useRef(0),B=wt.useRef("idle"),u=s.join(","),k=fs()??"",I=JSON.stringify(t),C=`${e}:${u}:${I}:${k}`,[D,A]=wt.useState({api:n,fetchIdentity:C});(D.api!==n||D.fetchIdentity!==C)&&(A({api:n,fetchIdentity:C}),N.current+=1,o(Et),d(Et),r(Et),y(Et),h(l(u?u.split(","):[])));let F=`${e}:${String(a??"")}:${k}`,[b,G]=wt.useState({api:n,conversionsIdentity:F});(b.api!==n||b.conversionsIdentity!==F)&&(G({api:n,conversionsIdentity:F}),E.current+=1,B.current="idle",c(Et));let Q=wt.useCallback(async H=>{let ne=++N.current,W=u?u.split(","):[];o(Et),d(Et),r(Et),y(Et),h(Object.fromEntries(W.map(_=>[_,Et()])));let he=B.current!=="pending"&&(H?.force===!0||B.current==="idle"),qe=(_,x)=>x.then(q=>{ne===N.current&&_({data:q,error:null,isLoading:!1})},q=>{ne===N.current&&_({data:null,error:q instanceof Error?q:new Error("Failed to fetch report"),isLoading:!1})}),rt=n.getAnalyticsStatus(),_e=qe(o,rt),Ve=Symbol("status-timeout"),Xe,xe=await Promise.race([rt.then(_=>_,()=>null),new Promise(_=>{Xe=setTimeout(()=>_(Ve),pd)})]);if(clearTimeout(Xe),ne!==N.current)return;if(xe===Ve&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),xe!==null&&xe!==Ve&&(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(_),y(_),h(Object.fromEntries(W.map(x=>[x,{..._}]))),he&&(c(_),B.current="done"),await _e;return}await Promise.all([xe===Ve?Promise.resolve():_e,qe(d,n.getAnalyticsSummary(e,t)),qe(r,n.getAnalyticsTimeseries(e,t)),qe(y,n.getAnalyticsChannels(e,t)),he?(()=>{B.current="pending";let _=++E.current;return c(Et),n.getAnalyticsConversions(e).then(x=>{_===E.current&&(c({data:x,error:null,isLoading:!1}),B.current="done")},x=>{_===E.current&&(c({data:null,error:x instanceof Error?x:new Error("Failed to fetch report"),isLoading:!1}),B.current="done")})})():Promise.resolve(),...W.map(_=>n.getAnalyticsBreakdown(_,e,t).then(x=>{ne===N.current&&h(q=>({...q,[_]:{data:x,error:null,isLoading:!1}}))},x=>{ne===N.current&&h(q=>({...q,[_]:{data:null,error:x instanceof Error?x:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,u,I,F,k]),z=wt.useCallback(async()=>{let H=N.current;try{let ne=await n.getAnalyticsStatus();if(H!==N.current)return;o({data:ne,error:null,isLoading:!1})}catch(ne){if(H!==N.current)return;o(W=>({data:W.data,error:ne instanceof Error?ne:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ce=wt.useCallback(()=>Q({force:!0}),[Q]);wt.useEffect(()=>{Q()},[Q,a]);let O=i.isLoading||f.isLoading||p.isLoading||g.isLoading||m.isLoading||Object.values(v).some(H=>H.isLoading),te=[p,f,g,m,...Object.values(v)].map(H=>H.data?.status==="ok"?H.data.timezone:void 0).find(H=>H!==void 0);return{status:i,summary:f,timeseries:p,channels:g,conversions:m,breakdowns:v,reportedZone:te,isLoading:O,refetch:ce,refetchStatus:z}}import*as Nt from"react";var Ur=3e4,Vr=3;function Zn(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=re(),[o,f]=Nt.useState(null),[d,p]=Nt.useState(null),[r,g]=Nt.useState(!1),[y,m]=Nt.useState(null),[c,l]=Nt.useState(!1),[v,h]=Nt.useState(!0),[N,E]=Nt.useState(0),B=Nt.useRef(0),u=Nt.useRef(0),k=Nt.useRef(void 0);s!==void 0&&(k.current=s);let I=a?k.current===!0||k.current===void 0&&t:!0,[C,D]=Nt.useState({api:i,identity:n}),A=n!==void 0&&n!==C.identity;(C.api!==i||A)&&(k.current=void 0,D({api:i,identity:n}),u.current+=1,B.current=0,f(null),p(null),g(!1),m(null),l(!1),h(!0),E(0));let F=Nt.useRef(()=>{}),b=Nt.useRef(null),G=Nt.useCallback(async()=>{if(b.current!==null&&b.current===u.current)return;let Q=++u.current;b.current=Q;try{let z=await i.getAnalyticsRealtime();if(Q!==u.current)return;if(z.status==="unreachable"){l(!0),g(!0),h(!1),E(ce=>ce+1);return}B.current=0,l(!1),f(z.data.current_visitors),p(z.as_of),g(!1),m(null),h(!1),E(ce=>ce+1)}catch(z){if(Q!==u.current)return;B.current+=1,h(!1),E(ce=>ce+1),g(!0),B.current>=Vr&&m(z instanceof Error?z:new Error("Realtime unavailable"))}finally{b.current===Q&&(b.current=null)}},[i]);return F.current=()=>void G(),Nt.useEffect(()=>{let Q,z=()=>{Q===void 0&&(Q=setInterval(()=>F.current(),Ur))},ce=()=>{Q!==void 0&&(clearInterval(Q),Q=void 0)},O=()=>{typeof document<"u"&&document.hidden?ce():(F.current(),z())};return I?((typeof document>"u"||!document.hidden)&&(F.current(),z()),document?.addEventListener("visibilitychange",O),()=>{ce(),document?.removeEventListener("visibilitychange",O),u.current+=1}):()=>{document?.removeEventListener("visibilitychange",O)}},[C.api,C.identity,I]),{currentVisitors:o,asOf:d,isStale:r,error:y,isUnreachable:c,isInitialLoad:v,polls:N}}import*as nt from"react";import*as Ro from"react";import{jsx as $r,jsxs as _o}from"react/jsx-runtime";function gd(){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 Hr({value:e,chosen:a,onChange:s}){let t=Us(),n=a===null&&t!==null&&e===t,i=Ro.useMemo(()=>{let o=gd();return o.includes(e)?o:[e,...o]},[e]);return _o("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[$r("span",{className:"af-sr-only",children:"Reporting timezone"}),_o("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:[$r("option",{value:"",children:t?`${t.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),i.map(o=>$r("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 vd=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(),vd))},f=()=>{i!==void 0&&(clearInterval(i),i=void 0)},d=()=>{typeof document<"u"&&document.hidden?f():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",d),()=>{f(),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 bd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ut(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?Ut(o*t):`${o}${n}`}return String(e)}function Ds(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 Co(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 To(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function ko(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 Eo(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 zr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${bd[a-1]} ${s}`}function Po(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function yd(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Io(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=Po(e.to,s);for(let o=Po(e.from,s);o<i;o=yd(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 Ao(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 xd,jsx as cs,jsxs as hd}from"react/jsx-runtime";function Do({what:e="This report",onRetry:a,collecting:s}){return hd("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(Do,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?cs(Do,{what:t,onRetry:n,collecting:i}):cs(xd,{children:o(e.data)})}import{Fragment as wd,jsx as Xt,jsxs as ys}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:f,maxRows:d=9}){let[p,r]=hs.useState(!1);if(e.length===0)return Xt(Qn,{what:i});let g=e.reduce((c,l)=>Math.max(c,Number(l[s]??0)),0)||1,y=Math.max(0,e.length-d),m=p?e:e.slice(0,d);return ys(wd,{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:m.map((c,l)=>{let v=Number(c[s]??0),h=c[a]??null,N=Qs(h),E=n?c[n]:null,B=h!==null&&(f?f(h,E):!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,v/g*100)}%`}}),h!==null&&o&&B?Xt("button",{type:"button",onClick:()=>o(h,E),title:`Filter by ${N}`,"aria-label":`Filter by ${N}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:N}):Xt("span",{className:"af-relative af-break-words af-text-foreground",children:N}),E?Xt("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:E}):null]}),Xt("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Ut(v)})]},`${N}-${E??""}-${l}`)})})]}),y>0?Xt("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:p?"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(m=>m.id===n)??a[0],f=hs.useId(),d=m=>`${f}-tab-${m}`,p=m=>`${f}-panel-${m}`,r=hs.useRef(null),g=(m,c)=>{m.preventDefault();let l=(c+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:m=>{let c=a.findIndex(l=>l.id===n);m.key==="ArrowRight"&&g(m,c+1),m.key==="ArrowLeft"&&g(m,c-1),m.key==="Home"&&g(m,0),m.key==="End"&&g(m,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(m=>Xt("button",{id:d(m.id),role:"tab",type:"button","aria-selected":m.id===n,"aria-controls":p(m.id),tabIndex:m.id===n?0:-1,onClick:()=>i(m.id),className:m.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:m.label},m.id))}),t]}),o?Xt("div",{id:p(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 Ls=3,Os=100;import{jsx as ut,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"},Nd=Object.keys(en);function Lo(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 jr(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 Sd(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 Oo(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 _d(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Bo(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=Sd(e.byDimension,s);for(let[i,o]of Object.entries(t)){let f=e.foldsByLabel.get(i)??new Set;for(let d of o)f.add(d);e.foldsByLabel.set(i,f)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Fo(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:[ut("span",{className:"af-text-foreground",children:Lo(n)}),ut("button",{type:"button","aria-label":`Remove filter ${Lo(n)}`,onClick:()=>s(a.filter((o,f)=>f!==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"}`)),ut(Rd,{...e,disabled:t}),a.length>0?ut("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 Rd({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,f]=ea.useState(!1),d=ea.useRef(null),[p,r]=ea.useState(null);ea.useEffect(()=>{r(d.current?.closest(".aifeatures-admin")??null)},[]);let[g,y]=ea.useState(null),[m,c]=ea.useState("is"),[l,v]=ea.useState(""),[h,N]=ea.useState([]);ea.useEffect(()=>{o||(y(null),c("is"),v(""),N([]))},[o]);let E=ea.useRef(t);E.current!==t&&(E.current=t,o&&f(!1),g!==null&&y(null),h.length>0&&N([]),l!==""&&v(""),m!=="is"&&c("is"));let B=A=>{let F=_d(A);y(F.dimension),N(F.picked),v(F.search),c(F.operator)},k=(g?s[g]??[]:[]).filter(A=>A.toLowerCase().includes(l.trim().toLowerCase())),I=g===null||h.length===0?null:jr(e,{dimension:g,operator:m,values:i?i(g,h):h}),C=I!==null&&I!==e,D=()=>{let A=I;!A||A===e||(a(A),f(!1))};return Ha(us.Root,{open:o,onOpenChange:f,children:[ut(us.Trigger,{asChild:!0,children:ut("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"})}),ut(us.Portal,{container:p,children:ut(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:[ut("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),ut("div",{className:"af-max-h-96 af-overflow-y-auto",children:Nd.filter(A=>s[A]!==void 0).map(A=>{let F=s[A]?.length??0,b=!e.some(G=>G.dimension===A)&&e.length>=3;return Ha("button",{type:"button",onClick:()=>B(A),disabled:F===0||b,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:[ut("span",{children:en[A]}),ut("span",{className:"af-text-muted-foreground",children:F===0?"no data":b?"no room":F})]},A)})})]}):Ha("div",{children:[Ha("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[ut("button",{type:"button",onClick:()=>B(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),ut("span",{className:"af-text-xs af-font-medium af-text-foreground",children:en[g]}),Ha("select",{"aria-label":"Operator",value:m,onChange:A=>c(A.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:[ut("option",{value:"is",children:"is"}),ut("option",{value:"is_not",children:"is not"})]})]}),ut("input",{type:"text",value:l,onChange:A=>v(A.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"}),ut("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(A=>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:[ut("input",{type:"checkbox",checked:h.includes(A),disabled:!h.includes(A)&&h.length>=100,onChange:F=>N(b=>F.target.checked?[...b,A]:b.filter(G=>G!==A))}),ut("span",{className:"af-break-all",children:Qs(A)})]},A))}),ut("button",{type:"button",onClick:D,disabled:!C,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:h.length<=1?"Apply filter":h.length>=100?`Apply filter (${h.length} values \u2014 the maximum)`:`Apply filter (${h.length} values)`})]})})})]})}import{Fragment as Td,jsx as Vt,jsxs as Xn}from"react/jsx-runtime";var Pd=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Ut,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Ut,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Ut,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:Ds,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ys,chart:"visit_duration_seconds"}];function Cd({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 Vt("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 Mo({summary:e,selected:a,onSelect:s}){return Vt("div",{className:"af-@container",children:Vt("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Pd.map(t=>{let n=t.chart===a,i=s!==void 0,o=Xn(Td,{children:[Vt("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:[Vt("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?Vt(Cd,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?Vt("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):Vt("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:[Vt("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Vt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return Vt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?Eo(a):"freshness unknown",f=i?" across the whole site, not the current filter,":"",d=s?`${e} current visitors${f} ${o} (not updating)`:`${e} current visitors${f} ${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:[Vt("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"}),Vt("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Vt("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),Vt("span",{className:"af-sr-only",children:d})]})}import*as Vo from"react";import{Fragment as Uo,jsx as $t,jsxs as Bs}from"react/jsx-runtime";function er({rows:e,denominator:a,windowPrecedesCollection:s=!1,coverageUnknown:t=!1,emptyCopy:n="No conversions in this period",maxRows:i=9}){let[o,f]=Vo.useState(!1),d=e.filter(m=>!m.implicit||m.visitors>0||m.events>0),p=s?$t("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?$t("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null;if(d.length===0)return Bs(Uo,{children:[$t(Qn,{what:n}),p]});let r=d.slice(0,i),g=o?e:r,y=Math.max(0,e.length-r.length);return Bs(Uo,{children:[Bs("table",{className:"af-w-full af-text-sm",children:[$t("thead",{children:Bs("tr",{className:"af-text-xs af-text-muted-foreground",children:[$t("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),$t("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),$t("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),$t("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),$t("tbody",{children:g.map((m,c)=>Bs("tr",{className:"af-border-t af-border-border",children:[$t("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:m.goal}),$t("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ut(m.visitors)}),$t("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Ut(m.events)}),$t("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:m.conversion_rate===null?$t("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Ds(m.conversion_rate)})]},`${m.goal}-${c}`))})]}),y>0?$t("button",{type:"button",onClick:()=>f(m=>!m),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:o?"Show fewer":`Show all ${e.length} goals`}):null,Bs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Ut(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),p]})}import{Area as kd,AreaChart as Ed,CartesianGrid as Id,ResponsiveContainer as Ad,Tooltip as Dd,XAxis as Ld,YAxis as Od}from"recharts";import{jsx as Ht,jsxs as tn}from"react/jsx-runtime";var tr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Kr={visitors:Ut,visits:Ut,pageviews:Ut,views_per_visit:e=>e.toFixed(2),bounce_rate:Ds,visit_duration_seconds:Ys},Bd=31,Fd=new Set(["visitors","visits","pageviews"]),Md={...Kr,bounce_rate:To,visit_duration_seconds:Co},Wr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Ud=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Vd=[.01,.02,.05,.1,.2,.25,.5,1],$d=[.25,.5,1,2,5,10,25,50],Hd={visitors:Wr,visits:Wr,pageviews:Wr,views_per_visit:$d,bounce_rate:Vd,visit_duration_seconds:Ud};function zd({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:tr[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:Ao(String(s))}),Ht("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Kr[t](Number(n[t]??0))})]})]})}function ar({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=Io(a,e,t),o=Kr[s],f=Md[s],d=ko(i.reduce((r,g)=>Math.max(r,Number(g[s]??0)),0),Hd[s]),p=`${tr[s]} by day: ${i.map(r=>`${zr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return tn("figure",{"aria-label":`${tr[s]} over time`,className:"af-m-0",children:[Ht(Ad,{width:"100%",height:n,children:tn(Ed,{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(Id,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Ht(Ld,{dataKey:"date",tickFormatter:zr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Ht(Od,{allowDecimals:!Fd.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...d?{ticks:d,domain:[0,d[d.length-1]]}:{},tickFormatter:r=>f(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Ht(Dd,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Ht(zd,{metric:s})}),Ht(kd,{type:"linear",dataKey:s,name:tr[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=Bd?{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:p})]})}import{Fragment as Zr,jsx as ve,jsxs as Ot}from"react/jsx-runtime";var qd="2026-08-13",jd=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Gd=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Wd({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[f,d]=nt.useState(30),[p,r]=nt.useState(()=>or()),g=e!==void 0&&a!==void 0,[y,m]=nt.useState(e??[]),{api:c}=re(),[l,v]=nt.useState(c);l!==c&&(v(c),!g&&y.length>0&&m([]));let h=g?e:y,N=nt.useCallback(x=>{a&&a(x),g||m(x)},[a,g]),E=nt.useCallback((x,q,pe)=>{let be=Array.isArray(q)?q:[q];if(be.length===0)return null;let Te=jr(h,{dimension:x,operator:"is",values:be});if(pe&&(!pe.value||(Te=Oo(Te,{dimension:pe.dimension,operator:"is",values:[pe.value]}),!Te.find(Ke=>Ke.dimension===pe.dimension&&Ke.operator!=="is_not")?.values.includes(pe.value))))return null;let je=Te.find(Oe=>Oe.dimension===x&&Oe.operator!=="is_not");return be.every(Oe=>je?.values.includes(Oe))?JSON.stringify(Te)===JSON.stringify(h)?null:Te:null},[h]),B=nt.useCallback((x,q,pe)=>E(x,q,pe)!==null,[E]),u=nt.useCallback((x,q,pe)=>{let be=E(x,q,pe);be&&N(be)},[E,N]),[k,I]=nt.useState("visitors"),C=As(f,{refreshKey:s,breakdowns:Gd,filters:h}),D=C.status.data,A=C.reportedZone??D?.timezone,F=A??p??Us()??"UTC",{notCollecting:b,awaitingFirstVisit:G,firstVisitTooRecent:Q,holdingForFirstData:z}=Jn(D,{published:i}),ce=i===!1,O=Zn({collecting:G||b?!1:D?.collecting,statusFailed:C.status.error!=null,identity:D?.analytics_id}),te=nt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),H=nt.useMemo(()=>{let x=C.breakdowns.sources?.data,q={};if(!x||x.status!=="ok")return q;for(let pe of x.data){let be=pe.source,Te=pe.sources;typeof be=="string"&&Array.isArray(Te)&&Te.length>0&&(q[be]=Te)}return q},[C.breakdowns.sources?.data]),ne=nt.useMemo(()=>{let x=(be,Te)=>{let je=C.breakdowns[be]?.data;return!je||je.status!=="ok"?[]:[...new Set(je.data.map(Oe=>Oe[Te]).filter(Oe=>typeof Oe=="string"&&Oe!==""))]};return{channel:C.channels.data?.status==="ok"?[...new Set(C.channels.data.data.map(be=>be.channel))]:[],source:x("sources","source"),campaign:x("utm/campaign","campaign"),page:x("pages","pathname"),entry_page:x("entry-pages","pathname"),exit_page:x("exit-pages","pathname"),country:x("countries","country"),browser:x("browsers","browser"),os:x("operating-systems","os"),device:x("devices","device")}},[C.breakdowns,C.channels.data]),[W,he]=nt.useState({}),qe=JSON.stringify(ne),[rt,_e]=nt.useState(new Map),Ve=JSON.stringify(H);nt.useEffect(()=>{let{suggestions:x,folds:q}=Bo(te.current,{api:c,period:f},JSON.parse(qe),JSON.parse(Ve));he(x),_e(q)},[qe,Ve,c,f]);let Xe=nt.useCallback((x,q)=>x!=="source"?q:[...new Set(q.flatMap(pe=>{let be=[...rt.get(pe)??[],...H[pe]??[]];return be.length>0?be:[pe]}))],[rt,H]),xe=nt.useMemo(()=>{let x=C.conversions.error;return x instanceof Gt&&x.details?.code==="goals_exceed_report_budget"?x.message:null},[C.conversions.error]),yt=nt.useMemo(()=>{let x=[C.summary,C.timeseries,C.channels,...Object.values(C.breakdowns)];for(let q of x){let pe=q?.error;if(pe instanceof Gt&&pe.details?.code==="filter_unsupported")return pe.message}return null},[C.summary,C.timeseries,C.channels,C.breakdowns]),_=(x,q,pe,be,Te,je,Oe,Ke,dt)=>()=>{let ie=C.breakdowns[x];return ve(Ya,{sourced:ie?.data??null,error:ie?.error,isLoading:ie?.isLoading,what:q,collecting:D?.collecting,onRetry:C.refetch,children:Ae=>{let et=Ct=>Ke?Xe(Ke,[Ct]):Ct;return ve(qr,{rows:Ae,dimension:pe,metric:be,metricLabel:Te,secondary:je,emptyCopy:h.length>0?"No data for this filter":Oe,canFilter:Ke?(Ct,It)=>B(Ke,et(Ct),dt?{dimension:dt,value:It}:void 0):()=>!1,onFilter:Ke?(Ct,It)=>u(Ke,et(Ct),dt?{dimension:dt,value:It}:void 0):void 0})}})};if(Yn({status:D,holdingForFirstData:z,refetchStatus:C.refetchStatus,refetch:C.refetch}),b){let x=!!o&&String(o).slice(0,10)<qd;return ve(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:Ot("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[ve("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),ve("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ce?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":x?"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 G?ve(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:Ot("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[ve("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),ve("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."})]})}):Q?Ot(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:[ve("div",{className:"af-mb-3 af-flex af-justify-end",children:ve(Hr,{value:F,chosen:p,onChange:x=>{lr(x),r(x)}})}),Ot("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[ve("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Ot("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",D?.timezone?` ${D.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),ve("div",{className:"af-mt-4 af-flex af-justify-center",children:ve(Gr,{currentVisitors:O.currentVisitors,asOf:O.asOf,isStale:O.isStale,isUnreachable:O.isUnreachable||O.error!==null,isInitialLoad:O.isInitialLoad})})]})]}):ve(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:Ot("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Ot("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[ve("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:jd.map(x=>ve("button",{type:"button","aria-pressed":x.value===f,onClick:()=>d(x.value),className:x.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:x.label},x.value))}),ve(Hr,{value:F,chosen:p,onChange:x=>{lr(x),r(x)}}),ve(Gr,{currentVisitors:O.currentVisitors,asOf:O.asOf,isStale:O.isStale,isUnreachable:O.isUnreachable||O.error!==null,isInitialLoad:O.isInitialLoad,scopeIsSiteWide:h.length>0})]}),ve(Fo,{filters:h,onChange:N,suggestions:W,expandValues:Xe,resetKey:c}),yt?Ot("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[ve("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),ve("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:yt}),ve("button",{type:"button",onClick:()=>N([]),className:"af-mt-4 af-rounded-md af-border af-border-border af-px-3 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Clear filters"})]}):null,!yt&&D?.timezone_defaulted?ve("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,yt?null:Ot(Zr,{children:[ve(Ya,{sourced:C.summary.data,error:C.summary.error,isLoading:C.summary.isLoading,what:"The traffic summary",collecting:D?.collecting,onRetry:C.refetch,children:x=>Ot(Zr,{children:[ve(Mo,{summary:x,selected:k,onSelect:I}),x.previous_unavailable?Ot("p",{className:"af-text-xs af-text-muted-foreground",children:[x.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]})}),ve("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:ve(Ya,{sourced:C.timeseries.data,error:C.timeseries.error,isLoading:C.timeseries.isLoading,what:"The visitors chart",collecting:D?.collecting,onRetry:C.refetch,children:x=>{let q=C.timeseries.data?.status==="ok"?C.timeseries.data.window:{from:"",to:""};return ve(ar,{rows:x,window:q,metric:k,timeZone:A??"UTC"})}})}),Ot("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[ve(Xs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>ve(Ya,{sourced:C.channels.data,error:C.channels.error,isLoading:C.channels.isLoading,what:"Channels",collecting:D?.collecting,onRetry:C.refetch,children:x=>ve(qr,{rows:x,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:h.length>0?"No data for this filter":"No data for this period",canFilter:q=>B("channel",q),onFilter:q=>u("channel",q)})})},{id:"sources",label:"Sources",render:_("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:_("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),ve(Xs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:_("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:_("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:_("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),ve(Xs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:_("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:_("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:_("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),ve(Xs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:_("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:_("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:_("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Ot("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[ve("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:ve("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Ot("div",{className:"af-px-3 af-py-2",children:[h.length>0?Ot("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",h.length===1?"filter":"filters"," above."]}):null,xe!==null?Ot("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:[ve("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),ve("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:xe})]}):ve(Ya,{sourced:C.conversions.data,error:C.conversions.error,isLoading:C.conversions.isLoading,what:"Conversions",collecting:D?.collecting,onRetry:C.refetch,children:x=>{let q=C.conversions.data?.status==="ok"?C.conversions.data:null;return ve(Zr,{children:ve(er,{rows:x,denominator:q?.denominator??0,windowPrecedesCollection:q?.window_precedes_collection??!1,coverageUnknown:q?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}import{Phone as Kd,Mail as Zd,ShoppingBag as Jd,ExternalLink as Yd,MessageCircle as Qd}from"lucide-react";import{jsx as $o,jsxs as ef}from"react/jsx-runtime";var Xd={calls:{icon:Kd,line:"This site is set up to get you phone calls."},enquiries:{icon:Zd,line:"This site is set up to get you enquiries."},sales:{icon:Jd,line:"This site is set up to sell."},whatsapp:{icon:Qd,line:"This site is set up to get you WhatsApp messages."},outbound:{icon:Yd,line:"This site is set up to send visitors on to book with you."}};function Ho({goal:e}){if(e==="unknown")return null;let{icon:a,line:s}=Xd[e];return ef("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[$o(a,{className:"af-h-4 af-w-4 af-shrink-0"}),$o("span",{children:s})]})}import{Fragment as tf,jsx as ds,jsxs as sr}from"react/jsx-runtime";function zo({refreshKey:e,onViewAll:a}){let s=As(7,{refreshKey:e,breakdowns:[]}),t=s.status.data??void 0,{nothingToReport:n,notCollecting:i,holdingForFirstData:o}=Jn(t);return Yn({status:t,holdingForFirstData:o,refetchStatus:s.refetchStatus,refetch:s.refetch}),sr("section",{className:"af-rounded-md af-border af-p-3",children:[sr("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"})]}),n?ds("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:i?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):sr(tf,{children:[ds(Ya,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:t?.collecting,onRetry:s.refetch,children:f=>{let d=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return ds(ar,{rows:f,window:d?.window??{from:"",to:""},metric:"visitors",timeZone:d?.timezone,height:140})}}),sr("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:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:t?.collecting,onRetry:s.refetch,children:f=>{let d=s.conversions.data?.status==="ok"?s.conversions.data:null;return ds(er,{rows:f,denominator:d?.denominator??0,windowPrecedesCollection:d?.window_precedes_collection??!1,coverageUnknown:d?.first_seen_unavailable??!1})}})]})]})]})}import{jsx as Ia,jsxs as an}from"react/jsx-runtime";var Jr=5;function Yr({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:[Ia("h3",{className:"af-text-sm af-font-medium",children:e}),s&&Ia(w,{type:"button",variant:"ghost",size:"sm",onClick:s,children:a})]})}function af({refreshKey:e,onBackToWebsite:a,goal:s="unknown",onOpenSurface:t,needsPaidPlan:n,onUpgradePlan:i,onConnectStripe:o}){let f=Es({refreshKey:e}),d=(f.summary?.products.count??0)>0||(f.summary?.commerce?.storefront_orders??!1),p=d||(f.summary?.commerce?.invoicing??!1);return Ia(xt,{title:"Dashboard",onBackToWebsite:a,children:an("div",{className:"af-flex af-flex-col af-gap-4",children:[Ia(Ho,{goal:s}),Ia(zo,{refreshKey:e,onViewAll:t&&(()=>t("analytics"))}),an("section",{className:"af-rounded-md af-border af-p-3",children:[Ia(Yr,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:t&&(()=>t("leads"))}),Ia(Gn,{refreshKey:e,maxRows:Jr,onViewAll:t&&(()=>t("leads"))})]}),d&&an("section",{className:"af-rounded-md af-border af-p-3",children:[Ia(Yr,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:t&&(()=>t("orders"))}),Ia(ns,{refreshKey:e,maxRows:Jr,onViewAll:t&&(()=>t("orders"))})]}),p&&an("section",{className:"af-rounded-md af-border af-p-3",children:[Ia(Yr,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:t&&(()=>t("invoices"))}),Ia(is,{refreshKey:e,maxRows:Jr,onViewAll:t&&(()=>t("invoices")),needsPaidPlan:n,onUpgradePlan:i,onConnectStripe:o})]})]})})}export{Gt as AifeaturesApiError,Wo as AifeaturesProvider,Wd as AnalyticsView,In as CustomerDetail,Dn as CustomersList,af as DashboardView,bn as FormSettings,mn as FormSubmissions,bi as FormsDashboard,ln as FormsList,kr as InvoiceDetail,Ws as InvoiceLabelBadge,is as InvoicesList,So as InvoicesView,Gn as LeadsView,Ls as MAX_ANALYTICS_FILTERS,Os as MAX_ANALYTICS_FILTER_VALUES,Cn as OrderDetail,gs as OrderStatusBadge,ns as OrdersList,eo as OrdersView,Yi as PaymentsDashboard,Mn as PaymentsSetup,Nn as ProductSettings,xn as ProductsList,lo as ProductsView,ws as PromosPanel,Vr as REALTIME_FAILURES_BEFORE_ERROR,Ur as REALTIME_POLL_MS,Er as RetainerStatusBadge,Ps as RetainersPanel,fn as SubmissionDetail,wo as SubscriptionsView,wn as VariantsEditor,xt as ViewShell,gn as WebhookDeliveries,vn as WebhookSettings,Ka as chargedTotal,ur as createApiClient,j as formatPrice,pa as isZeroDecimalCurrency,mt as toMajorUnits,Wt as toMinorUnits,re as useAifeatures,re as useAifeaturesContext,As as useAnalytics,Es as useBusinessSummary,En as useCustomers,pn as useEventDestinations,xs as useForms,_s as useInvoices,Sn as useOrders,as as usePaymentsStatus,qn as usePeople,jn as usePerson,Cs as useProducts,Zn as useRealtimeVisitors,Ts as useRetainers,dn as useSubmissions,Wn as useSubscriptions};
|
|
2
|
+
import*as ss from"react";var pr="aifeatures:analytics:timezone",gr;function zs(){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 as(){return vr()??zs()}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=as();return t&&s.set("timezone",t),a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var Bt=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 m;try{m=await o.json()}catch{}throw new Bt(yr(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 Bt(yr(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 Bt(yr(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=as();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=as();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)}),m=as();return m&&o.set("timezone",m),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=as();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 qs,jsxs as ml}from"react/jsx-runtime";var vi=ss.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=ss.useMemo(()=>dl(e),[e]),o=ss.useMemo(()=>hr(e,a),[e,a]),m=ss.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?qs("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:[qs("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),qs("p",{className:"af-text-sm af-text-destructive",children:i})]})}):qs(vi.Provider,{value:m,children:qs("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function ne(){let e=ss.useContext(vi);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as rs from"react";import{ArrowLeft as pc,Settings as gc,Inbox as vc}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 Z(...e){return vl(pl(e))}import{jsx as xr}from"react/jsx-runtime";var mn=xa.Root,js=fn.forwardRef(({className:e,...a},s)=>xr(xa.List,{ref:s,className:Z("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}));js.displayName=xa.List.displayName;var wa=fn.forwardRef(({className:e,...a},s)=>xr(xa.Trigger,{ref:s,className:Z("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:Z("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:Z(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:Z("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:Z("[&_tr]:af-border-b",e),...a}));Fe.displayName="TableHeader";var Me=Wa.forwardRef(({className:e,...a},s)=>Ga("tbody",{ref:s,className:Z("[&_tr:last-child]:af-border-0",e),...a}));Me.displayName="TableBody";var wl=Wa.forwardRef(({className:e,...a},s)=>Ga("tfoot",{ref:s,className:Z("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:Z("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));pe.displayName="TableRow";var M=Wa.forwardRef(({className:e,...a},s)=>Ga("th",{ref:s,className:Z("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}));M.displayName="TableHead";var U=Wa.forwardRef(({className:e,...a},s)=>Ga("td",{ref:s,className:Z("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:Z("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}=ne(),[a,s]=Sa.useState([]),[t,n]=Sa.useState(!0),[i,o]=Sa.useState(null),m=Sa.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]);Sa.useEffect(()=>{m()},[m]);let d=Sa.useCallback(async g=>{let b=await e.createForm(g);return s(v=>[...v,b]),b},[e]),f=Sa.useCallback(async(g,b)=>{let v=await e.updateForm(g,b);return s(c=>c.map(l=>l.id===g?v:l)),v},[e]),r=Sa.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 It,jsxs as Ka}from"react/jsx-runtime";function pn({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=Rs();return t?It("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:It("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?It("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:[It(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.",It("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):It("div",{className:a,children:Ka(Be,{children:[It(Fe,{children:Ka(pe,{children:[It(M,{children:"Name"}),It(M,{children:"Endpoint"}),It(M,{className:"af-text-right",children:"Actions"})]})}),It(Me,{children:s.map(i=>Ka(pe,{children:[It(U,{className:"af-font-medium",children:i.name}),It(U,{children:It("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","")})}),It(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:[It(yi,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ka(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[It(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:Z(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 Gs({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 Ws from"react";import{ChevronLeft as zl,ChevronRight as ql,Eye as jl,Inbox as Gl,Paperclip as Wl}from"lucide-react";import*as ns from"react";import*as we from"@radix-ui/react-select";import{Check as Al,ChevronDown as hi,ChevronUp as El}from"lucide-react";import{jsx as Ft,jsxs as Nr}from"react/jsx-runtime";var da=we.Root;var fa=we.Value,na=ns.forwardRef(({className:e,children:a,...s},t)=>Nr(we.Trigger,{ref:t,className:Z("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,Ft(we.Icon,{asChild:!0,children:Ft(hi,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));na.displayName=we.Trigger.displayName;var xi=ns.forwardRef(({className:e,...a},s)=>Ft(we.ScrollUpButton,{ref:s,className:Z("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Ft(El,{className:"af-h-4 af-w-4"})}));xi.displayName=we.ScrollUpButton.displayName;var wi=ns.forwardRef(({className:e,...a},s)=>Ft(we.ScrollDownButton,{ref:s,className:Z("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Ft(hi,{className:"af-h-4 af-w-4"})}));wi.displayName=we.ScrollDownButton.displayName;var ra=ns.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>Ft(we.Portal,{children:Nr(we.Content,{ref:n,className:Z("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:[Ft(xi,{}),Ft(we.Viewport,{className:Z("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}),Ft(wi,{})]})}));ra.displayName=we.Content.displayName;var Il=ns.forwardRef(({className:e,...a},s)=>Ft(we.Label,{ref:s,className:Z("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));Il.displayName=we.Label.displayName;var Ke=ns.forwardRef(({className:e,children:a,...s},t)=>Nr(we.Item,{ref:t,className:Z("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:[Ft("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:Ft(we.ItemIndicator,{children:Ft(Al,{className:"af-h-4 af-w-4"})})}),Ft(we.ItemText,{children:a})]}));Ke.displayName=we.Item.displayName;var Dl=ns.forwardRef(({className:e,...a},s)=>Ft(we.Separator,{ref:s,className:Z("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}=ne(),[t,n]=ma.useState([]),[i,o]=ma.useState(0),[m,d]=ma.useState(!0),[f,r]=ma.useState(null),[g,b]=ma.useState(0),[v,c]=ma.useState(a),l=ma.useCallback(async()=>{if(e)try{d(!0),r(null);let x={limit:v,offset:g*v},I=await s.getSubmissions(e,x);n(I.submissions),o(I.total)}catch(x){r(x instanceof Error?x:new Error("Failed to fetch submissions"))}finally{d(!1)}},[s,e,g,v]);ma.useEffect(()=>{l()},[l]);let p=ma.useCallback(async x=>{await s.deleteSubmission(x),n(I=>I.filter(O=>O.id!==x)),o(I=>I-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=>{c(x),b(0)},refetch:l,deleteSubmission:p}}import*as Si from"react";import{ArrowLeft as Ll,Download as Ol,Globe as Bl,Clock as Fl,FileText as Ml,Loader2 as Ul,Monitor as $l,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}=ne(),[t,n]=Si.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 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:[m.map(([d,f])=>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:d.replace(/_/g," ")}),ct("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof f=="string"&&f.includes(`
|
|
3
|
+
`)?ct("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&&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((d,f)=>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:d.name}),ut("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Hl(d.size),")"]})]}),ut(w,{variant:"ghost",size:"sm",onClick:()=>o(d),disabled:t===i(d),children:[t===i(d)?ct(Ul,{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(d)?"Downloading...":"Download"]})]},f))})]}),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($l,{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 Te,jsxs as _t}from"react/jsx-runtime";function Kl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Zl(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 Jl(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 hn({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}=bn({formId:e}),[v,c]=Ws.useState("list"),[l,p]=Ws.useState(null);Ws.useEffect(()=>{if(s&&t.length>0){let u=t.find(N=>N.id===s);u&&(p(u),c("detail"))}},[s,t]);let h=u=>{p(u),c("detail")},x=()=>{c("list"),p(null)};if(v==="detail"&&l)return Te("div",{className:a,children:Te(yn,{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:_t("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&m===0)return _t("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Te(Gl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),_t("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 I=m*d+1,O=Math.min((m+1)*d,n);return _t("div",{className:a,children:[_t(Be,{children:[Te(Fe,{children:_t(pe,{children:[Te(M,{children:"Email"}),Te(M,{children:"Preview"}),Te(M,{children:"Date"}),Te(M,{className:"af-text-right",children:"Actions"})]})}),Te(Me,{children:t.map(u=>{let N=Zl(u.data),T=Jl(u.data);return _t(pe,{children:[_t(U,{className:"af-font-medium",children:[_t("div",{className:"af-flex af-items-center af-gap-2",children:[N||Te("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),u.attachments.length>0&&_t("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${u.attachments.length} attachment(s)`,children:[Te(Wl,{className:"af-h-3 af-w-3"}),Te("span",{className:"af-text-xs",children:u.attachments.length})]})]}),Te(Gs,{deliveries:u.email_deliveries,label:"Notification email needs attention"})]}),Te(U,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:T||Te("span",{className:"af-italic",children:"No preview available"})}),Te(U,{className:"af-text-muted-foreground",children:Kl(u.metadata.submitted_at)}),Te(U,{className:"af-text-right",children:Te(w,{variant:"ghost",size:"icon",onClick:()=>h(u),title:"View details",children:Te(jl,{className:"af-h-4 af-w-4"})})})]},u.id)})})]}),_t("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[_t("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[_t("span",{children:["Showing ",I,"-",O," of ",n]}),_t(da,{value:String(d),onValueChange:u=>b(Number(u)),children:[Te(na,{className:"af-w-[70px] af-h-8",children:Te(fa,{})}),_t(ra,{children:[Te(Ke,{value:"10",children:"10"}),Te(Ke,{value:"25",children:"25"}),Te(Ke,{value:"50",children:"50"}),Te(Ke,{value:"100",children:"100"})]})]}),Te("span",{children:"per page"})]}),_t("div",{className:"af-flex af-items-center af-gap-2",children:[_t(w,{variant:"outline",size:"sm",onClick:()=>g(m-1),disabled:!r,children:[Te(zl,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),_t(w,{variant:"outline",size:"sm",onClick:()=>g(m+1),disabled:!f,children:["Next",Te(ql,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as oa from"react";import{Plus as uc,X as dc,Loader2 as fc,Check as mc}from"lucide-react";import*as _i from"react";import{jsx as Yl}from"react/jsx-runtime";var ge=_i.forwardRef(({className:e,type:a,...s},t)=>Yl("input",{type:a,className:Z("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 Ql}from"class-variance-authority";import{jsx as ec}from"react/jsx-runtime";var Xl=Ql("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)=>ec("label",{ref:s,className:Z(Xl(),e),...a}));ve.displayName="Label";import*as ga from"react";import{Plus as nc,Loader2 as _r,Copy as rc,Check as ic,Trash2 as oc,RefreshCw as lc,AlertTriangle as cc}from"lucide-react";import*as Ks from"react";import*as xt from"@radix-ui/react-dialog";import{X as tc}from"lucide-react";import{jsx as Za,jsxs as Sr}from"react/jsx-runtime";var Ba=xt.Root;var ac=xt.Portal;var Pi=Ks.forwardRef(({className:e,...a},s)=>Za(xt.Overlay,{ref:s,className:Z("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));Pi.displayName=xt.Overlay.displayName;var _a=Ks.forwardRef(({className:e,children:a,...s},t)=>Za(ac,{children:Sr("div",{className:"aifeatures-admin",children:[Za(Pi,{}),Sr(xt.Content,{ref:t,className:Z("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(xt.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(tc,{className:"af-h-4 af-w-4"}),Za("span",{className:"af-sr-only",children:"Close"})]})]})]})}));_a.displayName=xt.Content.displayName;var Ra=({className:e,...a})=>Za("div",{className:Z("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:Z("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(xt.Title,{ref:s,className:Z("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));Ca.displayName=xt.Title.displayName;var Ta=Ks.forwardRef(({className:e,...a},s)=>Za(xt.Description,{ref:s,className:Z("af-text-sm af-text-muted-foreground",e),...a}));Ta.displayName=xt.Description.displayName;import*as ia from"react";function xn(){let{api:e}=ne(),[a,s]=ia.useState([]),[t,n]=ia.useState(!0),[i,o]=ia.useState(null),m=ia.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]);ia.useEffect(()=>{m()},[m]);let d=ia.useCallback(async v=>{let c=await e.createEventDestination(v);return s(l=>[c,...l]),c},[e]),f=ia.useCallback(async(v,c)=>{let l=await e.updateEventDestination(v,c);return s(p=>p.map(h=>h.id===v?l:h)),l},[e]),r=ia.useCallback(async v=>{await e.deleteEventDestination(v),s(c=>c.filter(l=>l.id!==v))},[e]),g=ia.useCallback(async v=>{let c=await e.rotateEventDestinationSecret(v);return s(l=>l.map(p=>p.id===v?c:p)),c},[e]),b=ia.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 Ja from"react";import{Loader2 as Ci,RotateCw as sc}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}=ne(),[n,i]=Ja.useState([]),[o,m]=Ja.useState(!0),[d,f]=Ja.useState(null),[r,g]=Ja.useState(null),b=Ja.useCallback(async()=>{try{m(!0),f(null),i(await t.getEventDeliveries(e,a))}catch(c){f(c instanceof Error?c.message:"Failed to load deliveries")}finally{m(!1)}},[t,e,a]);Ja.useEffect(()=>{b()},[b]);let v=async c=>{try{g(c.id),f(null);let l=await t.retryEventDelivery(e,c.id);i(p=>p.map(h=>h.id===c.id?l:h))}catch(l){f(l instanceof Error?l.message:"Retry failed")}finally{g(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..."]}):d?pa("div",{className:"af-text-sm af-text-destructive af-py-2",children:d}):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:()=>v(c),children:r===c.id?pa(Ci,{className:"af-h-4 af-w-4 af-animate-spin"}):pa(sc,{className:"af-h-4 af-w-4"})})]},c.id)})})})}import{jsx as ke,jsxs as mt}from"react/jsx-runtime";function Nn({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}=xn(),[b,v]=ga.useState(""),[c,l]=ga.useState(!1),[p,h]=ga.useState(null),[x,I]=ga.useState(null),[O,u]=ga.useState(null),[N,T]=ga.useState(!1),[L,S]=ga.useState(null),[k,F]=ga.useState(null),[y,G]=ga.useState(null),X=ga.useMemo(()=>n.filter(W=>W.form_id===e),[n,e]),H=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{F(W.id),h(null),await r(W.id),T(!1),u(await g(W.id))}catch(he){h(he instanceof Error?he.message:"Failed to rotate secret")}finally{F(null)}},j=async W=>{try{F(W.id),h(null),await d(W.id,{status:"active"})}catch(he){h(he instanceof Error?he.message:"Failed to re-enable")}finally{F(null)}},K=async()=>{if(L)try{F(L.id),await f(L.id),S(null)}catch(W){h(W instanceof Error?W.message:"Failed to delete")}finally{F(null)}},z=async W=>{if(x===W.id){I(null),u(null);return}try{F(W.id),h(null),T(!1),I(W.id),u(await g(W.id))}catch(he){I(null),h(he instanceof Error?he.message:"Failed to read secret")}finally{F(null)}},se=async()=>{if(O)try{await navigator.clipboard.writeText(O),T(!0)}catch{}};return mt("div",{className:t,children:[mt("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."})]}),mt("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(),H())},disabled:c}),mt(w,{onClick:H,disabled:c||!b.trim(),children:[c?ke(_r,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(nc,{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}),mt("div",{className:"af-mt-4 af-space-y-2",children:[i&&mt("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&&X.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."}),X.map(W=>mt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[mt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[mt("div",{className:"af-min-w-0",children:[mt("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(", ")})]}),mt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[ke(w,{variant:"ghost",size:"sm",onClick:()=>G(y===W.id?null:W.id),children:y===W.id?"Hide log":"Deliveries"}),ke(w,{variant:"ghost",size:"sm",onClick:()=>z(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(oc,{className:"af-h-4 af-w-4"})})]})]}),W.status==="disabled"&&mt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[ke(cc,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),mt("div",{className:"af-text-sm",children:[mt("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:()=>j(W),children:"Re-enable"})]})]}),x===W.id&&O&&mt("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."}),mt("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:N?ke(ic,{className:"af-h-4 af-w-4"}):ke(rc,{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(lc,{className:"af-h-4 af-w-4"})})]})]}),y===W.id&&ke(wn,{destinationId:W.id})]},W.id))]}),ke(Ba,{open:!!L,onOpenChange:W=>{!W&&!k&&S(null)},children:mt(_a,{children:[mt(Ra,{children:[ke(Ca,{children:"Delete this webhook?"}),mt(Ta,{children:["New submissions will stop being sent to ",L?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),mt(Pa,{children:[ke(w,{variant:"outline",onClick:()=>S(null),disabled:!!k,children:"Cancel"}),ke(w,{variant:"destructive",onClick:K,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,m]=oa.useState(null),[d,f]=oa.useState(null),[r,g]=oa.useState(e.name),[b,v]=oa.useState(e.redirect_url||""),[c,l]=oa.useState(e.email_recipients),[p,h]=oa.useState("");oa.useEffect(()=>{g(e.name),v(e.redirect_url||""),l(e.email_recipients),f(null)},[e]);let x=oa.useCallback(async T=>{try{i(!0),f(null);let L=await t(e.id,T);m(new Date),a?.(L)}catch(L){f(L instanceof Error?L.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);oa.useEffect(()=>{if(o){let T=setTimeout(()=>m(null),2e3);return()=>clearTimeout(T)}},[o]);let I=async()=>{let T=p.trim().toLowerCase();if(!T)return;if(!T.includes("@")){f("Please enter a valid email address");return}if(c.includes(T)){f("This email is already added");return}let L=[...c,T];l(L),h(""),f(null),await x({email_recipients:L})},O=async T=>{let L=c.filter(S=>S!==T);l(L),await x({email_recipients:L})},u=async()=>{r!==e.name&&await x({name:r})},N=async()=>{let T=b||null;T!==e.redirect_url&&await x({redirect_url:T})};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(fc,{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(mc,{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:T=>g(T.target.value),onBlur:u,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(T=>ka(te,{variant:"secondary",className:"af-gap-1",children:[T,Le("button",{type:"button",onClick:()=>O(T),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:Le(dc,{className:"af-h-3 af-w-3"})})]},T)),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:p,onChange:T=>h(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),I())},disabled:n}),Le(w,{type:"button",variant:"outline",onClick:I,disabled:!p.trim()||n,children:Le(uc,{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:T=>v(T.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}),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 $t,jsxs as Fa}from"react/jsx-runtime";function Ti({className:e,submissionId:a}){let{api:s}=ne(),[t,n]=rs.useState("list"),[i,o]=rs.useState(null),[m,d]=rs.useState("submissions"),[f,r]=rs.useState(a),[g,b]=rs.useState(!!a);rs.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)},c=()=>{n("list"),o(null),r(void 0)},l=p=>{o(p)};return g?$t("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:$t("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Fa("div",{className:e,children:[t==="list"&&Fa("div",{children:[Fa("div",{className:"af-mb-6",children:[$t("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),$t("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),$t(pn,{onSelectForm:v})]}),t==="detail"&&i&&Fa("div",{children:[Fa("div",{className:"af-mb-6",children:[Fa(w,{variant:"ghost",size:"sm",onClick:c,className:"af-mb-2 af--ml-2",children:[$t(pc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),$t("h2",{className:"af-text-lg af-font-semibold",children:i.name}),$t("p",{className:"af-text-sm af-text-muted-foreground",children:$t("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Fa(mn,{value:m,onValueChange:p=>d(p),children:[Fa(js,{className:"af-mb-4",children:[Fa(wa,{value:"submissions",className:"af-gap-2",children:[$t(vc,{className:"af-h-4 af-w-4"}),"Submissions"]}),Fa(wa,{value:"settings",className:"af-gap-2",children:[$t(gc,{className:"af-h-4 af-w-4"}),"Settings"]})]}),$t(Na,{value:"submissions",children:$t(hn,{formId:i.id,defaultSubmissionId:f})}),$t(Na,{value:"settings",children:$t(Sn,{form:i,onSaved:l})})]})]})]})}import*as Oe from"react";import*as Ma from"react";function is(){let{api:e}=ne(),[a,s]=Ma.useState(null),[t,n]=Ma.useState(!0),[i,o]=Ma.useState(null),m=Ma.useRef(0),d=Ma.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 Ma.useEffect(()=>{d()},[d]),{status:a,isLoading:t,error:i,refetch:d}}var bc=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function va(e){return bc.has(e.toLowerCase())}function q(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 Ya(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 pt(e,a){return va(a)?e:e/100}function _n(e){return e.amount_paid??Math.max(0,Ya(e)-(e.credit_applied??0))}import{Fragment as xc,jsx as Ie,jsxs as He}from"react/jsx-runtime";function Js(e){return e instanceof Bt&&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?`${q(e.amount_off,e.currency)} off`:"Discount unavailable"}function Ps(){let{api:e,siteToken:a}=ne();return Ie(yc,{api:e},a)}function yc({api:e}){let{status:a,error:s}=is(),[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,c]=Oe.useState(""),[l,p]=Oe.useState(null),[h,x]=Oe.useState(null),[I,O]=Oe.useState(!1),u=Oe.useRef(0),N=Oe.useCallback(async S=>{let k=++u.current;r(!0),c("");try{let F=await e.getPromos(S);if(k!==u.current)return;n(y=>S?[...y,...F.promos.filter(G=>!y.some(X=>X.id===G.id))]:F.promos),o(F.next_cursor),d(F.checkout_enabled)}catch(F){k===u.current&&c(Js(F))}finally{k===u.current&&r(!1)}},[e]);Oe.useEffect(()=>(N(),()=>{u.current++}),[N]);async function T(S){let k=++u.current;r(!0),c(""),O(!1);try{let F=await e.getPromo(S);k===u.current&&p(F)}catch(F){k===u.current&&c(Js(F))}finally{k===u.current&&r(!1)}}async function L(){if(l){b(!0),r(!0),c("");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 N()}catch(S){c(Js(S))}finally{b(!1),r(!1)}}}return h?Ie(hc,{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),F=await e.getPromo(k.id);if(F.status==="pending"||F.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(F),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:f||!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."}),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?Js(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 T(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:g,onClick:()=>{p(null),O(!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: ${q(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 T(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"})]}),I&&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 L(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Ie(w,{variant:"ghost",disabled:f,onClick:()=>O(!1),children:"Cancel"})]})]}):He(xc,{children:[t.map(S=>He("button",{type:"button",disabled:f,onClick:()=>void T(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)),!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 N(i),children:"Load more"})]})]})}function hc({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(pt(a.amount_off,e)):"")),[b,v]=Oe.useState(a?.minimum_amount!=null&&e?String(pt(a.minimum_amount,e)):""),[c,l]=Oe.useState(()=>{if(!a?.expires_at)return"";let j=new Date(a.expires_at);return Number.isFinite(j.getTime())?new Date(j.getTime()-j.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,h]=Oe.useState(a?.max_redemptions?.toString()??""),[x,I]=Oe.useState(a?.duration??"once"),[O,u]=Oe.useState(a?.duration_in_months?.toString()??"3"),[N,T]=Oe.useState(null),[L,S]=Oe.useState(!1),[k,F]=Oe.useState(""),y=Oe.useRef(!1),G=e&&va(e)?"1":"0.01";async function X(j){if(j.preventDefault(),y.current)return;F("");let K=N;if(!K){if(!e){F("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){F("Choose a different code for the replacement.");return}let z=Zt(r,e),se=b?Zt(b,e):null;if(d==="fixed"&&(!z||z>999999999999)||b&&(!se||se>999999999999)){F("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){F("Choose a future expiry.");return}K={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:x,...d==="percent"?{percent_off:Number(r)}:{amount_off:z,currency:e},...b?{minimum_amount:se,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...x==="repeating"?{duration_in_months:Number(O)}:{}},T(K)}y.current=!0,S(!0);try{await t(K)}catch(z){F(Js(z)),z instanceof Bt&&z.status>=400&&z.status<500&&z.details?.retryable!==!0&&T(null)}finally{y.current=!1,S(!1)}}let H=(j,K,z,se={})=>He("label",{className:"af-grid af-gap-1 af-text-sm",children:[j,Ie(ge,{"aria-label":j,value:K,onChange:W=>z(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:X,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:L||!!N,className:"af-grid af-gap-4",children:[H("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),H("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:j=>f(j.target.value),children:[Ie("option",{value:"percent",children:"Percentage"}),He("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),H("Discount",r,g,{type:"number",required:!0,min:d==="percent"?"0.01":G,max:d==="percent"?"100":void 0,step:d==="percent"?"0.01":G}),H("Minimum order amount",b,v,{type:"number",min:G,step:G,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."]}),H("Expires at (local time)",c,l,{type:"datetime-local",step:1}),H("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:j=>I(j.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"&&H("Months",O,u,{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&&!L&&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:L,children:L?"Saving\u2026":N?"Retry same request":a?"Create replacement":"Create code"}),Ie(w,{type:"button",variant:"ghost",disabled:L||!!N,onClick:s,children:"Cancel"})]})]})}import*as Ls from"react";import{ArrowLeft as zu,FileText as qu,Package as ju,Receipt as Gu,Settings as Wu,Users as Ku}from"lucide-react";import*as Rn from"react";import{Package as wc,Pencil as Nc,Plus as Ai,Trash2 as Sc}from"lucide-react";import{jsx as Ue,jsxs as Mt}from"react/jsx-runtime";function _c(e){if(e.allow_custom_amount){let a=e.min_amount!==null?q(e.min_amount,e.currency):"?",s=e.max_amount!==null?q(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":q(e.unit_amount,e.currency)}function Rc(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:m}=e,[d,f]=Rn.useState(null),[r,g]=Rn.useState(!1),[b,v]=Rn.useState(null),c=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:Mt("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Mt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Ue(wc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Mt("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."]}),Mt(w,{variant:"outline",onClick:()=>s?.(),children:[Ue(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Mt("div",{className:t,children:[Ue("div",{className:"af-flex af-justify-end af-mb-4",children:Mt(w,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Ue(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Mt(Be,{children:[Ue(Fe,{children:Mt(pe,{children:[Ue(M,{children:"Name"}),Ue(M,{children:"Price"}),Ue(M,{children:"Fulfillment"}),Ue(M,{children:"Status"}),Ue(M,{className:"af-text-right",children:"Actions"})]})}),Ue(Me,{children:n.map(l=>Mt(pe,{children:[Ue(U,{className:"af-font-medium",children:l.name}),Ue(U,{children:_c(l)}),Ue(U,{className:"af-text-muted-foreground",children:Rc(l)}),Ue(U,{children:Ue(te,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),Ue(U,{className:"af-text-right",children:Mt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Mt(w,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[Ue(Nc,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Mt(w,{variant:"ghost",size:"sm",onClick:()=>{v(null),f(l)},children:[Ue(Sc,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),Ue(Ba,{open:!!d,onOpenChange:l=>{!l&&!r&&f(null)},children:Mt(_a,{children:[Mt(Ra,{children:[Ue(Ca,{children:"Delete product?"}),Mt(Ta,{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}),Mt(Pa,{children:[Ue(w,{variant:"outline",onClick:()=>f(null),disabled:r,children:"Cancel"}),Ue(w,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as Je from"react";import{FileText as Cc,Link2 as Tc,Loader2 as Di,Plus as kc,Upload as Ac,X as Ec}from"lucide-react";import*as gt from"react";import{Loader2 as Ei,Plus as Rr,Trash2 as Ii,X as Pc}from"lucide-react";import{jsx as J,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}=ne(),n=va(a)?"1":"0.01",[i,o]=gt.useState(null),[m,d]=gt.useState(!0),[f,r]=gt.useState(null),[g,b]=gt.useState(null),[v,c]=gt.useState(!1),l=gt.useRef(!0);gt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let p=gt.useCallback(async()=>{try{let R=await t.getProduct(e);if(!l.current)return;o(R)}catch(R){if(!l.current)return;r(R instanceof Error?R.message:"Failed to load product")}finally{l.current&&d(!1)}},[t,e]);gt.useEffect(()=>{p()},[p]);let h=async R=>{b(null),c(!0);try{await R(),await p()}catch(D){l.current&&b(D instanceof Error?D.message:"Something went wrong")}finally{l.current&&c(!1)}},[x,I]=gt.useState(""),[O,u]=gt.useState(""),[N,T]=gt.useState({}),L=()=>h(async()=>{let R=x.trim(),D=O.split(",").map(E=>E.trim()).filter(Boolean);if(!R)throw new Error("Option name is required");if(D.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:R,values:D}),l.current&&(I(""),u(""))}),S=R=>h(async()=>{let D=(N[R.id]??"").trim();if(!D)throw new Error("Enter a value");await t.updateOption(R.id,{add_values:[D]}),l.current&&T(E=>({...E,[R.id]:""}))}),k=(R,D)=>h(()=>t.updateOption(R.id,{remove_values:[D]})),F=R=>h(()=>t.deleteOption(R.id)),[y,G]=gt.useState(null),[X,H]=gt.useState(null),[ce,j]=gt.useState(!1),[K,z]=gt.useState(null),se=i?.options??[],W=i?.variants??[],he=()=>{H(null),G({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(se.map(R=>[R.id,R.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Ze=R=>{H(null);let D=R.inventory?.on_hand??0,E=D<0?"":String(D);G({variant:R,title:R.title??"",sku:R.sku??"",unitAmount:R.unit_amount!=null?String(pt(R.unit_amount,a)):"",compareAt:R.compare_at_amount!=null?String(pt(R.compare_at_amount,a)):"",active:R.active,optionValues:{},tracked:R.inventory?.tracked??!1,onHand:E,initialOnHand:E,allowBackorder:R.inventory?.allow_backorder??!1})},it=async()=>{if(!y)return;H(null);let R=y.variant?.allow_custom_amount??!1,D=null,E=null;if(!R){if(D=Zt(y.unitAmount,a),D===null||D<=0){H("Enter a valid price");return}if(y.compareAt.trim()&&(E=Zt(y.compareAt,a),E===null||E<=D)){H("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)){H("On-hand quantity must be zero or more");return}try{if(j(!0),y.variant)await t.updateVariant(y.variant.id,{title:y.title.trim()||null,sku:y.sku.trim()||null,...R?{}:{unit_amount:D,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 tt=y.optionValues[Ce.id];if(!tt){H(`Choose a ${Ce.title}`),j(!1);return}Se[Ce.title]=tt}await t.createVariant(e,{title:y.title.trim()||null,sku:y.sku.trim()||null,unit_amount:D,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&&G(null)}catch(Se){if(l.current&&H(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&&j(!1)}},Re=()=>h(async()=>{K&&(await t.deleteVariant(K.id),l.current&&z(null))}),je=y?.variant?.allow_custom_amount??!1,et=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 At(R){let D=R.inventory;if(!D||!D.tracked)return J("span",{className:"af-text-muted-foreground",children:"Unlimited"});let E=D.available??D.on_hand;return E<0?de("span",{children:[-E," backordered"]}):de("span",{children:[E," in stock",D.allow_backorder&&J("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return m?J("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:J(Ei,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):f?J("div",{className:s,children:J("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:[J(ve,{children:"Options"}),J("p",{className:"af-text-xs af-text-muted-foreground",children:"Add options like Size or Color, then create a variant for each combination you sell. Simple products don't need options."})]}),se.length>0&&J("div",{className:"af-space-y-3",children:se.map(R=>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:[J("span",{className:"af-text-sm af-font-medium",children:R.title}),J(w,{variant:"ghost",size:"sm",onClick:()=>F(R),disabled:v,children:J(Ii,{className:"af-h-4 af-w-4"})})]}),J("div",{className:"af-flex af-flex-wrap af-gap-2",children:R.values.map(D=>de(te,{variant:"secondary",className:"af-gap-1",children:[D.value,J("button",{type:"button",onClick:()=>k(R,D.value),className:"af-ml-1 hover:af-text-destructive",disabled:v,title:"Remove value",children:J(Pc,{className:"af-h-3 af-w-3"})})]},D.id))}),de("div",{className:"af-flex af-gap-2",children:[J(ge,{value:N[R.id]??"",onChange:D=>T(E=>({...E,[R.id]:D.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),S(R))},disabled:v}),J(w,{type:"button",variant:"outline",size:"sm",onClick:()=>S(R),disabled:v||!(N[R.id]??"").trim(),children:J(Rr,{className:"af-h-4 af-w-4"})})]})]},R.id))}),de("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[de("div",{className:"af-space-y-1",children:[J(ve,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),J(ge,{id:"new-option-title",value:x,onChange:R=>I(R.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:[J(ve,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),J(ge,{id:"new-option-values",value:O,onChange:R=>u(R.target.value),placeholder:"S, M, L",disabled:v})]}),de(w,{type:"button",variant:"outline",onClick:L,disabled:v||!x.trim()||!O.trim(),children:[J(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:[J(ve,{children:"Variants"}),de(w,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:v||se.length===0,children:[J(Rr,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),se.length===0&&J("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),W.length===0?J("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):de(Be,{children:[J(Fe,{children:de(pe,{children:[J(M,{children:"Variant"}),J(M,{children:"SKU"}),J(M,{children:"Price"}),J(M,{children:"Stock"}),J(M,{children:"Status"}),J(M,{className:"af-text-right",children:"Actions"})]})}),J(Me,{children:W.map(R=>de(pe,{children:[J(U,{className:"af-font-medium",children:Pr(R)}),J(U,{className:"af-text-muted-foreground",children:R.sku||"-"}),J(U,{children:R.unit_amount!=null?de("span",{children:[R.compare_at_amount!=null&&J("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:q(R.compare_at_amount,R.currency)}),q(R.unit_amount,R.currency)]}):R.allow_custom_amount?J("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),J(U,{children:At(R)}),J(U,{children:J(te,{variant:R.active?"success":"secondary",children:R.active?"Active":"Inactive"})}),J(U,{className:"af-text-right",children:de("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[J(w,{variant:"ghost",size:"sm",onClick:()=>Ze(R),disabled:v,children:"Edit"}),J(w,{variant:"ghost",size:"icon",onClick:()=>z(R),disabled:v,title:"Delete variant",children:J(Ii,{className:"af-h-4 af-w-4"})})]})})]},R.id))})]})]}),g&&J("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),J(Ba,{open:y!==null,onOpenChange:R=>{!R&&!ce&&G(null)},children:de(_a,{children:[de(Ra,{children:[J(Ca,{children:y?.variant?"Edit variant":"Add variant"}),J(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:[J("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Pr(y.variant)]}):se.map(R=>de("div",{className:"af-space-y-1",children:[J(ve,{className:"af-text-xs af-text-muted-foreground",children:R.title}),de(da,{value:y.optionValues[R.id]??"",onValueChange:D=>G(E=>E&&{...E,optionValues:{...E.optionValues,[R.id]:D}}),children:[J(na,{children:J(fa,{placeholder:`Choose ${R.title}`})}),J(ra,{children:R.values.map(D=>J(Ke,{value:D.value,children:D.value},D.id))})]})]},R.id)),je?de("div",{className:"af-space-y-1",children:[J(ve,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),J("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):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(),")"]}),J(ge,{id:"variant-price",type:"number",min:"0",step:n,value:y.unitAmount,onChange:R=>G(D=>D&&{...D,unitAmount:R.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),de("div",{className:"af-space-y-1",children:[J(ve,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),J(ge,{id:"variant-compare",type:"number",min:"0",step:n,value:y.compareAt,onChange:R=>G(D=>D&&{...D,compareAt:R.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),de("div",{className:"af-space-y-1",children:[J(ve,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),J(ge,{id:"variant-sku",value:y.sku,onChange:R=>G(D=>D&&{...D,sku:R.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:[J("input",{type:"checkbox",checked:y.tracked,onChange:R=>G(D=>D&&{...D,tracked:R.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:[J(ve,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),J(ge,{id:"variant-onhand",type:"number",min:"0",step:"1",value:y.onHand,onChange:R=>G(D=>D&&{...D,onHand:R.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:[J("input",{type:"checkbox",checked:y.allowBackorder,onChange:R=>G(D=>D&&{...D,allowBackorder:R.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:[J("input",{type:"checkbox",checked:y.active,onChange:R=>G(D=>D&&{...D,active:R.target.checked}),className:"af-h-4 af-w-4",disabled:et}),"Active (buyers can purchase this variant)"]}),et&&J("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),X&&J("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:X})]}),de(Pa,{children:[J(w,{variant:"outline",onClick:()=>G(null),disabled:ce,children:"Cancel"}),de(w,{onClick:it,disabled:ce,children:[ce?J(Ei,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?.variant?"Save":"Add variant"]})]})]})}),J(Ba,{open:K!==null,onOpenChange:R=>{!R&&!v&&z(null)},children:de(_a,{children:[de(Ra,{children:[J(Ca,{children:"Delete variant?"}),J(Ta,{children:K&&`"${Pr(K)}" will no longer be purchasable. Past orders are unaffected.`})]}),de(Pa,{children:[J(w,{variant:"outline",onClick:()=>z(null),disabled:v,children:"Cancel"}),J(w,{variant:"destructive",onClick:Re,disabled:v,children:"Delete"})]})]})})]})}import{Fragment as Dc,jsx as fe,jsxs as _e}from"react/jsx-runtime";function Ic(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:m,attachProductFileFromUrl:d}=e,f=!!a,r=a?.currency??s,g=va(r)?"1":"0.01",b=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[v,c]=Je.useState(!1),[l,p]=Je.useState(null),h=Je.useRef(!0);Je.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);let[x,I]=Je.useState(a?.name??""),[O,u]=Je.useState(a?.description??""),[N,T]=Je.useState(a?.allow_custom_amount?"custom":"fixed"),[L,S]=Je.useState(a?.unit_amount!=null?String(pt(a.unit_amount,r)):""),[k,F]=Je.useState(a?.min_amount!=null?String(pt(a.min_amount,r)):""),[y,G]=Je.useState(a?.max_amount!=null?String(pt(a.max_amount,r)):""),[X,H]=Je.useState(String(a?.max_quantity??10)),ce=Je.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(pt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(pt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(pt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[j,K]=Je.useState(a?.collect_shipping_address??!1),[z,se]=Je.useState(a?.active??!0),[W,he]=Je.useState(a?.images??[]),[Ze,it]=Je.useState(""),[Re,je]=Je.useState(a?.fulfillment??null),[et,xe]=Je.useState(!1),[At,R]=Je.useState(""),[D,E]=Je.useState(null),ue=Je.useRef(null),me=v||et,Se=()=>{let ie=Ze.trim();if(ie){if(W.includes(ie)){p("This image URL is already added");return}he(Ae=>[...Ae,ie]),it(""),p(null)}},Ce=ie=>{he(Ae=>Ae.filter(ot=>ot!==ie))},tt=async()=>{if(p(null),!x.trim()){p("Product name is required");return}let ie=null,Ae=null,ot=null,sa=!f||N!==ce.pricingMode||(N==="fixed"?L!==ce.unitAmount:k!==ce.minAmount||y!==ce.maxAmount),ht=!f||X!==ce.maxQuantity,Et=b||N==="fixed";if(!(b||!sa))if(N==="fixed"){if(ie=Zt(L,r),ie===null||ie<=0){p("Enter a valid price");return}}else{if(Ae=Zt(k,r),ot=Zt(y,r),Ae===null||ot===null){p("Enter valid minimum and maximum amounts");return}if(ot<Ae){p("Maximum amount must be at least the minimum amount");return}}let Gt=parseInt(X,10);if(Et&&ht&&(!Number.isFinite(Gt)||Gt<1)){p("Max quantity must be at least 1");return}try{c(!0);let Ve;if(f&&a){let at={name:x.trim(),description:O.trim()||null,images:W,collect_shipping_address:j,active:z};!b&&sa&&(at.allow_custom_amount=N==="custom",N==="fixed"?at.unit_amount=ie:(at.min_amount=Ae,at.max_amount=ot)),Et&&ht&&(at.max_quantity=Gt),Ve=await o(a.id,at),ce.pricingMode=Ve.allow_custom_amount?"custom":"fixed",ce.unitAmount=Ve.unit_amount!=null?String(pt(Ve.unit_amount,r)):"",ce.minAmount=Ve.min_amount!=null?String(pt(Ve.min_amount,r)):"",ce.maxAmount=Ve.max_amount!=null?String(pt(Ve.max_amount,r)):"",ce.maxQuantity=String(Ve.max_quantity)}else{let at={name:x.trim(),allow_custom_amount:N==="custom",collect_shipping_address:j,active:z};O.trim()&&(at.description=O.trim()),W.length>0&&(at.images=W),N==="fixed"?(at.unit_amount=ie,at.max_quantity=Gt):(at.min_amount=Ae,at.max_amount=ot),Ve=await i(at)}if(!h.current)return;je(Ve.fulfillment),t?.(Ve)}catch(Ve){if(!h.current)return;p(Ve instanceof Error?Ve.message:"Failed to save product")}finally{h.current&&c(!1)}},$e=async ie=>{let Ae=ie.target.files?.[0];if(!(!Ae||!a))try{xe(!0),E(null);let ot=await m(a.id,Ae);if(!h.current)return;je(ot.fulfillment),t?.(ot)}catch(ot){if(!h.current)return;E(ot instanceof Error?ot.message:"Failed to upload file")}finally{h.current&&(xe(!1),ue.current&&(ue.current.value=""))}},Ge=async()=>{let ie=At.trim();if(!(!ie||!a))try{xe(!0),E(null);let Ae=await d(a.id,ie);if(!h.current)return;je(Ae.fulfillment),R(""),t?.(Ae)}catch(Ae){if(!h.current)return;E(Ae instanceof Error?Ae.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:ie=>I(ie.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:ie=>u(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"})]}),_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(Dc,{children:[_e(da,{value:N,onValueChange:ie=>T(ie),children:[fe(na,{className:"af-w-[260px]",children:fe(fa,{})}),_e(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:_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:L,onChange:ie=>S(ie.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:k,onChange:ie=>F(ie.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:ie=>G(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."})]}),_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||N==="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:X,onChange:ie=>H(ie.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(ie=>_e(te,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[fe("span",{className:"af-truncate",children:ie}),fe("button",{type:"button",onClick:()=>Ce(ie),className:"af-ml-1 hover:af-text-destructive",disabled:v,children:fe(Ec,{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"})]}),_e("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(),Se())},disabled:v}),fe(w,{type:"button",variant:"outline",onClick:Se,disabled:!Ze.trim()||v,children:fe(kc,{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(Cc,{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:["(",Ic(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(Tc,{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:$e,className:"af-hidden",disabled:me}),_e(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(Ac,{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:At,onChange:ie=>R(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:!At.trim()||me,children:"Fetch from URL"})]}),D&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:D})]}):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:j,onChange:ie=>K(ie.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:z,onChange:ie=>se(ie.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(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:_e(w,{type:"button",onClick:tt,disabled:me,children:[v?fe(Di,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,f?"Save changes":"Create product"]})})]})}import*as Rt from"react";import{ChevronLeft as su,ChevronRight as qi,Loader2 as nu,Receipt as ru,Search as iu,SlidersHorizontal as ou}from"lucide-react";import*as lt from"react";var Lc=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function kn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ne(),[t,n]=lt.useState([]),[i,o]=lt.useState(0),[m,d]=lt.useState(!0),[f,r]=lt.useState(null),[g,b]=lt.useState(0),[v,c]=lt.useState(e),[l,p]=lt.useState(void 0),[h,x]=lt.useState(""),[I,O]=lt.useState(""),[u,N]=lt.useState(""),[T,L]=lt.useState(!1),[S,k]=lt.useState(!1),[F,y]=lt.useState(void 0),G=F?F.join(","):"",X=lt.useMemo(()=>{if(!G)return;let K=new Set(G.split(","));return Lc.filter(z=>!K.has(z))},[G]),H=lt.useRef(0),ce=lt.useCallback(async()=>{let K=++H.current;try{d(!0),r(null);let z={limit:v,offset:g*v};l?z.status=l:X?z.excludeStatus=X:T||(z.excludeStatus=["pending","expired"]),h.trim()&&(z.customerEmail=h.trim()),I.trim()&&(z.from=I.trim()),u.trim()&&(z.to=u.trim()),S&&(z.unfulfilledOnly=!0);let se=await s.getOrders(z);if(K!==H.current)return;n(se.orders),o(se.total)}catch(z){if(K!==H.current)return;r(z instanceof Error?z:new Error("Failed to fetch orders"))}finally{K===H.current&&d(!1)}},[s,g,v,l,X,T,S,h,I,u,a]);lt.useEffect(()=>{ce()},[ce]);let j=Math.ceil(i/v);return{orders:t,total:i,isLoading:m,error:f,page:g,pageSize:v,hasNextPage:g<j-1,hasPreviousPage:g>0,setPage:b,setPageSize:K=>{c(K),b(0)},status:l,setStatus:K=>{p(K),b(0)},statusIn:F,setStatusIn:K=>{y(K&&K.length>0?K:void 0),b(0)},customerEmail:h,setCustomerEmail:K=>{x(K),b(0)},from:I,setFrom:K=>{O(K),b(0)},to:u,setTo:K=>{N(K),b(0)},showAbandoned:T,setShowAbandoned:K=>{L(K),b(0)},unfulfilledOnly:S,setUnfulfilledOnly:K=>{k(K),b(0)},clearFilters:()=>{p(void 0),y(void 0),L(!1),k(!1),x(""),O(""),N(""),b(0)},refetch:ce}}import*as dt from"react";import{ArrowLeft as Fc,Check as Bi,ChevronLeft as Mc,ChevronRight as Uc,ClipboardCopy as $c,Copy as Vc,Download as Hc,Loader2 as Dn,Mail as Fi,MoreHorizontal as zc,Package as qc,RotateCcw as jc,Truck as Gc,Undo2 as Mi}from"lucide-react";import*as Li from"react";import*as Ua from"@radix-ui/react-popover";import{jsx as Cr}from"react/jsx-runtime";var An=Ua.Root,En=Ua.Trigger;var Ys=Li.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>Cr(Ua.Portal,{children:Cr("div",{className:"aifeatures-admin",children:Cr(Ua.Content,{ref:n,align:a,sideOffset:s,className:Z("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=Ua.Content.displayName;import{jsx as In}from"react/jsx-runtime";var Oc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Bc(e){return Oc[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:Bc(e)})}function ys({status:e}){return In(bs,{status:e})}function Cs({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 Qa(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as eu,jsx as P,jsxs as Q}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 Wc(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,Kc=["paid","partially_refunded"],Zc=["paid","partially_refunded","disputed"],Jc=/^[A-Za-z0-9 _-]*$/,Ui=100;function Er(e,a,s,t,n){let i=Kc.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 $i({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:m}){if(m)return Q("div",{children:[P(Oa,{deliveries:[m]}),o&&P("div",{className:"af-mt-2",children:o})]});let d=Er(n,s,t,i,a);return Q("div",{children:[Q("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Q("div",{className:"af-min-w-0",children:[P("div",{className:"af-text-sm",children:e}),a&&P("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:a})]}),P(te,{variant:d.variant,className:"af-shrink-0",children:d.label})]}),d.detail&&P("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:d.detail}),o&&P("div",{className:"af-mt-2",children:o})]})}function Vi(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=Wc(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 Yc(){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(!Yc())return null;let m=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},d=i?P(Bi,{className:"af-h-3 af-w-3"}):P(Vc,{className:"af-h-3 af-w-3"});return n==="icon"?P(w,{variant:"ghost",size:"icon",className:Z("af-h-6 af-w-6 af-shrink-0",t),onClick:m,title:a,"aria-label":a,children:d}):Q(w,{variant:"outline",size:"sm",className:t,onClick:m,"aria-label":a,children:[i?P(Bi,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):P($c,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function kr({label:e,value:a}){return Q("div",{children:[P("div",{className:hs,children:e}),Q("div",{className:"af-flex af-items-center af-gap-1",children:[P("code",{className:"af-text-xs af-font-mono af-break-all",children:a}),P(Ir,{value:a,label:`Copy ${e}`})]})]})}function Qc({src:e}){let[a,s]=dt.useState(!1);return!e||a?P("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:P(qc,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):P("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 $a({title:e,action:a,children:s,className:t}){return Q("section",{className:Z("af-rounded-lg af-border af-p-4",t),children:[Q("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[P("h4",{className:Hi,children:e}),a]}),P("div",{className:"af-mt-3",children:s})]})}function Jt({label:e,emphasis:a,divider:s,children:t}){return Q("div",{className:Z("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[P("span",{className:a?"af-text-base af-font-semibold":hs,children:e}),P("span",{className:Z("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Ar({onSelect:e,disabled:a,icon:s,children:t}){return Q(w,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:a,children:[P("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),t]})}function Xc(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 ${q(_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):Er("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):Er("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 ${q(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:m=!1,hasNextOrder:d=!1}){let{api:f}=ne(),[r,g]=dt.useState(e),[b,v]=dt.useState(null),[c,l]=dt.useState(null),[p,h]=dt.useState(!1),[x,I]=dt.useState(!1),[O,u]=dt.useState(!1),[N,T]=dt.useState(!1),[L,S]=dt.useState(""),[k,F]=dt.useState(!1),[y,G]=dt.useState(null),[X,H]=dt.useState(!1),[ce,j]=dt.useState(""),[K,z]=dt.useState([]),[se,W]=dt.useState(!1),[he,Ze]=dt.useState(!1),[it,Re]=dt.useState(null);dt.useEffect(()=>{g(e)},[e]);let je=A=>{let Ee=A.id===r.id&&A.email_deliveries===void 0?{...A,email_deliveries:r.email_deliveries}:A;g(Ee),t?.(Ee)},et=Object.entries(r.metadata??{}),xe=Math.max(0,_n(r)-r.amount_refunded),At=(r.status==="paid"||r.status==="partially_refunded")&&xe>0,R=r.exclusive_tax_total!=null,D=A=>typeof A.amountNet=="number"?A.amountNet+(A.exclusiveTax??0):(typeof A.unitAmount=="number"?A.unitAmount:0)*(typeof A.quantity=="number"&&A.quantity>0?A.quantity:1),E=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),ue=K.reduce((A,Ee)=>A+D(r.line_items[Ee]??{}),0)+(se?E:0),me=r.tax_total??0,Se=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((A,Ee)=>A+(Ee.exclusiveTax??0),0)),Ce=R?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,tt=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(ue+Ce,xe):ue+Ce,$e=K.length>0||se,Ge=$e?tt:Zt(ce,r.currency),ie=va(r.currency)?"1":"0.01",Ae=async()=>{try{h(!0),v(null),l(null),await f.resendOrderReceipt(r.id);let A=await f.getOrder(r.id);je(A),l("Receipt email queued.")}catch(A){v(A instanceof Error?A.message:"Failed to resend receipt")}finally{h(!1)}},ot=async()=>{try{I(!0),v(null),l(null);let A=await f.resetOrderDownloads(r.id);je(A),u(!1),l("Download count reset.")}catch(A){v(A instanceof Error?A.message:"Failed to reset downloads")}finally{I(!1)}},sa=r.line_items.some(A=>A.collectShippingAddress===!0&&!A.refunded&&!A.unavailableReason),ht=typeof r.merchant_fulfilled_at=="string",Et=Zc.includes(r.status)||r.status==="refunded"&&r.line_items.some(A=>A.collectShippingAddress===!0&&A.amountNet===0&&!A.refunded&&!A.unavailableReason),Gt=L.trim(),Ve=Jc.test(Gt)&&Gt.length<=Ui,at=async A=>{try{F(!0),G(null),l(null);let Ee=await f.setOrderFulfillment(r.id,{fulfilled:A,...A&&Gt?{trackingNumber:Gt}:{}});je(Ee),S(""),l(A?"Marked as shipped.":"Marked as not shipped.")}catch(Ee){Ee instanceof Bt&&Ee.status===409?G(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):G(Ee instanceof Error?Ee.message:"Failed to update the order")}finally{F(!1)}},ts=()=>{Re(null),j(String(pt(xe,r.currency))),z([]),W(!1),H(!0)},Vs=A=>z(Ee=>Ee.includes(A)?Ee.filter(Kt=>Kt!==A):[...Ee,A]),Ot=async(A,Ee)=>{if(s)try{Ze(!0),Re(null),await s(r,A,Ee);let Kt=await f.getOrder(r.id);je(Kt),H(!1),l("Refund issued.")}catch(Kt){Re(Kt instanceof Error?Kt.message:"Refund failed")}finally{Ze(!1)}},un=async()=>{if($e){if(tt<=0){Re("The lines you picked were charged nothing");return}if(tt>xe){Re(`That selection exceeds the refundable remainder (${q(xe,r.currency)})`);return}await Ot(tt,{...K.length>0?{line_items:[...K].sort((Ee,Kt)=>Ee-Kt)}:{},...se?{shipping:!0}:{}});return}let A=Zt(ce,r.currency);if(A===null||A<=0){Re("Enter a valid refund amount");return}if(A>xe){Re(`Amount exceeds the refundable remainder (${q(xe,r.currency)})`);return}await Ot(A,{amount:A})},$=()=>Ot(xe,{full:!0}),We=!r.subscription_history_only&&r.fulfillment_type==="download",V=!r.subscription_history_only&&n&&sa,Wt=Xc(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,Hs=[];return r.subscription_history_only||Hs.push(P(Ar,{icon:p?P(Dn,{className:"af-h-4 af-w-4 af-animate-spin"}):P(Fi,{className:"af-h-4 af-w-4"}),disabled:p||r.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Ae()},children:"Resend receipt"},"resend")),We&&Hs.push(P(Ar,{icon:P(jc,{className:"af-h-4 af-w-4"}),disabled:x,onSelect:()=>{T(!1),u(!0)},children:"Reset download count"},"reset")),At&&Hs.push(Q("div",{children:[P(Ar,{icon:P(Mi,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{T(!1),ts()},children:"Refund\u2026"}),!s&&P("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),Q("div",{children:[Q("div",{className:"af-mb-6",children:[Q(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[P(Fc,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),Q("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[Q("div",{className:"af-min-w-0",children:[Q("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[P("h3",{className:"af-text-xl af-font-semibold",children:Qa(r)}),P(bs,{status:r.status}),n&&!r.subscription_history_only&&P(Cs,{order:r}),r.is_test&&P(te,{variant:"outline",children:"Test"})]}),Q("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Tr(r.created_at)]}),r.is_test&&P("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),Q("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&Q("div",{className:"af-flex af-items-center",children:[P(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:P(Mc,{className:"af-h-4 af-w-4"})}),P(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:P(Uc,{className:"af-h-4 af-w-4"})})]}),V&&(ht?Q("div",{className:"af-flex af-items-center af-gap-1",children:[Q("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${Tr(r.merchant_fulfilled_at)}`:""]}),Et&&Q(w,{variant:"ghost",size:"sm",onClick:()=>at(!1),disabled:k,children:[k?P(Dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Et?Q("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[P(ge,{value:L,onChange:A=>S(A.target.value),placeholder:"Tracking number (optional)",maxLength:Ui,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),Q(w,{variant:"default",className:"af-shrink-0",onClick:()=>at(!0),disabled:k||!Ve,children:[k?P(Dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(Gc,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Hs.length>0&&Q(An,{open:N,onOpenChange:T,children:[P(En,{asChild:!0,children:P(w,{variant:"outline",size:"icon","aria-label":"More actions",children:P(zc,{className:"af-h-4 af-w-4"})})}),P(Ys,{children:P("div",{className:"af-space-y-0.5",children:Hs})})]})]})]}),V&&!ht&&!Ve&&P("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&&P("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&&P("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&&P("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})]}),Q("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[Q("div",{className:"af-space-y-6",children:[r.line_items.length>0&&P($a,{title:"Items",children:P("ul",{className:"af-space-y-3",children:r.line_items.map((A,Ee)=>{let Kt=typeof A.name=="string"&&A.name?A.name:"Item",mi=typeof A.quantity=="number"&&A.quantity>0?A.quantity:1,pi=typeof A.unitAmount=="number";return Q("li",{className:"af-flex af-items-start af-gap-3",children:[P(Qc,{src:typeof A.imageUrl=="string"&&A.imageUrl?A.imageUrl:void 0}),Q("div",{className:"af-min-w-0 af-flex-1",children:[Q("div",{className:"af-text-sm af-font-medium",children:[Kt,typeof A.variantTitle=="string"&&A.variantTitle&&Q("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",A.variantTitle]})]}),Q("div",{className:hs,children:[mi," \xD7"," ",pi?q(A.unitAmount,r.currency):"\u2014"]}),A.unavailableReason==="oversold"&&!A.refunded&&P(te,{variant:"secondary",className:"af-mt-1",children:A.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),A.refunded===!0&&P(te,{variant:"secondary",className:"af-mt-1",children:A.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),P("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof A.amountNet=="number"||pi?q(A.amountNet??A.unitAmount*mi,r.currency):"\u2014"})]},Ee)})})}),et.length>0&&P($a,{title:"Order details",children:P("dl",{className:"af-space-y-2",children:et.map(([A,Ee])=>Q("div",{children:[P("dt",{className:Z(hs,"af-capitalize"),children:A.replace(/_/g," ")}),P("dd",{className:"af-text-sm af-break-words",children:zi(Ee)})]},A))})}),P($a,{title:"Totals",children:Q("div",{className:"af-w-full",children:[fi&&P(Jt,{label:"Subtotal",children:q(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&Q(Jt,{label:"Discount",children:["\u2212",q(r.discount_total,r.currency)]}),ci&&P(Jt,{label:"Shipping",children:r.shipping_total===0?"Free":q(r.shipping_total??0,r.currency)}),di&&P(Jt,{label:"Tax",children:q(mr,r.currency)}),P(Jt,{label:"Total",emphasis:!0,divider:fi,children:q(Ya(r),r.currency)}),(r.credit_applied??0)>0&&Q(Jt,{label:"Credit applied",children:["\u2212",q(r.credit_applied,r.currency)]}),r.amount_paid!=null&&P(Jt,{label:"Amount paid",children:q(r.amount_paid,r.currency)}),ul&&P(Jt,{label:"incl. tax",children:q(ui,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&Q(Jt,{label:"Your price",children:[q(r.base_amount_total,r.base_currency),Q("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&Q(eu,{children:[Q(Jt,{label:"Refunded",children:["\u2212",q(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&Q("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",q(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),P(Jt,{label:"Net",children:P("span",{className:"af-font-medium",children:q(Math.max(0,_n(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&Q($a,{title:"Platform fee",children:[r.application_fee_original!=null&&P(Jt,{label:"Collected",children:q(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&P(Jt,{label:"Returned",children:q(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&P(Jt,{label:"Retained",children:q(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&P("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"})]}),P($a,{title:"Timeline",children:P("ol",{className:"af-space-y-3",children:Wt.map(A=>Q("li",{className:"af-flex af-gap-3",children:[P("span",{"aria-hidden":"true",className:Z("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",A.tone==="destructive"?"af-bg-destructive":A.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),Q("div",{className:"af-min-w-0",children:[P("div",{className:"af-text-sm af-break-words",children:A.text}),A.at&&P("div",{className:"af-text-xs af-text-muted-foreground",children:Tr(A.at)})]})]},A.key))})})]}),Q("div",{className:"af-space-y-6",children:[P($a,{title:"Customer",children:Q("div",{className:"af-space-y-2",children:[Q("div",{children:[P("div",{className:hs,children:"Email"}),Q("div",{className:"af-flex af-items-center af-gap-1",children:[P("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||P("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&P(Ir,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&Q("div",{children:[P("div",{className:hs,children:"Name"}),P("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&Q("div",{children:[P("div",{className:hs,children:"Customer record"}),Q("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[P("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),P(te,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&P($a,{title:"Ship to",action:P(Ir,{value:cl,label:"Copy address",size:"sm",children:"Copy address"}),children:P("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Vi(r.shipping_address).map((A,Ee)=>P("div",{children:A},Ee))})}),r.subscription_history_only?P($a,{title:"Subscription history",children:P("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."})}):Q($a,{title:"Emails",children:[P(Oa,{deliveries:r.email_deliveries?.filter(A=>!["purchase_receipt","merchant_sale"].includes(A.kind)),problemsOnly:!0,className:"af-mb-4"}),Q("div",{className:"af-space-y-4",children:[P($i,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(A=>A.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:Q(w,{variant:"outline",size:"sm",onClick:Ae,disabled:p||r.fulfillment_status!=="fulfilled",children:[p?P(Dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(Fi,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),P($i,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(A=>A.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),We&&P($a,{title:"Download",children:Q("div",{className:"af-space-y-2",children:[Q("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[P(Hc,{className:"af-h-4 af-w-4"}),Q("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&P("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"})]})}),Q("details",{className:"af-rounded-lg af-border af-p-4",children:[P("summary",{className:Z(Hi,"af-cursor-pointer af-select-none"),children:"Technical details"}),Q("div",{className:"af-mt-3 af-space-y-2",children:[P(kr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&P(kr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&P(kr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),P(Ba,{open:O,onOpenChange:A=>{!A&&!x&&u(!1)},children:Q(_a,{children:[Q(Ra,{children:[P(Ca,{children:"Reset download count?"}),P(Ta,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),Q(Pa,{children:[P(w,{variant:"outline",onClick:()=>u(!1),disabled:x,children:"Cancel"}),P(w,{onClick:ot,disabled:x,children:x?"Resetting...":"Reset"})]})]})}),P(Ba,{open:X,onOpenChange:A=>{!A&&!he&&H(!1)},children:Q(_a,{children:[Q(Ra,{children:[P(Ca,{children:"Refund order"}),Q(Ta,{children:["Refund up to ",q(xe,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),Q("div",{className:"af-space-y-4",children:[(r.line_items.length>0||E>0)&&Q("div",{className:"af-space-y-2",children:[P(ve,{children:"Items"}),Q("div",{className:"af-space-y-2",children:[r.line_items.map((A,Ee)=>{let Kt=A.refunded===!0;return Q("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:K.includes(Ee),onChange:()=>Vs(Ee),disabled:he||Kt||!!A.unavailableReason||D(A)<=0,className:"af-h-4 af-w-4"}),Q("span",{className:Kt?"af-text-muted-foreground af-line-through":void 0,children:[typeof A.name=="string"&&A.name?A.name:"Item",typeof A.variantTitle=="string"&&A.variantTitle?` \u2014 ${A.variantTitle}`:"",typeof A.quantity=="number"&&A.quantity>1?` \xD7 ${A.quantity}`:""]}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:Kt?"Refunded":q(D(A),r.currency)})]},Ee)}),E>0&&Q("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:se,onChange:A=>W(A.target.checked),disabled:he,className:"af-h-4 af-w-4"}),P("span",{children:"Shipping"}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:q(E,r.currency)})]})]})]}),Q("div",{className:"af-space-y-2",children:[Q(ve,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),P(ge,{id:"refund-amount",type:"number",min:"0",step:ie,value:$e?String(pt(tt,r.currency)):ce,onChange:A=>j(A.target.value),disabled:he||$e}),$e&&P("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),it&&P("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:it}),Q(Pa,{children:[P(w,{variant:"outline",onClick:()=>H(!1),disabled:he,children:"Cancel"}),P(w,{variant:"outline",onClick:$,disabled:he,children:"Refund everything"}),P(w,{variant:"destructive",onClick:un,disabled:he,children:he?"Refunding...":Ge!==null&&Ge>0?`Refund ${q(Ge,r.currency)}`:"Refund"})]})]})})]})}import*as Bn from"react";import{ArrowLeft as tu,RefreshCw as au}from"lucide-react";import{jsx as Yt,jsxs as os}from"react/jsx-runtime";function wt({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:Z("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(tu,{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:Z("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:Z("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(au,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Aa({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 Ts({icon:e,heading:a,body:s,action:t,className:n,children:i}){return os("div",{className:Z("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 B,jsxs as ye}from"react/jsx-runtime";var lu={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 cu({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}=ne(),g=kn({refreshKey:s}),{orders:b,total:v,isLoading:c,error:l,page:p,pageSize:h,hasNextPage:x,hasPreviousPage:I,setPage:O,setPageSize:u,customerEmail:N,setCustomerEmail:T,setStatusIn:L,from:S,setFrom:k,to:F,setTo:y,showAbandoned:G,setShowAbandoned:X,setUnfulfilledOnly:H,refetch:ce}=g,[j,K]=Rt.useState("list"),[z,se]=Rt.useState(null),[W,he]=Rt.useState(""),[Ze,it]=Rt.useState(""),[Re,je]=Rt.useState(!f&&n?"needs_shipping":"all"),[et,xe]=Rt.useState(!1),[At,R]=Rt.useState(!!t&&!f),[D,E]=Rt.useState(null);Rt.useEffect(()=>{if(!t||f)return;let V=!1;return R(!0),E(null),r.getOrder(t).then(Wt=>{V||(se(Wt),K("detail"))}).catch(()=>{V||E("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{V||R(!1)}),()=>{V=!0}},[r,t,f]);let ue=Rt.useCallback(V=>{je(V);let Wt=ji[V];L(Wt.statusIn),H(Wt.unfulfilledOnly)},[L,H]);Rt.useEffect(()=>{n&&!f&&H(!0)},[]);let me=Rt.useRef(!n);Rt.useEffect(()=>{me.current||c||(me.current=!0,b.length===0&&ue("all"))},[c,b.length,ue]);let Se=j==="detail"&&!!z;Rt.useEffect(()=>{o?.(Se)},[Se,o]);let Ce=(S?1:0)+(F?1:0)+(G?1:0),tt=Ce>0||!!N||!!Ze,$e=!!S&&!!F&&S>F,Ge=!f||!!d,ie=V=>{if(f){d?.();return}se(V),K("detail")},Ae=()=>{K("list"),se(null),ce()},ot=V=>{let Wt=V.trim();if(!Wt){it(""),N&&T("");return}if(Wt.startsWith("#")||/^\d+$/.test(Wt)){it(Wt),N&&T("");return}it(""),T(Wt)},sa=()=>{he(""),it(""),T(""),k(""),y(""),X(!1),xe(!1)},ht=Ze.replace(/^#/,"").toLowerCase(),Et=ht?b.filter(V=>String(V.order_number??"")===ht||V.id.toLowerCase().startsWith(ht)):b,Gt=f?Et.slice(0,m):Et,Ve=z?b.findIndex(V=>V.id===z.id):-1,at=Ve>0,ts=Ve>=0&&Ve<b.length-1;if(At)return B("div",{className:a,children:B("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:B(nu,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(j==="detail"&&z)return B("div",{className:a,children:B(On,{order:z,onBack:Ae,onRefund:e,onOrderUpdated:V=>se(V),allowFulfillment:n,onPrevOrder:at?()=>se(b[Ve-1]):void 0,onNextOrder:ts?()=>se(b[Ve+1]):void 0,hasPrevOrder:at,hasNextOrder:ts},z.id)});let Ot=ye("div",{className:"af-mb-4 af-space-y-3",children:[D&&B("p",{className:"af-text-xs af-text-muted-foreground",children:D}),ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[B("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=>B("button",{type:"button","aria-pressed":Re===V,onClick:()=>ue(V),className:Z("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:lu[V]},V))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[B(iu,{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"}),B(ge,{type:"text",value:W,onChange:V=>he(V.target.value),onBlur:()=>ot(W),onKeyDown:V=>{V.key==="Enter"&&(V.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:Ce>0?"secondary":"ghost",size:"sm",onClick:()=>xe(V=>!V),"aria-expanded":et,children:[B(ou,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ce>0&&B(te,{variant:"secondary",className:"af-ml-2",children:Ce})]}),tt&&B(w,{type:"button",variant:"ghost",size:"sm",onClick:sa,children:"Clear filters"})]}),(et||!!S||!!F)&&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:[B(ve,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),B(ge,{id:"orders-from",type:"date",value:S,max:F||void 0,onChange:V=>k(V.target.value),className:"af-w-[170px]"}),B(ve,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),B(ge,{id:"orders-to",type:"date",value:F,min:S||void 0,onChange:V=>y(V.target.value),className:"af-w-[170px]"}),!ji[Re].statusIn&&B(w,{type:"button",variant:G?"secondary":"ghost",size:"sm",onClick:()=>X(!G),"aria-pressed":G,children:G?"Hide abandoned":"Show abandoned"})]}),$e&&B("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:[f?null:Ot,B("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:[B(ae,{className:"af-h-4 af-w-16"}),B(ae,{className:"af-h-4 af-w-14"})]}),B(ae,{className:"af-mt-2 af-h-3 af-w-40"}),B(ae,{className:"af-mt-2 af-h-3 af-w-24"})]},V))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[B(Fe,{children:ye(pe,{children:[B(M,{children:"Order"}),B(M,{children:"Date"}),B(M,{children:"Customer"}),B(M,{children:"Items"}),B(M,{className:"af-text-right",children:"Total"}),B(M,{children:"Status"}),B(M,{className:"af-w-8"})]})}),B(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(V=>ye(pe,{children:[B(U,{children:B(ae,{className:"af-h-4 af-w-14"})}),B(U,{children:B(ae,{className:"af-h-4 af-w-24"})}),B(U,{children:B(ae,{className:"af-h-4 af-w-40"})}),B(U,{children:B(ae,{className:"af-h-4 af-w-32"})}),B(U,{children:B(ae,{className:"af-ml-auto af-h-4 af-w-16"})}),B(U,{children:B(ae,{className:"af-h-5 af-w-16"})}),B(U,{})]},V))})]})}),B("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return ye("div",{className:a,children:[f?null:Ot,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[B("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),B(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let un=Re!=="all";if(Et.length===0&&p===0)return tt||un?ye("div",{className:a,children:[!f&&Ot,B(Aa,{children:"No orders match these filters."})]}):B("div",{className:a,children:B(Ts,{icon:ru,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!f&&B(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>X(!0),children:"Show abandoned checkouts"})})});let $=p*h+1,We=Math.min((p+1)*h,v);return ye("div",{className:a,children:[f?null:Ot,B("div",{className:"af-space-y-3 lg:af-hidden",children:Gt.map(V=>ye("button",{type:"button",onClick:()=>ie(V),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:[B("span",{className:"af-font-medium",children:Qa(V)}),B("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:q(Ya(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||B("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Fn(V)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Fn(V)]})]}),B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Wi(V)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",q(V.amount_refunded,V.currency)," refunded"]})]}),ye("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[B(bs,{status:V.status}),B(Gs,{deliveries:V.email_deliveries}),V.is_test&&B(te,{variant:"outline",children:"Test"}),n&&B(Cs,{order:V}),B("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Gi(V.created_at)})]})]},V.id))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Be,{children:[B(Fe,{children:ye(pe,{children:[B(M,{children:"Order"}),B(M,{children:"Date"}),B(M,{children:"Customer"}),B(M,{children:"Items"}),B(M,{className:"af-text-right",children:"Total"}),B(M,{children:"Status"}),B(M,{className:"af-w-8"})]})}),B(Me,{children:Gt.map(V=>ye(pe,{onClick:Ge?()=>ie(V):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:[B("button",{type:"button",onClick:Wt=>{Wt.stopPropagation(),ie(V)},disabled:!Ge,"aria-label":`Open order ${Qa(V)}`,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:Qa(V)}),V.is_test&&B(te,{variant:"outline",className:"af-ml-2",children:"Test"})]}),B(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Gi(V.created_at)}),ye(U,{className:"af-max-w-[220px]",children:[B("div",{className:"af-truncate",children:V.customer_email||B("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Fn(V)&&B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Fn(V)})]}),B(U,{className:"af-max-w-[220px]",children:B("div",{className:"af-truncate af-text-muted-foreground",children:Wi(V)})}),ye(U,{className:"af-whitespace-nowrap af-text-right",children:[B("div",{className:"af-font-medium af-tabular-nums",children:q(Ya(V),V.currency)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",q(V.amount_refunded,V.currency)," ","refunded"]})]}),B(U,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[B(bs,{status:V.status}),B(Gs,{deliveries:V.email_deliveries}),n&&B(Cs,{order:V})]})}),B(U,{className:"af-w-8 af-text-right",children:B(qi,{"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:[B("span",{children:ht?`${Et.length} matching this page`:`Showing ${$}-${We} of ${v}`}),ye(da,{value:String(h),onValueChange:V=>u(Number(V)),children:[B(na,{className:"af-w-[70px] af-h-8",children:B(fa,{})}),ye(ra,{children:[B(Ke,{value:"10",children:"10"}),B(Ke,{value:"25",children:"25"}),B(Ke,{value:"50",children:"50"}),B(Ke,{value:"100",children:"100"})]})]}),B("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:!I,children:[B(su,{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",B(qi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function ls(e){return B(cu,{...e},e.maxRows==null?"full":"compact")}import*as $n from"react";import{ChevronLeft as mu,ChevronRight as pu,Eye as gu,Search as vu,Users as bu}from"lucide-react";import*as Qt from"react";function Mn({initialPageSize:e=25}={}){let{api:a}=ne(),[s,t]=Qt.useState([]),[n,i]=Qt.useState(0),[o,m]=Qt.useState(!0),[d,f]=Qt.useState(null),[r,g]=Qt.useState(0),[b,v]=Qt.useState(e),[c,l]=Qt.useState(""),p=Qt.useRef(0),h=Qt.useCallback(async()=>{let I=++p.current;try{m(!0),f(null);let O={limit:b,offset:r*b};c.trim()&&(O.email=c.trim());let u=await a.getCustomers(O);if(I!==p.current)return;t(u.customers),i(u.total)}catch(O){if(I!==p.current)return;f(O instanceof Error?O:new Error("Failed to fetch customers"))}finally{I===p.current&&m(!1)}},[a,r,b,c]);Qt.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:I=>{v(I),g(0)},email:c,setEmail:I=>{l(I),g(0)},refetch:h}}import*as xs from"react";import{ArrowLeft as uu,Loader2 as du}from"lucide-react";import{jsx as De,jsxs as Dt}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 fu(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 Un({customer:e,onBack:a,className:s}){let{api:t}=ne(),[n,i]=xs.useState(null),[o,m]=xs.useState([]),[d,f]=xs.useState(!0),[r,g]=xs.useState(null);xs.useEffect(()=>{let c=!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])=>{c||(i(l),m(p.orders))}).catch(l=>{c||g(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{c||f(!1)}),()=>{c=!0}},[t,e.id,e.email]);let b=n?.addresses??[],v=n?.order_count??o.length;return Dt("div",{className:s,children:[Dt("div",{className:"af-mb-6",children:[Dt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[De(uu,{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}),Dt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Ki(e.created_at)]})]}),d?De("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:De(du,{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}):Dt("div",{className:"af-space-y-6",children:[De(Oa,{deliveries:n?.email_deliveries}),Dt("div",{children:[De("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Dt("div",{className:"af-space-y-1 af-text-sm",children:[Dt("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&&Dt("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&&Dt("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})]}),Dt("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&&Dt("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=>Dt("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"}),fu(c).map((l,p)=>De("div",{children:l},p))]},c.id))})]}),Dt("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."}):Dt(Be,{children:[De(Fe,{children:Dt(pe,{children:[De(M,{children:"Date"}),De(M,{children:"Amount"}),De(M,{children:"Status"})]})}),De(Me,{children:o.map(c=>Dt(pe,{children:[De(U,{className:"af-text-muted-foreground",children:Ki(c.created_at)}),De(U,{children:q(Ya(c),c.currency)}),De(U,{children:De(ys,{status:c.status})})]},c.id))})]})]})]})]})}import{Fragment as hu,jsx as Pe,jsxs as vt}from"react/jsx-runtime";function yu(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:m,hasPreviousPage:d,setPage:f,setPageSize:r,email:g,setEmail:b,refetch:v}=Mn(),[c,l]=$n.useState("list"),[p,h]=$n.useState(null),[x,I]=$n.useState(""),O=S=>{h(S),l("detail")},u=()=>{l("list"),h(null),v()};if(c==="detail"&&p)return Pe("div",{className:e,children:Pe(Un,{customer:p,onBack:u})});let N=vt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Pe(ge,{type:"email",value:x,onChange:S=>I(S.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),b(x.trim()))}}),vt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>b(x.trim()),children:[Pe(vu,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&Pe(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{I(""),b("")},children:"Clear"})]});if(t)return vt("div",{className:e,children:[N,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 vt("div",{className:e,children:[N,Pe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:vt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return vt("div",{className:e,children:[g&&N,vt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Pe(bu,{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.":vt(hu,{children:["No customers yet.",Pe("br",{}),"Customers appear here after their first purchase."]})})]})]});let T=i*o+1,L=Math.min((i+1)*o,s);return vt("div",{className:e,children:[N,vt(Be,{children:[Pe(Fe,{children:vt(pe,{children:[Pe(M,{children:"Email"}),Pe(M,{children:"Name"}),Pe(M,{children:"Customer since"}),Pe(M,{className:"af-text-right",children:"Actions"})]})}),Pe(Me,{children:a.map(S=>vt(pe,{children:[Pe(U,{className:"af-font-medium",children:S.email}),Pe(U,{children:S.name||Pe("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Pe(U,{className:"af-text-muted-foreground",children:yu(S.created_at)}),Pe(U,{className:"af-text-right",children:Pe(w,{variant:"ghost",size:"icon",onClick:()=>O(S),title:"View customer",children:Pe(gu,{className:"af-h-4 af-w-4"})})})]},S.id))})]}),vt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[vt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[vt("span",{children:["Showing ",T,"-",L," of ",s]}),vt(da,{value:String(o),onValueChange:S=>r(Number(S)),children:[Pe(na,{className:"af-w-[70px] af-h-8",children:Pe(fa,{})}),vt(ra,{children:[Pe(Ke,{value:"10",children:"10"}),Pe(Ke,{value:"25",children:"25"}),Pe(Ke,{value:"50",children:"50"}),Pe(Ke,{value:"100",children:"100"})]})]}),Pe("span",{children:"per page"})]}),vt("div",{className:"af-flex af-items-center af-gap-2",children:[vt(w,{variant:"outline",size:"sm",onClick:()=>f(i-1),disabled:!d,children:[Pe(mu,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),vt(w,{variant:"outline",size:"sm",onClick:()=>f(i+1),disabled:!m,children:["Next",Pe(pu,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ne from"react";import{ArrowLeft as xu,ChevronLeft as wu,ChevronRight as Zi,Copy as Nu,Download as Su,ExternalLink as _u,FileText as Qi,Loader2 as Ru,Search as Pu}from"lucide-react";import*as bt from"react";function ks({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=ne(),[n,i]=bt.useState([]),[o,m]=bt.useState(0),[d,f]=bt.useState(null),[r,g]=bt.useState(!0),[b,v]=bt.useState(null),[c,l]=bt.useState(0),[p,h]=bt.useState(e),[x,I]=bt.useState(void 0),[O,u]=bt.useState(""),[N,T]=bt.useState(""),[L,S]=bt.useState(""),[k,F]=bt.useState(""),[y,G]=bt.useState(""),X=x?x.join(","):"",H=bt.useRef(0),ce=bt.useCallback(async()=>{let K=++H.current;g(!0),v(null);try{let z={labels:X?X.split(","):void 0,customerEmail:O||void 0,q:N||void 0,from:L||void 0,to:k||void 0,retainerId:y||void 0,includeAggregates:s,limit:p,offset:c*p},se=await t.getInvoices(z);if(K!==H.current)return;if(c>0&&c*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(z){if(K!==H.current)return;v(z instanceof Error?z:new Error("Failed to fetch invoices"))}finally{K===H.current&&g(!1)}},[t,X,O,N,L,k,y,c,p,s]);bt.useEffect(()=>{ce()},[ce,a]);let j=K=>z=>{l(0),K(z)};return{invoices:n,total:o,aggregates:d,isLoading:r,error:b,page:c,pageSize:p,hasNextPage:(c+1)*p<o,hasPreviousPage:c>0,setPage:l,setPageSize:j(h),labels:x,setLabels:j(I),customerEmail:O,setCustomerEmail:j(u),q:N,setQ:j(T),from:L,setFrom:j(S),to:k,setTo:j(F),retainerId:y,setRetainerId:j(G),clearFilters:()=>{l(0),I(void 0),u(""),T(""),S(""),F(""),G("")},refetch:ce}}import{Fragment as Lu,jsx as C,jsxs as Y}from"react/jsx-runtime";var Cu={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`:Cu[e.label]??e.label}function Tu(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"},ku={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Qs({invoice:e,className:a}){return Y("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[C(te,{variant:Tu(e.label),className:a,children:Br(e)}),e.collection_method==="charge_automatically"&&C(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 C(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 Au(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 Eu(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(),q(t.amount_subtotal,t.currency),q(t.tax_total,t.currency),q(t.amount_total,t.currency),t.amount_due===null?"":q(t.amount_due,t.currency),t.amount_paid===null?"":q(t.amount_paid,t.currency),q(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?"":q(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(Au).join(",")).join(`
|
|
5
|
+
`)}function Iu(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 Du({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}=ne(),{invoices:v,total:c,isLoading:l,error:p,page:h,pageSize:x,hasNextPage:I,hasPreviousPage:O,setPage:u,labels:N,setLabels:T,customerEmail:L,setCustomerEmail:S,q:k,setQ:F,from:y,setFrom:G,to:X,setTo:H,retainerId:ce,setRetainerId:j,refetch:K}=ks({refreshKey:a}),[z,se]=Ne.useState(typeof f=="number"?"all":"open"),[W,he]=Ne.useState(""),[Ze,it]=Ne.useState(null),Re=Ne.useRef(0),je=!g||!!r,et=Ne.useCallback($=>{if(g){r?.();return}Re.current++,At(!1),it($)},[g,r]),[xe,At]=Ne.useState(!1),[R,D]=Ne.useState(0),[E,ue]=Ne.useState(null),[me,Se]=Ne.useState(!1),[Ce,tt]=Ne.useState(0);Ne.useEffect(()=>{it($=>{if(!$)return $;let We=v.find(V=>V.id===$.id);return We&&We!==$?We:$})},[v]);let[$e,Ge]=Ne.useState(!1),[ie,Ae]=Ne.useState(null),ot=async()=>{if(!$e){Ge(!0),Ae(null);try{let{invoices:$,total:We,truncated:V}=await Eu(b,{labels:N,customerEmail:L,q:k,from:y,to:X,retainerId:ce});Iu($),Ae(V?`Exported the first ${$.length.toLocaleString()} of ${We.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ae("Couldn't export \u2014 try again.")}finally{Ge(!1)}}},sa=!L&&!k&&!y&&!X&&!ce,[ht,Et]=Ne.useState(null);Ne.useEffect(()=>{if(l||c>0||!sa||z!=="open")return;let $=!1;return b.getInvoices({limit:1}).then(We=>{$||Et(We.total>0)}).catch(()=>{$||Et(!0)}),()=>{$=!0}},[b,l,c,sa,z,a]),Ne.useEffect(()=>{T(g?Hn.all:Hn.open)},[]),Ne.useEffect(()=>{let $=m?.id??"";$!==ce&&(j($),$&&(se("all"),T(Hn.all),S(""),F(""),he(""),G(""),H("")))},[m?.id]),Ne.useEffect(()=>{let $=!1;return Se(!1),b.getInvoiceSettings().then(We=>{$||ue({payments_active:We.payments_active,blocked:We.blocked})}).catch(()=>{$||Se(!0)}),()=>{$=!0}},[b,a,Ce]),Ne.useEffect(()=>{if(!s||g)return;let $=!1,We=Re.current;return At(!1),b.getInvoice(s).then(V=>{!$&&We===Re.current&&it(V)}).catch(()=>{!$&&We===Re.current&&At(!0)}),()=>{$=!0}},[b,s,R,g]),Ne.useEffect(()=>{t?.(Ze!==null)},[Ze,t]);let Gt=$=>{se($),T(Hn[$])},Ve=$=>{let We=$.trim();if(!We){k&&F(""),L&&S("");return}if(We.includes("@")){k&&F(""),S(We);return}L&&S(""),F(We.replace(/^#/,""))},at=v,ts=g?at.slice(0,f):at,Vs=xe&&Y("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",C(w,{type:"button",variant:"link",size:"sm",onClick:()=>D($=>$+1),children:"Retry opening invoice"})]});if(Ze)return Y("div",{className:e,children:[Vs,C(Fr,{invoice:Ze,refreshKey:a,onBack:()=>{et(null),K()}},Ze.id)]});let Ot=Y("div",{className:"af-mb-4 af-space-y-3",children:[me&&Y("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",C(w,{type:"button",variant:"link",size:"sm",onClick:()=>tt($=>$+1),children:"Retry setup check"})]}),Vs,E?.blocked&&Y("div",{role:"alert",className:"af-rounded-md af-border af-border-destructive/40 af-bg-destructive/5 af-px-3 af-py-2 af-text-sm",children:["Invoicing is paused",E.blocked.reason?`: ${E.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),m&&Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[Y(te,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",m.label]}),d&&C(w,{type:"button",variant:"link",size:"sm",onClick:d,children:"Clear schedule filter"})]}),Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[C("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($=>C("button",{type:"button","aria-pressed":z===$,onClick:()=>Gt($),className:Z("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",z===$?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ji[$]},$))}),Y("div",{className:"af-relative af-w-full af-max-w-xs",children:[C(Pu,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),C(ge,{type:"text",value:W,onChange:$=>he($.target.value),onBlur:()=>Ve(W),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),Ve(W))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),Y("div",{className:"af-flex af-items-center af-gap-2",children:[C(ve,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),C(ge,{id:"invoices-from",type:"date",value:y,max:X||void 0,onChange:$=>G($.target.value),className:"af-invoice-date af-w-[150px]"})]}),Y("div",{className:"af-flex af-items-center af-gap-2",children:[C(ve,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),C(ge,{id:"invoices-to",type:"date",value:X,min:y||void 0,onChange:$=>H($.target.value),className:"af-invoice-date af-w-[150px]"})]}),Y(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ot(),disabled:$e||l||!!p||c===0,"aria-busy":$e,children:[C(Su,{className:"af-h-4 af-w-4 af-mr-1"}),$e?"Exporting\u2026":"Export CSV (all matching)"]})]}),ie&&C("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:ie})]});return l?Y("div",{className:e,children:[g?null:Ot,C("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map($=>Y("div",{className:"af-rounded-md af-border af-p-3",children:[Y("div",{className:"af-flex af-items-center af-justify-between",children:[C(ae,{className:"af-h-4 af-w-20"}),C(ae,{className:"af-h-4 af-w-16"})]}),C(ae,{className:"af-mt-2 af-h-3 af-w-40"})]},$))})]}):p?Y("div",{className:e,children:[g?null:Ot,Y("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",C(w,{type:"button",variant:"link",size:"sm",onClick:()=>void K(),children:"Retry"})]})]}):c===0&&sa&&(z==="all"||ht===!1)&&(z==="open"||z==="all")?E?.blocked?Y("div",{className:e,children:[g?null:Ot,C(zn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?Y("div",{className:e,children:[g?null:Ot,C(zn,{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?Y("div",{className:e,children:[g?null:Ot,C(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})]}):Y("div",{className:e,children:[g?null:Ot,C(zn,{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."})]}):Y("div",{className:e,children:[g?null:Ot,ts.length===0?C("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):Y(Lu,{children:[C("div",{className:"af-space-y-3 lg:af-hidden",children:ts.map($=>Y("button",{type:"button",onClick:()=>et($),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:[Y("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[C("span",{className:"af-font-medium",children:As($)}),C(Qs,{invoice:$})]}),C("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:$.customer_name??$.customer_email??"\u2014"}),$.delivery&&C("div",{className:"af-mt-1",children:C(qn,{delivery:$.delivery})}),Y("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[C("span",{children:$.collection_method==="charge_automatically"?"Automatic collection":$.due_at?`Due ${ya($.due_at)}`:"Due on receipt"}),C("span",{className:"af-font-medium af-tabular-nums",children:q($.amount_due??$.amount_total,$.currency)})]})]},$.id))}),C("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Y(Be,{children:[C(Fe,{children:Y(pe,{children:[C(M,{children:"Invoice"}),C(M,{children:"Created"}),C(M,{children:"Customer"}),C(M,{children:"Due"}),C(M,{className:"af-text-right",children:"Amount"}),C(M,{children:"Status"}),C(M,{children:"Delivery"}),C(M,{className:"af-w-8"})]})}),C(Me,{children:ts.map($=>Y(pe,{className:je?"af-cursor-pointer":void 0,onClick:je?()=>et($):void 0,children:[C(U,{className:"af-font-medium",children:C("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($)},"aria-label":`Open invoice ${As($)}`,children:As($)})}),C(U,{children:ya($.created_at)}),Y(U,{children:[C("div",{children:$.customer_name??"\u2014"}),C("div",{className:"af-text-xs af-text-muted-foreground",children:$.customer_email})]}),C(U,{children:$.collection_method==="charge_automatically"?"Automatic":$.due_at?ya($.due_at):"On receipt"}),C(U,{className:"af-text-right af-tabular-nums",children:q($.amount_due??$.amount_total,$.currency)}),C(U,{children:C(Qs,{invoice:$})}),C(U,{children:C(qn,{delivery:$.delivery})}),C(U,{children:C(Zi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},$.id))})]})}),g?null:Y("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[Y("span",{children:[c," invoice",c===1?"":"s"]}),Y("div",{className:"af-flex af-items-center af-gap-1",children:[C(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(h-1),disabled:!O,"aria-label":"Previous page",children:C(wu,{className:"af-h-4 af-w-4"})}),Y("span",{className:"af-tabular-nums",children:[h*x+1,"\u2013",Math.min((h+1)*x,c)]}),C(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(h+1),disabled:!I,"aria-label":"Next page",children:C(Zi,{className:"af-h-4 af-w-4"})})]})]})]})]})}function zn({heading:e,body:a,action:s}){return C(Ts,{icon:Qi,heading:e,body:a,action:s})}function us(e){return C(Du,{...e},e.maxRows==null?"full":"compact")}var Xa="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}=ne(),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),c=Ne.useRef(0),[l,p]=Ne.useState(null),[h,x]=Ne.useState(!1),[I,O]=Ne.useState(0);Ne.useEffect(()=>{let y=!1;return x(!1),n.getInvoice(e.id).then(G=>{y||p({source:e,value:G})}).catch(()=>{y||x(!0)}),()=>{y=!0}},[n,e,s,I]);let u=l?.source===e?l.value:e,N=u.collection_method==="charge_automatically";Ne.useEffect(()=>(c.current++,f(null),g(!1),v(!1),m(!1),()=>{c.current++}),[n,u,s]);let T=y=>y==null?"\u2014":q(y,u.currency),L=async()=>{if(!(!u.pay_url||!Yi()))try{await navigator.clipboard.writeText(u.pay_url),m(!0),setTimeout(()=>m(!1),1500)}catch{}},S=async()=>{if(d){f(null);return}let y=++c.current;v(!1),g(!0);try{let G=await n.getInvoicePreview(u.id);y===c.current&&f(G)}catch{y===c.current&&v(!0)}finally{y===c.current&&g(!1)}},k=u.bill_to,F=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 Y("div",{className:t,children:[Y("div",{className:"af-mb-4",children:[Y(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[C(xu,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),Y("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[Y("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",As(u)]}),C(Qs,{invoice:u}),C(qn,{delivery:u.delivery})]}),Y("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[u.customer_name??u.customer_email,u.customer_name&&u.customer_email?` \xB7 ${u.customer_email}`:""]})]}),h&&Y("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",C(w,{type:"button",variant:"link",size:"sm",onClick:()=>O(y=>y+1),children:"Retry details"})]}),u.label==="failed"&&C("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."}),u.label==="creating"&&C("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),Y("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[Y("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[Y("section",{className:"af-rounded-md af-border af-p-4",children:[Y(Be,{children:[C(Fe,{children:Y(pe,{children:[C(M,{children:"Description"}),C(M,{className:"af-text-right",children:"Qty"}),C(M,{className:"af-text-right",children:"Amount"})]})}),C(Me,{children:u.line_items.map((y,G)=>Y(pe,{children:[C(U,{style:{overflowWrap:"anywhere"},children:y.description}),C(U,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:y.quantity}),C(U,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(y.amount)})]},G))})]}),Y("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[C(cs,{label:"Subtotal",value:T(u.amount_subtotal)}),(u.discount_total??0)>0&&C(cs,{label:"Discount",value:`-${T(u.discount_total)}`}),u.tax_total>0&&C(cs,{label:u.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(u.tax_total)}),C(cs,{label:"Total",value:T(u.amount_total),strong:!0}),u.credit_applied>0&&C(cs,{label:"Credit applied",value:`-${T(u.credit_applied)}`}),u.amount_due!==null&&u.amount_due!==u.amount_total&&C(cs,{label:"Amount due",value:T(u.amount_due),strong:!0}),u.amount_paid!==null&&u.amount_paid>0&&C(cs,{label:"Amount paid",value:T(u.amount_paid)}),u.amount_refunded>0&&C(cs,{label:"Refunded",value:T(u.amount_refunded)})]}),u.credit_notes?.length>0&&Y("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[C("div",{className:Xa,children:"Credit notes"}),u.credit_notes.map(y=>Y("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[Y("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"]}),Y("span",{className:"af-tabular-nums",children:["-",q(y.amount,y.currency)]})]},y.id))]})]}),(u.note||u.footer)&&Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[u.note&&Y("div",{children:[C("div",{className:Xa,children:"Note"}),C("div",{className:"af-whitespace-pre-wrap af-break-words",children:u.note})]}),u.footer&&Y("div",{children:[C("div",{className:Xa,children:"Footer"}),C("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:u.footer})]})]}),d&&!N&&Y("section",{className:"af-rounded-md af-border af-p-4",children:[Y("div",{className:Z(Xa,"af-break-words"),children:["Email preview \u2014 ",d.subject]}),C("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),C("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"})]})]}),Y("div",{className:"af-min-w-0 af-space-y-4",children:[Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C(ba,{label:"Created",value:ya(u.created_at)}),C(ba,{label:"Due",value:u.collection_method==="charge_automatically"?"Managed in Stripe":u.due_at?ya(u.due_at):"On receipt"}),u.paid_at&&C(ba,{label:"Paid",value:ya(u.paid_at)}),u.payment_method&&C(ba,{label:"Paid by",value:u.paid_out_of_band?`${u.payment_method} (recorded outside Stripe)`:u.payment_method}),u.payment_state!=="none"&&C(ba,{label:"Payment",value:u.payment_state==="processing"?"Processing":u.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),u.delivery&&C(ba,{label:"Delivery",value:`${Or[u.delivery.state]} \xB7 ${u.delivery.recipient}`}),u.marked_uncollectible_at&&C(ba,{label:"Written off",value:ya(u.marked_uncollectible_at)}),u.correction_reason&&C(ba,{label:"Correction",value:u.correction_reason}),u.replaced_by_order_id&&C(ba,{label:"Replaced by",value:u.replaced_by_order_id}),u.collection_method==="charge_automatically"?C(ba,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):u.retainer_id&&C(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"}),u.replaces_order_id&&C(ba,{label:"Replaces",value:u.replaces_order_id})]}),Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C("div",{className:Xa,children:"Reminders"}),N?C("div",{children:"View automatic payment reminders in Stripe."}):u.reminders.disabled?C("div",{children:"Off for this invoice."}):u.reminders.paused_until?Y("div",{children:["Paused until ",ya(u.reminders.paused_until),"."]}):u.reminders.next_at?Y("div",{children:["Next on ",ya(u.reminders.next_at),"."]}):u.reminders.final_sent_at?Y("div",{children:["Final reminder sent ",ya(u.reminders.final_sent_at),"."]}):C("div",{children:"None scheduled."}),!N&&Y("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",u.reminders.schedule.length===0?"none":u.reminders.schedule.map(y=>y<0?`${-y}d before`:y===0?"due day":`${y}d after`).join(", ")]})]}),u.communications&&u.communications.length>0&&Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C("div",{className:Xa,children:"Email delivery history"}),u.communications.map(y=>Y("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[Y("span",{className:"af-min-w-0 af-break-words",children:[ku[y.kind]??y.kind,y.kind==="reminder"&&y.slot!==null?` #${y.slot}`:"",Y("span",{className:"af-text-muted-foreground",children:[" \xB7 ",y.recipient]})]}),Y("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))]}),F.length>0&&Y("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[C("div",{className:Xa,children:"Bill to"}),F.map((y,G)=>C("div",{className:"af-break-words",children:y},G))]}),Y("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[u.pay_url&&Y(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void L(),disabled:!Yi(),children:[C(Nu,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":N?"Copy invoice link":"Copy pay link"]}),u.pdf_url&&C(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:Y("a",{href:u.pdf_url,target:"_blank",rel:"noreferrer",children:[C(_u,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!N&&Y(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void S(),disabled:r,children:[r?C(Ru,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):C(Qi,{className:"af-h-4 af-w-4 af-mr-1"}),d?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!N&&C("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),u.pay_url&&C("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:u.pay_url}),C("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 Y("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[C("span",{className:Z(Xa,"af-shrink-0"),children:e}),C("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function cs({label:e,value:a,strong:s}){return Y("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[C("dt",{className:Z(Xa,s&&"af-font-medium af-text-foreground"),children:e}),C("dd",{className:Z("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as Ou}from"lucide-react";import{jsx as yt,jsxs as Ea}from"react/jsx-runtime";var Bu={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 Fu(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":Bu[e.status]}function ao(e){let a=e.interval==="year"?"every year":"every month";return`${q(e.amount,e.currency)} ${a}`}function Mu(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 yt(te,{variant:Fu(e.status),className:Z("af-max-w-full af-whitespace-normal af-break-words",a),children:to(e)})}function Es({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 c=o!==void 0?Math.max(0,o-e.length):0;return Ea("section",{className:Z("af-mb-6",b),"aria-label":"Recurring invoices",children:[Ea("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[yt(Ou,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),yt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),yt("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&&yt(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?Ea("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",yt(w,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?yt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>Ea("div",{className:"af-rounded-md af-border af-p-3",children:[yt(ae,{className:"af-h-4 af-w-48"}),yt(ae,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?yt("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."}):yt("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 Ea("li",{className:Z("af-rounded-md af-border af-p-3",p&&"af-border-primary af-bg-muted/40"),children:[Ea("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Ea("div",{className:"af-min-w-0",children:[yt("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),yt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),yt(Mr,{retainer:l})]}),l.collection_method==="charge_automatically"?Ea("div",{className:"af-mt-2 af-space-y-1",children:[yt(te,{variant:"secondary",children:"Managed in Stripe"}),yt("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."})]}):yt("div",{className:"af-mt-2 af-text-sm",children:ao(l)}),Ea("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:[Ea("span",{children:[Mu(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&&yt(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&&Ea("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&&f&&yt("div",{className:"af-mt-2",children:yt(w,{type:"button",variant:"outline",size:"sm",onClick:f,disabled:d,children:d?"Loading\u2026":`Load more (${c} more)`})})]})}import*as no from"react";import{AlertTriangle as so,CheckCircle2 as Uu,CreditCard as Ur,Loader2 as $u,RefreshCw as Vu}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(),[m,d]=no.useState(!1),f=async()=>{d(!0);try{await o()}finally{d(!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(Uu,{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(Ur,{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(Ur,{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(Ur,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Pt(w,{variant:"outline",onClick:f,disabled:m,children:[m?nt($u,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):nt(Vu,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Vt from"react";function $r(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function Is({includeStats:e=!1,refreshKey:a}={}){let{api:s}=ne(),[t,n]=Vt.useState([]),[i,o]=Vt.useState(!0),[m,d]=Vt.useState(null),f=Vt.useRef(0),r=Vt.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]);Vt.useEffect(()=>{r()},[r]);let g=Vt.useCallback(async p=>{let h=await s.createProduct(p);return n(x=>[h,...x]),h},[s]),b=Vt.useCallback(async(p,h)=>{let x=await s.updateProduct(p,h);return n(I=>$r(I,p,x)),x},[s]),v=Vt.useCallback(async p=>{await s.deleteProduct(p),n(h=>h.filter(x=>x.id!==p))},[s]),c=Vt.useCallback(async(p,h)=>{let x=await s.attachProductFile(p,h);return n(I=>$r(I,p,x)),x},[s]),l=Vt.useCallback(async(p,h)=>{let x=await s.attachProductFileFromUrl(p,h);return n(I=>$r(I,p,x)),x},[s]);return{products:t,isLoading:i,error:m,refetch:r,createProduct:g,updateProduct:b,deleteProduct:v,attachProductFile:c,attachProductFileFromUrl:l}}import*as Ht from"react";var ro=["creating","active","paused","canceling"],Hu=["canceled","failed"];function Ds({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=ne(),[n,i]=Ht.useState([]),[o,m]=Ht.useState(0),[d,f]=Ht.useState(0),[r,g]=Ht.useState(!0),[b,v]=Ht.useState(!1),[c,l]=Ht.useState(null),[p,h]=Ht.useState(a),x=Ht.useRef(0),I=Ht.useCallback(async()=>{let u=++x.current;g(!0),v(!1),l(null);try{let N=await t.getRetainers({statuses:p?void 0:ro,limit:s,offset:0});if(u!==x.current)return;if(i(N.retainers),m(N.total),!p&&N.total===0){let T=await t.getRetainers({statuses:Hu,limit:1,offset:0});if(u!==x.current)return;f(T.total)}else f(0)}catch(N){if(u!==x.current)return;l(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{u===x.current&&g(!1)}},[t,p,s]);Ht.useEffect(()=>{I()},[I,e]);let O=Ht.useCallback(async()=>{if(r||b||n.length>=o)return;let u=x.current;v(!0);try{let N=await t.getRetainers({statuses:p?void 0:ro,limit:s,offset:n.length});if(u!==x.current)return;i(T=>{let L=new Set(T.map(S=>S.id));return[...T,...N.retainers.filter(S=>!L.has(S.id))]}),m(N.total)}catch(N){if(u!==x.current)return;l(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{u===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:c,includeEnded:p,setIncludeEnded:h,loadMore:O,refetch:I}}import{Fragment as Ju,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]=Ls.useState(a),[m,d]=Ls.useState("list"),[f,r]=Ls.useState(null),g=Is(),{status:b,error:v}=is(),c=b?.currency,l=I=>{r(I),d("edit")},p=()=>{r(null),d("create")},h=()=>{d("list"),r(null)},x=I=>{r(I),d("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:I=>o(I),children:[Xt(js,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Xt(wa,{value:"products",className:"af-gap-2",children:[ze(ju,{className:"af-h-4 af-w-4"}),"Products"]}),Xt(wa,{value:"orders",className:"af-gap-2",children:[ze(Gu,{className:"af-h-4 af-w-4"}),"Orders"]}),Xt(wa,{value:"invoices",className:"af-gap-2",children:[ze(qu,{className:"af-h-4 af-w-4"}),"Invoices"]}),Xt(wa,{value:"customers",className:"af-gap-2",children:[ze(Ku,{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(Wu,{className:"af-h-4 af-w-4"}),"Setup"]})]}),ze(Na,{value:"products",children:m==="list"?ze(Pn,{productsState:g,onSelectProduct:l,onCreateProduct:p}):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(zu,{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"&&!c?ze("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:v?Xt("div",{className:"af-text-destructive",children:["Error: ",v.message]}):ze("div",{className:"af-text-muted-foreground",children:"Loading..."})}):ze(Tn,{productsState:g,product:m==="edit"?f:null,currency:c??"usd",onSaved:x},m==="edit"?f?.id??"edit":"new")]})}),ze(Na,{value:"orders",children:ze(ls,{onRefund:t})}),ze(Na,{value:"invoices",children:ze(Zu,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:b?.reason==="needs_paid_plan"})}),ze(Na,{value:"customers",children:ze(Vn,{})}),ze(Na,{value:"promos",children:ze(Ps,{})}),ze(Na,{value:"setup",children:ze(Gn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Zu({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=Ds(),[n,i]=Ls.useState(null),[o,m]=Ls.useState(!1);return Xt(Ju,{children:[!o&&ze(Es,{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(us,{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 lo from"react";import*as Va from"react";function Os({refreshKey:e}={}){let{api:a}=ne(),[s,t]=Va.useState(null),[n,i]=Va.useState(!0),[o,m]=Va.useState(null),d=Va.useRef(0),f=Va.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 Va.useEffect(()=>{f()},[f]),{summary:s,isLoading:n,error:o,refetch:f}}import{Fragment as Vr,jsx as Ct,jsxs as Hr}from"react/jsx-runtime";function oo(e,a){if(e.settled.complete)return{headline:q(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:q(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${q(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:q(0,a),extra:[]}}function co({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:m,error:d,refetch:f}=Os({refreshKey:e}),[r,g]=lo.useState(!1),b=Ct("div",{className:"af-mb-6",children:d&&!o?Ct(la,{message:"Couldn't load your revenue summary.",onRetry:()=>f()}):Ct("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!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 v=oo(o.revenue.d7,o.currency),c=oo(o.revenue.today,o.currency);return Hr(Vr,{children:[Ct(st,{label:"This week",detail:v.extra.length>0?Ct("div",{children:v.extra.map(l=>Ct("div",{children:l},l))}):void 0,children:v.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(wt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[b,Ct(ls,{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 za from"react";import{ImageOff as td,Package as ad,Search as sd}from"lucide-react";import*as Ha from"react";import{ArrowLeft as Xu,ImageOff as ed}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",Yu=3;function Qu(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 (${q(d,s)} \u2013 ${q(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?q(n,s):`${q(n,s)} \u2013 ${q(i,s)}`,m=a?.compare_at_amount??null;return{text:o,compareAt:m!==null&&m>i?q(m,s):null}}function Kn({product:e,className:a}){let s=Qu(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=>q(a.amount,a.currency)).join(" + ")}function fo(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${q(e.min_amount,e.currency)} \u2013 ${q(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":q(e.unit_amount,e.currency)}function 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<=Yu&&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:Z("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:Z("af-flex af-items-center af-justify-center af-bg-muted",a),children:le(ed,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):le("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:Z("af-object-cover",a)})}function go({product:e,showStats:a=!1,onBack:s}){let{api:t}=ne(),[n,i]=Ha.useState(null),[o,m]=Ha.useState(!0),[d,f]=Ha.useState(null),[r,g]=Ha.useState(0),[b,v]=Ha.useState(0);Ha.useEffect(()=>{let u=!1;return m(!0),f(null),t.getProduct(e.id).then(N=>{u||i(N)}).catch(N=>{u||f(N instanceof Error?N:new Error("Failed to load product"))}).finally(()=>{u||m(!1)}),()=>{u=!0}},[t,e.id,r]);let c=n?{...e,...n}:e,l=c.images.length>0?c.images:e.images,p=l[b]??l[0],h=Jn(c),x=a?c.stats:void 0,I=n?.variants??[],O=I.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(Xu,{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: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((u,N)=>le("button",{type:"button",onClick:()=>v(N),"aria-label":`Show photo ${N+1} of ${l.length}`,"aria-pressed":N===b,className:Z("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:u,className:"af-h-12 af-w-12 af-rounded-md"})},`${u}-${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(u=>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"})]},u))}),le("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):d?le(la,{message:"Couldn't load this product's variants.",onRetry:()=>g(u=>u+1)}):O?le(en,{title:`Variants \xB7 ${I.length}`,children:le("div",{className:"af-overflow-x-auto",children:Ye(Be,{children:[le(Fe,{children:Ye(pe,{children:[le(M,{children:"Variant"}),le(M,{children:"SKU"}),le(M,{className:"af-text-right",children:"Price"}),le(M,{children:"Stock"})]})}),le(Me,{children:I.map(u=>Ye(pe,{children:[Ye(U,{className:"af-font-medium",children:[u.title||u.option_values.map(N=>N.value).join(" / ")||"\u2014",!u.active&&le(te,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),le(U,{className:"af-text-muted-foreground",children:u.sku?le("code",{className:"af-font-mono af-text-xs af-break-all",children:u.sku}):"\u2014"}),Ye(U,{className:"af-whitespace-nowrap af-text-right",children:[le("div",{className:Wn,children:fo(u)}),u.compare_at_amount!==null&&u.unit_amount!==null&&u.compare_at_amount>u.unit_amount&&le("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:q(u.compare_at_amount,u.currency)})]}),le(U,{className:"af-text-sm",children:le(mo,{variant:u})})]},u.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 nd={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},rd=["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 id(e){return e.inventory?.out_of_stock??!1}function od(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 id(e);default:return!0}}function ld({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(td,{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 cd(){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:m}=Is({includeStats:a,refreshKey:e}),[d,f]=za.useState(!1),[r,g]=za.useState(null),[b,v]=za.useState("all"),[c,l]=za.useState(""),[p,h]=za.useState("newest"),x=za.useMemo(()=>{if(!a)return null;let y=null;for(let G of n)!G.stats||G.stats.units_sold===0||(!y||G.stats.units_sold>(y.stats?.units_sold??0))&&(y=G);return y},[n,a]),I=za.useMemo(()=>n.filter(bo).length,[n]),O=c.trim().toLowerCase(),u=za.useMemo(()=>{let G=[...n.filter(X=>od(X,b)&&(!O||X.name.toLowerCase().includes(O)))];return p==="name"?G.sort((X,H)=>X.name.localeCompare(H.name)):p==="best_selling"?G.sort((X,H)=>(H.stats?.units_sold??0)-(X.stats?.units_sold??0)):G.sort((X,H)=>vo(H.created_at)-vo(X.created_at)),G},[n,b,O,p]),N=b!=="all"||!!O,T=()=>{v("all"),l("")},L=i||o!==null&&n.length===0,S=re("div",{className:"af-mb-6",children:re("div",{className:Z("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:L?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:I})]}):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:rd.map(y=>re("button",{type:"button","aria-pressed":b===y,onClick:()=>v(y),className:Z("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:nd[y]},y))}),Qe("div",{className:"af-relative af-w-full af-max-w-xs",children:[re(sd,{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:p,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:T,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?`${u.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${I>0?` \xB7 ${I} low stock`:""}`})]}),F;return r?F=re(go,{product:r,showStats:a,onBack:()=>{g(null),m()}},r.id):i&&n.length===0?F=Qe(fs,{children:[k,re(cd,{}),re("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?F=re("div",{className:"af-flex af-justify-center af-py-8",children:re(la,{message:"Couldn't load your products.",onRetry:()=>m()})}):n.length===0?F=Qe(Aa,{icon:re(ad,{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."]}):F=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:()=>m()})}),u.length===0?Qe(Aa,{children:["No products match these filters.",re("br",{}),re(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:T,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:u.map(y=>re(ld,{product:y,showStats:a,onOpen:()=>g(y)},y.id))})]}),re(wt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:d?Qe(fs,{children:[re(w,{variant:"ghost",onClick:()=>f(!1),children:"Back to products"}),re(Ps,{})]}):Qe(fs,{children:[!r&&re("div",{className:"af-mb-4 af-flex af-justify-end",children:re(w,{variant:"outline",onClick:()=>f(!0),children:"Promo codes"})}),!r&&S,F]})})}import*as Da from"react";import{ArrowLeft as So,Check as ud,ChevronLeft as ho,ChevronRight as xo,ClipboardCopy as dd,Mail as qr,Search as fd,Users as md}from"lucide-react";import*as ca from"react";function Qn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ne(),[t,n]=ca.useState([]),[i,o]=ca.useState(!0),[m,d]=ca.useState(null),[f,r]=ca.useState(0),[g]=ca.useState(e),[b,v]=ca.useState(""),c=ca.useRef(0),l=ca.useCallback(async()=>{let p=++c.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!==c.current)return;n(x.people)}catch(h){if(p!==c.current)return;d(h instanceof Error?h:new Error("Failed to fetch people"))}finally{p===c.current&&o(!1)}},[s,f,g,b,a]);return ca.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 qa from"react";function Xn(e,{refreshKey:a}={}){let{api:s}=ne(),[t,n]=qa.useState(null),[i,o]=qa.useState(e!==null),[m,d]=qa.useState(null),f=qa.useRef(0),r=qa.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 qa.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:m,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",pd="af-text-xs af-text-muted-foreground";function Bs(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 gd(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function vd({value:e,label:a}){let[s,t]=Da.useState(!1);return gd()?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?_(ud,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):_(dd,{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 bd=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,yd=40;function hd(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>bd.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=yd).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 xd(e){return e.replace(/_/g," ")}function wd(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Nd({data:e}){let{message:a,rest:s}=hd(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:Z(pd,"af-w-28 af-shrink-0 af-capitalize"),children:xd(t)}),_("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:wd(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:Bs(a)})]}),_(Nd,{data:s})]})}function Sd(e){return e.charged_total??e.amount_total}function _d({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=Xn(e,{refreshKey:a}),m=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}),_(vd,{value:e,label:"Copy email address"})]})]}),_(w,{asChild:!0,children:oe("a",{href:m,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(d=>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"})]},d)),_("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:Z(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:Bs(t.customer.created_at)})]})]})]}),t.orders.length>0&&oe("div",{children:[_("h4",{className:Z(zr,"af-mb-3"),children:"Purchases"}),_("div",{className:"af-overflow-x-auto",children:oe(Be,{children:[_(Fe,{children:oe(pe,{children:[_(M,{children:"Order"}),_(M,{children:"Date"}),_(M,{className:"af-text-right",children:"Total"}),_(M,{children:"Status"})]})}),_(Me,{children:t.orders.map(d=>oe(pe,{children:[_(U,{className:"af-whitespace-nowrap af-font-medium",children:Qa(d)}),_(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bs(d.created_at)}),_(U,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:q(Sd(d),d.currency)}),_(U,{children:_(ys,{status:d.status})})]},d.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:Z(zr,"af-mb-3"),children:"Messages"}),_("div",{className:"af-space-y-3",children:t.submissions.map(d=>_(_o,{formName:d.form_name,createdAt:d.created_at,data:d.data},d.id))})]})]})]})}function Rd({submissionId:e,onBack:a}){let{api:s}=ne(),[t,n]=Da.useState(null),[i,o]=Da.useState(!0),[m,d]=Da.useState(null),[f,r]=Da.useState(0);return Da.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:[_(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:Bs(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"})]}):m||!t?_("div",{className:"af-flex af-justify-center af-py-8",children:_(la,{message:"Couldn't load this submission.",onRetry:()=>r(g=>g+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 Pd={all:"All",customers:"Customers",leads:"Leads"},Cd=["all","customers","leads"];function Td(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function kd({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:c,setQ:l,refetch:p}=Qn({refreshKey:e}),[h,x]=Da.useState({kind:"list"}),[I,O]=Da.useState(""),[u,N]=Da.useState("all"),T=!i||!!n,L=X=>{if(i){n?.();return}X.email?x({kind:"person",email:X.email}):X.submission_id&&x({kind:"submission",submissionId:X.submission_id})},S=()=>{x({kind:"list"}),p()},k=X=>{let H=X.trim();H!==c&&l(H)},F=o.filter(X=>Td(X,u)),y=i?F.slice(0,t):F,G;if(h.kind==="person")G=_(_d,{email:h.email,refreshKey:e,onBack:S});else if(h.kind==="submission")G=_(Rd,{submissionId:h.submissionId,onBack:S});else{let X=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:Cd.map(H=>_("button",{type:"button","aria-pressed":u===H,onClick:()=>N(H),className:Z("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",u===H?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Pd[H]},H))}),oe("div",{className:"af-relative af-w-full af-max-w-xs",children:[_(fd,{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:I,onChange:H=>O(H.target.value),onBlur:()=>k(I),onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),k(I))},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:()=>{O(""),l("")},children:"Clear search"})]});if(m)G=oe("div",{children:[i?null:X,_("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(H=>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"})]},H))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[_(Fe,{children:oe(pe,{children:[_(M,{children:"Person"}),_(M,{children:"Came from"}),_(M,{children:"Latest message"}),_(M,{children:"Last activity"}),_(M,{className:"af-w-8"}),_(M,{className:"af-w-8"})]})}),_(Me,{"aria-hidden":"true",children:[0,1,2,3,4].map(H=>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,{})]},H))})]})}),_("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(d)G=oe("div",{children:[i?null:X,_("div",{className:"af-flex af-justify-center af-py-8",children:_(la,{message:"Couldn't load your leads.",onRetry:()=>p()})})]});else if(y.length===0&&f===0){let H=!!c||u!=="all";G=oe("div",{children:[H&&X,H?_(Aa,{children:c?"Nobody matches that search.":u==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):_(Ts,{icon:md,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)G=oe("div",{children:[i?null:X,_(Aa,{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:()=>v(f-1),children:[_(ho,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let H=f*r+1,ce=f*r+o.length;G=oe("div",{children:[i?null:X,_("div",{className:"af-space-y-3 lg:af-hidden",children:y.map((j,K)=>oe("div",{onClick:T?()=>L(j):void 0,className:`af-rounded-md af-border af-p-3${T?" 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:z=>{z.stopPropagation(),L(j)},disabled:!T,"aria-label":`Open ${j.name||j.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${T?" hover:af-underline":""}`,children:No(j)}),j.name&&j.email&&_("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:j.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:Bs(j.last_activity_at)}),j.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:jr(j.email),onClick:z=>z.stopPropagation(),"aria-label":`Email ${j.email}`,children:_(qr,{className:"af-h-4 af-w-4"})})})]})]}),_("div",{className:"af-mt-2",children:wo(j)}),j.latest_message_excerpt&&_("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:j.latest_message_excerpt})]},j.email??j.submission_id??K))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:oe(Be,{children:[_(Fe,{children:oe(pe,{children:[_(M,{children:"Person"}),_(M,{children:"Came from"}),_(M,{children:"Latest message"}),_(M,{children:"Last activity"}),_(M,{className:"af-w-8",children:_("span",{className:"af-sr-only",children:"Reply"})}),_(M,{className:"af-w-8"})]})}),_(Me,{children:y.map((j,K)=>oe(pe,{onClick:T?()=>L(j):void 0,className:T?"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:z=>{z.stopPropagation(),L(j)},disabled:!T,"aria-label":`Open ${j.name||j.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${T?" hover:af-underline":""}`,children:No(j)}),j.name&&j.email&&_("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:j.email})]}),_(U,{children:wo(j)}),_(U,{className:"af-max-w-[320px]",children:j.latest_message_excerpt?_("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:j.latest_message_excerpt}):_("span",{className:"af-text-muted-foreground",children:"\u2014"})}),_(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bs(j.last_activity_at)}),_(U,{className:"af-w-8",children:j.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:jr(j.email),onClick:z=>z.stopPropagation(),"aria-label":`Email ${j.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"})})]},j.email??j.submission_id??K))})]})}),!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:u==="all"?`Showing ${H}-${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:[_(ho,{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",_(xo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?_("div",{className:s,children:G}):_(wt,{title:"Leads",onBackToWebsite:a,hideBackButton:h.kind!=="list",className:s,children:G})}function er(e){return _(kd,{...e},e.maxRows==null?"full":"compact")}import{ChevronLeft as Ro,ChevronRight as Ad,Repeat as Ed}from"lucide-react";import*as ea from"react";function tr({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ne(),[t,n]=ea.useState([]),[i,o]=ea.useState(0),[m,d]=ea.useState(!0),[f,r]=ea.useState(null),[g,b]=ea.useState(0),[v,c]=ea.useState(e),[l,p]=ea.useState(void 0),h=ea.useRef(0),x=ea.useCallback(async()=>{let O=++h.current;try{d(!0),r(null);let u={limit:v,offset:g*v};l&&(u.status=l);let N=await s.getSubscriptions(u);if(O!==h.current)return;n(N.subscriptions),o(N.total)}catch(u){if(O!==h.current)return;r(u instanceof Error?u:new Error("Failed to fetch subscriptions"))}finally{O===h.current&&d(!1)}},[s,g,v,l,a]);ea.useEffect(()=>{x()},[x]);let I=Math.ceil(i/v);return{subscriptions:t,total:i,isLoading:m,error:f,page:g,pageSize:v,hasNextPage:g<I-1,hasPreviousPage:g>0,setPage:b,setPageSize:O=>{c(O),b(0)},status:l,setStatus:O=>{p(O),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 Id(e,a){let s=q(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:Id(e,e.current_amount)}),a&&Xe("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",q(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 Ao({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}=tr({refreshKey:e}),v;if(i)v=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(M,{children:"Subscriber"}),ee(M,{children:"Plan"}),ee(M,{className:"af-text-right",children:"Amount"}),ee(M,{children:"Renews"}),ee(M,{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)v=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&&m===0)v=ee(Aa,{icon:ee(Ed,{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=Xe("div",{children:[ee(Aa,{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:()=>g(m-1),children:[ee(Ro,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=m*d+1,l=m*d+t.length;v=Xe("div",{children:[ee("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(p=>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: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(To,{sub:p})})]}),Xe("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(Co,{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:ko(p)})]}),ee(Oa,{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:Xe(Be,{children:[ee(Fe,{children:Xe(pe,{children:[ee(M,{children:"Subscriber"}),ee(M,{children:"Plan"}),ee(M,{className:"af-text-right",children:"Amount"}),ee(M,{children:"Renews"}),ee(M,{children:"Status"})]})}),ee(Me,{children:t.map(p=>Xe(pe,{children:[ee(U,{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(U,{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(U,{className:"af-whitespace-nowrap af-text-right",children:ee(To,{sub:p})}),ee(U,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ko(p)}),Xe(U,{children:[Xe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ee(Co,{sub:p}),p.is_test&&ee(te,{variant:"outline",children:"Test"})]}),ee(Oa,{deliveries:p.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},p.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:()=>g(m-1),disabled:!r,children:[ee(Ro,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Xe(w,{variant:"outline",size:"sm",onClick:()=>g(m+1),disabled:!f,children:["Next",ee(Ad,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return ee(wt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:v})}import*as Gr from"react";import{Fragment as Eo,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:m,isLoading:d,error:f,refetch:r}=ks({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=Ds({refreshKey:e}),[b,v]=Gr.useState(!1),[c,l]=Gr.useState(null),p=ua("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!d&&!m?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"})]}):d||!m?ar(Eo,{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(Eo,{children:[ua(st,{label:"Outstanding",detail:`${m.outstanding.count} open`,children:q(m.outstanding.amount,m.currency)}),ua(st,{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:q(m.overdue.amount,m.currency)}),ua(st,{label:"Paid this month",detail:`${m.paid_this_month.count} paid`,children:q(m.paid_this_month.amount,m.currency)})]})});return ar(wt,{title:"Invoices",onBackToWebsite:s,hideBackButton:b,className:o,children:[p,!b&&ua(Es,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:c?.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}),ua(us,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:v,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 Nt from"react";var Dd=2e3,Lt=()=>({data:null,error:null,isLoading:!0});function Fs(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=ne(),[i,o]=Nt.useState(Lt),[m,d]=Nt.useState(Lt),[f,r]=Nt.useState(Lt),[g,b]=Nt.useState(Lt),[v,c]=Nt.useState(Lt),l=z=>Object.fromEntries(z.map(se=>[se,Lt()])),[p,h]=Nt.useState(()=>l(s)),x=Nt.useRef(0),I=Nt.useRef(0),O=Nt.useRef("idle"),u=s.join(","),N=as()??"",T=JSON.stringify(t),L=`${e}:${u}:${T}:${N}`,[S,k]=Nt.useState({api:n,fetchIdentity:L});(S.api!==n||S.fetchIdentity!==L)&&(k({api:n,fetchIdentity:L}),x.current+=1,o(Lt),d(Lt),r(Lt),b(Lt),h(l(u?u.split(","):[])));let F=`${e}:${String(a??"")}:${N}`,[y,G]=Nt.useState({api:n,conversionsIdentity:F});(y.api!==n||y.conversionsIdentity!==F)&&(G({api:n,conversionsIdentity:F}),I.current+=1,O.current="idle",c(Lt));let X=Nt.useCallback(async z=>{let se=++x.current,W=u?u.split(","):[];o(Lt),d(Lt),r(Lt),b(Lt),h(Object.fromEntries(W.map(R=>[R,Lt()])));let he=O.current!=="pending"&&(z?.force===!0||O.current==="idle"),Ze=(R,D)=>D.then(E=>{se===x.current&&R({data:E,error:null,isLoading:!1})},E=>{se===x.current&&R({data:null,error:E instanceof Error?E:new Error("Failed to fetch report"),isLoading:!1})}),it=n.getAnalyticsStatus(),Re=Ze(o,it),je=Symbol("status-timeout"),et,xe=await Promise.race([it.then(R=>R,()=>null),new Promise(R=>{et=setTimeout(()=>R(je),Dd)})]);if(clearTimeout(et),se!==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 R={data:null,error:null,isLoading:!1};d(R),r(R),b(R),h(Object.fromEntries(W.map(D=>[D,{...R}]))),he&&(c(R),O.current="done"),await Re;return}await Promise.all([xe===je?Promise.resolve():Re,Ze(d,n.getAnalyticsSummary(e,t)),Ze(r,n.getAnalyticsTimeseries(e,t)),Ze(b,n.getAnalyticsChannels(e,t)),he?(()=>{O.current="pending";let R=++I.current;return c(Lt),n.getAnalyticsConversions(e).then(D=>{R===I.current&&(c({data:D,error:null,isLoading:!1}),O.current="done")},D=>{R===I.current&&(c({data:null,error:D instanceof Error?D:new Error("Failed to fetch report"),isLoading:!1}),O.current="done")})})():Promise.resolve(),...W.map(R=>n.getAnalyticsBreakdown(R,e,t).then(D=>{se===x.current&&h(E=>({...E,[R]:{data:D,error:null,isLoading:!1}}))},D=>{se===x.current&&h(E=>({...E,[R]:{data:null,error:D instanceof Error?D:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,u,T,F,N]),H=Nt.useCallback(async()=>{let z=x.current;try{let se=await n.getAnalyticsStatus();if(z!==x.current)return;o({data:se,error:null,isLoading:!1})}catch(se){if(z!==x.current)return;o(W=>({data:W.data,error:se instanceof Error?se:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),ce=Nt.useCallback(()=>X({force:!0}),[X]);Nt.useEffect(()=>{X()},[X,a]);let j=i.isLoading||m.isLoading||f.isLoading||g.isLoading||v.isLoading||Object.values(p).some(z=>z.isLoading),K=[f,m,g,v,...Object.values(p)].map(z=>z.data?.status==="ok"?z.data.timezone:void 0).find(z=>z!==void 0);return{status:i,summary:m,timeseries:f,channels:g,conversions:v,breakdowns:p,reportedZone:K,isLoading:j,refetch:ce,refetchStatus:H}}import*as St 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}=ne(),[o,m]=St.useState(null),[d,f]=St.useState(null),[r,g]=St.useState(!1),[b,v]=St.useState(null),[c,l]=St.useState(!1),[p,h]=St.useState(!0),[x,I]=St.useState(0),O=St.useRef(0),u=St.useRef(0),N=St.useRef(void 0);s!==void 0&&(N.current=s);let T=a?N.current===!0||N.current===void 0&&t:!0,[L,S]=St.useState({api:i,identity:n}),k=n!==void 0&&n!==L.identity;(L.api!==i||k)&&(N.current=void 0,S({api:i,identity:n}),u.current+=1,O.current=0,m(null),f(null),g(!1),v(null),l(!1),h(!0),I(0));let F=St.useRef(()=>{}),y=St.useRef(null),G=St.useCallback(async()=>{if(y.current!==null&&y.current===u.current)return;let X=++u.current;y.current=X;try{let H=await i.getAnalyticsRealtime();if(X!==u.current)return;if(H.status==="unreachable"){l(!0),g(!0),h(!1),I(ce=>ce+1);return}O.current=0,l(!1),m(H.data.current_visitors),f(H.as_of),g(!1),v(null),h(!1),I(ce=>ce+1)}catch(H){if(X!==u.current)return;O.current+=1,h(!1),I(ce=>ce+1),g(!0),O.current>=Kr&&v(H instanceof Error?H:new Error("Realtime unavailable"))}finally{y.current===X&&(y.current=null)}},[i]);return F.current=()=>void G(),St.useEffect(()=>{let X,H=()=>{X===void 0&&(X=setInterval(()=>F.current(),Wr))},ce=()=>{X!==void 0&&(clearInterval(X),X=void 0)},j=()=>{typeof document<"u"&&document.hidden?ce():(F.current(),H())};return T?((typeof document>"u"||!document.hidden)&&(F.current(),H()),document?.addEventListener("visibilitychange",j),()=>{ce(),document?.removeEventListener("visibilitychange",j),u.current+=1}):()=>{document?.removeEventListener("visibilitychange",j)}},[L.api,L.identity,T]),{currentVisitors:o,asOf:d,isStale:r,error:b,isUnreachable:c,isInitialLoad:p,polls:x}}import*as rt from"react";import*as Lo from"react";import{jsx as Zr,jsxs as Do}from"react/jsx-runtime";function Ld(){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=zs(),n=a===null&&t!==null&&e===t,i=Lo.useMemo(()=>{let o=Ld();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 Od=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(),Od))},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=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 Bd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function zt(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?zt(o*t):`${o}${n}`}return String(e)}function Ms(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 Uo(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`${Bd[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 Fd(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function $o(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=Fd(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 Ud,jsx as ms,jsxs as Md}from"react/jsx-runtime";function Ho({what:e="This report",onRetry:a,collecting:s}){return Md("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 es({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(Ud,{children:o(e.data)})}import{Fragment as $d,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:m,maxRows:d=9}){let[f,r]=Ns.useState(!1);if(e.length===0)return ta(ir,{what:i});let g=e.reduce((c,l)=>Math.max(c,Number(l[s]??0)),0)||1,b=Math.max(0,e.length-d),v=f?e:e.slice(0,d);return ws($d,{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:v.map((c,l)=>{let p=Number(c[s]??0),h=c[a]??null,x=sn(h),I=n?c[n]:null,O=h!==null&&(m?m(h,I):!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,p/g*100)}%`}}),h!==null&&o&&O?ta("button",{type:"button",onClick:()=>o(h,I),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}),I?ta("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:I}):null]}),ta("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:zt(p)})]},`${x}-${I??""}-${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:f?"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(v=>v.id===n)??a[0],m=Ns.useId(),d=v=>`${m}-tab-${v}`,f=v=>`${m}-panel-${v}`,r=Ns.useRef(null),g=(v,c)=>{v.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:v=>{let c=a.findIndex(l=>l.id===n);v.key==="ArrowRight"&&g(v,c+1),v.key==="ArrowLeft"&&g(v,c-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=>ta("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?ta("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 aa from"react";import*as ps from"@radix-ui/react-popover";var Us=3,$s=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"},Vd=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 Hd(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 zd(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=Hd(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 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,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"}`)),ft(qd,{...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 qd({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,m]=aa.useState(!1),d=aa.useRef(null),[f,r]=aa.useState(null);aa.useEffect(()=>{r(d.current?.closest(".aifeatures-admin")??null)},[]);let[g,b]=aa.useState(null),[v,c]=aa.useState("is"),[l,p]=aa.useState(""),[h,x]=aa.useState([]);aa.useEffect(()=>{o||(b(null),c("is"),p(""),x([]))},[o]);let I=aa.useRef(t);I.current!==t&&(I.current=t,o&&m(!1),g!==null&&b(null),h.length>0&&x([]),l!==""&&p(""),v!=="is"&&c("is"));let O=k=>{let F=zd(k);b(F.dimension),x(F.picked),p(F.search),c(F.operator)},N=(g?s[g]??[]:[]).filter(k=>k.toLowerCase().includes(l.trim().toLowerCase())),T=g===null||h.length===0?null:Xr(e,{dimension:g,operator:v,values:i?i(g,h):h}),L=T!==null&&T!==e,S=()=>{let k=T;!k||k===e||(a(k),m(!1))};return ja(ps.Root,{open:o,onOpenChange:m,children:[ft(ps.Trigger,{asChild:!0,children:ft("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"})}),ft(ps.Portal,{container:f,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:g===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:Vd.filter(k=>s[k]!==void 0).map(k=>{let F=s[k]?.length??0,y=!e.some(G=>G.dimension===k)&&e.length>=3;return ja("button",{type:"button",onClick:()=>O(k),disabled:F===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:F===0?"no data":y?"no room":F})]},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:()=>O(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[g]}),ja("select",{"aria-label":"Operator",value:v,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=>p(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${rn[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"}),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:F=>x(y=>F.target.checked?[...y,k]:y.filter(G=>G!==k))}),ft("span",{className:"af-break-all",children:sn(k)})]},k))}),ft("button",{type:"button",onClick:S,disabled:!L,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 Wd,jsx as qt,jsxs as or}from"react/jsx-runtime";var jd=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:zt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:zt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:zt,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:Ms,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:an,chart:"visit_duration_seconds"}];function Gd({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 qt("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 qt("div",{className:"af-@container",children:qt("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:jd.map(t=>{let n=t.chart===a,i=s!==void 0,o=or(Wd,{children:[qt("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:[qt("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?qt(Gd,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?qt("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):qt("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:[qt("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),qt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return qt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?Uo(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 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:d,children:[qt("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"}),qt("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),qt("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),qt("span",{className:"af-sr-only",children:d})]})}import*as Zo from"react";import{Star as Kd}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[m,d]=Zo.useState(!1),f=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||lr(p,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(f.length===0)return Ss(Ko,{children:[Tt(ir,{what:n}),r]});let g=f.slice(0,i),b=o?f.find(p=>lr(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,c=m?e:v,l=Math.max(0,e.length-v.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((p,h)=>Ss("tr",{className:"af-border-t af-border-border","aria-current":lr(p,o)?"true":void 0,children:[Tt("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:lr(p,o)?Ss("span",{className:"af-flex af-items-center af-gap-1.5",children:[Tt(Kd,{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:p.goal}),Tt("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),Tt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:zt(p.visitors)}),Tt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:zt(p.events)}),Tt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?Tt("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Ms(p.conversion_rate)})]},`${p.goal}-${h}`))})]}),l>0?Tt("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,Ss("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",zt(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),r]})}import{Area as Zd,AreaChart as Jd,CartesianGrid as Yd,ResponsiveContainer as Qd,Tooltip as Xd,XAxis as ef,YAxis as tf}from"recharts";import{jsx as jt,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:zt,visits:zt,pageviews:zt,views_per_visit:e=>e.toFixed(2),bounce_rate:Ms,visit_duration_seconds:an},af=31,sf=new Set(["visitors","visits","pageviews"]),nf={...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],rf=[5,10,15,30,60,120,300,600,900,1800,3600,7200],of=[.01,.02,.05,.1,.2,.25,.5,1],lf=[.25,.5,1,2,5,10,25,50],cf={visitors:ti,visits:ti,pageviews:ti,views_per_visit:lf,bounce_rate:of,visit_duration_seconds:rf};function uf({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:[jt("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:[jt("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),jt("span",{className:"af-text-muted-foreground",children:Vo(String(s))}),jt("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=$o(a,e,t),o=ai[s],m=nf[s],d=Mo(i.reduce((r,g)=>Math.max(r,Number(g[s]??0)),0),cf[s]),f=`${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:[jt(Qd,{width:"100%",height:n,children:on(Jd,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[jt("defs",{children:on("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[jt("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),jt("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),jt(Yd,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),jt(ef,{dataKey:"date",tickFormatter:Yr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),jt(tf,{allowDecimals:!sf.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}}),jt(Xd,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:jt(uf,{metric:s})}),jt(Zd,{type:"linear",dataKey:s,name:ur[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=af?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),jt("figcaption",{className:"af-sr-only",children:f})]})}import{Fragment as si,jsx as be,jsxs as Ut}from"react/jsx-runtime";var df="2026-08-13",ff=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],mf=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function pf({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,primaryConversion:n,className:i,published:o,lastPublishedAt:m}){let[d,f]=rt.useState(30),[r,g]=rt.useState(()=>vr()),b=e!==void 0&&a!==void 0,[v,c]=rt.useState(e??[]),{api:l}=ne(),[p,h]=rt.useState(l);p!==l&&(h(l),!b&&v.length>0&&c([]));let x=b?e:v,I=rt.useCallback(E=>{a&&a(E),b||c(E)},[a,b]),O=rt.useCallback((E,ue,me)=>{let Se=Array.isArray(ue)?ue:[ue];if(Se.length===0)return null;let Ce=Xr(x,{dimension:E,operator:"is",values:Se});if(me&&(!me.value||(Ce=qo(Ce,{dimension:me.dimension,operator:"is",values:[me.value]}),!Ce.find(Ge=>Ge.dimension===me.dimension&&Ge.operator!=="is_not")?.values.includes(me.value))))return null;let tt=Ce.find($e=>$e.dimension===E&&$e.operator!=="is_not");return Se.every($e=>tt?.values.includes($e))?JSON.stringify(Ce)===JSON.stringify(x)?null:Ce:null},[x]),u=rt.useCallback((E,ue,me)=>O(E,ue,me)!==null,[O]),N=rt.useCallback((E,ue,me)=>{let Se=O(E,ue,me);Se&&I(Se)},[O,I]),[T,L]=rt.useState("visitors"),S=Fs(d,{refreshKey:s,breakdowns:mf,filters:x}),k=S.status.data,F=S.reportedZone??k?.timezone,y=F??r??zs()??"UTC",{notCollecting:G,awaitingFirstVisit:X,firstVisitTooRecent:H,holdingForFirstData:ce}=nr(k,{published:o}),j=o===!1,K=sr({collecting:X||G?!1:k?.collecting,statusFailed:S.status.error!=null,identity:k?.analytics_id}),z=rt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),se=rt.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=rt.useMemo(()=>{let E=(Se,Ce)=>{let tt=S.breakdowns[Se]?.data;return!tt||tt.status!=="ok"?[]:[...new Set(tt.data.map($e=>$e[Ce]).filter($e=>typeof $e=="string"&&$e!==""))]};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,Ze]=rt.useState({}),it=JSON.stringify(W),[Re,je]=rt.useState(new Map),et=JSON.stringify(se);rt.useEffect(()=>{let{suggestions:E,folds:ue}=jo(z.current,{api:l,period:d},JSON.parse(it),JSON.parse(et));Ze(E),je(ue)},[it,et,l,d]);let xe=rt.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]),At=rt.useMemo(()=>{let E=S.conversions.error;return E instanceof Bt&&E.details?.code==="goals_exceed_report_budget"?E.message:null},[S.conversions.error]),R=rt.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 Bt&&me.details?.code==="filter_unsupported")return me.message}return null},[S.summary,S.timeseries,S.channels,S.breakdowns]),D=(E,ue,me,Se,Ce,tt,$e,Ge,ie)=>()=>{let Ae=S.breakdowns[E];return be(es,{sourced:Ae?.data??null,error:Ae?.error,isLoading:Ae?.isLoading,what:ue,collecting:k?.collecting,onRetry:S.refetch,children:ot=>{let sa=ht=>Ge?xe(Ge,[ht]):ht;return be(Qr,{rows:ot,dimension:me,metric:Se,metricLabel:Ce,secondary:tt,emptyCopy:x.length>0?"No data for this filter":$e,canFilter:Ge?(ht,Et)=>u(Ge,sa(ht),ie?{dimension:ie,value:Et}:void 0):()=>!1,onFilter:Ge?(ht,Et)=>N(Ge,sa(ht),ie?{dimension:ie,value:Et}:void 0):void 0})}})};if(rr({status:k,holdingForFirstData:ce,refetchStatus:S.refetchStatus,refetch:S.refetch}),G){let E=!!m&&String(m).slice(0,10)<df;return be(wt,{title:"Analytics",onBackToWebsite:t,className:i,children:Ut("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:j?"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 X?be(wt,{title:"Analytics",onBackToWebsite:t,className:i,children:Ut("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."})]})}):H?Ut(wt,{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:E=>{br(E),g(E)}})}),Ut("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"}),Ut("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:K.currentVisitors,asOf:K.asOf,isStale:K.isStale,isUnreachable:K.isUnreachable||K.error!==null,isInitialLoad:K.isInitialLoad})})]})]}):be(wt,{title:"Analytics",onBackToWebsite:t,className:i,children:Ut("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Ut("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:ff.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(Jr,{value:y,chosen:r,onChange:E=>{br(E),g(E)}}),be(ei,{currentVisitors:K.currentVisitors,asOf:K.asOf,isStale:K.isStale,isUnreachable:K.isUnreachable||K.error!==null,isInitialLoad:K.isInitialLoad,scopeIsSiteWide:x.length>0})]}),be(Go,{filters:x,onChange:I,suggestions:he,expandValues:xe,resetKey:l}),R?Ut("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:R}),be("button",{type:"button",onClick:()=>I([]),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,!R&&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,R?null:Ut(si,{children:[be(es,{sourced:S.summary.data,error:S.summary.error,isLoading:S.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:S.refetch,children:E=>Ut(si,{children:[be(Wo,{summary:E,selected:T,onSelect:L}),E.previous_unavailable?Ut("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(es,{sourced:S.timeseries.data,error:S.timeseries.error,isLoading:S.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:S.refetch,children:E=>{let ue=S.timeseries.data?.status==="ok"?S.timeseries.data.window:{from:"",to:""};return be(dr,{rows:E,window:ue,metric:T,timeZone:F??"UTC"})}})}),Ut("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(es,{sourced:S.channels.data,error:S.channels.error,isLoading:S.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:S.refetch,children:E=>be(Qr,{rows:E,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:x.length>0?"No data for this filter":"No data for this period",canFilter:ue=>u("channel",ue),onFilter:ue=>N("channel",ue)})})},{id:"sources",label:"Sources",render:D("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:D("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:D("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:D("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:D("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:D("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:D("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:D("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),be(nn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:D("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:D("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:D("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Ut("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"})}),Ut("div",{className:"af-px-3 af-py-2",children:[x.length>0?Ut("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,At!==null?Ut("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:At})]}):be(es,{sourced:S.conversions.data,error:S.conversions.error,isLoading:S.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:S.refetch,children:E=>{let ue=S.conversions.data?.status==="ok"?S.conversions.data:null;return be(si,{children:be(cr,{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*as nl from"react";import{Phone as tl,Mail as ri,ShoppingBag as yf,ExternalLink as hf,MessageCircle as xf,Download as wf,Target as rl}from"lucide-react";import*as ha from"react";import{Check as ni,ChevronLeft as gf,Loader2 as Jo}from"lucide-react";import{jsx as qe,jsxs as kt}from"react/jsx-runtime";var Yo=90,Qo=100;function vf(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Xo(e){return!!e.label&&e.label!==e.target}function bf(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}=ne(),[n,i]=ha.useState(null),[o,m]=ha.useState(!1),[d,f]=ha.useState({at:"goals"}),[r,g]=ha.useState(null),[b,v]=ha.useState(null),[c,l]=ha.useState(!1),[p,h]=ha.useState(null),x=ha.useRef(0);ha.useEffect(()=>{let N=!0;return i(null),m(!1),f({at:"goals"}),g(null),v(null),l(!1),h(null),x.current+=1,t.getAnalyticsConversions(Yo).then(T=>{if(N){if(T.status!=="ok"){m(!0);return}i(T.data)}}).catch(()=>{N&&m(!0)}),()=>{N=!1}},[t]);let I=N=>{f({at:"targets",row:N}),g(null),v(null),l(!1),h(null);let T=++x.current;t.getAnalyticsGoalTargets(N.goal,Yo,Qo).then(L=>{if(T===x.current){if(L.status!=="ok"){v("failed");return}g(L.data),l(L.truncated===!0),h(L.coverage??null)}}).catch(L=>{if(T!==x.current)return;let S=L instanceof Bt?L.details?.code:void 0;v(S==="goal_has_no_targets"?"no-values":"failed")})},O=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(d.at==="targets"){let N=d.row,T=new Map;for(let L of r??[])T.set(L.label,(T.get(L.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:()=>f({at:"goals"}),children:[qe(gf,{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:()=>O({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:()=>I(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:bf(r.length,p,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(L=>{let S=!!(e&&ln(N,e)&&e.target===L.target),k=T.get(L.label)>1;return Xo(L)?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:L.label}),k&&qe("span",{className:"af-block af-truncate af-text-xs",children:L.target})]}),qe("span",{className:"af-shrink-0 af-text-xs",children:L.visitors.toLocaleString()})]},L.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:()=>O({goal:N.goal,implicit:N.implicit,target:L.target,...L.label&&L.label!==L.target?{label:L.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:L.label}),k&&qe("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:L.target})]})]}),qe("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:L.visitors.toLocaleString()})]},L.target)})]})}let u=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:[u&&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 T=e?ln(N,e):!1;return kt("div",{className:"af-flex af-items-center af-gap-1",children:[kt("button",{type:"button","aria-current":T?"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:()=>O({goal:N.goal,implicit:N.implicit}),children:[kt("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[T&&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()})]}),vf(N)&&qe(w,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${N.goal}`,onClick:()=>I(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:()=>O(null),children:"No main conversion"})]})}import{Fragment as Rf,jsx as _s,jsxs as sl}from"react/jsx-runtime";function Nf(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 Sf(e){if(ii(e,"whatsapp"))return!0;let a=Nf(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=>Sf(e),icon:xf,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:hf,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:yf,line:"This site is set up to sell."},{goal:"File Download",icon:wf,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 _f(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(),m=e?_f(e):rl,d=e?.goal?o?`Your main conversion is ${o}.`:i?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",f=sl(Rf,{children:[_s(m,{className:"af-h-4 af-w-4 af-shrink-0"}),_s("span",{children:d})]});return a?sl(An,{open:s,onOpenChange:t,children:[_s(En,{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:f})}),_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:f})}import{Fragment as Pf,jsx as gs,jsxs as fr}from"react/jsx-runtime";function ll({refreshKey:e,onViewAll:a,primaryConversion:s}){let t=Fs(7,{refreshKey:e,breakdowns:[]}),n=t.status.data??void 0,{nothingToReport:i,notCollecting:o,holdingForFirstData:m}=nr(n);return rr({status:n,holdingForFirstData:m,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(Pf,{children:[gs(es,{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 gs(dr,{rows:d,window:f?.window??{from:"",to:""},metric:"visitors",timeZone:f?.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(es,{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 gs(cr,{rows:d,primaryConversion:s,denominator:f?.denominator??0,windowPrecedesCollection:f?.window_precedes_collection??!1,coverageUnknown:f?.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 Cf({refreshKey:e,onBackToWebsite:a,primaryConversion:s,onChangePrimaryConversion:t,onOpenSurface:n,needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:m}){let d=Os({refreshKey:e}),f=(d.summary?.products.count??0)>0||(d.summary?.commerce?.storefront_orders??!1),r=f||(d.summary?.commerce?.invoicing??!1);return La(wt,{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"))})]}),f&&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:m})]})]})})}export{Bt as AifeaturesApiError,fl as AifeaturesProvider,pf as AnalyticsView,Un as CustomerDetail,Vn as CustomersList,Cf 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,$s 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,Ps as PromosPanel,Kr as REALTIME_FAILURES_BEFORE_ERROR,Wr as REALTIME_POLL_MS,Mr as RetainerStatusBadge,Es as RetainersPanel,yn as SubmissionDetail,Ao as SubscriptionsView,Cn as VariantsEditor,wt as ViewShell,wn as WebhookDeliveries,Nn as WebhookSettings,Ya as chargedTotal,hr as createApiClient,q as formatPrice,va as isZeroDecimalCurrency,pt as toMajorUnits,Zt as toMinorUnits,ne as useAifeatures,ne as useAifeaturesContext,Fs as useAnalytics,Os as useBusinessSummary,Mn as useCustomers,xn as useEventDestinations,Rs as useForms,ks as useInvoices,kn as useOrders,is as usePaymentsStatus,Qn as usePeople,Xn as usePerson,Is as useProducts,sr as useRealtimeVisitors,Ds as useRetainers,bn as useSubmissions,tr as useSubscriptions};
|