@aifeatures/admin-react 0.13.0 → 0.14.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 +30 -3
- package/dist/index.d.ts +30 -3
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import*as Ka from"react";function qs(e,a){let s=new URLSearchParams({period:String(e)});return a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var Ht=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function $n(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 Vn(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 Ht($n(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,f=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(m)}`,g=await fetch(f,{headers:{Authorization:`Bearer ${e}`}});if(!g.ok){let p;try{p=await g.json()}catch{}throw new Ht($n(p?.error,g.status),g.status,p)}let r=await g.blob(),v=URL.createObjectURL(r),h=document.createElement("a");h.href=v,h.download=o,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(v)},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 Ht($n(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(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${qs(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${qs(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${qs(t,n)}`)},async getAnalyticsConversions(t){return s(`/api/v1/analytics/conversions?period=${String(t)}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${qs(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;return n.set("tz_offset_minutes",String(t.tzOffsetMinutes)),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 Ts,jsxs as So}from"react/jsx-runtime";var Lr=Ka.createContext(null);function wo(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 No({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Ka.useMemo(()=>wo(e),[e]),o=Ka.useMemo(()=>Vn(e,a),[e,a]),m=Ka.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?Ts("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:So("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[Ts("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),Ts("p",{className:"af-text-sm af-text-destructive",children:i})]})}):Ts(Lr.Provider,{value:m,children:Ts("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function ie(){let e=Ka.useContext(Lr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as Ya from"react";import{ArrowLeft as _l,Settings as Rl,Inbox as Pl}from"lucide-react";import*as js from"react";import*as fa from"@radix-ui/react-tabs";import{clsx as _o}from"clsx";import{extendTailwindMerge as Ro}from"tailwind-merge";var Po=Ro({prefix:"af-"});function W(...e){return Po(_o(e))}import{jsx as Hn}from"react/jsx-runtime";var Gs=fa.Root,ks=js.forwardRef(({className:e,...a},s)=>Hn(fa.List,{ref:s,className:W("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...a}));ks.displayName=fa.List.displayName;var ma=js.forwardRef(({className:e,...a},s)=>Hn(fa.Trigger,{ref:s,className:W("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...a}));ma.displayName=fa.Trigger.displayName;var pa=js.forwardRef(({className:e,...a},s)=>Hn(fa.Content,{ref:s,className:W("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...a}));pa.displayName=fa.Content.displayName;import*as Or from"react";import{Slot as Co}from"@radix-ui/react-slot";import{cva as To}from"class-variance-authority";import{jsx as Eo}from"react/jsx-runtime";var ko=To("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=Or.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>Eo(t?Co:"button",{className:W(ko({variant:a,size:s,className:e})),ref:i,...n}));w.displayName="Button";import{Inbox as Br,Settings as Do}from"lucide-react";import*as Va from"react";import{jsx as $a}from"react/jsx-runtime";var Oe=Va.forwardRef(({className:e,...a},s)=>$a("div",{className:"af-relative af-w-full af-overflow-auto",children:$a("table",{ref:s,className:W("af-w-full af-caption-bottom af-text-sm",e),...a})}));Oe.displayName="Table";var Be=Va.forwardRef(({className:e,...a},s)=>$a("thead",{ref:s,className:W("[&_tr]:af-border-b",e),...a}));Be.displayName="TableHeader";var Fe=Va.forwardRef(({className:e,...a},s)=>$a("tbody",{ref:s,className:W("[&_tr:last-child]:af-border-0",e),...a}));Fe.displayName="TableBody";var Io=Va.forwardRef(({className:e,...a},s)=>$a("tfoot",{ref:s,className:W("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));Io.displayName="TableFooter";var pe=Va.forwardRef(({className:e,...a},s)=>$a("tr",{ref:s,className:W("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));pe.displayName="TableRow";var F=Va.forwardRef(({className:e,...a},s)=>$a("th",{ref:s,className:W("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));F.displayName="TableHead";var M=Va.forwardRef(({className:e,...a},s)=>$a("td",{ref:s,className:W("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));M.displayName="TableCell";var Ao=Va.forwardRef(({className:e,...a},s)=>$a("caption",{ref:s,className:W("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));Ao.displayName="TableCaption";import*as ga from"react";function ds(){let{api:e}=ie(),[a,s]=ga.useState([]),[t,n]=ga.useState(!0),[i,o]=ga.useState(null),m=ga.useCallback(async()=>{try{n(!0),o(null);let v=await e.getForms();s(v)}catch(v){o(v instanceof Error?v:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);ga.useEffect(()=>{m()},[m]);let f=ga.useCallback(async v=>{let h=await e.createForm(v);return s(p=>[...p,h]),h},[e]),g=ga.useCallback(async(v,h)=>{let p=await e.updateForm(v,h);return s(u=>u.map(l=>l.id===v?p:l)),p},[e]),r=ga.useCallback(async v=>{await e.deleteForm(v),s(h=>h.filter(p=>p.id!==v))},[e]);return{forms:a,isLoading:t,error:i,refetch:m,createForm:f,updateForm:g,deleteForm:r}}import{jsx as _t,jsxs as Ha}from"react/jsx-runtime";function Ws({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=ds();return t?_t("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:_t("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?_t("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ha("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?Ha("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[_t(Br,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ha("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",_t("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):_t("div",{className:a,children:Ha(Oe,{children:[_t(Be,{children:Ha(pe,{children:[_t(F,{children:"Name"}),_t(F,{children:"Endpoint"}),_t(F,{className:"af-text-right",children:"Actions"})]})}),_t(Fe,{children:s.map(i=>Ha(pe,{children:[_t(M,{className:"af-font-medium",children:i.name}),_t(M,{children:_t("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","")})}),_t(M,{className:"af-text-right",children:Ha("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ha(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[_t(Br,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ha(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[_t(Do,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as Fo}from"lucide-react";import{cva as Lo}from"class-variance-authority";import{jsx as Bo}from"react/jsx-runtime";var Oo=Lo("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 Z({className:e,variant:a,...s}){return Bo("div",{className:W(Oo({variant:a}),e),...s})}import{jsx as ss,jsxs as Ks}from"react/jsx-runtime";var Mo={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 Js(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 zn(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function Uo(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 Es({deliveries:e,label:a="Email needs attention"}){return zn(e)?Ks("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:[ss(Fo,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function Pa({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||zn([n]));return t.length?ss("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=Js(n),o=Uo(n);return Ks("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Ks("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[ss("span",{className:"af-font-medium",children:Mo[n.kind]??"Email notification"}),ss(Z,{variant:i.variant,children:i.label})]}),Ks("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&zn([n])&&ss("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&&ss("p",{className:"af-mt-1",children:i.detail}),o&&ss("p",{className:"af-mt-1",children:o})]},n.id)})}):null}import*as Is from"react";import{ChevronLeft as Xo,ChevronRight as el,Eye as tl,Inbox as al,Paperclip as sl}from"lucide-react";import*as Ja from"react";import*as Ne from"@radix-ui/react-select";import{Check as $o,ChevronDown as Fr,ChevronUp as Vo}from"lucide-react";import{jsx as kt,jsxs as qn}from"react/jsx-runtime";var na=Ne.Root;var ra=Ne.Value,Yt=Ja.forwardRef(({className:e,children:a,...s},t)=>qn(Ne.Trigger,{ref:t,className:W("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[a,kt(Ne.Icon,{asChild:!0,children:kt(Fr,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Yt.displayName=Ne.Trigger.displayName;var Mr=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.ScrollUpButton,{ref:s,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:kt(Vo,{className:"af-h-4 af-w-4"})}));Mr.displayName=Ne.ScrollUpButton.displayName;var Ur=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.ScrollDownButton,{ref:s,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:kt(Fr,{className:"af-h-4 af-w-4"})}));Ur.displayName=Ne.ScrollDownButton.displayName;var Zt=Ja.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>kt(Ne.Portal,{children:qn(Ne.Content,{ref:n,className:W("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",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:[kt(Mr,{}),kt(Ne.Viewport,{className:W("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}),kt(Ur,{})]})}));Zt.displayName=Ne.Content.displayName;var Ho=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.Label,{ref:s,className:W("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));Ho.displayName=Ne.Label.displayName;var ze=Ja.forwardRef(({className:e,children:a,...s},t)=>qn(Ne.Item,{ref:t,className:W("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[kt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:kt(Ne.ItemIndicator,{children:kt($o,{className:"af-h-4 af-w-4"})})}),kt(Ne.ItemText,{children:a})]}));ze.displayName=Ne.Item.displayName;var zo=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.Separator,{ref:s,className:W("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));zo.displayName=Ne.Separator.displayName;import*as ia from"react";function Ys({formId:e,initialPageSize:a=25}){let{api:s}=ie(),[t,n]=ia.useState([]),[i,o]=ia.useState(0),[m,f]=ia.useState(!0),[g,r]=ia.useState(null),[v,h]=ia.useState(0),[p,u]=ia.useState(a),l=ia.useCallback(async()=>{if(e)try{f(!0),r(null);let N={limit:p,offset:v*p},I=await s.getSubmissions(e,N);n(I.submissions),o(I.total)}catch(N){r(N instanceof Error?N:new Error("Failed to fetch submissions"))}finally{f(!1)}},[s,e,v,p]);ia.useEffect(()=>{l()},[l]);let b=ia.useCallback(async N=>{await s.deleteSubmission(N),n(I=>I.filter(O=>O.id!==N)),o(I=>I-1)},[s]),x=Math.ceil(i/p);return{submissions:t,total:i,isLoading:m,error:g,page:v,pageSize:p,hasNextPage:v<x-1,hasPreviousPage:v>0,setPage:h,setPageSize:N=>{u(N),h(0)},refetch:l,deleteSubmission:b}}import*as Vr from"react";import{ArrowLeft as qo,Download as jo,Globe as Go,Clock as Wo,FileText as Ko,Loader2 as Jo,Monitor as Yo,Mail as Zo}from"lucide-react";import{jsx as nt,jsxs as rt}from"react/jsx-runtime";function $r(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Qo(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 Zs({submission:e,onBack:a}){let{api:s}=ie(),[t,n]=Vr.useState(null),i=f=>f.id??f.name,o=async f=>{n(i(f));try{await s.downloadAttachment(e.id,f)}catch(g){console.error("Download failed:",g)}finally{n(null)}},m=Object.entries(e.data).filter(([f])=>!f.startsWith("_"));return rt("div",{children:[rt("div",{className:"af-mb-6",children:[rt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[nt(qo,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),nt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),rt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",$r(e.metadata.submitted_at)]})]}),rt("div",{className:"af-space-y-6",children:[nt(Pa,{deliveries:e.email_deliveries}),rt("div",{children:[nt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),rt("div",{className:"af-space-y-3",children:[m.map(([f,g])=>rt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[nt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:f.replace(/_/g," ")}),nt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof g=="string"&&g.includes(`
|
|
3
|
-
`)?nt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:g}):String(g)})]},f)),m.length===0&&nt("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&rt("div",{children:[nt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),nt("div",{className:"af-space-y-2",children:e.attachments.map((f,g)=>rt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[rt("div",{className:"af-flex af-items-center af-gap-2",children:[nt(Ko,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),nt("span",{className:"af-text-sm",children:f.name}),rt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Qo(f.size),")"]})]}),rt(w,{variant:"ghost",size:"sm",onClick:()=>o(f),disabled:t===i(f),children:[t===i(f)?nt(Jo,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):nt(jo,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(f)?"Downloading...":"Download"]})]},g))})]}),rt("div",{children:[nt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),rt("div",{className:"af-space-y-2 af-text-sm",children:[rt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[nt(Wo,{className:"af-h-4 af-w-4"}),nt("span",{children:$r(e.metadata.submitted_at)})]}),e.metadata.ip_address&&rt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[nt(Go,{className:"af-h-4 af-w-4"}),rt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&rt("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[nt(Yo,{className:"af-h-4 af-w-4 af-mt-0.5"}),nt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&rt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[nt(Zo,{className:"af-h-4 af-w-4"}),rt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as Te,jsxs as xt}from"react/jsx-runtime";function nl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function rl(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 Qs({formId:e,className:a,defaultSubmissionId:s}){let{submissions:t,total:n,isLoading:i,error:o,page:m,pageSize:f,hasNextPage:g,hasPreviousPage:r,setPage:v,setPageSize:h}=Ys({formId:e}),[p,u]=Is.useState("list"),[l,b]=Is.useState(null);Is.useEffect(()=>{if(s&&t.length>0){let c=t.find(y=>y.id===s);c&&(b(c),u("detail"))}},[s,t]);let x=c=>{b(c),u("detail")},N=()=>{u("list"),b(null)};if(p==="detail"&&l)return Te("div",{className:a,children:Te(Zs,{submission:l,onBack:N})});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:xt("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&m===0)return xt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Te(al,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),xt("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*f+1,O=Math.min((m+1)*f,n);return xt("div",{className:a,children:[xt(Oe,{children:[Te(Be,{children:xt(pe,{children:[Te(F,{children:"Email"}),Te(F,{children:"Preview"}),Te(F,{children:"Date"}),Te(F,{className:"af-text-right",children:"Actions"})]})}),Te(Fe,{children:t.map(c=>{let y=rl(c.data),T=il(c.data);return xt(pe,{children:[xt(M,{className:"af-font-medium",children:[xt("div",{className:"af-flex af-items-center af-gap-2",children:[y||Te("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&xt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[Te(sl,{className:"af-h-3 af-w-3"}),Te("span",{className:"af-text-xs",children:c.attachments.length})]})]}),Te(Es,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),Te(M,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:T||Te("span",{className:"af-italic",children:"No preview available"})}),Te(M,{className:"af-text-muted-foreground",children:nl(c.metadata.submitted_at)}),Te(M,{className:"af-text-right",children:Te(w,{variant:"ghost",size:"icon",onClick:()=>x(c),title:"View details",children:Te(tl,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),xt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[xt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[xt("span",{children:["Showing ",I,"-",O," of ",n]}),xt(na,{value:String(f),onValueChange:c=>h(Number(c)),children:[Te(Yt,{className:"af-w-[70px] af-h-8",children:Te(ra,{})}),xt(Zt,{children:[Te(ze,{value:"10",children:"10"}),Te(ze,{value:"25",children:"25"}),Te(ze,{value:"50",children:"50"}),Te(ze,{value:"100",children:"100"})]})]}),Te("span",{children:"per page"})]}),xt("div",{className:"af-flex af-items-center af-gap-2",children:[xt(w,{variant:"outline",size:"sm",onClick:()=>v(m-1),disabled:!r,children:[Te(Xo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xt(w,{variant:"outline",size:"sm",onClick:()=>v(m+1),disabled:!g,children:["Next",Te(el,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Xt from"react";import{Plus as xl,X as wl,Loader2 as Nl,Check as Sl}from"lucide-react";import*as Hr from"react";import{jsx as ol}from"react/jsx-runtime";var ge=Hr.forwardRef(({className:e,type:a,...s},t)=>ol("input",{type:a,className:W("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:t,...s}));ge.displayName="Input";import*as zr from"react";import{cva as ll}from"class-variance-authority";import{jsx as ul}from"react/jsx-runtime";var cl=ll("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),be=zr.forwardRef(({className:e,...a},s)=>ul("label",{ref:s,className:W(cl(),e),...a}));be.displayName="Label";import*as la from"react";import{Plus as pl,Loader2 as Gn,Copy as gl,Check as vl,Trash2 as bl,RefreshCw as yl,AlertTriangle as hl}from"lucide-react";import*as As from"react";import*as bt from"@radix-ui/react-dialog";import{X as dl}from"lucide-react";import{jsx as za,jsxs as jn}from"react/jsx-runtime";var Ca=bt.Root;var fl=bt.Portal;var qr=As.forwardRef(({className:e,...a},s)=>za(bt.Overlay,{ref:s,className:W("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));qr.displayName=bt.Overlay.displayName;var va=As.forwardRef(({className:e,children:a,...s},t)=>za(fl,{children:jn("div",{className:"aifeatures-admin",children:[za(qr,{}),jn(bt.Content,{ref:t,className:W("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[a,jn(bt.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(dl,{className:"af-h-4 af-w-4"}),za("span",{className:"af-sr-only",children:"Close"})]})]})]})}));va.displayName=bt.Content.displayName;var ba=({className:e,...a})=>za("div",{className:W("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});ba.displayName="DialogHeader";var ya=({className:e,...a})=>za("div",{className:W("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});ya.displayName="DialogFooter";var ha=As.forwardRef(({className:e,...a},s)=>za(bt.Title,{ref:s,className:W("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));ha.displayName=bt.Title.displayName;var xa=As.forwardRef(({className:e,...a},s)=>za(bt.Description,{ref:s,className:W("af-text-sm af-text-muted-foreground",e),...a}));xa.displayName=bt.Description.displayName;import*as Qt from"react";function Xs(){let{api:e}=ie(),[a,s]=Qt.useState([]),[t,n]=Qt.useState(!0),[i,o]=Qt.useState(null),m=Qt.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(p){o(p instanceof Error?p:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);Qt.useEffect(()=>{m()},[m]);let f=Qt.useCallback(async p=>{let u=await e.createEventDestination(p);return s(l=>[u,...l]),u},[e]),g=Qt.useCallback(async(p,u)=>{let l=await e.updateEventDestination(p,u);return s(b=>b.map(x=>x.id===p?l:x)),l},[e]),r=Qt.useCallback(async p=>{await e.deleteEventDestination(p),s(u=>u.filter(l=>l.id!==p))},[e]),v=Qt.useCallback(async p=>{let u=await e.rotateEventDestinationSecret(p);return s(l=>l.map(b=>b.id===p?u:b)),u},[e]),h=Qt.useCallback(p=>e.getEventDestinationSecret(p),[e]);return{destinations:a,isLoading:t,error:i,refetch:m,createDestination:f,updateDestination:g,deleteDestination:r,rotateSecret:v,getSecret:h}}import*as qa from"react";import{Loader2 as jr,RotateCw as ml}from"lucide-react";import{jsx as oa,jsxs as Ds}from"react/jsx-runtime";function en({destinationId:e,limit:a=25,className:s}){let{api:t}=ie(),[n,i]=qa.useState([]),[o,m]=qa.useState(!0),[f,g]=qa.useState(null),[r,v]=qa.useState(null),h=qa.useCallback(async()=>{try{m(!0),g(null),i(await t.getEventDeliveries(e,a))}catch(u){g(u instanceof Error?u.message:"Failed to load deliveries")}finally{m(!1)}},[t,e,a]);qa.useEffect(()=>{h()},[h]);let p=async u=>{try{v(u.id),g(null);let l=await t.retryEventDelivery(e,u.id);i(b=>b.map(x=>x.id===u.id?l:x))}catch(l){g(l instanceof Error?l.message:"Retry failed")}finally{v(null)}};return o?Ds("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[oa(jr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?oa("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?oa("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):oa("div",{className:s,children:oa("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let l=u.delivered_at!==null;return Ds("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ds("div",{className:"af-min-w-0",children:[Ds("div",{className:"af-flex af-items-center af-gap-2",children:[l?oa(Z,{variant:"secondary",children:u.last_status??200}):oa(Z,{variant:"destructive",children:u.last_status??"failed"}),oa("span",{className:"af-text-sm af-truncate",children:u.type})]}),Ds("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!l&&u.last_error&&oa("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),oa(w,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>p(u),children:r===u.id?oa(jr,{className:"af-h-4 af-w-4 af-animate-spin"}):oa(ml,{className:"af-h-4 af-w-4"})})]},u.id)})})})}import{jsx as ke,jsxs as ut}from"react/jsx-runtime";function tn({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:m,updateDestination:f,deleteDestination:g,rotateSecret:r,getSecret:v}=Xs(),[h,p]=la.useState(""),[u,l]=la.useState(!1),[b,x]=la.useState(null),[N,I]=la.useState(null),[O,c]=la.useState(null),[y,T]=la.useState(!1),[z,L]=la.useState(null),[R,$]=la.useState(null),[d,U]=la.useState(null),se=la.useMemo(()=>n.filter(q=>q.form_id===e),[n,e]),Q=async()=>{let q=h.trim();if(q){if(!q.startsWith("https://")){x("Webhook URLs must start with https://");return}try{l(!0),x(null),await m({url:q,form_id:e,...a&&a.length>0?{topics:a}:{}}),p("")}catch(ve){x(ve instanceof Error?ve.message:"Failed to add webhook")}finally{l(!1)}}},oe=async q=>{try{$(q.id),x(null),await r(q.id),T(!1),c(await v(q.id))}catch(ve){x(ve instanceof Error?ve.message:"Failed to rotate secret")}finally{$(null)}},ne=async q=>{try{$(q.id),x(null),await f(q.id,{status:"active"})}catch(ve){x(ve instanceof Error?ve.message:"Failed to re-enable")}finally{$(null)}},J=async()=>{if(z)try{$(z.id),await g(z.id),L(null)}catch(q){x(q instanceof Error?q.message:"Failed to delete")}finally{$(null)}},ee=async q=>{if(N===q.id){I(null),c(null);return}try{$(q.id),x(null),T(!1),I(q.id),c(await v(q.id))}catch(ve){I(null),x(ve instanceof Error?ve.message:"Failed to read secret")}finally{$(null)}},de=async()=>{if(O)try{await navigator.clipboard.writeText(O),T(!0)}catch{}};return ut("div",{className:t,children:[ut("div",{className:"af-space-y-1",children:[ke(be,{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."})]}),ut("div",{className:"af-flex af-gap-2 af-mt-4",children:[ke(ge,{value:h,placeholder:"https://hooks.zapier.com/...",onChange:q=>p(q.target.value),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),Q())},disabled:u}),ut(w,{onClick:Q,disabled:u||!h.trim(),children:[u?ke(Gn,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(pl,{className:"af-h-4 af-w-4"}),ke("span",{className:"af-ml-1",children:"Add"})]})]}),(b||o)&&ke("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:b||o?.message}),ut("div",{className:"af-mt-4 af-space-y-2",children:[i&&ut("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ke(Gn,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&se.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."}),se.map(q=>ut("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[ut("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[ut("div",{className:"af-min-w-0",children:[ut("div",{className:"af-flex af-items-center af-gap-2",children:[ke("span",{className:"af-font-mono af-text-sm af-truncate",children:q.url}),q.status==="disabled"?ke(Z,{variant:"destructive",children:"Disabled"}):ke(Z,{variant:"secondary",children:"Active"})]}),ke("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:q.topics.includes("*")?"All events":q.topics.join(", ")})]}),ut("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[ke(w,{variant:"ghost",size:"sm",onClick:()=>U(d===q.id?null:q.id),children:d===q.id?"Hide log":"Deliveries"}),ke(w,{variant:"ghost",size:"sm",onClick:()=>ee(q),disabled:R===q.id,children:N===q.id?"Hide secret":"Show secret"}),ke(w,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:R===q.id,onClick:()=>L(q),children:ke(bl,{className:"af-h-4 af-w-4"})})]})]}),q.status==="disabled"&&ut("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[ke(hl,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),ut("div",{className:"af-text-sm",children:[ut("p",{children:["We stopped sending after repeated failures."," ",q.disabled_reason]}),ke(w,{variant:"outline",size:"sm",className:"af-mt-2",disabled:R===q.id,onClick:()=>ne(q),children:"Re-enable"})]})]}),N===q.id&&O&&ut("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."}),ut("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:de,children:y?ke(vl,{className:"af-h-4 af-w-4"}):ke(gl,{className:"af-h-4 af-w-4"})}),ke(w,{variant:"outline",title:"Rotate signing secret",disabled:R===q.id,onClick:()=>oe(q),children:R===q.id?ke(Gn,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(yl,{className:"af-h-4 af-w-4"})})]})]}),d===q.id&&ke(en,{destinationId:q.id})]},q.id))]}),ke(Ca,{open:!!z,onOpenChange:q=>{!q&&!R&&L(null)},children:ut(va,{children:[ut(ba,{children:[ke(ha,{children:"Delete this webhook?"}),ut(xa,{children:["New submissions will stop being sent to ",z?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),ut(ya,{children:[ke(w,{variant:"outline",onClick:()=>L(null),disabled:!!R,children:"Cancel"}),ke(w,{variant:"destructive",onClick:J,disabled:!!R,children:R?"Deleting...":"Delete"})]})]})})]})}import{jsx as De,jsxs as wa}from"react/jsx-runtime";function an({form:e,onSaved:a,className:s}){let{updateForm:t}=ds(),[n,i]=Xt.useState(!1),[o,m]=Xt.useState(null),[f,g]=Xt.useState(null),[r,v]=Xt.useState(e.name),[h,p]=Xt.useState(e.redirect_url||""),[u,l]=Xt.useState(e.email_recipients),[b,x]=Xt.useState("");Xt.useEffect(()=>{v(e.name),p(e.redirect_url||""),l(e.email_recipients),g(null)},[e]);let N=Xt.useCallback(async T=>{try{i(!0),g(null);let z=await t(e.id,T);m(new Date),a?.(z)}catch(z){g(z instanceof Error?z.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);Xt.useEffect(()=>{if(o){let T=setTimeout(()=>m(null),2e3);return()=>clearTimeout(T)}},[o]);let I=async()=>{let T=b.trim().toLowerCase();if(!T)return;if(!T.includes("@")){g("Please enter a valid email address");return}if(u.includes(T)){g("This email is already added");return}let z=[...u,T];l(z),x(""),g(null),await N({email_recipients:z})},O=async T=>{let z=u.filter(L=>L!==T);l(z),await N({email_recipients:z})},c=async()=>{r!==e.name&&await N({name:r})},y=async()=>{let T=h||null;T!==e.redirect_url&&await N({redirect_url:T})};return wa("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?wa("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(Nl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),De("span",{className:"af-text-sm",children:"Saving..."})]}):wa("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(Sl,{className:"af-h-4 af-w-4 af-text-green-600"}),De("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),wa("div",{className:"af-space-y-2",children:[De(be,{htmlFor:"form-name",children:"Form Name"}),De(ge,{id:"form-name",value:r,onChange:T=>v(T.target.value),onBlur:c,placeholder:"Contact Form"}),De("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),wa("div",{className:"af-space-y-2",children:[De(be,{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."}),wa("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(T=>wa(Z,{variant:"secondary",className:"af-gap-1",children:[T,De("button",{type:"button",onClick:()=>O(T),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:De(wl,{className:"af-h-3 af-w-3"})})]},T)),u.length===0&&De("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),wa("div",{className:"af-flex af-gap-2",children:[De(ge,{type:"email",value:b,onChange:T=>x(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),I())},disabled:n}),De(w,{type:"button",variant:"outline",onClick:I,disabled:!b.trim()||n,children:De(xl,{className:"af-h-4 af-w-4"})})]})]}),wa("div",{className:"af-space-y-2",children:[De(be,{htmlFor:"redirect-url",children:"Redirect URL"}),De(ge,{id:"redirect-url",value:h,onChange:T=>p(T.target.value),onBlur:y,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."})]}),wa("div",{className:"af-space-y-2",children:[De(be,{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."})]}),wa("div",{className:"af-space-y-2",children:[De(be,{children:"Captcha Protection"}),De("div",{className:"af-flex af-items-center af-gap-2",children:De(Z,{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(tn,{formId:e.id}),f&&De("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}import{jsx as It,jsxs as Ta}from"react/jsx-runtime";function Gr({className:e,submissionId:a}){let{api:s}=ie(),[t,n]=Ya.useState("list"),[i,o]=Ya.useState(null),[m,f]=Ya.useState("submissions"),[g,r]=Ya.useState(a),[v,h]=Ya.useState(!!a);Ya.useEffect(()=>{if(!a)return;async function b(){try{let x=await s.getSubmission(a),N=await s.getForm(x.form_id);o(N),n("detail"),f("submissions"),r(a)}catch(x){console.error("Failed to load submission for deep link:",x)}finally{h(!1)}}b()},[a,s]);let p=(b,x)=>{o(b),n("detail"),f(x),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},l=b=>{o(b)};return v?It("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:It("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Ta("div",{className:e,children:[t==="list"&&Ta("div",{children:[Ta("div",{className:"af-mb-6",children:[It("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),It("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),It(Ws,{onSelectForm:p})]}),t==="detail"&&i&&Ta("div",{children:[Ta("div",{className:"af-mb-6",children:[Ta(w,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[It(_l,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),It("h2",{className:"af-text-lg af-font-semibold",children:i.name}),It("p",{className:"af-text-sm af-text-muted-foreground",children:It("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Ta(Gs,{value:m,onValueChange:b=>f(b),children:[Ta(ks,{className:"af-mb-4",children:[Ta(ma,{value:"submissions",className:"af-gap-2",children:[It(Pl,{className:"af-h-4 af-w-4"}),"Submissions"]}),Ta(ma,{value:"settings",className:"af-gap-2",children:[It(Rl,{className:"af-h-4 af-w-4"}),"Settings"]})]}),It(pa,{value:"submissions",children:It(Qs,{formId:i.id,defaultSubmissionId:g})}),It(pa,{value:"settings",children:It(an,{form:i,onSaved:l})})]})]})]})}import*as Le from"react";import*as ka from"react";function Za(){let{api:e}=ie(),[a,s]=ka.useState(null),[t,n]=ka.useState(!0),[i,o]=ka.useState(null),m=ka.useRef(0),f=ka.useCallback(async()=>{let g=++m.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(g!==m.current)return;s(r)}catch(r){if(g!==m.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{g===m.current&&n(!1)}},[e]);return ka.useEffect(()=>{f()},[f]),{status:a,isLoading:t,error:i,refetch:f}}var Cl=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function ca(e){return Cl.has(e.toLowerCase())}function H(e,a,s){let t=ca(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function ja(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=ca(a)?s:s*100;return Math.round(t)}function dt(e,a){return ca(a)?e:e/100}function sn(e){return e.amount_paid??Math.max(0,ja(e)-(e.credit_applied??0))}import{Fragment as El,jsx as Ie,jsxs as Ue}from"react/jsx-runtime";function Ls(e){return e instanceof Ht&&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 Wr(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${H(e.amount_off,e.currency)} off`:"Discount unavailable"}function fs(){let{api:e,siteToken:a}=ie();return Ie(Tl,{api:e},a)}function Tl({api:e}){let{status:a,error:s}=Za(),[t,n]=Le.useState([]),[i,o]=Le.useState(null),[m,f]=Le.useState(null),[g,r]=Le.useState(!1),[v,h]=Le.useState(!1),[p,u]=Le.useState(""),[l,b]=Le.useState(null),[x,N]=Le.useState(null),[I,O]=Le.useState(!1),c=Le.useRef(0),y=Le.useCallback(async L=>{let R=++c.current;r(!0),u("");try{let $=await e.getPromos(L);if(R!==c.current)return;n(d=>L?[...d,...$.promos.filter(U=>!d.some(se=>se.id===U.id))]:$.promos),o($.next_cursor),f($.checkout_enabled)}catch($){R===c.current&&u(Ls($))}finally{R===c.current&&r(!1)}},[e]);Le.useEffect(()=>(y(),()=>{c.current++}),[y]);async function T(L){let R=++c.current;r(!0),u(""),O(!1);try{let $=await e.getPromo(L);R===c.current&&b($)}catch($){R===c.current&&u(Ls($))}finally{R===c.current&&r(!1)}}async function z(){if(l){h(!0),r(!0),u("");try{let L=await e.disablePromo(l.id);if(b(L),!["inactive","expired","exhausted"].includes(L.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");O(!1),await y()}catch(L){u(Ls(L))}finally{h(!1),r(!1)}}}return x?Ie(kl,{currency:a?.currency??void 0,replaces:x.replaces,onCancel:()=>N(null),onSave:async L=>{let R=x.replaces?await e.replacePromo(x.replaces.id,L):await e.createPromo(L),$=await e.getPromo(R.id);if($.status==="pending"||$.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");b($),N(null),await y()}}):Ue("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[Ue("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:g||!a?.currency,onClick:()=>{u(""),N({})},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?Ls(s):"Connect Stripe and set the payment currency before creating codes."}),p&&Ue("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[p," ",Ie(w,{variant:"outline",disabled:g,onClick:()=>l?void T(l.id):void y(),children:"Refresh"})]}),l?Ue("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Ie(w,{variant:"ghost",disabled:v,onClick:()=>{b(null),O(!1),y()},children:"Back to codes"}),Ue("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),Ue("p",{children:[Wr(l)," \xB7 ",l.status]}),Ue("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),Ue("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${H(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),Ue("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"}),Ue("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{variant:"outline",disabled:g,onClick:()=>void T(l.id),children:"Refresh details"}),Ie(w,{variant:"outline",disabled:g||l.status==="pending"||l.status==="unavailable"||!a?.currency,onClick:()=>N({replaces:l}),children:"Replace with new code"}),Ie(w,{variant:"outline",disabled:g||!["active","pending","unavailable"].includes(l.status),onClick:()=>O(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),I&&Ue("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[Ue("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:g,onClick:()=>void z(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Ie(w,{variant:"ghost",disabled:g,onClick:()=>O(!1),children:"Cancel"})]})]}):Ue(El,{children:[t.map(L=>Ue("button",{type:"button",disabled:g,onClick:()=>void T(L.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:[Ue("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Ie("span",{className:"af-font-semibold af-break-all",children:L.code}),Ie("span",{className:"af-text-sm",children:L.status})]}),Ue("div",{className:"af-text-sm",children:[Wr(L)," \xB7"," ",L.times_redeemed==null?"Usage unavailable":`${L.times_redeemed} redemptions`]})]},L.id)),!g&&!p&&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."}),g&&Ie("p",{role:"status",children:"Loading promo codes\u2026"}),i&&Ie(w,{variant:"outline",disabled:g,onClick:()=>void y(i),children:"Load more"})]})]})}function kl({currency:e,replaces:a,onCancel:s,onSave:t}){let[n,i]=Le.useState(""),[o,m]=Le.useState(a?.name??""),[f,g]=Le.useState(a?.amount_off!=null?"fixed":"percent"),[r,v]=Le.useState(a?.percent_off?.toString()??(a?.amount_off!=null&&e?String(dt(a.amount_off,e)):"")),[h,p]=Le.useState(a?.minimum_amount!=null&&e?String(dt(a.minimum_amount,e)):""),[u,l]=Le.useState(()=>{if(!a?.expires_at)return"";let ne=new Date(a.expires_at);return Number.isFinite(ne.getTime())?new Date(ne.getTime()-ne.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[b,x]=Le.useState(a?.max_redemptions?.toString()??""),[N,I]=Le.useState(a?.duration??"once"),[O,c]=Le.useState(a?.duration_in_months?.toString()??"3"),[y,T]=Le.useState(null),[z,L]=Le.useState(!1),[R,$]=Le.useState(""),d=Le.useRef(!1),U=e&&ca(e)?"1":"0.01";async function se(ne){if(ne.preventDefault(),d.current)return;$("");let J=y;if(!J){if(!e){$("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){$("Choose a different code for the replacement.");return}let ee=zt(r,e),de=h?zt(h,e):null;if(f==="fixed"&&(!ee||ee>999999999999)||h&&(!de||de>999999999999)){$("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){$("Choose a future expiry.");return}J={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:N,...f==="percent"?{percent_off:Number(r)}:{amount_off:ee,currency:e},...h?{minimum_amount:de,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...b?{max_redemptions:Number(b)}:{},...N==="repeating"?{duration_in_months:Number(O)}:{}},T(J)}d.current=!0,L(!0);try{await t(J)}catch(ee){$(Ls(ee)),ee instanceof Ht&&ee.status>=400&&ee.status<500&&ee.details?.retryable!==!0&&T(null)}finally{d.current=!1,L(!1)}}let Q=(ne,J,ee,de={})=>Ue("label",{className:"af-grid af-gap-1 af-text-sm",children:[ne,Ie(ge,{"aria-label":ne,value:J,onChange:q=>ee(q.target.value),...de})]}),oe="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return Ue("form",{onSubmit:se,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."}),Ue("fieldset",{disabled:z||!!y,className:"af-grid af-gap-4",children:[Q("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),Q("Name",o,m,{required:!0,maxLength:40}),Ue("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",Ue("select",{"aria-label":"Discount type",className:oe,value:f,onChange:ne=>g(ne.target.value),children:[Ie("option",{value:"percent",children:"Percentage"}),Ue("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),Q("Discount",r,v,{type:"number",required:!0,min:f==="percent"?"0.01":U,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":U}),Q("Minimum order amount",h,p,{type:"number",min:U,step:U,placeholder:e?.toUpperCase()}),Ue("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."]}),Q("Expires at (local time)",u,l,{type:"datetime-local",step:1}),Q("Maximum redemptions",b,x,{type:"number",min:1,max:1e6,step:1}),Ue("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",Ue("select",{"aria-label":"Subscription duration",className:oe,value:N,onChange:ne=>I(ne.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"})]})]}),N==="repeating"&&Q("Months",O,c,{type:"number",required:!0,min:1,max:36,step:1})]}),R&&Ie("p",{role:"alert",className:"af-text-sm af-text-destructive",children:R}),y&&!z&&Ue("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:y.request_id})]}),Ue("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{type:"submit",disabled:z,children:z?"Saving\u2026":y?"Retry same request":a?"Create replacement":"Create code"}),Ie(w,{type:"button",variant:"ghost",disabled:z||!!y,onClick:s,children:"Cancel"})]})]})}import*as ws from"react";import{ArrowLeft as Qc,FileText as Xc,Package as eu,Receipt as tu,Settings as au,Users as su}from"lucide-react";import*as nn from"react";import{Package as Il,Pencil as Al,Plus as Kr,Trash2 as Dl}from"lucide-react";import{jsx as Me,jsxs as Et}from"react/jsx-runtime";function Ll(e){if(e.allow_custom_amount){let a=e.min_amount!==null?H(e.min_amount,e.currency):"?",s=e.max_amount!==null?H(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":H(e.unit_amount,e.currency)}function Ol(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function rn({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:m}=e,[f,g]=nn.useState(null),[r,v]=nn.useState(!1),[h,p]=nn.useState(null),u=async()=>{if(f)try{v(!0),p(null),await m(f.id),g(null)}catch(l){p(l instanceof Error?l.message:"Failed to delete product")}finally{v(!1)}};return i?Me("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Me("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?Me("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Et("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Et("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Me(Il,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Et("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",Me("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Et(w,{variant:"outline",onClick:()=>s?.(),children:[Me(Kr,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Et("div",{className:t,children:[Me("div",{className:"af-flex af-justify-end af-mb-4",children:Et(w,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Me(Kr,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Et(Oe,{children:[Me(Be,{children:Et(pe,{children:[Me(F,{children:"Name"}),Me(F,{children:"Price"}),Me(F,{children:"Fulfillment"}),Me(F,{children:"Status"}),Me(F,{className:"af-text-right",children:"Actions"})]})}),Me(Fe,{children:n.map(l=>Et(pe,{children:[Me(M,{className:"af-font-medium",children:l.name}),Me(M,{children:Ll(l)}),Me(M,{className:"af-text-muted-foreground",children:Ol(l)}),Me(M,{children:Me(Z,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),Me(M,{className:"af-text-right",children:Et("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Et(w,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[Me(Al,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Et(w,{variant:"ghost",size:"sm",onClick:()=>{p(null),g(l)},children:[Me(Dl,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),Me(Ca,{open:!!f,onOpenChange:l=>{!l&&!r&&g(null)},children:Et(va,{children:[Et(ba,{children:[Me(ha,{children:"Delete product?"}),Et(xa,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),h&&Me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:h}),Et(ya,{children:[Me(w,{variant:"outline",onClick:()=>g(null),disabled:r,children:"Cancel"}),Me(w,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as Ge from"react";import{FileText as Fl,Link2 as Ml,Loader2 as Zr,Plus as Ul,Upload as $l,X as Vl}from"lucide-react";import*as ft from"react";import{Loader2 as Jr,Plus as Wn,Trash2 as Yr,X as Bl}from"lucide-react";import{jsx as j,jsxs as fe}from"react/jsx-runtime";function Kn(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function on({productId:e,currency:a,className:s}){let{api:t}=ie(),n=ca(a)?"1":"0.01",[i,o]=ft.useState(null),[m,f]=ft.useState(!0),[g,r]=ft.useState(null),[v,h]=ft.useState(null),[p,u]=ft.useState(!1),l=ft.useRef(!0);ft.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let b=ft.useCallback(async()=>{try{let S=await t.getProduct(e);if(!l.current)return;o(S)}catch(S){if(!l.current)return;r(S instanceof Error?S.message:"Failed to load product")}finally{l.current&&f(!1)}},[t,e]);ft.useEffect(()=>{b()},[b]);let x=async S=>{h(null),u(!0);try{await S(),await b()}catch(A){l.current&&h(A instanceof Error?A.message:"Something went wrong")}finally{l.current&&u(!1)}},[N,I]=ft.useState(""),[O,c]=ft.useState(""),[y,T]=ft.useState({}),z=()=>x(async()=>{let S=N.trim(),A=O.split(",").map(ue=>ue.trim()).filter(Boolean);if(!S)throw new Error("Option name is required");if(A.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:S,values:A}),l.current&&(I(""),c(""))}),L=S=>x(async()=>{let A=(y[S.id]??"").trim();if(!A)throw new Error("Enter a value");await t.updateOption(S.id,{add_values:[A]}),l.current&&T(ue=>({...ue,[S.id]:""}))}),R=(S,A)=>x(()=>t.updateOption(S.id,{remove_values:[A]})),$=S=>x(()=>t.deleteOption(S.id)),[d,U]=ft.useState(null),[se,Q]=ft.useState(null),[oe,ne]=ft.useState(!1),[J,ee]=ft.useState(null),de=i?.options??[],q=i?.variants??[],ve=()=>{Q(null),U({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(de.map(S=>[S.id,S.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},st=S=>{Q(null);let A=S.inventory?.on_hand??0,ue=A<0?"":String(A);U({variant:S,title:S.title??"",sku:S.sku??"",unitAmount:S.unit_amount!=null?String(dt(S.unit_amount,a)):"",compareAt:S.compare_at_amount!=null?String(dt(S.compare_at_amount,a)):"",active:S.active,optionValues:{},tracked:S.inventory?.tracked??!1,onHand:ue,initialOnHand:ue,allowBackorder:S.inventory?.allow_backorder??!1})},lt=async()=>{if(!d)return;Q(null);let S=d.variant?.allow_custom_amount??!1,A=null,ue=null;if(!S){if(A=zt(d.unitAmount,a),A===null||A<=0){Q("Enter a valid price");return}if(d.compareAt.trim()&&(ue=zt(d.compareAt,a),ue===null||ue<=A)){Q("Compare-at price must be greater than the price");return}}let Ve=d.onHand.trim()!==d.initialOnHand.trim(),we=parseInt(d.onHand,10);if(d.tracked&&Ve&&(!Number.isFinite(we)||we<0)){Q("On-hand quantity must be zero or more");return}try{if(ne(!0),d.variant)await t.updateVariant(d.variant.id,{title:d.title.trim()||null,sku:d.sku.trim()||null,...S?{}:{unit_amount:A,compare_at_amount:ue},active:d.active}),await t.setVariantInventory(d.variant.id,{tracked:d.tracked,on_hand:d.tracked&&Ve?we:void 0,allow_backorder:d.allowBackorder});else{let He={};for(let et of de){let ct=d.optionValues[et.id];if(!ct){Q(`Choose a ${et.title}`),ne(!1);return}He[et.title]=ct}await t.createVariant(e,{title:d.title.trim()||null,sku:d.sku.trim()||null,unit_amount:A,compare_at_amount:ue,active:d.active,option_values:de.length>0?He:void 0,inventory:d.tracked?{tracked:!0,on_hand:we,allow_backorder:d.allowBackorder}:{tracked:!1,allow_backorder:d.allowBackorder}})}await b(),l.current&&U(null)}catch(He){if(l.current&&Q(He instanceof Error?He.message:"Failed to save variant"),d.variant)try{let et=await t.getProduct(e);l.current&&o(et)}catch{}}finally{l.current&&ne(!1)}},Re=()=>x(async()=>{J&&(await t.deleteVariant(J.id),l.current&&ee(null))}),xe=d?.variant?.allow_custom_amount??!1,vt=d?.variant!=null&&d.variant.option_values.length===0&&de.length>0&&!d.variant.active,E=d?.variant?.inventory!=null&&d.variant.inventory.on_hand<0?-d.variant.inventory.on_hand:null;function te(S){let A=S.inventory;if(!A||!A.tracked)return j("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ue=A.available??A.on_hand;return ue<0?fe("span",{children:[-ue," backordered"]}):fe("span",{children:[ue," in stock",A.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(Jr,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):g?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:g})}):fe("div",{className:`af-space-y-6 ${s||""}`,children:[fe("div",{className:"af-space-y-3",children:[fe("div",{children:[j(be,{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."})]}),de.length>0&&j("div",{className:"af-space-y-3",children:de.map(S=>fe("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[fe("div",{className:"af-flex af-items-center af-justify-between",children:[j("span",{className:"af-text-sm af-font-medium",children:S.title}),j(w,{variant:"ghost",size:"sm",onClick:()=>$(S),disabled:p,children:j(Yr,{className:"af-h-4 af-w-4"})})]}),j("div",{className:"af-flex af-flex-wrap af-gap-2",children:S.values.map(A=>fe(Z,{variant:"secondary",className:"af-gap-1",children:[A.value,j("button",{type:"button",onClick:()=>R(S,A.value),className:"af-ml-1 hover:af-text-destructive",disabled:p,title:"Remove value",children:j(Bl,{className:"af-h-3 af-w-3"})})]},A.id))}),fe("div",{className:"af-flex af-gap-2",children:[j(ge,{value:y[S.id]??"",onChange:A=>T(ue=>({...ue,[S.id]:A.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),L(S))},disabled:p}),j(w,{type:"button",variant:"outline",size:"sm",onClick:()=>L(S),disabled:p||!(y[S.id]??"").trim(),children:j(Wn,{className:"af-h-4 af-w-4"})})]})]},S.id))}),fe("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[fe("div",{className:"af-space-y-1",children:[j(be,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),j(ge,{id:"new-option-title",value:N,onChange:S=>I(S.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:p})]}),fe("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[j(be,{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:S=>c(S.target.value),placeholder:"S, M, L",disabled:p})]}),fe(w,{type:"button",variant:"outline",onClick:z,disabled:p||!N.trim()||!O.trim(),children:[j(Wn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),fe("div",{className:"af-space-y-3",children:[fe("div",{className:"af-flex af-items-center af-justify-between",children:[j(be,{children:"Variants"}),fe(w,{type:"button",variant:"outline",size:"sm",onClick:ve,disabled:p||de.length===0,children:[j(Wn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),de.length===0&&j("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),q.length===0?j("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):fe(Oe,{children:[j(Be,{children:fe(pe,{children:[j(F,{children:"Variant"}),j(F,{children:"SKU"}),j(F,{children:"Price"}),j(F,{children:"Stock"}),j(F,{children:"Status"}),j(F,{className:"af-text-right",children:"Actions"})]})}),j(Fe,{children:q.map(S=>fe(pe,{children:[j(M,{className:"af-font-medium",children:Kn(S)}),j(M,{className:"af-text-muted-foreground",children:S.sku||"-"}),j(M,{children:S.unit_amount!=null?fe("span",{children:[S.compare_at_amount!=null&&j("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:H(S.compare_at_amount,S.currency)}),H(S.unit_amount,S.currency)]}):S.allow_custom_amount?j("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),j(M,{children:te(S)}),j(M,{children:j(Z,{variant:S.active?"success":"secondary",children:S.active?"Active":"Inactive"})}),j(M,{className:"af-text-right",children:fe("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[j(w,{variant:"ghost",size:"sm",onClick:()=>st(S),disabled:p,children:"Edit"}),j(w,{variant:"ghost",size:"icon",onClick:()=>ee(S),disabled:p,title:"Delete variant",children:j(Yr,{className:"af-h-4 af-w-4"})})]})})]},S.id))})]})]}),v&&j("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),j(Ca,{open:d!==null,onOpenChange:S=>{!S&&!oe&&U(null)},children:fe(va,{children:[fe(ba,{children:[j(ha,{children:d?.variant?"Edit variant":"Add variant"}),j(xa,{children:"Price, markdown, and stock live on the variant."})]}),d&&fe("div",{className:"af-space-y-3",children:[d.variant?d.variant.option_values.length>0&&fe("div",{className:"af-text-sm",children:[j("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Kn(d.variant)]}):de.map(S=>fe("div",{className:"af-space-y-1",children:[j(be,{className:"af-text-xs af-text-muted-foreground",children:S.title}),fe(na,{value:d.optionValues[S.id]??"",onValueChange:A=>U(ue=>ue&&{...ue,optionValues:{...ue.optionValues,[S.id]:A}}),children:[j(Yt,{children:j(ra,{placeholder:`Choose ${S.title}`})}),j(Zt,{children:S.values.map(A=>j(ze,{value:A.value,children:A.value},A.id))})]})]},S.id)),xe?fe("div",{className:"af-space-y-1",children:[j(be,{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."})]}):fe("div",{className:"af-flex af-gap-3",children:[fe("div",{className:"af-space-y-1",children:[fe(be,{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:d.unitAmount,onChange:S=>U(A=>A&&{...A,unitAmount:S.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),fe("div",{className:"af-space-y-1",children:[j(be,{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:d.compareAt,onChange:S=>U(A=>A&&{...A,compareAt:S.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),fe("div",{className:"af-space-y-1",children:[j(be,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),j(ge,{id:"variant-sku",value:d.sku,onChange:S=>U(A=>A&&{...A,sku:S.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),fe("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[fe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[j("input",{type:"checkbox",checked:d.tracked,onChange:S=>U(A=>A&&{...A,tracked:S.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),d.tracked&&fe("div",{className:"af-space-y-1 af-pl-6",children:[fe("div",{className:"af-flex af-items-end af-gap-3",children:[fe("div",{className:"af-space-y-1",children:[j(be,{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:d.onHand,onChange:S=>U(A=>A&&{...A,onHand:S.target.value}),placeholder:E!=null?"0":void 0,className:"af-w-[100px]"})]}),fe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[j("input",{type:"checkbox",checked:d.allowBackorder,onChange:S=>U(A=>A&&{...A,allowBackorder:S.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),E!=null&&fe("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",E," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),fe("div",{className:"af-space-y-1",children:[fe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[j("input",{type:"checkbox",checked:d.active,onChange:S=>U(A=>A&&{...A,active:S.target.checked}),className:"af-h-4 af-w-4",disabled:vt}),"Active (buyers can purchase this variant)"]}),vt&&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."})]}),se&&j("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:se})]}),fe(ya,{children:[j(w,{variant:"outline",onClick:()=>U(null),disabled:oe,children:"Cancel"}),fe(w,{onClick:lt,disabled:oe,children:[oe?j(Jr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?.variant?"Save":"Add variant"]})]})]})}),j(Ca,{open:J!==null,onOpenChange:S=>{!S&&!p&&ee(null)},children:fe(va,{children:[fe(ba,{children:[j(ha,{children:"Delete variant?"}),j(xa,{children:J&&`"${Kn(J)}" will no longer be purchasable. Past orders are unaffected.`})]}),fe(ya,{children:[j(w,{variant:"outline",onClick:()=>ee(null),disabled:p,children:"Cancel"}),j(w,{variant:"destructive",onClick:Re,disabled:p,children:"Delete"})]})]})})]})}import{Fragment as zl,jsx as me,jsxs as _e}from"react/jsx-runtime";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 ln({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:m,attachProductFileFromUrl:f}=e,g=!!a,r=a?.currency??s,v=ca(r)?"1":"0.01",h=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[p,u]=Ge.useState(!1),[l,b]=Ge.useState(null),x=Ge.useRef(!0);Ge.useEffect(()=>(x.current=!0,()=>{x.current=!1}),[]);let[N,I]=Ge.useState(a?.name??""),[O,c]=Ge.useState(a?.description??""),[y,T]=Ge.useState(a?.allow_custom_amount?"custom":"fixed"),[z,L]=Ge.useState(a?.unit_amount!=null?String(dt(a.unit_amount,r)):""),[R,$]=Ge.useState(a?.min_amount!=null?String(dt(a.min_amount,r)):""),[d,U]=Ge.useState(a?.max_amount!=null?String(dt(a.max_amount,r)):""),[se,Q]=Ge.useState(String(a?.max_quantity??10)),oe=Ge.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(dt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(dt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(dt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[ne,J]=Ge.useState(a?.collect_shipping_address??!1),[ee,de]=Ge.useState(a?.active??!0),[q,ve]=Ge.useState(a?.images??[]),[st,lt]=Ge.useState(""),[Re,xe]=Ge.useState(a?.fulfillment??null),[vt,E]=Ge.useState(!1),[te,S]=Ge.useState(""),[A,ue]=Ge.useState(null),Ve=Ge.useRef(null),we=p||vt,He=()=>{let ae=st.trim();if(ae){if(q.includes(ae)){b("This image URL is already added");return}ve(Pe=>[...Pe,ae]),lt(""),b(null)}},et=ae=>{ve(Pe=>Pe.filter(Ye=>Ye!==ae))},ct=async()=>{if(b(null),!N.trim()){b("Product name is required");return}let ae=null,Pe=null,Ye=null,Ra=!g||y!==oe.pricingMode||(y==="fixed"?z!==oe.unitAmount:R!==oe.minAmount||d!==oe.maxAmount),sa=!g||se!==oe.maxQuantity,Ua=h||y==="fixed";if(!(h||!Ra))if(y==="fixed"){if(ae=zt(z,r),ae===null||ae<=0){b("Enter a valid price");return}}else{if(Pe=zt(R,r),Ye=zt(d,r),Pe===null||Ye===null){b("Enter valid minimum and maximum amounts");return}if(Ye<Pe){b("Maximum amount must be at least the minimum amount");return}}let tt=parseInt(se,10);if(Ua&&sa&&(!Number.isFinite(tt)||tt<1)){b("Max quantity must be at least 1");return}try{u(!0);let Ze;if(g&&a){let D={name:N.trim(),description:O.trim()||null,images:q,collect_shipping_address:ne,active:ee};!h&&Ra&&(D.allow_custom_amount=y==="custom",y==="fixed"?D.unit_amount=ae:(D.min_amount=Pe,D.max_amount=Ye)),Ua&&sa&&(D.max_quantity=tt),Ze=await o(a.id,D),oe.pricingMode=Ze.allow_custom_amount?"custom":"fixed",oe.unitAmount=Ze.unit_amount!=null?String(dt(Ze.unit_amount,r)):"",oe.minAmount=Ze.min_amount!=null?String(dt(Ze.min_amount,r)):"",oe.maxAmount=Ze.max_amount!=null?String(dt(Ze.max_amount,r)):"",oe.maxQuantity=String(Ze.max_quantity)}else{let D={name:N.trim(),allow_custom_amount:y==="custom",collect_shipping_address:ne,active:ee};O.trim()&&(D.description=O.trim()),q.length>0&&(D.images=q),y==="fixed"?(D.unit_amount=ae,D.max_quantity=tt):(D.min_amount=Pe,D.max_amount=Ye),Ze=await i(D)}if(!x.current)return;xe(Ze.fulfillment),t?.(Ze)}catch(Ze){if(!x.current)return;b(Ze instanceof Error?Ze.message:"Failed to save product")}finally{x.current&&u(!1)}},Ut=async ae=>{let Pe=ae.target.files?.[0];if(!(!Pe||!a))try{E(!0),ue(null);let Ye=await m(a.id,Pe);if(!x.current)return;xe(Ye.fulfillment),t?.(Ye)}catch(Ye){if(!x.current)return;ue(Ye instanceof Error?Ye.message:"Failed to upload file")}finally{x.current&&(E(!1),Ve.current&&(Ve.current.value=""))}},$t=async()=>{let ae=te.trim();if(!(!ae||!a))try{E(!0),ue(null);let Pe=await f(a.id,ae);if(!x.current)return;xe(Pe.fulfillment),S(""),t?.(Pe)}catch(Pe){if(!x.current)return;ue(Pe instanceof Error?Pe.message:"Failed to fetch file")}finally{x.current&&E(!1)}};return _e("div",{className:`af-space-y-6 ${n||""}`,children:[_e("div",{className:"af-space-y-2",children:[me(be,{htmlFor:"product-name",children:"Name"}),me(ge,{id:"product-name",value:N,onChange:ae=>I(ae.target.value),placeholder:"My product"})]}),_e("div",{className:"af-space-y-2",children:[me(be,{htmlFor:"product-description",children:"Description"}),me("textarea",{id:"product-description",value:O,onChange:ae=>c(ae.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:[me(be,{children:"Pricing"}),h?me("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(zl,{children:[_e(na,{value:y,onValueChange:ae=>T(ae),children:[me(Yt,{className:"af-w-[260px]",children:me(ra,{})}),_e(Zt,{children:[me(ze,{value:"fixed",children:"Fixed price"}),me(ze,{value:"custom",children:"Buyer chooses the amount"})]})]}),y==="fixed"?me("div",{className:"af-flex af-items-end af-gap-3",children:_e("div",{className:"af-space-y-1",children:[_e(be,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),me(ge,{id:"product-price",type:"number",min:"0",step:v,value:z,onChange:ae=>L(ae.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(be,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),me(ge,{id:"product-min-amount",type:"number",min:"0",step:v,value:R,onChange:ae=>$(ae.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),_e("div",{className:"af-space-y-1",children:[_e(be,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),me(ge,{id:"product-max-amount",type:"number",min:"0",step:v,value:d,onChange:ae=>U(ae.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),me("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."]})]}),(h||y==="fixed")&&_e("div",{className:"af-space-y-1",children:[me(be,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),me(ge,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:se,onChange:ae=>Q(ae.target.value),className:"af-w-[140px]"})]})]}),_e("div",{className:"af-space-y-2",children:[me(be,{children:"Images"}),me("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:[q.map(ae=>_e(Z,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[me("span",{className:"af-truncate",children:ae}),me("button",{type:"button",onClick:()=>et(ae),className:"af-ml-1 hover:af-text-destructive",disabled:p,children:me(Vl,{className:"af-h-3 af-w-3"})})]},ae)),q.length===0&&me("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),_e("div",{className:"af-flex af-gap-2",children:[me(ge,{type:"url",value:st,onChange:ae=>lt(ae.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),He())},disabled:p}),me(w,{type:"button",variant:"outline",onClick:He,disabled:!st.trim()||p,children:me(Ul,{className:"af-h-4 af-w-4"})})]})]}),_e("div",{className:"af-space-y-2",children:[me(be,{children:"Digital File"}),me("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."}),g?_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:[me(Fl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),me("span",{className:"af-text-sm",children:Re.filename}),Re.size!=null&&_e("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Hl(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:[me(Ml,{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:[me("input",{ref:Ve,type:"file",onChange:Ut,className:"af-hidden",disabled:we}),_e(w,{type:"button",variant:"outline",size:"sm",onClick:()=>Ve.current?.click(),disabled:we,children:[vt?me(Zr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):me($l,{className:"af-h-4 af-w-4 af-mr-1"}),Re?.type==="download"?"Replace file":"Upload file"]}),me("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),me(ge,{type:"url",value:te,onChange:ae=>S(ae.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:vt}),me(w,{type:"button",variant:"outline",size:"sm",onClick:$t,disabled:!te.trim()||we,children:"Fetch from URL"})]}),A&&me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:A})]}):me("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:[me(be,{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:[me("input",{type:"checkbox",checked:ne,onChange:ae=>J(ae.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:[me("input",{type:"checkbox",checked:ee,onChange:ae=>de(ae.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),g&&a&&_e("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[me(be,{children:"Options & Variants"}),me(on,{productId:a.id,currency:r})]}),l&&me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),me("div",{className:"af-flex af-items-center af-gap-2",children:_e(w,{type:"button",onClick:ct,disabled:we,children:[p?me(Zr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,g?"Save changes":"Create product"]})})]})}import*as wt from"react";import{ChevronLeft as mc,ChevronRight as ui,Loader2 as pc,Receipt as gc,Search as vc,SlidersHorizontal as bc}from"lucide-react";import*as at from"react";var ql=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function cn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=at.useState([]),[i,o]=at.useState(0),[m,f]=at.useState(!0),[g,r]=at.useState(null),[v,h]=at.useState(0),[p,u]=at.useState(e),[l,b]=at.useState(void 0),[x,N]=at.useState(""),[I,O]=at.useState(""),[c,y]=at.useState(""),[T,z]=at.useState(!1),[L,R]=at.useState(!1),[$,d]=at.useState(void 0),U=$?$.join(","):"",se=at.useMemo(()=>{if(!U)return;let J=new Set(U.split(","));return ql.filter(ee=>!J.has(ee))},[U]),Q=at.useRef(0),oe=at.useCallback(async()=>{let J=++Q.current;try{f(!0),r(null);let ee={limit:p,offset:v*p};l?ee.status=l:se?ee.excludeStatus=se:T||(ee.excludeStatus=["pending","expired"]),x.trim()&&(ee.customerEmail=x.trim()),I.trim()&&(ee.from=I.trim()),c.trim()&&(ee.to=c.trim()),L&&(ee.unfulfilledOnly=!0);let de=await s.getOrders(ee);if(J!==Q.current)return;n(de.orders),o(de.total)}catch(ee){if(J!==Q.current)return;r(ee instanceof Error?ee:new Error("Failed to fetch orders"))}finally{J===Q.current&&f(!1)}},[s,v,p,l,se,T,L,x,I,c,a]);at.useEffect(()=>{oe()},[oe]);let ne=Math.ceil(i/p);return{orders:t,total:i,isLoading:m,error:g,page:v,pageSize:p,hasNextPage:v<ne-1,hasPreviousPage:v>0,setPage:h,setPageSize:J=>{u(J),h(0)},status:l,setStatus:J=>{b(J),h(0)},statusIn:$,setStatusIn:J=>{d(J&&J.length>0?J:void 0),h(0)},customerEmail:x,setCustomerEmail:J=>{N(J),h(0)},from:I,setFrom:J=>{O(J),h(0)},to:c,setTo:J=>{y(J),h(0)},showAbandoned:T,setShowAbandoned:J=>{z(J),h(0)},unfulfilledOnly:L,setUnfulfilledOnly:J=>{R(J),h(0)},clearFilters:()=>{b(void 0),d(void 0),z(!1),R(!1),N(""),O(""),y(""),h(0)},refetch:oe}}import*as it from"react";import{ArrowLeft as Wl,Check as ai,ChevronLeft as Kl,ChevronRight as Jl,ClipboardCopy as Yl,Copy as Zl,Download as Ql,Loader2 as dn,Mail as si,MoreHorizontal as Xl,Package as ec,RotateCcw as tc,Truck as ac,Undo2 as ni}from"lucide-react";import*as Qr from"react";import*as Ea from"@radix-ui/react-popover";import{jsx as Jn}from"react/jsx-runtime";var Xr=Ea.Root,ei=Ea.Trigger;var Yn=Qr.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>Jn(Ea.Portal,{children:Jn("div",{className:"aifeatures-admin",children:Jn(Ea.Content,{ref:n,align:a,sideOffset:s,className:W("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...t})})}));Yn.displayName=Ea.Content.displayName;import{jsx as un}from"react/jsx-runtime";var jl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Gl(e){return jl[e]??e}function ti(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 ns({status:e,className:a}){return un(Z,{variant:ti(e),className:a,children:Gl(e)})}function rs({status:e}){return un(ns,{status:e})}function ms({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?un(Z,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?un(Z,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Ga(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as uc,jsx as P,jsxs as K}from"react/jsx-runtime";var li="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",is="af-text-xs af-text-muted-foreground";function Zn(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 sc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ci(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 fn=24,nc=["paid","partially_refunded"],rc=["paid","partially_refunded","disputed"],ic=/^[A-Za-z0-9 _-]*$/,ri=100;function er(e,a,s,t,n){let i=nc.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 ${fn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${fn} 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<fn&&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<fn&&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:m}){if(m)return K("div",{children:[P(Pa,{deliveries:[m]}),o&&P("div",{className:"af-mt-2",children:o})]});let f=er(n,s,t,i,a);return K("div",{children:[K("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[K("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(Z,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&P("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),o&&P("div",{className:"af-mt-2",children:o})]})}function oi(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=sc(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}: ${ci(n)}`)}function oc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function tr({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=it.useState(!1);if(!oc())return null;let m=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},f=i?P(ai,{className:"af-h-3 af-w-3"}):P(Zl,{className:"af-h-3 af-w-3"});return n==="icon"?P(w,{variant:"ghost",size:"icon",className:W("af-h-6 af-w-6 af-shrink-0",t),onClick:m,title:a,"aria-label":a,children:f}):K(w,{variant:"outline",size:"sm",className:t,onClick:m,"aria-label":a,children:[i?P(ai,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):P(Yl,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Qn({label:e,value:a}){return K("div",{children:[P("div",{className:is,children:e}),K("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(tr,{value:a,label:`Copy ${e}`})]})]})}function lc({src:e}){let[a,s]=it.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(ec,{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 Ia({title:e,action:a,children:s,className:t}){return K("section",{className:W("af-rounded-lg af-border af-p-4",t),children:[K("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[P("h4",{className:li,children:e}),a]}),P("div",{className:"af-mt-3",children:s})]})}function qt({label:e,emphasis:a,divider:s,children:t}){return K("div",{className:W("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":is,children:e}),P("span",{className:W("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Xn({onSelect:e,disabled:a,icon:s,children:t}){return K(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 cc(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 ${H(sn(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?Js(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?Js(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 ${H(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 mn({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:m=!1,hasNextOrder:f=!1}){let{api:g}=ie(),[r,v]=it.useState(e),[h,p]=it.useState(null),[u,l]=it.useState(null),[b,x]=it.useState(!1),[N,I]=it.useState(!1),[O,c]=it.useState(!1),[y,T]=it.useState(!1),[z,L]=it.useState(""),[R,$]=it.useState(!1),[d,U]=it.useState(null),[se,Q]=it.useState(!1),[oe,ne]=it.useState(""),[J,ee]=it.useState([]),[de,q]=it.useState(!1),[ve,st]=it.useState(!1),[lt,Re]=it.useState(null);it.useEffect(()=>{v(e)},[e]);let xe=k=>{let Ee=k.id===r.id&&k.email_deliveries===void 0?{...k,email_deliveries:r.email_deliveries}:k;v(Ee),t?.(Ee)},vt=Object.entries(r.metadata??{}),E=Math.max(0,sn(r)-r.amount_refunded),te=(r.status==="paid"||r.status==="partially_refunded")&&E>0,S=r.exclusive_tax_total!=null,A=k=>typeof k.amountNet=="number"?k.amountNet+(k.exclusiveTax??0):(typeof k.unitAmount=="number"?k.unitAmount:0)*(typeof k.quantity=="number"&&k.quantity>0?k.quantity:1),ue=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),Ve=J.reduce((k,Ee)=>k+A(r.line_items[Ee]??{}),0)+(de?ue:0),we=r.tax_total??0,He=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((k,Ee)=>k+(Ee.exclusiveTax??0),0)),et=S?de&&ue>0?He:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&we>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,we-(r.tax_refunded??0)),Math.round(we*Ve/(r.amount_total+(r.shipping_total??0)))):0,ct=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(Ve+et,E):Ve+et,Ut=J.length>0||de,$t=Ut?ct:zt(oe,r.currency),ae=ca(r.currency)?"1":"0.01",Pe=async()=>{try{x(!0),p(null),l(null),await g.resendOrderReceipt(r.id);let k=await g.getOrder(r.id);xe(k),l("Receipt email queued.")}catch(k){p(k instanceof Error?k.message:"Failed to resend receipt")}finally{x(!1)}},Ye=async()=>{try{I(!0),p(null),l(null);let k=await g.resetOrderDownloads(r.id);xe(k),c(!1),l("Download count reset.")}catch(k){p(k instanceof Error?k.message:"Failed to reset downloads")}finally{I(!1)}},Ra=r.line_items.some(k=>k.collectShippingAddress===!0&&!k.refunded&&!k.unavailableReason),sa=typeof r.merchant_fulfilled_at=="string",Ua=rc.includes(r.status)||r.status==="refunded"&&r.line_items.some(k=>k.collectShippingAddress===!0&&k.amountNet===0&&!k.refunded&&!k.unavailableReason),tt=z.trim(),Ze=ic.test(tt)&&tt.length<=ri,D=async k=>{try{$(!0),U(null),l(null);let Ee=await g.setOrderFulfillment(r.id,{fulfilled:k,...k&&tt?{trackingNumber:tt}:{}});xe(Ee),L(""),l(k?"Marked as shipped.":"Marked as not shipped.")}catch(Ee){Ee instanceof Ht&&Ee.status===409?U(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):U(Ee instanceof Error?Ee.message:"Failed to update the order")}finally{$(!1)}},je=()=>{Re(null),ne(String(dt(E,r.currency))),ee([]),q(!1),Q(!0)},V=k=>ee(Ee=>Ee.includes(k)?Ee.filter(Vt=>Vt!==k):[...Ee,k]),Tt=async(k,Ee)=>{if(s)try{st(!0),Re(null),await s(r,k,Ee);let Vt=await g.getOrder(r.id);xe(Vt),Q(!1),l("Refund issued.")}catch(Vt){Re(Vt instanceof Error?Vt.message:"Refund failed")}finally{st(!1)}},vo=async()=>{if(Ut){if(ct<=0){Re("The lines you picked were charged nothing");return}if(ct>E){Re(`That selection exceeds the refundable remainder (${H(E,r.currency)})`);return}await Tt(ct,{...J.length>0?{line_items:[...J].sort((Ee,Vt)=>Ee-Vt)}:{},...de?{shipping:!0}:{}});return}let k=zt(oe,r.currency);if(k===null||k<=0){Re("Enter a valid refund amount");return}if(k>E){Re(`Amount exceeds the refundable remainder (${H(E,r.currency)})`);return}await Tt(k,{amount:k})},bo=()=>Tt(E,{full:!0}),Pr=!r.subscription_history_only&&r.fulfillment_type==="download",Cr=!r.subscription_history_only&&n&&Ra,yo=cc(r),ho=r.shipping_address?oi(r.shipping_address).join(`
|
|
4
|
-
`):"",Tr=r.shipping_total!=null,Un=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),kr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-Un):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,Er=Un>0,xo=kr>0,Ir=r.amount_subtotal!=null||Tr||Er||(r.discount_total??0)>0,Cs=[];return r.subscription_history_only||Cs.push(P(Xn,{icon:b?P(dn,{className:"af-h-4 af-w-4 af-animate-spin"}):P(si,{className:"af-h-4 af-w-4"}),disabled:b||r.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Pe()},children:"Resend receipt"},"resend")),Pr&&Cs.push(P(Xn,{icon:P(tc,{className:"af-h-4 af-w-4"}),disabled:N,onSelect:()=>{T(!1),c(!0)},children:"Reset download count"},"reset")),te&&Cs.push(K("div",{children:[P(Xn,{icon:P(ni,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{T(!1),je()},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")),K("div",{children:[K("div",{className:"af-mb-6",children:[K(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[P(Wl,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),K("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[K("div",{className:"af-min-w-0",children:[K("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[P("h3",{className:"af-text-xl af-font-semibold",children:Ga(r)}),P(ns,{status:r.status}),n&&!r.subscription_history_only&&P(ms,{order:r}),r.is_test&&P(Z,{variant:"outline",children:"Test"})]}),K("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Zn(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."})]}),K("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&K("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(Kl,{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:!f,"aria-label":"Next order",children:P(Jl,{className:"af-h-4 af-w-4"})})]}),Cr&&(sa?K("div",{className:"af-flex af-items-center af-gap-1",children:[K("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${Zn(r.merchant_fulfilled_at)}`:""]}),Ua&&K(w,{variant:"ghost",size:"sm",onClick:()=>D(!1),disabled:R,children:[R?P(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(ni,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Ua?K("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[P(ge,{value:z,onChange:k=>L(k.target.value),placeholder:"Tracking number (optional)",maxLength:ri,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:R}),K(w,{variant:"default",className:"af-shrink-0",onClick:()=>D(!0),disabled:R||!Ze,children:[R?P(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(ac,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Cs.length>0&&K(Xr,{open:y,onOpenChange:T,children:[P(ei,{asChild:!0,children:P(w,{variant:"outline",size:"icon","aria-label":"More actions",children:P(Xl,{className:"af-h-4 af-w-4"})})}),P(Yn,{children:P("div",{className:"af-space-y-0.5",children:Cs})})]})]})]}),Cr&&!sa&&!Ze&&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."}),d&&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:d}),u&&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:u}),h&&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:h})]}),K("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[K("div",{className:"af-space-y-6",children:[r.line_items.length>0&&P(Ia,{title:"Items",children:P("ul",{className:"af-space-y-3",children:r.line_items.map((k,Ee)=>{let Vt=typeof k.name=="string"&&k.name?k.name:"Item",Ar=typeof k.quantity=="number"&&k.quantity>0?k.quantity:1,Dr=typeof k.unitAmount=="number";return K("li",{className:"af-flex af-items-start af-gap-3",children:[P(lc,{src:typeof k.imageUrl=="string"&&k.imageUrl?k.imageUrl:void 0}),K("div",{className:"af-min-w-0 af-flex-1",children:[K("div",{className:"af-text-sm af-font-medium",children:[Vt,typeof k.variantTitle=="string"&&k.variantTitle&&K("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",k.variantTitle]})]}),K("div",{className:is,children:[Ar," \xD7"," ",Dr?H(k.unitAmount,r.currency):"\u2014"]}),k.unavailableReason==="oversold"&&!k.refunded&&P(Z,{variant:"secondary",className:"af-mt-1",children:k.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),k.refunded===!0&&P(Z,{variant:"secondary",className:"af-mt-1",children:k.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),P("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof k.amountNet=="number"||Dr?H(k.amountNet??k.unitAmount*Ar,r.currency):"\u2014"})]},Ee)})})}),vt.length>0&&P(Ia,{title:"Order details",children:P("dl",{className:"af-space-y-2",children:vt.map(([k,Ee])=>K("div",{children:[P("dt",{className:W(is,"af-capitalize"),children:k.replace(/_/g," ")}),P("dd",{className:"af-text-sm af-break-words",children:ci(Ee)})]},k))})}),P(Ia,{title:"Totals",children:K("div",{className:"af-w-full",children:[Ir&&P(qt,{label:"Subtotal",children:H(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&K(qt,{label:"Discount",children:["\u2212",H(r.discount_total,r.currency)]}),Tr&&P(qt,{label:"Shipping",children:r.shipping_total===0?"Free":H(r.shipping_total??0,r.currency)}),Er&&P(qt,{label:"Tax",children:H(Un,r.currency)}),P(qt,{label:"Total",emphasis:!0,divider:Ir,children:H(ja(r),r.currency)}),(r.credit_applied??0)>0&&K(qt,{label:"Credit applied",children:["\u2212",H(r.credit_applied,r.currency)]}),r.amount_paid!=null&&P(qt,{label:"Amount paid",children:H(r.amount_paid,r.currency)}),xo&&P(qt,{label:"incl. tax",children:H(kr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&K(qt,{label:"Your price",children:[H(r.base_amount_total,r.base_currency),K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&K(uc,{children:[K(qt,{label:"Refunded",children:["\u2212",H(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",H(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),P(qt,{label:"Net",children:P("span",{className:"af-font-medium",children:H(Math.max(0,sn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&K(Ia,{title:"Platform fee",children:[r.application_fee_original!=null&&P(qt,{label:"Collected",children:H(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&P(qt,{label:"Returned",children:H(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&P(qt,{label:"Retained",children:H(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(Ia,{title:"Timeline",children:P("ol",{className:"af-space-y-3",children:yo.map(k=>K("li",{className:"af-flex af-gap-3",children:[P("span",{"aria-hidden":"true",className:W("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",k.tone==="destructive"?"af-bg-destructive":k.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),K("div",{className:"af-min-w-0",children:[P("div",{className:"af-text-sm af-break-words",children:k.text}),k.at&&P("div",{className:"af-text-xs af-text-muted-foreground",children:Zn(k.at)})]})]},k.key))})})]}),K("div",{className:"af-space-y-6",children:[P(Ia,{title:"Customer",children:K("div",{className:"af-space-y-2",children:[K("div",{children:[P("div",{className:is,children:"Email"}),K("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(tr,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&K("div",{children:[P("div",{className:is,children:"Name"}),P("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&K("div",{children:[P("div",{className:is,children:"Customer record"}),K("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(Z,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&P(Ia,{title:"Ship to",action:P(tr,{value:ho,label:"Copy address",size:"sm",children:"Copy address"}),children:P("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:oi(r.shipping_address).map((k,Ee)=>P("div",{children:k},Ee))})}),r.subscription_history_only?P(Ia,{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."})}):K(Ia,{title:"Emails",children:[P(Pa,{deliveries:r.email_deliveries?.filter(k=>!["purchase_receipt","merchant_sale"].includes(k.kind)),problemsOnly:!0,className:"af-mb-4"}),K("div",{className:"af-space-y-4",children:[P(ii,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(k=>k.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:K(w,{variant:"outline",size:"sm",onClick:Pe,disabled:b||r.fulfillment_status!=="fulfilled",children:[b?P(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(si,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),P(ii,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(k=>k.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),Pr&&P(Ia,{title:"Download",children:K("div",{className:"af-space-y-2",children:[K("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[P(Ql,{className:"af-h-4 af-w-4"}),K("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"})]})}),K("details",{className:"af-rounded-lg af-border af-p-4",children:[P("summary",{className:W(li,"af-cursor-pointer af-select-none"),children:"Technical details"}),K("div",{className:"af-mt-3 af-space-y-2",children:[P(Qn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&P(Qn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&P(Qn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),P(Ca,{open:O,onOpenChange:k=>{!k&&!N&&c(!1)},children:K(va,{children:[K(ba,{children:[P(ha,{children:"Reset download count?"}),P(xa,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),K(ya,{children:[P(w,{variant:"outline",onClick:()=>c(!1),disabled:N,children:"Cancel"}),P(w,{onClick:Ye,disabled:N,children:N?"Resetting...":"Reset"})]})]})}),P(Ca,{open:se,onOpenChange:k=>{!k&&!ve&&Q(!1)},children:K(va,{children:[K(ba,{children:[P(ha,{children:"Refund order"}),K(xa,{children:["Refund up to ",H(E,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),K("div",{className:"af-space-y-4",children:[(r.line_items.length>0||ue>0)&&K("div",{className:"af-space-y-2",children:[P(be,{children:"Items"}),K("div",{className:"af-space-y-2",children:[r.line_items.map((k,Ee)=>{let Vt=k.refunded===!0;return K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:J.includes(Ee),onChange:()=>V(Ee),disabled:ve||Vt||!!k.unavailableReason||A(k)<=0,className:"af-h-4 af-w-4"}),K("span",{className:Vt?"af-text-muted-foreground af-line-through":void 0,children:[typeof k.name=="string"&&k.name?k.name:"Item",typeof k.variantTitle=="string"&&k.variantTitle?` \u2014 ${k.variantTitle}`:"",typeof k.quantity=="number"&&k.quantity>1?` \xD7 ${k.quantity}`:""]}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:Vt?"Refunded":H(A(k),r.currency)})]},Ee)}),ue>0&&K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:de,onChange:k=>q(k.target.checked),disabled:ve,className:"af-h-4 af-w-4"}),P("span",{children:"Shipping"}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:H(ue,r.currency)})]})]})]}),K("div",{className:"af-space-y-2",children:[K(be,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),P(ge,{id:"refund-amount",type:"number",min:"0",step:ae,value:Ut?String(dt(ct,r.currency)):oe,onChange:k=>ne(k.target.value),disabled:ve||Ut}),Ut&&P("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),lt&&P("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:lt}),K(ya,{children:[P(w,{variant:"outline",onClick:()=>Q(!1),disabled:ve,children:"Cancel"}),P(w,{variant:"outline",onClick:bo,disabled:ve,children:"Refund everything"}),P(w,{variant:"destructive",onClick:vo,disabled:ve,children:ve?"Refunding...":$t!==null&&$t>0?`Refund ${H($t,r.currency)}`:"Refund"})]})]})})]})}import*as pn from"react";import{ArrowLeft as dc,RefreshCw as fc}from"lucide-react";import{jsx as Aa,jsxs as os}from"react/jsx-runtime";function Rt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=pn.useRef(null);return pn.useEffect(()=>{i.current?.focus()},[]),os("div",{className:W("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-justify-between af-gap-2 af-border-b af-bg-background af-px-4 af-py-2",children:[Aa("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&os(w,{type:"button",variant:"outline",size:"sm",onClick:a,children:[Aa(dc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Aa("div",{className:"af-p-4",children:t})]})}function X({className:e}){return Aa("div",{"aria-hidden":"true",className:W("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Qe({label:e,children:a,detail:s,valueClassName:t}){return os("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Aa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Aa("div",{className:W("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&Aa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function ea({message:e,onRetry:a}){return os("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Aa("span",{children:e}),os(w,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[Aa(fc,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Da({icon:e,children:a}){return os("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Aa("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}import{Fragment as hc,jsx as B,jsxs as ye}from"react/jsx-runtime";var yc={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},di={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 gn(e){return e.customer?.name||e.customer_name||null}function ps({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:m}=ie(),f=cn({refreshKey:s}),{orders:g,total:r,isLoading:v,error:h,page:p,pageSize:u,hasNextPage:l,hasPreviousPage:b,setPage:x,setPageSize:N,customerEmail:I,setCustomerEmail:O,setStatusIn:c,from:y,setFrom:T,to:z,setTo:L,showAbandoned:R,setShowAbandoned:$,setUnfulfilledOnly:d,refetch:U}=f,[se,Q]=wt.useState("list"),[oe,ne]=wt.useState(null),[J,ee]=wt.useState(""),[de,q]=wt.useState(""),[ve,st]=wt.useState(n?"needs_shipping":"all"),[lt,Re]=wt.useState(!1),[xe,vt]=wt.useState(!!t),[E,te]=wt.useState(null);wt.useEffect(()=>{if(!t)return;let V=!1;return vt(!0),te(null),m.getOrder(t).then(Tt=>{V||(ne(Tt),Q("detail"))}).catch(()=>{V||te("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{V||vt(!1)}),()=>{V=!0}},[m,t]);let S=wt.useCallback(V=>{st(V);let Tt=di[V];c(Tt.statusIn),d(Tt.unfulfilledOnly)},[c,d]);wt.useEffect(()=>{n&&d(!0)},[]);let A=wt.useRef(!n);wt.useEffect(()=>{A.current||v||(A.current=!0,g.length===0&&S("all"))},[v,g.length,S]);let ue=se==="detail"&&!!oe;wt.useEffect(()=>{o?.(ue)},[ue,o]);let Ve=(y?1:0)+(z?1:0)+(R?1:0),we=Ve>0||!!I||!!de,He=!!y&&!!z&&y>z,et=V=>{ne(V),Q("detail")},ct=()=>{Q("list"),ne(null),U()},Ut=V=>{let Tt=V.trim();if(!Tt){q(""),I&&O("");return}if(Tt.startsWith("#")||/^\d+$/.test(Tt)){q(Tt),I&&O("");return}q(""),O(Tt)},$t=()=>{ee(""),q(""),O(""),T(""),L(""),$(!1),Re(!1)},ae=de.replace(/^#/,"").toLowerCase(),Pe=ae?g.filter(V=>String(V.order_number??"")===ae||V.id.toLowerCase().startsWith(ae)):g,Ye=oe?g.findIndex(V=>V.id===oe.id):-1,Ra=Ye>0,sa=Ye>=0&&Ye<g.length-1;if(xe)return B("div",{className:a,children:B("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:B(pc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(se==="detail"&&oe)return B("div",{className:a,children:B(mn,{order:oe,onBack:ct,onRefund:e,onOrderUpdated:V=>ne(V),allowFulfillment:n,onPrevOrder:Ra?()=>ne(g[Ye-1]):void 0,onNextOrder:sa?()=>ne(g[Ye+1]):void 0,hasPrevOrder:Ra,hasNextOrder:sa},oe.id)});let tt=ye("div",{className:"af-mb-4 af-space-y-3",children:[E&&B("p",{className:"af-text-xs af-text-muted-foreground",children:E}),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":ve===V,onClick:()=>S(V),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",ve===V?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:yc[V]},V))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[B(vc,{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:J,onChange:V=>ee(V.target.value),onBlur:()=>Ut(J),onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),Ut(J))},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:Ve>0?"secondary":"ghost",size:"sm",onClick:()=>Re(V=>!V),"aria-expanded":lt,children:[B(bc,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ve>0&&B(Z,{variant:"secondary",className:"af-ml-2",children:Ve})]}),we&&B(w,{type:"button",variant:"ghost",size:"sm",onClick:$t,children:"Clear filters"})]}),(lt||!!y||!!z)&&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(be,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),B(ge,{id:"orders-from",type:"date",value:y,max:z||void 0,onChange:V=>T(V.target.value),className:"af-w-[170px]"}),B(be,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),B(ge,{id:"orders-to",type:"date",value:z,min:y||void 0,onChange:V=>L(V.target.value),className:"af-w-[170px]"}),!di[ve].statusIn&&B(w,{type:"button",variant:R?"secondary":"ghost",size:"sm",onClick:()=>$(!R),"aria-pressed":R,children:R?"Hide abandoned":"Show abandoned"})]}),He&&B("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(v)return ye("div",{className:a,children:[tt,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(X,{className:"af-h-4 af-w-16"}),B(X,{className:"af-h-4 af-w-14"})]}),B(X,{className:"af-mt-2 af-h-3 af-w-40"}),B(X,{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(Oe,{children:[B(Be,{children:ye(pe,{children:[B(F,{children:"Order"}),B(F,{children:"Date"}),B(F,{children:"Customer"}),B(F,{children:"Items"}),B(F,{className:"af-text-right",children:"Total"}),B(F,{children:"Status"}),B(F,{className:"af-w-8"})]})}),B(Fe,{"aria-hidden":"true",children:[0,1,2,3,4].map(V=>ye(pe,{children:[B(M,{children:B(X,{className:"af-h-4 af-w-14"})}),B(M,{children:B(X,{className:"af-h-4 af-w-24"})}),B(M,{children:B(X,{className:"af-h-4 af-w-40"})}),B(M,{children:B(X,{className:"af-h-4 af-w-32"})}),B(M,{children:B(X,{className:"af-ml-auto af-h-4 af-w-16"})}),B(M,{children:B(X,{className:"af-h-5 af-w-16"})}),B(M,{})]},V))})]})}),B("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(h)return ye("div",{className:a,children:[tt,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:()=>U(),children:"Try again"})]})]});let Ze=ve!=="all";if(Pe.length===0&&p===0)return ye("div",{className:a,children:[(we||Ze)&&tt,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[B(gc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),B("p",{className:"af-text-muted-foreground af-text-center",children:we||Ze?"No orders match these filters.":i??ye(hc,{children:["No orders yet.",B("br",{}),"Orders will appear here when someone buys from your website."]})}),!we&&!Ze&&B(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>$(!0),children:"Show abandoned checkouts"})]})]});let D=p*u+1,je=Math.min((p+1)*u,r);return ye("div",{className:a,children:[tt,B("div",{className:"af-space-y-3 lg:af-hidden",children:Pe.map(V=>ye("button",{type:"button",onClick:()=>et(V),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left 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:Ga(V)}),B("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:H(ja(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"}),gn(V)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",gn(V)]})]}),B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:mi(V)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(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(ns,{status:V.status}),B(Es,{deliveries:V.email_deliveries}),V.is_test&&B(Z,{variant:"outline",children:"Test"}),n&&B(ms,{order:V}),B("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:fi(V.created_at)})]})]},V.id))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Oe,{children:[B(Be,{children:ye(pe,{children:[B(F,{children:"Order"}),B(F,{children:"Date"}),B(F,{children:"Customer"}),B(F,{children:"Items"}),B(F,{className:"af-text-right",children:"Total"}),B(F,{children:"Status"}),B(F,{className:"af-w-8"})]})}),B(Fe,{children:Pe.map(V=>ye(pe,{onClick:()=>et(V),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[ye(M,{className:"af-whitespace-nowrap af-font-medium",children:[B("button",{type:"button",onClick:Tt=>{Tt.stopPropagation(),et(V)},"aria-label":`Open order ${Ga(V)}`,className:"af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ga(V)}),V.is_test&&B(Z,{variant:"outline",className:"af-ml-2",children:"Test"})]}),B(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:fi(V.created_at)}),ye(M,{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"})}),gn(V)&&B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:gn(V)})]}),B(M,{className:"af-max-w-[220px]",children:B("div",{className:"af-truncate af-text-muted-foreground",children:mi(V)})}),ye(M,{className:"af-whitespace-nowrap af-text-right",children:[B("div",{className:"af-font-medium af-tabular-nums",children:H(ja(V),V.currency)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(V.amount_refunded,V.currency)," ","refunded"]})]}),B(M,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[B(ns,{status:V.status}),B(Es,{deliveries:V.email_deliveries}),n&&B(ms,{order:V})]})}),B(M,{className:"af-w-8 af-text-right",children:B(ui,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},V.id))})]})}),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:ae?`${Pe.length} matching this page`:`Showing ${D}-${je} of ${r}`}),ye(na,{value:String(u),onValueChange:V=>N(Number(V)),children:[B(Yt,{className:"af-w-[70px] af-h-8",children:B(ra,{})}),ye(Zt,{children:[B(ze,{value:"10",children:"10"}),B(ze,{value:"25",children:"25"}),B(ze,{value:"50",children:"50"}),B(ze,{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:()=>x(p-1),disabled:!b,children:[B(mc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ye(w,{variant:"outline",size:"sm",onClick:()=>x(p+1),disabled:!l,children:["Next",B(ui,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as yn from"react";import{ChevronLeft as Sc,ChevronRight as _c,Eye as Rc,Search as Pc,Users as Cc}from"lucide-react";import*as jt from"react";function vn({initialPageSize:e=25}={}){let{api:a}=ie(),[s,t]=jt.useState([]),[n,i]=jt.useState(0),[o,m]=jt.useState(!0),[f,g]=jt.useState(null),[r,v]=jt.useState(0),[h,p]=jt.useState(e),[u,l]=jt.useState(""),b=jt.useRef(0),x=jt.useCallback(async()=>{let I=++b.current;try{m(!0),g(null);let O={limit:h,offset:r*h};u.trim()&&(O.email=u.trim());let c=await a.getCustomers(O);if(I!==b.current)return;t(c.customers),i(c.total)}catch(O){if(I!==b.current)return;g(O instanceof Error?O:new Error("Failed to fetch customers"))}finally{I===b.current&&m(!1)}},[a,r,h,u]);jt.useEffect(()=>{x()},[x]);let N=Math.ceil(n/h);return{customers:s,total:n,isLoading:o,error:f,page:r,pageSize:h,hasNextPage:r<N-1,hasPreviousPage:r>0,setPage:v,setPageSize:I=>{p(I),v(0)},email:u,setEmail:I=>{l(I),v(0)},refetch:x}}import*as ls from"react";import{ArrowLeft as xc,Loader2 as wc}from"lucide-react";import{jsx as Ae,jsxs as Pt}from"react/jsx-runtime";function pi(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 Nc(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 bn({customer:e,onBack:a,className:s}){let{api:t}=ie(),[n,i]=ls.useState(null),[o,m]=ls.useState([]),[f,g]=ls.useState(!0),[r,v]=ls.useState(null);ls.useEffect(()=>{let u=!1;return g(!0),v(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,b])=>{u||(i(l),m(b.orders))}).catch(l=>{u||v(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{u||g(!1)}),()=>{u=!0}},[t,e.id,e.email]);let h=n?.addresses??[],p=n?.order_count??o.length;return Pt("div",{className:s,children:[Pt("div",{className:"af-mb-6",children:[Pt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[Ae(xc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Ae("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Pt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",pi(e.created_at)]})]}),f?Ae("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ae(wc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?Ae("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):Pt("div",{className:"af-space-y-6",children:[Ae(Pa,{deliveries:n?.email_deliveries}),Pt("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Pt("div",{className:"af-space-y-1 af-text-sm",children:[Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Ae("span",{children:e.email})]}),e.name&&Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Ae("span",{children:e.name})]}),e.phone&&Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Ae("span",{children:e.phone})]}),Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Ae("span",{children:p})]})]})]}),h.length>0&&Pt("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Ae("div",{className:"af-flex af-flex-wrap af-gap-3",children:h.map(u=>Pt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&Ae(Z,{variant:"secondary",className:"af-mb-1",children:"Default"}),Nc(u).map((l,b)=>Ae("div",{children:l},b))]},u.id))})]}),Pt("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Ae("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Pt(Oe,{children:[Ae(Be,{children:Pt(pe,{children:[Ae(F,{children:"Date"}),Ae(F,{children:"Amount"}),Ae(F,{children:"Status"})]})}),Ae(Fe,{children:o.map(u=>Pt(pe,{children:[Ae(M,{className:"af-text-muted-foreground",children:pi(u.created_at)}),Ae(M,{children:H(ja(u),u.currency)}),Ae(M,{children:Ae(rs,{status:u.status})})]},u.id))})]})]})]})]})}import{Fragment as kc,jsx as Ce,jsxs as mt}from"react/jsx-runtime";function Tc(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 hn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:m,hasPreviousPage:f,setPage:g,setPageSize:r,email:v,setEmail:h,refetch:p}=vn(),[u,l]=yn.useState("list"),[b,x]=yn.useState(null),[N,I]=yn.useState(""),O=L=>{x(L),l("detail")},c=()=>{l("list"),x(null),p()};if(u==="detail"&&b)return Ce("div",{className:e,children:Ce(bn,{customer:b,onBack:c})});let y=mt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Ce(ge,{type:"email",value:N,onChange:L=>I(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),h(N.trim()))}}),mt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>h(N.trim()),children:[Ce(Pc,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),v&&Ce(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{I(""),h("")},children:"Clear"})]});if(t)return mt("div",{className:e,children:[y,Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ce("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return mt("div",{className:e,children:[y,Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:mt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return mt("div",{className:e,children:[v&&y,mt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Ce(Cc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ce("p",{className:"af-text-muted-foreground af-text-center",children:v?"No customers match that email.":mt(kc,{children:["No customers yet.",Ce("br",{}),"Customers appear here after their first purchase."]})})]})]});let T=i*o+1,z=Math.min((i+1)*o,s);return mt("div",{className:e,children:[y,mt(Oe,{children:[Ce(Be,{children:mt(pe,{children:[Ce(F,{children:"Email"}),Ce(F,{children:"Name"}),Ce(F,{children:"Customer since"}),Ce(F,{className:"af-text-right",children:"Actions"})]})}),Ce(Fe,{children:a.map(L=>mt(pe,{children:[Ce(M,{className:"af-font-medium",children:L.email}),Ce(M,{children:L.name||Ce("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ce(M,{className:"af-text-muted-foreground",children:Tc(L.created_at)}),Ce(M,{className:"af-text-right",children:Ce(w,{variant:"ghost",size:"icon",onClick:()=>O(L),title:"View customer",children:Ce(Rc,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),mt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[mt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[mt("span",{children:["Showing ",T,"-",z," of ",s]}),mt(na,{value:String(o),onValueChange:L=>r(Number(L)),children:[Ce(Yt,{className:"af-w-[70px] af-h-8",children:Ce(ra,{})}),mt(Zt,{children:[Ce(ze,{value:"10",children:"10"}),Ce(ze,{value:"25",children:"25"}),Ce(ze,{value:"50",children:"50"}),Ce(ze,{value:"100",children:"100"})]})]}),Ce("span",{children:"per page"})]}),mt("div",{className:"af-flex af-items-center af-gap-2",children:[mt(w,{variant:"outline",size:"sm",onClick:()=>g(i-1),disabled:!f,children:[Ce(Sc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),mt(w,{variant:"outline",size:"sm",onClick:()=>g(i+1),disabled:!m,children:["Next",Ce(_c,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Se from"react";import{ArrowLeft as Ec,ChevronLeft as Ic,ChevronRight as gi,Copy as Ac,Download as Dc,ExternalLink as Lc,FileText as yi,Loader2 as Oc,Search as Bc}from"lucide-react";import*as pt from"react";function gs({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=ie(),[n,i]=pt.useState([]),[o,m]=pt.useState(0),[f,g]=pt.useState(null),[r,v]=pt.useState(!0),[h,p]=pt.useState(null),[u,l]=pt.useState(0),[b,x]=pt.useState(e),[N,I]=pt.useState(void 0),[O,c]=pt.useState(""),[y,T]=pt.useState(""),[z,L]=pt.useState(""),[R,$]=pt.useState(""),[d,U]=pt.useState(""),se=N?N.join(","):"",Q=pt.useRef(0),oe=pt.useCallback(async()=>{let J=++Q.current;v(!0),p(null);try{let ee={labels:se?se.split(","):void 0,customerEmail:O||void 0,q:y||void 0,from:z||void 0,to:R||void 0,retainerId:d||void 0,includeAggregates:s,limit:b,offset:u*b},de=await t.getInvoices(ee);if(J!==Q.current)return;if(u>0&&u*b>=de.total){l(Math.max(0,Math.ceil(de.total/b)-1));return}i(de.invoices),m(de.total),s&&g(de.aggregates??null)}catch(ee){if(J!==Q.current)return;p(ee instanceof Error?ee:new Error("Failed to fetch invoices"))}finally{J===Q.current&&v(!1)}},[t,se,O,y,z,R,d,u,b,s]);pt.useEffect(()=>{oe()},[oe,a]);let ne=J=>ee=>{l(0),J(ee)};return{invoices:n,total:o,aggregates:f,isLoading:r,error:h,page:u,pageSize:b,hasNextPage:(u+1)*b<o,hasPreviousPage:u>0,setPage:l,setPageSize:ne(x),labels:N,setLabels:ne(I),customerEmail:O,setCustomerEmail:ne(c),q:y,setQ:ne(T),from:z,setFrom:ne(L),to:R,setTo:ne($),retainerId:d,setRetainerId:ne(U),clearFilters:()=>{l(0),I(void 0),c(""),T(""),L(""),$(""),U("")},refetch:oe}}import{Fragment as zc,jsx as C,jsxs as G}from"react/jsx-runtime";var Fc={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 ir(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Fc[e.label]??e.label}function Mc(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 rr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Uc={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Os({invoice:e,className:a}){return G("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[C(Z,{variant:Mc(e.label),className:a,children:ir(e)}),e.collection_method==="charge_automatically"&&C(Z,{variant:"secondary",children:"Managed in Stripe"})]})}function wn({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(Z,{variant:s,className:a,children:rr[e.state]??e.state})}function vs(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function da(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 vi={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ar={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 $c(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 sr=100,nr=5e3;async function Vc(e,a){let s=[],t=0;for(let n=0;n<nr;n+=sr){let i=await e.getInvoices({...a,limit:sr,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<sr||s.length>=t)break}return{invoices:s.slice(0,nr),total:t,truncated:t>s.length||t>nr}}function hi(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,vs(t),ir(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),H(t.amount_subtotal,t.currency),H(t.tax_total,t.currency),H(t.amount_total,t.currency),t.amount_due===null?"":H(t.amount_due,t.currency),t.amount_paid===null?"":H(t.amount_paid,t.currency),H(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?"":H(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map($c).join(",")).join(`
|
|
5
|
-
`)}function Hc(e){if(typeof document>"u")return;let a=new Blob([hi(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 bs({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:m=null,onClearRetainerFilter:f}){let{api:g}=ie(),{invoices:r,total:v,isLoading:h,error:p,page:u,pageSize:l,hasNextPage:b,hasPreviousPage:x,setPage:N,labels:I,setLabels:O,customerEmail:c,setCustomerEmail:y,q:T,setQ:z,from:L,setFrom:R,to:$,setTo:d,retainerId:U,setRetainerId:se,refetch:Q}=gs({refreshKey:a}),[oe,ne]=Se.useState("open"),[J,ee]=Se.useState(""),[de,q]=Se.useState(null),ve=Se.useRef(0),st=Se.useCallback(D=>{ve.current++,Re(!1),q(D)},[]),[lt,Re]=Se.useState(!1),[xe,vt]=Se.useState(0),[E,te]=Se.useState(null),[S,A]=Se.useState(!1),[ue,Ve]=Se.useState(0);Se.useEffect(()=>{q(D=>{if(!D)return D;let je=r.find(V=>V.id===D.id);return je&&je!==D?je:D})},[r]);let[we,He]=Se.useState(!1),[et,ct]=Se.useState(null),Ut=async()=>{if(!we){He(!0),ct(null);try{let{invoices:D,total:je,truncated:V}=await Vc(g,{labels:I,customerEmail:c,q:T,from:L,to:$,retainerId:U});Hc(D),ct(V?`Exported the first ${D.length.toLocaleString()} of ${je.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{ct("Couldn't export \u2014 try again.")}finally{He(!1)}}},$t=!c&&!T&&!L&&!$&&!U,[ae,Pe]=Se.useState(null);Se.useEffect(()=>{if(h||v>0||!$t||oe!=="open")return;let D=!1;return g.getInvoices({limit:1}).then(je=>{D||Pe(je.total>0)}).catch(()=>{D||Pe(!0)}),()=>{D=!0}},[g,h,v,$t,oe,a]),Se.useEffect(()=>{O(ar.open)},[]),Se.useEffect(()=>{let D=m?.id??"";D!==U&&(se(D),D&&(ne("all"),O(ar.all),y(""),z(""),ee(""),R(""),d("")))},[m?.id]),Se.useEffect(()=>{let D=!1;return A(!1),g.getInvoiceSettings().then(je=>{D||te({payments_active:je.payments_active,blocked:je.blocked})}).catch(()=>{D||A(!0)}),()=>{D=!0}},[g,a,ue]),Se.useEffect(()=>{if(!s)return;let D=!1,je=ve.current;return Re(!1),g.getInvoice(s).then(V=>{!D&&je===ve.current&&q(V)}).catch(()=>{!D&&je===ve.current&&Re(!0)}),()=>{D=!0}},[g,s,xe]),Se.useEffect(()=>{t?.(de!==null)},[de,t]);let Ye=D=>{ne(D),O(ar[D])},Ra=D=>{let je=D.trim();if(!je){T&&z(""),c&&y("");return}if(je.includes("@")){T&&z(""),y(je);return}c&&y(""),z(je.replace(/^#/,""))},sa=r,Ua=lt&&G("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:()=>vt(D=>D+1),children:"Retry opening invoice"})]});if(de)return G("div",{className:e,children:[Ua,C(or,{invoice:de,refreshKey:a,onBack:()=>{st(null),Q()}},de.id)]});let tt=G("div",{className:"af-mb-4 af-space-y-3",children:[S&&G("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:()=>Ve(D=>D+1),children:"Retry setup check"})]}),Ua,E?.blocked&&G("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&&G("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[G(Z,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",m.label]}),f&&C(w,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),G("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(vi).map(D=>C("button",{type:"button","aria-pressed":oe===D,onClick:()=>Ye(D),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",oe===D?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:vi[D]},D))}),G("div",{className:"af-relative af-w-full af-max-w-xs",children:[C(Bc,{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:J,onChange:D=>ee(D.target.value),onBlur:()=>Ra(J),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),Ra(J))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),G("div",{className:"af-flex af-items-center af-gap-2",children:[C(be,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),C(ge,{id:"invoices-from",type:"date",value:L,max:$||void 0,onChange:D=>R(D.target.value),className:"af-invoice-date af-w-[150px]"})]}),G("div",{className:"af-flex af-items-center af-gap-2",children:[C(be,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),C(ge,{id:"invoices-to",type:"date",value:$,min:L||void 0,onChange:D=>d(D.target.value),className:"af-invoice-date af-w-[150px]"})]}),G(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Ut(),disabled:we||h||!!p||v===0,"aria-busy":we,children:[C(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),we?"Exporting\u2026":"Export CSV (all matching)"]})]}),et&&C("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:et})]});return h?G("div",{className:e,children:[tt,C("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(D=>G("div",{className:"af-rounded-md af-border af-p-3",children:[G("div",{className:"af-flex af-items-center af-justify-between",children:[C(X,{className:"af-h-4 af-w-20"}),C(X,{className:"af-h-4 af-w-16"})]}),C(X,{className:"af-mt-2 af-h-3 af-w-40"})]},D))})]}):p?G("div",{className:e,children:[tt,G("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 Q(),children:"Retry"})]})]}):v===0&&$t&&ae===!1&&oe==="open"?E?.blocked?G("div",{className:e,children:[tt,C(xn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?G("div",{className:e,children:[tt,C(xn,{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?G("div",{className:e,children:[tt,C(xn,{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})]}):G("div",{className:e,children:[tt,C(xn,{heading:"No invoices yet",body:!E||S?"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."})]}):G("div",{className:e,children:[tt,sa.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."}):G(zc,{children:[C("div",{className:"af-space-y-3 lg:af-hidden",children:sa.map(D=>G("button",{type:"button",onClick:()=>st(D),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[G("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[C("span",{className:"af-font-medium",children:vs(D)}),C(Os,{invoice:D})]}),C("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:D.customer_name??D.customer_email??"\u2014"}),D.delivery&&C("div",{className:"af-mt-1",children:C(wn,{delivery:D.delivery})}),G("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:D.collection_method==="charge_automatically"?"Automatic collection":D.due_at?`Due ${da(D.due_at)}`:"Due on receipt"}),C("span",{className:"af-font-medium af-tabular-nums",children:H(D.amount_due??D.amount_total,D.currency)})]})]},D.id))}),C("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:G(Oe,{children:[C(Be,{children:G(pe,{children:[C(F,{children:"Invoice"}),C(F,{children:"Created"}),C(F,{children:"Customer"}),C(F,{children:"Due"}),C(F,{className:"af-text-right",children:"Amount"}),C(F,{children:"Status"}),C(F,{children:"Delivery"}),C(F,{className:"af-w-8"})]})}),C(Fe,{children:sa.map(D=>G(pe,{className:"af-cursor-pointer",onClick:()=>st(D),children:[C(M,{className:"af-font-medium",children:C("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:je=>{je.stopPropagation(),st(D)},"aria-label":`Open invoice ${vs(D)}`,children:vs(D)})}),C(M,{children:da(D.created_at)}),G(M,{children:[C("div",{children:D.customer_name??"\u2014"}),C("div",{className:"af-text-xs af-text-muted-foreground",children:D.customer_email})]}),C(M,{children:D.collection_method==="charge_automatically"?"Automatic":D.due_at?da(D.due_at):"On receipt"}),C(M,{className:"af-text-right af-tabular-nums",children:H(D.amount_due??D.amount_total,D.currency)}),C(M,{children:C(Os,{invoice:D})}),C(M,{children:C(wn,{delivery:D.delivery})}),C(M,{children:C(gi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},D.id))})]})}),G("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[G("span",{children:[v," invoice",v===1?"":"s"]}),G("div",{className:"af-flex af-items-center af-gap-1",children:[C(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>N(u-1),disabled:!x,"aria-label":"Previous page",children:C(Ic,{className:"af-h-4 af-w-4"})}),G("span",{className:"af-tabular-nums",children:[u*l+1,"\u2013",Math.min((u+1)*l,v)]}),C(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>N(u+1),disabled:!b,"aria-label":"Next page",children:C(gi,{className:"af-h-4 af-w-4"})})]})]})]})]})}function xn({heading:e,body:a,action:s}){return G("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[C(yi,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),C("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),C("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&C(w,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var Wa="af-text-xs af-text-muted-foreground";function bi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function or({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=ie(),i=Se.useRef(null);Se.useEffect(()=>{i.current?.focus()},[e.id]);let[o,m]=Se.useState(!1),[f,g]=Se.useState(null),[r,v]=Se.useState(!1),[h,p]=Se.useState(!1),u=Se.useRef(0),[l,b]=Se.useState(null),[x,N]=Se.useState(!1),[I,O]=Se.useState(0);Se.useEffect(()=>{let d=!1;return N(!1),n.getInvoice(e.id).then(U=>{d||b({source:e,value:U})}).catch(()=>{d||N(!0)}),()=>{d=!0}},[n,e,s,I]);let c=l?.source===e?l.value:e,y=c.collection_method==="charge_automatically";Se.useEffect(()=>(u.current++,g(null),v(!1),p(!1),m(!1),()=>{u.current++}),[n,c,s]);let T=d=>d==null?"\u2014":H(d,c.currency),z=async()=>{if(!(!c.pay_url||!bi()))try{await navigator.clipboard.writeText(c.pay_url),m(!0),setTimeout(()=>m(!1),1500)}catch{}},L=async()=>{if(f){g(null);return}let d=++u.current;p(!1),v(!0);try{let U=await n.getInvoicePreview(c.id);d===u.current&&g(U)}catch{d===u.current&&p(!0)}finally{d===u.current&&v(!1)}},R=c.bill_to,$=R?[R.company,R.name,R.address?.line1,R.address?.line2,[R.address?.city,R.address?.state,R.address?.postal_code].filter(Boolean).join(", "),R.address?.country,R.tax_id?`${R.tax_id.value}`:null,R.po_number?`PO ${R.po_number}`:null,R.service_period?`Service period: ${R.service_period}`:null].filter(d=>!!d&&d.length>0):[];return G("div",{className:t,children:[G("div",{className:"af-mb-4",children:[G(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[C(Ec,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),G("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[G("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",vs(c)]}),C(Os,{invoice:c}),C(wn,{delivery:c.delivery})]}),G("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),x&&G("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(d=>d+1),children:"Retry details"})]}),c.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."}),c.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."}),G("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[G("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[G("section",{className:"af-rounded-md af-border af-p-4",children:[G(Oe,{children:[C(Be,{children:G(pe,{children:[C(F,{children:"Description"}),C(F,{className:"af-text-right",children:"Qty"}),C(F,{className:"af-text-right",children:"Amount"})]})}),C(Fe,{children:c.line_items.map((d,U)=>G(pe,{children:[C(M,{style:{overflowWrap:"anywhere"},children:d.description}),C(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:d.quantity}),C(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(d.amount)})]},U))})]}),G("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[C(Qa,{label:"Subtotal",value:T(c.amount_subtotal)}),(c.discount_total??0)>0&&C(Qa,{label:"Discount",value:`-${T(c.discount_total)}`}),c.tax_total>0&&C(Qa,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(c.tax_total)}),C(Qa,{label:"Total",value:T(c.amount_total),strong:!0}),c.credit_applied>0&&C(Qa,{label:"Credit applied",value:`-${T(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&C(Qa,{label:"Amount due",value:T(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&C(Qa,{label:"Amount paid",value:T(c.amount_paid)}),c.amount_refunded>0&&C(Qa,{label:"Refunded",value:T(c.amount_refunded)})]}),c.credit_notes?.length>0&&G("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[C("div",{className:Wa,children:"Credit notes"}),c.credit_notes.map(d=>G("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[G("span",{className:"af-text-muted-foreground",children:[da(d.created_at)," \xB7 ",d.origin==="dashboard"?"issued in Stripe":"refund",d.stripe_credit_note_id?"":" \xB7 being created"]}),G("span",{className:"af-tabular-nums",children:["-",H(d.amount,d.currency)]})]},d.id))]})]}),(c.note||c.footer)&&G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&G("div",{children:[C("div",{className:Wa,children:"Note"}),C("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&G("div",{children:[C("div",{className:Wa,children:"Footer"}),C("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),f&&!y&&G("section",{className:"af-rounded-md af-border af-p-4",children:[G("div",{className:W(Wa,"af-break-words"),children:["Email preview \u2014 ",f.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:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),G("div",{className:"af-min-w-0 af-space-y-4",children:[G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C(ua,{label:"Created",value:da(c.created_at)}),C(ua,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?da(c.due_at):"On receipt"}),c.paid_at&&C(ua,{label:"Paid",value:da(c.paid_at)}),c.payment_method&&C(ua,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&C(ua,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&C(ua,{label:"Delivery",value:`${rr[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&C(ua,{label:"Written off",value:da(c.marked_uncollectible_at)}),c.correction_reason&&C(ua,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&C(ua,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?C(ua,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&C(ua,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&C(ua,{label:"Replaces",value:c.replaces_order_id})]}),G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C("div",{className:Wa,children:"Reminders"}),y?C("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?C("div",{children:"Off for this invoice."}):c.reminders.paused_until?G("div",{children:["Paused until ",da(c.reminders.paused_until),"."]}):c.reminders.next_at?G("div",{children:["Next on ",da(c.reminders.next_at),"."]}):c.reminders.final_sent_at?G("div",{children:["Final reminder sent ",da(c.reminders.final_sent_at),"."]}):C("div",{children:"None scheduled."}),!y&&G("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(d=>d<0?`${-d}d before`:d===0?"due day":`${d}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C("div",{className:Wa,children:"Email delivery history"}),c.communications.map(d=>G("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[G("span",{className:"af-min-w-0 af-break-words",children:[Uc[d.kind]??d.kind,d.kind==="reminder"&&d.slot!==null?` #${d.slot}`:"",G("span",{className:"af-text-muted-foreground",children:[" \xB7 ",d.recipient]})]}),G("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[rr[d.state]??d.state," \xB7 ",da(d.state_at??d.created_at)]})]},d.id))]}),$.length>0&&G("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[C("div",{className:Wa,children:"Bill to"}),$.map((d,U)=>C("div",{className:"af-break-words",children:d},U))]}),G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&G(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void z(),disabled:!bi(),children:[C(Ac,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":y?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&C(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:G("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[C(Lc,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!y&&G(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void L(),disabled:r,children:[r?C(Oc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):C(yi,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":h?"Retry email preview":"Show email preview"]}),h&&!y&&C("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&C("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),C("p",{className:"af-text-xs af-text-muted-foreground",children:y?"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 ua({label:e,value:a}){return G("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[C("span",{className:W(Wa,"af-shrink-0"),children:e}),C("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function Qa({label:e,value:a,strong:s}){return G("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[C("dt",{className:W(Wa,s&&"af-font-medium af-text-foreground"),children:e}),C("dd",{className:W("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as qc}from"lucide-react";import{jsx as gt,jsxs as Na}from"react/jsx-runtime";var jc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},xi={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Gc(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 wi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>xi[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>xi[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":jc[e.status]}function Ni(e){let a=e.interval==="year"?"every year":"every month";return`${H(e.amount,e.currency)} ${a}`}function Wc(e){return e.status==="canceled"?`Ended ${Nn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Nn(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 ${Nn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Nn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Nn(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 lr({retainer:e,className:a}){return gt(Z,{variant:Gc(e.status),className:W("af-max-w-full af-whitespace-normal af-break-words",a),children:wi(e)})}function ys({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:m=0,isLoadingMore:f=!1,onLoadMore:g,includeEnded:r=!1,onIncludeEndedChange:v,className:h}){let p=!!v;if(!a&&!s&&e.length===0&&!(p&&(r||m>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return Na("section",{className:W("af-mb-6",h),"aria-label":"Recurring invoices",children:[Na("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[gt(qc,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),gt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),gt("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."}),p&>(w,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>v?.(!r),children:r?"Hide ended recurring invoices":m>0&&e.length===0?`Show ended recurring invoices (${m})`:"Show ended recurring invoices"})]}),s?Na("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",gt(w,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?gt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>Na("div",{className:"af-rounded-md af-border af-p-3",children:[gt(X,{className:"af-h-4 af-w-48"}),gt(X,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?gt("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."}):gt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let b=i===l.id;return Na("li",{className:W("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[Na("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Na("div",{className:"af-min-w-0",children:[gt("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),gt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),gt(lr,{retainer:l})]}),l.collection_method==="charge_automatically"?Na("div",{className:"af-mt-2 af-space-y-1",children:[gt(Z,{variant:"secondary",children:"Managed in Stripe"}),gt("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."})]}):gt("div",{className:"af-mt-2 af-text-sm",children:Ni(l)}),Na("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:[Na("span",{children:[Wc(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&>(w,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&Na("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!a&&!s&&u>0&&g&>("div",{className:"af-mt-2",children:gt(w,{type:"button",variant:"outline",size:"sm",onClick:g,disabled:f,children:f?"Loading\u2026":`Load more (${u} more)`})})]})}import*as _i from"react";import{AlertTriangle as Si,CheckCircle2 as Kc,CreditCard as cr,Loader2 as Jc,RefreshCw as Yc}from"lucide-react";import{jsx as Xe,jsxs as Nt}from"react/jsx-runtime";function Sn({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=Za(),[m,f]=_i.useState(!1),g=async()=>{f(!0);try{await o()}finally{f(!1)}};return n&&!t?Xe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Xe("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?Xe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Nt("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?Xe("div",{className:s,children:Nt("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:[Xe(Kc,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),Nt("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."]})]})]})}):Nt("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&Nt("div",{className:"af-space-y-3",children:[Nt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Xe(cr,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Xe("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?Nt(w,{onClick:e,children:[Xe(cr,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):Xe("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"&&Nt("div",{className:"af-space-y-3",children:[Nt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Xe(Si,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Xe("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?Xe(w,{onClick:a,children:"Upgrade plan"}):Xe("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&Nt("div",{className:"af-space-y-3",children:[Nt("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:[Xe(Si,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?Xe("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."}):Xe("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."})]})]}),Nt("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&Nt(w,{onClick:e,children:[Xe(cr,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Nt(w,{variant:"outline",onClick:g,disabled:m,children:[m?Xe(Jc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Xe(Yc,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as At from"react";function ur(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function hs({includeStats:e=!1,refreshKey:a}={}){let{api:s}=ie(),[t,n]=At.useState([]),[i,o]=At.useState(!0),[m,f]=At.useState(null),g=At.useRef(0),r=At.useCallback(async()=>{let b=++g.current;try{o(!0),f(null);let x=await s.getProducts(e?{include:"stats"}:{});if(b!==g.current)return;n(x)}catch(x){if(b!==g.current)return;f(x instanceof Error?x:new Error("Failed to fetch products"))}finally{b===g.current&&o(!1)}},[s,e,a]);At.useEffect(()=>{r()},[r]);let v=At.useCallback(async b=>{let x=await s.createProduct(b);return n(N=>[x,...N]),x},[s]),h=At.useCallback(async(b,x)=>{let N=await s.updateProduct(b,x);return n(I=>ur(I,b,N)),N},[s]),p=At.useCallback(async b=>{await s.deleteProduct(b),n(x=>x.filter(N=>N.id!==b))},[s]),u=At.useCallback(async(b,x)=>{let N=await s.attachProductFile(b,x);return n(I=>ur(I,b,N)),N},[s]),l=At.useCallback(async(b,x)=>{let N=await s.attachProductFileFromUrl(b,x);return n(I=>ur(I,b,N)),N},[s]);return{products:t,isLoading:i,error:m,refetch:r,createProduct:v,updateProduct:h,deleteProduct:p,attachProductFile:u,attachProductFileFromUrl:l}}import*as Dt from"react";var Ri=["creating","active","paused","canceling"],Zc=["canceled","failed"];function xs({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=ie(),[n,i]=Dt.useState([]),[o,m]=Dt.useState(0),[f,g]=Dt.useState(0),[r,v]=Dt.useState(!0),[h,p]=Dt.useState(!1),[u,l]=Dt.useState(null),[b,x]=Dt.useState(a),N=Dt.useRef(0),I=Dt.useCallback(async()=>{let c=++N.current;v(!0),p(!1),l(null);try{let y=await t.getRetainers({statuses:b?void 0:Ri,limit:s,offset:0});if(c!==N.current)return;if(i(y.retainers),m(y.total),!b&&y.total===0){let T=await t.getRetainers({statuses:Zc,limit:1,offset:0});if(c!==N.current)return;g(T.total)}else g(0)}catch(y){if(c!==N.current)return;l(y instanceof Error?y:new Error("Failed to fetch retainers"))}finally{c===N.current&&v(!1)}},[t,b,s]);Dt.useEffect(()=>{I()},[I,e]);let O=Dt.useCallback(async()=>{if(r||h||n.length>=o)return;let c=N.current;p(!0);try{let y=await t.getRetainers({statuses:b?void 0:Ri,limit:s,offset:n.length});if(c!==N.current)return;i(T=>{let z=new Set(T.map(L=>L.id));return[...T,...y.retainers.filter(L=>!z.has(L.id))]}),m(y.total)}catch(y){if(c!==N.current)return;l(y instanceof Error?y:new Error("Failed to fetch retainers"))}finally{c===N.current&&p(!1)}},[t,b,s,r,h,n.length,o]);return{retainers:n,total:o,endedTotal:f,hasMore:n.length<o,isLoading:r,isLoadingMore:h,error:u,includeEnded:b,setIncludeEnded:x,loadMore:O,refetch:I}}import{Fragment as ru,jsx as $e,jsxs as Gt}from"react/jsx-runtime";function Pi({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=ws.useState(a),[m,f]=ws.useState("list"),[g,r]=ws.useState(null),v=hs(),{status:h,error:p}=Za(),u=h?.currency,l=I=>{r(I),f("edit")},b=()=>{r(null),f("create")},x=()=>{f("list"),r(null)},N=I=>{r(I),f("edit")};return Gt("div",{className:e,children:[Gt("div",{className:"af-mb-6",children:[$e("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),$e("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Gt(Gs,{value:i,onValueChange:I=>o(I),children:[Gt(ks,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Gt(ma,{value:"products",className:"af-gap-2",children:[$e(eu,{className:"af-h-4 af-w-4"}),"Products"]}),Gt(ma,{value:"orders",className:"af-gap-2",children:[$e(tu,{className:"af-h-4 af-w-4"}),"Orders"]}),Gt(ma,{value:"invoices",className:"af-gap-2",children:[$e(Xc,{className:"af-h-4 af-w-4"}),"Invoices"]}),Gt(ma,{value:"customers",className:"af-gap-2",children:[$e(su,{className:"af-h-4 af-w-4"}),"Customers"]}),$e(ma,{value:"promos",children:"Promo codes"}),Gt(ma,{value:"setup",className:"af-gap-2",children:[$e(au,{className:"af-h-4 af-w-4"}),"Setup"]})]}),$e(pa,{value:"products",children:m==="list"?$e(rn,{productsState:v,onSelectProduct:l,onCreateProduct:b}):Gt("div",{children:[Gt("div",{className:"af-mb-6",children:[Gt(w,{variant:"ghost",size:"sm",onClick:x,className:"af-mb-2 af--ml-2",children:[$e(Qc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),$e("h3",{className:"af-text-lg af-font-semibold",children:m==="create"?"New Product":g?.name})]}),m==="create"&&!u?$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:p?Gt("div",{className:"af-text-destructive",children:["Error: ",p.message]}):$e("div",{className:"af-text-muted-foreground",children:"Loading..."})}):$e(ln,{productsState:v,product:m==="edit"?g:null,currency:u??"usd",onSaved:N},m==="edit"?g?.id??"edit":"new")]})}),$e(pa,{value:"orders",children:$e(ps,{onRefund:t})}),$e(pa,{value:"invoices",children:$e(nu,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:h?.reason==="needs_paid_plan"})}),$e(pa,{value:"customers",children:$e(hn,{})}),$e(pa,{value:"promos",children:$e(fs,{})}),$e(pa,{value:"setup",children:$e(Sn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function nu({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=xs(),[n,i]=ws.useState(null),[o,m]=ws.useState(!1);return Gt(ru,{children:[!o&&$e(ys,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>i(g=>g?.id===f.id?null:f),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),$e(bs,{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 Ti from"react";import*as La from"react";function _n({refreshKey:e}={}){let{api:a}=ie(),[s,t]=La.useState(null),[n,i]=La.useState(!0),[o,m]=La.useState(null),f=La.useRef(0),g=La.useCallback(async()=>{let r=++f.current;try{i(!0),m(null);let v=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==f.current)return;t(v)}catch(v){if(r!==f.current)return;m(v instanceof Error?v:new Error("Failed to fetch summary"))}finally{r===f.current&&i(!1)}},[a,e]);return La.useEffect(()=>{g()},[g]),{summary:s,isLoading:n,error:o,refetch:g}}import{Fragment as dr,jsx as St,jsxs as fr}from"react/jsx-runtime";function Ci(e,a){if(e.settled.complete)return{headline:H(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:H(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${H(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:H(0,a),extra:[]}}function ki({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:m,error:f,refetch:g}=_n({refreshKey:e}),[r,v]=Ti.useState(!1),h=St("div",{className:"af-mb-6",children:f&&!o?St(ea,{message:"Couldn't load your revenue summary.",onRetry:()=>g()}):St("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:m||!o?fr(dr,{children:[St(Qe,{label:"This week",children:St(X,{className:"af-h-6 af-w-24"})}),St(Qe,{label:"Today",children:St(X,{className:"af-h-6 af-w-24"})}),St(Qe,{label:"Needs attention",children:St(X,{className:"af-h-6 af-w-10"})})]}):St(dr,{children:(()=>{let p=Ci(o.revenue.d7,o.currency),u=Ci(o.revenue.today,o.currency);return fr(dr,{children:[St(Qe,{label:"This week",detail:p.extra.length>0?St("div",{children:p.extra.map(l=>St("div",{children:l},l))}):void 0,children:p.headline}),St(Qe,{label:"Today",detail:u.extra.length>0?St("div",{children:u.extra.map(l=>St("div",{children:l},l))}):void 0,children:u.headline}),St(Qe,{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 fr(Rt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[h,St(ps,{refreshKey:e,initialOrderId:a,onDetailOpenChange:v,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as Ba from"react";import{ImageOff as uu,Package as du,Search as fu}from"lucide-react";import*as Oa from"react";import{ArrowLeft as lu,ImageOff as cu}from"lucide-react";import{jsx as Sa,jsxs as Bs}from"react/jsx-runtime";var Ei="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Xa="af-text-xs af-text-muted-foreground",Rn="af-text-sm af-font-medium af-tabular-nums",iu=3;function ou(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let f=e.min_amount??a?.min_amount??null,g=e.max_amount??a?.max_amount??null;return f!==null&&g!==null?{text:`Buyer chooses (${H(f,s)} \u2013 ${H(g,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?H(n,s):`${H(n,s)} \u2013 ${H(i,s)}`,m=a?.compare_at_amount??null;return{text:o,compareAt:m!==null&&m>i?H(m,s):null}}function Pn({product:e,className:a}){let s=ou(e);return Bs("div",{className:a,children:[Sa("span",{className:Rn,children:s.text}),s.compareAt&&Sa("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Cn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?Sa(Z,{variant:"destructive",children:"Out of stock"}):a.low_stock?Bs(Z,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?Sa(Z,{variant:"secondary",children:"Backorder"}):a.available===null?null:Bs(Z,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?Sa(Z,{variant:"warning",children:"Low stock"}):null}function Tn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function kn(e){return e.map(a=>H(a.amount,a.currency)).join(" + ")}function Ii(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${H(e.min_amount,e.currency)} \u2013 ${H(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":H(e.unit_amount,e.currency)}function Ai({variant:e}){let a=e.inventory;if(!a||!a.tracked)return Sa("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?Bs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Sa("span",{className:"af-tabular-nums",children:Math.max(0,s)}),Sa(Z,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?Sa(Z,{variant:"destructive",children:"Out of stock"}):Bs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Sa("span",{className:"af-tabular-nums",children:s}),s<=iu&&Sa(Z,{variant:"warning",children:"Low"})]})}import{jsx as ce,jsxs as We}from"react/jsx-runtime";function Fs({title:e,children:a,className:s}){return We("section",{className:W("af-rounded-lg af-border af-p-4",s),children:[ce("h4",{className:Ei,children:e}),ce("div",{className:"af-mt-3",children:a})]})}function Di({src:e,className:a}){let[s,t]=Oa.useState(!1);return Oa.useEffect(()=>t(!1),[e]),!e||s?ce("div",{"aria-hidden":"true",className:W("af-flex af-items-center af-justify-center af-bg-muted",a),children:ce(cu,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):ce("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:W("af-object-cover",a)})}function Li({product:e,showStats:a=!1,onBack:s}){let{api:t}=ie(),[n,i]=Oa.useState(null),[o,m]=Oa.useState(!0),[f,g]=Oa.useState(null),[r,v]=Oa.useState(0),[h,p]=Oa.useState(0);Oa.useEffect(()=>{let c=!1;return m(!0),g(null),t.getProduct(e.id).then(y=>{c||i(y)}).catch(y=>{c||g(y instanceof Error?y:new Error("Failed to load product"))}).finally(()=>{c||m(!1)}),()=>{c=!0}},[t,e.id,r]);let u=n?{...e,...n}:e,l=u.images.length>0?u.images:e.images,b=l[h]??l[0],x=Tn(u),N=a?u.stats:void 0,I=n?.variants??[],O=I.length>1;return We("div",{children:[We("div",{className:"af-mb-6",children:[We(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[ce(lu,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),We("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ce("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),ce(Z,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),ce(Cn,{product:u})]}),ce(Pn,{product:u,className:"af-mt-1"}),!u.active&&ce("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),We("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[We("div",{className:"af-space-y-2",children:[ce(Di,{src:b,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&ce("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((c,y)=>ce("button",{type:"button",onClick:()=>p(y),"aria-label":`Show photo ${y+1} of ${l.length}`,"aria-pressed":y===h,className:W("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",y===h?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:ce(Di,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${y}`))})]}),We("div",{className:"af-space-y-6",children:[u.description&&ce(Fs,{title:"Description",children:ce("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?We(Fs,{title:"Variants",children:[ce("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>We("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[ce(X,{className:"af-h-4 af-w-28"}),ce(X,{className:"af-h-4 af-w-20"}),ce(X,{className:"af-h-4 af-w-16"})]},c))}),ce("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?ce(ea,{message:"Couldn't load this product's variants.",onRetry:()=>v(c=>c+1)}):O?ce(Fs,{title:`Variants \xB7 ${I.length}`,children:ce("div",{className:"af-overflow-x-auto",children:We(Oe,{children:[ce(Be,{children:We(pe,{children:[ce(F,{children:"Variant"}),ce(F,{children:"SKU"}),ce(F,{className:"af-text-right",children:"Price"}),ce(F,{children:"Stock"})]})}),ce(Fe,{children:I.map(c=>We(pe,{children:[We(M,{className:"af-font-medium",children:[c.title||c.option_values.map(y=>y.value).join(" / ")||"\u2014",!c.active&&ce(Z,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),ce(M,{className:"af-text-muted-foreground",children:c.sku?ce("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),We(M,{className:"af-whitespace-nowrap af-text-right",children:[ce("div",{className:Rn,children:Ii(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&ce("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:H(c.compare_at_amount,c.currency)})]}),ce(M,{className:"af-text-sm",children:ce(Ai,{variant:c})})]},c.id))})]})})}):null,ce(Fs,{title:"Details",children:We("dl",{className:"af-space-y-2",children:[We("div",{children:[ce("dt",{className:Xa,children:"Delivery"}),ce("dd",{className:"af-text-sm",children:x==="Digital download"?u.fulfillment.filename??"Digital download":x??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&We("div",{children:[ce("dt",{className:Xa,children:"Sends buyers to"}),ce("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),We("div",{children:[ce("dt",{className:Xa,children:"Shipping address"}),ce("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),We("div",{children:[ce("dt",{className:Xa,children:"Most one buyer can order"}),ce("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),N&&ce(Fs,{title:"Last 30 days",children:We("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[We("div",{children:[ce("dt",{className:Xa,children:"Units sold"}),ce("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:N.units_sold})]}),We("div",{children:[ce("dt",{className:Xa,children:"Orders"}),ce("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:N.orders})]}),We("div",{children:[ce("dt",{className:Xa,children:"Gross"}),ce("dd",{className:Rn,children:N.gross.length>0?kn(N.gross):"\u2014"})]})]})}),ce("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 es,jsx as re,jsxs as Ke}from"react/jsx-runtime";var mu={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},pu=["all","active","draft","low_stock","out_of_stock"];function Oi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function Bi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function gu(e){return e.inventory?.out_of_stock??!1}function vu(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Bi(e);case"out_of_stock":return gu(e);default:return!0}}function bu({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Tn(e),o=e.variant_count??0;return Ke("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(uu,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ke("div",{className:"af-space-y-2 af-p-3",children:[Ke("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ke("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(Pn,{product:e,className:"af-mt-0.5"})]}),!e.active&&re(Z,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ke("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[re(Cn,{product:e}),o>1&&Ke(Z,{variant:"outline",children:[o," variants"]}),i&&re(Z,{variant:"outline",children:i})]}),n&&Ke("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${kn(n.gross)}`:""," ",re("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function yu(){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=>Ke("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"}),Ke("div",{className:"af-space-y-2 af-p-3",children:[re(X,{className:"af-w-32"}),re(X,{className:"af-w-16"}),re(X,{className:"af-h-5 af-w-24"})]})]},e))})}function Fi({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:m}=hs({includeStats:a,refreshKey:e}),[f,g]=Ba.useState(!1),[r,v]=Ba.useState(null),[h,p]=Ba.useState("all"),[u,l]=Ba.useState(""),[b,x]=Ba.useState("newest"),N=Ba.useMemo(()=>{if(!a)return null;let d=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!d||U.stats.units_sold>(d.stats?.units_sold??0))&&(d=U);return d},[n,a]),I=Ba.useMemo(()=>n.filter(Bi).length,[n]),O=u.trim().toLowerCase(),c=Ba.useMemo(()=>{let U=[...n.filter(se=>vu(se,h)&&(!O||se.name.toLowerCase().includes(O)))];return b==="name"?U.sort((se,Q)=>se.name.localeCompare(Q.name)):b==="best_selling"?U.sort((se,Q)=>(Q.stats?.units_sold??0)-(se.stats?.units_sold??0)):U.sort((se,Q)=>Oi(Q.created_at)-Oi(se.created_at)),U},[n,h,O,b]),y=h!=="all"||!!O,T=()=>{p("all"),l("")},z=i||o!==null&&n.length===0,L=re("div",{className:"af-mb-6",children:re("div",{className:W("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:z?Ke(es,{children:[re(Qe,{label:"Products",children:re(X,{className:"af-h-6 af-w-10"})}),a?Ke(es,{children:[re(Qe,{label:"Best seller",children:re(X,{className:"af-h-6 af-w-28"})}),re(Qe,{label:"Low stock",children:re(X,{className:"af-h-6 af-w-10"})})]}):re(Qe,{label:"Active",children:re(X,{className:"af-h-6 af-w-10"})})]}):Ke(es,{children:[re(Qe,{label:"Products",children:n.length}),a?Ke(es,{children:[re(Qe,{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?re("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:N.name}):re("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),re(Qe,{label:"Low stock",children:I})]}):re(Qe,{label:"Active",children:n.filter(d=>d.active).length})]})})}),R=Ke("div",{className:"af-mb-4 af-space-y-3",children:[Ke("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:pu.map(d=>re("button",{type:"button","aria-pressed":h===d,onClick:()=>p(d),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",h===d?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:mu[d]},d))}),Ke("div",{className:"af-relative af-w-full af-max-w-xs",children:[re(fu,{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:u,onChange:d=>l(d.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ke(na,{value:b,onValueChange:d=>x(d),children:[re(Yt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:re(ra,{})}),Ke(Zt,{children:[re(ze,{value:"newest",children:"Newest"}),re(ze,{value:"name",children:"Name A\u2013Z"}),a&&re(ze,{value:"best_selling",children:"Best selling"})]})]}),y&&re(w,{type:"button",variant:"ghost",size:"sm",onClick:T,children:"Clear filters"})]}),i&&n.length===0?re(X,{className:"af-h-4 af-w-28"}):re("p",{className:"af-text-sm af-text-muted-foreground",children:y?`${c.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${I>0?` \xB7 ${I} low stock`:""}`})]}),$;return r?$=re(Li,{product:r,showStats:a,onBack:()=>{v(null),m()}},r.id):i&&n.length===0?$=Ke(es,{children:[R,re(yu,{}),re("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?$=re("div",{className:"af-flex af-justify-center af-py-8",children:re(ea,{message:"Couldn't load your products.",onRetry:()=>m()})}):n.length===0?$=Ke(Da,{icon:re(du,{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."]}):$=Ke(es,{children:[R,o&&re("div",{className:"af-mb-4",children:re(ea,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>m()})}),c.length===0?Ke(Da,{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:c.map(d=>re(bu,{product:d,showStats:a,onOpen:()=>v(d)},d.id))})]}),re(Rt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:f?Ke(es,{children:[re(w,{variant:"ghost",onClick:()=>g(!1),children:"Back to products"}),re(fs,{})]}):Ke(es,{children:[!r&&re("div",{className:"af-mb-4 af-flex af-justify-end",children:re(w,{variant:"outline",onClick:()=>g(!0),children:"Promo codes"})}),!r&&L,$]})})}import*as _a from"react";import{ArrowLeft as Hi,Check as hu,ChevronLeft as Mi,ChevronRight as Ui,ClipboardCopy as xu,Mail as pr,Search as wu,Users as Nu}from"lucide-react";import*as ta from"react";function En({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=ta.useState([]),[i,o]=ta.useState(!0),[m,f]=ta.useState(null),[g,r]=ta.useState(0),[v]=ta.useState(e),[h,p]=ta.useState(""),u=ta.useRef(0),l=ta.useCallback(async()=>{let b=++u.current;try{o(!0),f(null);let x={limit:v,offset:g*v};h.trim()&&(x.q=h.trim());let N=await s.getPeople(x);if(b!==u.current)return;n(N.people)}catch(x){if(b!==u.current)return;f(x instanceof Error?x:new Error("Failed to fetch people"))}finally{b===u.current&&o(!1)}},[s,g,v,h,a]);return ta.useEffect(()=>{l()},[l]),{people:t,isLoading:i,error:m,page:g,pageSize:v,hasNextPage:t.length===v,hasPreviousPage:g>0,setPage:r,q:h,setQ:b=>{p(b),r(0)},refetch:l}}import*as Fa from"react";function In(e,{refreshKey:a}={}){let{api:s}=ie(),[t,n]=Fa.useState(null),[i,o]=Fa.useState(e!==null),[m,f]=Fa.useState(null),g=Fa.useRef(0),r=Fa.useCallback(async()=>{if(e===null){n(null),o(!1),f(null);return}let v=++g.current;try{o(!0),f(null);let h=await s.getPerson(e);if(v!==g.current)return;n(h)}catch(h){if(v!==g.current)return;f(h instanceof Error?h:new Error("Failed to fetch person"))}finally{v===g.current&&o(!1)}},[s,e,a]);return Fa.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:m,refetch:r}}import{jsx as _,jsxs as le}from"react/jsx-runtime";var mr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Su="af-text-xs af-text-muted-foreground";function Ns(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 gr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function _u(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Ru({value:e,label:a}){let[s,t]=_a.useState(!1);return _u()?le(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?_(hu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):_(xu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function $i(e){return le("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&le(Z,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&_(Z,{variant:"secondary",children:"Contact form"})]})}function Vi(e){return e.name?e.name:e.email?e.email:_("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Pu=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Cu=40;function Tu(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>Pu.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=Cu).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 ku(e){return e.replace(/_/g," ")}function Eu(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Iu({data:e}){let{message:a,rest:s}=Tu(e);return a===null&&s.length===0?_("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):le("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])=>le("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[_("dt",{className:W(Su,"af-w-28 af-shrink-0 af-capitalize"),children:ku(t)}),_("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Eu(n)})]},t))})]})}function zi({formName:e,createdAt:a,data:s}){return le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[_(Z,{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:Ns(a)})]}),_(Iu,{data:s})]})}function Au(e){return e.charged_total??e.amount_total}function Du({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=In(e,{refreshKey:a}),m=gr(e,t?.submissions[0]?.form_name);return le("div",{children:[le("div",{className:"af-mb-6",children:[le(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[_(Hi,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),le("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[le("div",{className:"af-min-w-0",children:[n?_(X,{className:"af-h-7 af-w-48"}):_("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),le("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}),_(Ru,{value:e,label:"Copy email address"})]})]}),_(w,{asChild:!0,children:le("a",{href:m,children:[_(pr,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?le("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>le("div",{className:"af-rounded-md af-border af-p-3",children:[_(X,{className:"af-w-40"}),_(X,{className:"af-mt-2 af-w-64"})]},f)),_("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?_("div",{className:"af-flex af-justify-center af-py-8",children:_(ea,{message:"Couldn't load this person.",onRetry:()=>o()})}):le("div",{className:"af-space-y-6",children:[t.customer&&le("div",{children:[_("h4",{className:W(mr,"af-mb-3"),children:"Customer"}),le("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&le("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&&le("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})]}),le("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:Ns(t.customer.created_at)})]})]})]}),t.orders.length>0&&le("div",{children:[_("h4",{className:W(mr,"af-mb-3"),children:"Purchases"}),_("div",{className:"af-overflow-x-auto",children:le(Oe,{children:[_(Be,{children:le(pe,{children:[_(F,{children:"Order"}),_(F,{children:"Date"}),_(F,{className:"af-text-right",children:"Total"}),_(F,{children:"Status"})]})}),_(Fe,{children:t.orders.map(f=>le(pe,{children:[_(M,{className:"af-whitespace-nowrap af-font-medium",children:Ga(f)}),_(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ns(f.created_at)}),_(M,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:H(Au(f),f.currency)}),_(M,{children:_(rs,{status:f.status})})]},f.id))})]})}),_("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),t.submissions.length>0&&le("div",{children:[_("h4",{className:W(mr,"af-mb-3"),children:"Messages"}),_("div",{className:"af-space-y-3",children:t.submissions.map(f=>_(zi,{formName:f.form_name,createdAt:f.created_at,data:f.data},f.id))})]})]})]})}function Lu({submissionId:e,onBack:a}){let{api:s}=ie(),[t,n]=_a.useState(null),[i,o]=_a.useState(!0),[m,f]=_a.useState(null),[g,r]=_a.useState(0);return _a.useEffect(()=>{let v=!1;return o(!0),f(null),s.getSubmission(e).then(h=>{v||n(h)}).catch(h=>{v||f(h instanceof Error?h:new Error("Failed to load submission"))}).finally(()=>{v||o(!1)}),()=>{v=!0}},[s,e,g]),le("div",{children:[le("div",{className:"af-mb-6",children:[le(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[_(Hi,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),_("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?_(X,{className:"af-mt-1 af-h-4 af-w-32"}):t&&_("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Ns(t.metadata.submitted_at)})]}),i?le("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[_(X,{className:"af-w-40"}),_(X,{className:"af-mt-2 af-w-64"}),_(X,{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:_(ea,{message:"Couldn't load this submission.",onRetry:()=>r(v=>v+1)})}):le("div",{className:"af-space-y-3",children:[_(zi,{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 Ou={all:"All",customers:"Customers",leads:"Leads"},Bu=["all","customers","leads"];function Fu(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function qi({refreshKey:e,onBackToWebsite:a,className:s}){let{people:t,isLoading:n,error:i,page:o,pageSize:m,hasNextPage:f,hasPreviousPage:g,setPage:r,q:v,setQ:h,refetch:p}=En({refreshKey:e}),[u,l]=_a.useState({kind:"list"}),[b,x]=_a.useState(""),[N,I]=_a.useState("all"),O=L=>{L.email?l({kind:"person",email:L.email}):L.submission_id&&l({kind:"submission",submissionId:L.submission_id})},c=()=>{l({kind:"list"}),p()},y=L=>{let R=L.trim();R!==v&&h(R)},T=t.filter(L=>Fu(L,N)),z;if(u.kind==="person")z=_(Du,{email:u.email,refreshKey:e,onBack:c});else if(u.kind==="submission")z=_(Lu,{submissionId:u.submissionId,onBack:c});else{let L=le("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:Bu.map(R=>_("button",{type:"button","aria-pressed":N===R,onClick:()=>I(R),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===R?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Ou[R]},R))}),le("div",{className:"af-relative af-w-full af-max-w-xs",children:[_(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"}),_(ge,{type:"text",value:b,onChange:R=>x(R.target.value),onBlur:()=>y(b),onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),y(b))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),v&&_(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{x(""),h("")},children:"Clear search"})]});if(n)z=le("div",{children:[L,_("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(R=>le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-flex af-items-center af-justify-between",children:[_(X,{className:"af-h-4 af-w-32"}),_(X,{className:"af-h-4 af-w-16"})]}),_(X,{className:"af-mt-2 af-h-5 af-w-28"}),_(X,{className:"af-mt-2 af-h-3 af-w-56"})]},R))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le(Oe,{children:[_(Be,{children:le(pe,{children:[_(F,{children:"Person"}),_(F,{children:"Came from"}),_(F,{children:"Latest message"}),_(F,{children:"Last activity"}),_(F,{className:"af-w-8"}),_(F,{className:"af-w-8"})]})}),_(Fe,{"aria-hidden":"true",children:[0,1,2,3,4].map(R=>le(pe,{children:[_(M,{children:_(X,{className:"af-h-4 af-w-40"})}),_(M,{children:_(X,{className:"af-h-5 af-w-24"})}),_(M,{children:_(X,{className:"af-h-4 af-w-56"})}),_(M,{children:_(X,{className:"af-h-4 af-w-24"})}),_(M,{}),_(M,{})]},R))})]})}),_("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)z=le("div",{children:[L,_("div",{className:"af-flex af-justify-center af-py-8",children:_(ea,{message:"Couldn't load your leads.",onRetry:()=>p()})})]});else if(T.length===0&&o===0){let R=!!v||N!=="all";z=le("div",{children:[R&&L,R?_(Da,{children:v?"Nobody matches that search.":N==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):_(Da,{icon:_(Nu,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Form submissions and customers will show up here."})]})}else if(t.length===0)z=le("div",{children:[L,_(Da,{children:"No more results."}),_("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:le(w,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[_(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let R=o*m+1,$=o*m+t.length;z=le("div",{children:[L,_("div",{className:"af-space-y-3 lg:af-hidden",children:T.map((d,U)=>le("div",{onClick:()=>O(d),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[le("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[le("div",{className:"af-min-w-0",children:[_("button",{type:"button",onClick:se=>{se.stopPropagation(),O(d)},"aria-label":`Open ${d.name||d.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 hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Vi(d)}),d.name&&d.email&&_("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:d.email})]}),le("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[_("span",{className:"af-text-xs af-text-muted-foreground",children:Ns(d.last_activity_at)}),d.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:gr(d.email),onClick:se=>se.stopPropagation(),"aria-label":`Email ${d.email}`,children:_(pr,{className:"af-h-4 af-w-4"})})})]})]}),_("div",{className:"af-mt-2",children:$i(d)}),d.latest_message_excerpt&&_("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:d.latest_message_excerpt})]},d.email??d.submission_id??U))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le(Oe,{children:[_(Be,{children:le(pe,{children:[_(F,{children:"Person"}),_(F,{children:"Came from"}),_(F,{children:"Latest message"}),_(F,{children:"Last activity"}),_(F,{className:"af-w-8",children:_("span",{className:"af-sr-only",children:"Reply"})}),_(F,{className:"af-w-8"})]})}),_(Fe,{children:T.map((d,U)=>le(pe,{onClick:()=>O(d),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[le(M,{className:"af-max-w-[260px] af-font-medium",children:[_("button",{type:"button",onClick:se=>{se.stopPropagation(),O(d)},"aria-label":`Open ${d.name||d.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Vi(d)}),d.name&&d.email&&_("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:d.email})]}),_(M,{children:$i(d)}),_(M,{className:"af-max-w-[320px]",children:d.latest_message_excerpt?_("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:d.latest_message_excerpt}):_("span",{className:"af-text-muted-foreground",children:"\u2014"})}),_(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ns(d.last_activity_at)}),_(M,{className:"af-w-8",children:d.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:gr(d.email),onClick:se=>se.stopPropagation(),"aria-label":`Email ${d.email}`,children:_(pr,{className:"af-h-4 af-w-4"})})})}),_(M,{className:"af-w-8 af-text-right",children:_(Ui,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},d.email??d.submission_id??U))})]})}),le("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:N==="all"?`Showing ${R}-${$}`:`${T.length} of ${t.length} on this page`}),le("div",{className:"af-flex af-items-center af-gap-2",children:[le(w,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!g,children:[_(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),le(w,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!f,children:["Next",_(Ui,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return _(Rt,{title:"Leads",onBackToWebsite:a,hideBackButton:u.kind!=="list",className:s,children:z})}import{ChevronLeft as ji,ChevronRight as Mu,Repeat as Uu}from"lucide-react";import*as Wt from"react";function An({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=Wt.useState([]),[i,o]=Wt.useState(0),[m,f]=Wt.useState(!0),[g,r]=Wt.useState(null),[v,h]=Wt.useState(0),[p,u]=Wt.useState(e),[l,b]=Wt.useState(void 0),x=Wt.useRef(0),N=Wt.useCallback(async()=>{let O=++x.current;try{f(!0),r(null);let c={limit:p,offset:v*p};l&&(c.status=l);let y=await s.getSubscriptions(c);if(O!==x.current)return;n(y.subscriptions),o(y.total)}catch(c){if(O!==x.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{O===x.current&&f(!1)}},[s,v,p,l,a]);Wt.useEffect(()=>{N()},[N]);let I=Math.ceil(i/p);return{subscriptions:t,total:i,isLoading:m,error:g,page:v,pageSize:p,hasNextPage:v<I-1,hasPreviousPage:v>0,setPage:h,setPageSize:O=>{u(O),h(0)},status:l,setStatus:O=>{b(O),h(0)},refetch:N}}import{jsx as Y,jsxs as Je}from"react/jsx-runtime";function Gi(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 Wi({sub:e}){return e.status==="canceled"?Y(Z,{variant:"outline",children:"Canceled"}):e.status==="past_due"?Y(Z,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?Y(Z,{variant:"warning",children:"Scheduled to cancel"}):Y(Z,{variant:"success",children:"Active"}):Y(Z,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function $u(e,a){let s=H(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ki({sub:e}){let a=e.current_amount!==e.plan_amount;return Je("div",{children:[Y("div",{className:"af-font-medium af-tabular-nums",children:$u(e,e.current_amount)}),a&&Je("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",H(e.plan_amount,e.currency)]})]})}function Ji(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Gi(e.current_period_end)}`:"Ends at period end":e.current_period_end?Gi(e.current_period_end):"\u2014"}function Yi({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:m,pageSize:f,hasNextPage:g,hasPreviousPage:r,setPage:v,refetch:h}=An({refreshKey:e}),p;if(i)p=Je("div",{children:[Y("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>Je("div",{className:"af-rounded-md af-border af-p-3",children:[Je("div",{className:"af-flex af-items-center af-justify-between",children:[Y(X,{className:"af-h-4 af-w-40"}),Y(X,{className:"af-h-4 af-w-20"})]}),Y(X,{className:"af-mt-2 af-h-3 af-w-32"}),Y(X,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),Y("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Je(Oe,{children:[Y(Be,{children:Je(pe,{children:[Y(F,{children:"Subscriber"}),Y(F,{children:"Plan"}),Y(F,{className:"af-text-right",children:"Amount"}),Y(F,{children:"Renews"}),Y(F,{children:"Status"})]})}),Y(Fe,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>Je(pe,{children:[Y(M,{children:Y(X,{className:"af-h-4 af-w-44"})}),Y(M,{children:Y(X,{className:"af-h-4 af-w-32"})}),Y(M,{className:"af-text-right",children:Y(X,{className:"af-ml-auto af-h-4 af-w-24"})}),Y(M,{children:Y(X,{className:"af-h-4 af-w-24"})}),Y(M,{children:Y(X,{className:"af-h-5 af-w-20"})})]},u))})]})}),Y("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=Y("div",{className:"af-flex af-justify-center af-py-8",children:Y(ea,{message:"Couldn't load your subscriptions.",onRetry:()=>h()})});else if(t.length===0&&m===0)p=Y(Da,{icon:Y(Uu,{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)p=Je("div",{children:[Y(Da,{children:"No more results."}),Y("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Je(w,{variant:"outline",size:"sm",onClick:()=>v(m-1),children:[Y(ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=m*f+1,l=m*f+t.length;p=Je("div",{children:[Y("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(b=>Je("div",{className:"af-rounded-md af-border af-p-3",children:[Je("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Je("div",{className:"af-min-w-0",children:[Y("div",{className:"af-truncate af-text-sm af-font-medium",children:b.customer_email||Y("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Y("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:b.plan_title||"Untitled plan"})]}),Y("div",{className:"af-shrink-0 af-text-right",children:Y(Ki,{sub:b})})]}),Je("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[Y(Wi,{sub:b}),b.is_test&&Y(Z,{variant:"outline",children:"Test"}),Y("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ji(b)})]}),Y(Pa,{deliveries:b.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},b.id))}),Y("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Je(Oe,{children:[Y(Be,{children:Je(pe,{children:[Y(F,{children:"Subscriber"}),Y(F,{children:"Plan"}),Y(F,{className:"af-text-right",children:"Amount"}),Y(F,{children:"Renews"}),Y(F,{children:"Status"})]})}),Y(Fe,{children:t.map(b=>Je(pe,{children:[Y(M,{className:"af-max-w-[240px]",children:Y("div",{className:"af-truncate af-font-medium",children:b.customer_email||Y("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),Y(M,{className:"af-max-w-[220px]",children:Y("div",{className:"af-truncate",children:b.plan_title||Y("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),Y(M,{className:"af-whitespace-nowrap af-text-right",children:Y(Ki,{sub:b})}),Y(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ji(b)}),Je(M,{children:[Je("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Y(Wi,{sub:b}),b.is_test&&Y(Z,{variant:"outline",children:"Test"})]}),Y(Pa,{deliveries:b.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},b.id))})]})}),Je("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Y("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${u}-${l} of ${n}`}),Je("div",{className:"af-flex af-items-center af-gap-2",children:[Je(w,{variant:"outline",size:"sm",onClick:()=>v(m-1),disabled:!r,children:[Y(ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Je(w,{variant:"outline",size:"sm",onClick:()=>v(m+1),disabled:!g,children:["Next",Y(Mu,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return Y(Rt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:p})}import*as vr from"react";import{Fragment as Zi,jsx as aa,jsxs as Dn}from"react/jsx-runtime";function Qi({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:m,isLoading:f,error:g,refetch:r}=gs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),v=xs({refreshKey:e}),[h,p]=vr.useState(!1),[u,l]=vr.useState(null),b=aa("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!f&&!m?Dn("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. ",aa(w,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):f||!m?Dn(Zi,{children:[aa(Qe,{label:"Outstanding",children:aa(X,{className:"af-h-6 af-w-24"})}),aa(Qe,{label:"Overdue",children:aa(X,{className:"af-h-6 af-w-24"})}),aa(Qe,{label:"Paid this month",children:aa(X,{className:"af-h-6 af-w-24"})})]}):Dn(Zi,{children:[aa(Qe,{label:"Outstanding",detail:`${m.outstanding.count} open`,children:H(m.outstanding.amount,m.currency)}),aa(Qe,{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:H(m.overdue.amount,m.currency)}),aa(Qe,{label:"Paid this month",detail:`${m.paid_this_month.count} paid`,children:H(m.paid_this_month.amount,m.currency)})]})});return Dn(Rt,{title:"Invoices",onBackToWebsite:s,hideBackButton:h,className:o,children:[b,!h&&aa(ys,{retainers:v.retainers,isLoading:v.isLoading,error:v.error,onRetry:()=>void v.refetch(),activeRetainerId:u?.id??null,onShowCycles:x=>l(N=>N?.id===x.id?null:x),total:v.total,endedTotal:v.endedTotal,isLoadingMore:v.isLoadingMore,onLoadMore:()=>void v.loadMore(),includeEnded:v.includeEnded,onIncludeEndedChange:v.setIncludeEnded}),aa(bs,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:p,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:u?{id:u.id,label:`${u.customer_name??u.customer_email??"Recurring invoices"} \u2014 ${u.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}import*as yt from"react";var Vu=2e3,Ct=()=>({data:null,error:null,isLoading:!0});function Ln(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=ie(),[i,o]=yt.useState(Ct),[m,f]=yt.useState(Ct),[g,r]=yt.useState(Ct),[v,h]=yt.useState(Ct),[p,u]=yt.useState(Ct),l=ne=>Object.fromEntries(ne.map(J=>[J,Ct()])),[b,x]=yt.useState(()=>l(s)),N=yt.useRef(0),I=yt.useRef(0),O=yt.useRef("idle"),c=s.join(","),y=JSON.stringify(t),T=`${e}:${c}:${y}`,[z,L]=yt.useState({api:n,fetchIdentity:T});(z.api!==n||z.fetchIdentity!==T)&&(L({api:n,fetchIdentity:T}),N.current+=1,o(Ct),f(Ct),r(Ct),h(Ct),x(l(c?c.split(","):[])));let R=`${e}:${String(a??"")}`,[$,d]=yt.useState({api:n,conversionsIdentity:R});($.api!==n||$.conversionsIdentity!==R)&&(d({api:n,conversionsIdentity:R}),I.current+=1,O.current="idle",u(Ct));let U=yt.useCallback(async ne=>{let J=++N.current,ee=c?c.split(","):[];o(Ct),f(Ct),r(Ct),h(Ct),x(Object.fromEntries(ee.map(E=>[E,Ct()])));let de=O.current!=="pending"&&(ne?.force===!0||O.current==="idle"),q=(E,te)=>te.then(S=>{J===N.current&&E({data:S,error:null,isLoading:!1})},S=>{J===N.current&&E({data:null,error:S instanceof Error?S:new Error("Failed to fetch report"),isLoading:!1})}),ve=n.getAnalyticsStatus(),st=q(o,ve),lt=Symbol("status-timeout"),Re,xe=await Promise.race([ve.then(E=>E,()=>null),new Promise(E=>{Re=setTimeout(()=>E(lt),Vu)})]);if(clearTimeout(Re),J!==N.current)return;if(xe===lt&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),xe!==null&&xe!==lt&&(xe.collecting!==!0||xe.first_seen===null&&!xe.first_seen_unavailable||xe.first_seen!==null&&xe.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};f(E),r(E),h(E),x(Object.fromEntries(ee.map(te=>[te,{...E}]))),de&&(u(E),O.current="done"),await st;return}await Promise.all([xe===lt?Promise.resolve():st,q(f,n.getAnalyticsSummary(e,t)),q(r,n.getAnalyticsTimeseries(e,t)),q(h,n.getAnalyticsChannels(e,t)),de?(()=>{O.current="pending";let E=++I.current;return u(Ct),n.getAnalyticsConversions(e).then(te=>{E===I.current&&(u({data:te,error:null,isLoading:!1}),O.current="done")},te=>{E===I.current&&(u({data:null,error:te instanceof Error?te:new Error("Failed to fetch report"),isLoading:!1}),O.current="done")})})():Promise.resolve(),...ee.map(E=>n.getAnalyticsBreakdown(E,e,t).then(te=>{J===N.current&&x(S=>({...S,[E]:{data:te,error:null,isLoading:!1}}))},te=>{J===N.current&&x(S=>({...S,[E]:{data:null,error:te instanceof Error?te:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,c,y,R]),se=yt.useCallback(async()=>{let ne=N.current;try{let J=await n.getAnalyticsStatus();if(ne!==N.current)return;o({data:J,error:null,isLoading:!1})}catch(J){if(ne!==N.current)return;o(ee=>({data:ee.data,error:J instanceof Error?J:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),Q=yt.useCallback(()=>U({force:!0}),[U]);yt.useEffect(()=>{U()},[U,a]);let oe=i.isLoading||m.isLoading||g.isLoading||v.isLoading||p.isLoading||Object.values(b).some(ne=>ne.isLoading);return{status:i,summary:m,timeseries:g,channels:v,conversions:p,breakdowns:b,isLoading:oe,refetch:Q,refetchStatus:se}}import*as ht from"react";var br=3e4,yr=3;function On(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=ie(),[o,m]=ht.useState(null),[f,g]=ht.useState(null),[r,v]=ht.useState(!1),[h,p]=ht.useState(null),[u,l]=ht.useState(!1),[b,x]=ht.useState(!0),[N,I]=ht.useState(0),O=ht.useRef(0),c=ht.useRef(0),y=ht.useRef(void 0);s!==void 0&&(y.current=s);let T=a?y.current===!0||y.current===void 0&&t:!0,[z,L]=ht.useState({api:i,identity:n}),R=n!==void 0&&n!==z.identity;(z.api!==i||R)&&(y.current=void 0,L({api:i,identity:n}),c.current+=1,O.current=0,m(null),g(null),v(!1),p(null),l(!1),x(!0),I(0));let $=ht.useRef(()=>{}),d=ht.useRef(null),U=ht.useCallback(async()=>{if(d.current!==null&&d.current===c.current)return;let se=++c.current;d.current=se;try{let Q=await i.getAnalyticsRealtime();if(se!==c.current)return;if(Q.status==="unreachable"){l(!0),v(!0),x(!1),I(oe=>oe+1);return}O.current=0,l(!1),m(Q.data.current_visitors),g(Q.as_of),v(!1),p(null),x(!1),I(oe=>oe+1)}catch(Q){if(se!==c.current)return;O.current+=1,x(!1),I(oe=>oe+1),v(!0),O.current>=yr&&p(Q instanceof Error?Q:new Error("Realtime unavailable"))}finally{d.current===se&&(d.current=null)}},[i]);return $.current=()=>void U(),ht.useEffect(()=>{let se,Q=()=>{se===void 0&&(se=setInterval(()=>$.current(),br))},oe=()=>{se!==void 0&&(clearInterval(se),se=void 0)},ne=()=>{typeof document<"u"&&document.hidden?oe():($.current(),Q())};return T?((typeof document>"u"||!document.hidden)&&($.current(),Q()),document?.addEventListener("visibilitychange",ne),()=>{oe(),document?.removeEventListener("visibilitychange",ne),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",ne)}},[z.api,z.identity,T]),{currentVisitors:o,asOf:f,isStale:r,error:h,isUnreachable:u,isInitialLoad:b,polls:N}}import*as qe from"react";import*as us from"react";var Hu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Lt(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?Lt(o*t):`${o}${n}`}return String(e)}function Ss(e){return`${(e*100).toFixed(1)}%`}function Ms(e){let a=Math.max(0,Math.round(e));if(a<60)return`${a}s`;let s=Math.floor(a/60);return s<60?`${s}m ${a%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function eo(e){let a=Math.max(0,Math.round(e));return a>=3600&&a%3600===0?`${a/3600}h`:a>=60&&a%60===0?`${a/60}m`:Ms(a)}function to(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function ao(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 Us(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function so(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 hr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${Hu[a-1]} ${s}`}function Xi(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function zu(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function no(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=Xi(e.to,s);for(let o=Xi(e.from,s);o<i;o=zu(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 ro(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 ju,jsx as ts,jsxs as qu}from"react/jsx-runtime";function io({what:e="This report",onRetry:a,collecting:s}){return qu("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:[ts("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),ts("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?ts("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 Bn({what:e="No data"}){return ts("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 _s({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?ts("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?ts(io,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?ts(io,{what:t,onRetry:n,collecting:i}):ts(ju,{children:o(e.data)})}import{Fragment as Gu,jsx as Kt,jsxs as cs}from"react/jsx-runtime";function xr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:m,maxRows:f=9}){let[g,r]=us.useState(!1);if(e.length===0)return Kt(Bn,{what:i});let v=e.reduce((u,l)=>Math.max(u,Number(l[s]??0)),0)||1,h=Math.max(0,e.length-f),p=g?e:e.slice(0,f);return cs(Gu,{children:[cs("table",{className:"af-w-full af-text-sm",children:[Kt("thead",{children:cs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Kt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),Kt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),Kt("tbody",{children:p.map((u,l)=>{let b=Number(u[s]??0),x=u[a]??null,N=Us(x),I=n?u[n]:null,O=x!==null&&(m?m(x,I):!0);return cs("tr",{className:"af-border-t af-border-border",children:[cs("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Kt("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,b/v*100)}%`}}),x!==null&&o&&O?Kt("button",{type:"button",onClick:()=>o(x,I),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}):Kt("span",{className:"af-relative af-break-words af-text-foreground",children:N}),I?Kt("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:I}):null]}),Kt("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Lt(b)})]},`${N}-${I??""}-${l}`)})})]}),h>0?Kt("button",{type:"button",onClick:()=>r(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:g?"Show fewer":`Show all ${e.length}`}):null]})}function $s({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=us.useState(s),o=a.find(p=>p.id===n)??a[0],m=us.useId(),f=p=>`${m}-tab-${p}`,g=p=>`${m}-panel-${p}`,r=us.useRef(null),v=(p,u)=>{p.preventDefault();let l=(u+a.length)%a.length;i(a[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return cs("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[cs("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:[Kt("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:p=>{let u=a.findIndex(l=>l.id===n);p.key==="ArrowRight"&&v(p,u+1),p.key==="ArrowLeft"&&v(p,u-1),p.key==="Home"&&v(p,0),p.key==="End"&&v(p,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(p=>Kt("button",{id:f(p.id),role:"tab",type:"button","aria-selected":p.id===n,"aria-controls":g(p.id),tabIndex:p.id===n?0:-1,onClick:()=>i(p.id),className:p.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:p.label},p.id))}),t]}),o?Kt("div",{id:g(o.id),role:"tabpanel","aria-labelledby":f(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as Jt from"react";import*as as from"@radix-ui/react-popover";var Rs=3,Ps=100;import{jsx as ot,jsxs as Ma}from"react/jsx-runtime";var Vs={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"},Wu=Object.keys(Vs);function oo(e){let a=Vs[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>Us(n)).join(" or ");return`${a} ${s} ${t}`}function wr(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function Ku(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 lo(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 Ju(e){return{dimension:e,operator:"is",search:"",picked:[]}}function co(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=Ku(e.byDimension,s);for(let[i,o]of Object.entries(t)){let m=e.foldsByLabel.get(i)??new Set;for(let f of o)m.add(f);e.foldsByLabel.set(i,m)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function uo(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Jt.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]),Ma("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>Ma("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:[ot("span",{className:"af-text-foreground",children:oo(n)}),ot("button",{type:"button","aria-label":`Remove filter ${oo(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"}`)),ot(Yu,{...e,disabled:t}),a.length>0?ot("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 Yu({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,m]=Jt.useState(!1),f=Jt.useRef(null),[g,r]=Jt.useState(null);Jt.useEffect(()=>{r(f.current?.closest(".aifeatures-admin")??null)},[]);let[v,h]=Jt.useState(null),[p,u]=Jt.useState("is"),[l,b]=Jt.useState(""),[x,N]=Jt.useState([]);Jt.useEffect(()=>{o||(h(null),u("is"),b(""),N([]))},[o]);let I=Jt.useRef(t);I.current!==t&&(I.current=t,o&&m(!1),v!==null&&h(null),x.length>0&&N([]),l!==""&&b(""),p!=="is"&&u("is"));let O=R=>{let $=Ju(R);h($.dimension),N($.picked),b($.search),u($.operator)},y=(v?s[v]??[]:[]).filter(R=>R.toLowerCase().includes(l.trim().toLowerCase())),T=v===null||x.length===0?null:wr(e,{dimension:v,operator:p,values:i?i(v,x):x}),z=T!==null&&T!==e,L=()=>{let R=T;!R||R===e||(a(R),m(!1))};return Ma(as.Root,{open:o,onOpenChange:m,children:[ot(as.Trigger,{asChild:!0,children:ot("button",{ref:f,type:"button",disabled:!1,title:n?`At most ${3} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),ot(as.Portal,{container:g,children:ot(as.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:v===null?Ma("div",{children:[ot("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),ot("div",{className:"af-max-h-96 af-overflow-y-auto",children:Wu.filter(R=>s[R]!==void 0).map(R=>{let $=s[R]?.length??0,d=!e.some(U=>U.dimension===R)&&e.length>=3;return Ma("button",{type:"button",onClick:()=>O(R),disabled:$===0||d,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:[ot("span",{children:Vs[R]}),ot("span",{className:"af-text-muted-foreground",children:$===0?"no data":d?"no room":$})]},R)})})]}):Ma("div",{children:[Ma("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[ot("button",{type:"button",onClick:()=>O(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),ot("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Vs[v]}),Ma("select",{"aria-label":"Operator",value:p,onChange:R=>u(R.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:[ot("option",{value:"is",children:"is"}),ot("option",{value:"is_not",children:"is not"})]})]}),ot("input",{type:"text",value:l,onChange:R=>b(R.target.value),placeholder:"Search\u2026","aria-label":`Search ${Vs[v]}`,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"}),ot("div",{className:"af-max-h-48 af-overflow-y-auto",children:y.length===0?Ma("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):y.map(R=>Ma("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:[ot("input",{type:"checkbox",checked:x.includes(R),disabled:!x.includes(R)&&x.length>=100,onChange:$=>N(d=>$.target.checked?[...d,R]:d.filter(U=>U!==R))}),ot("span",{className:"af-break-all",children:Us(R)})]},R))}),ot("button",{type:"button",onClick:L,disabled:!z,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:x.length<=1?"Apply filter":x.length>=100?`Apply filter (${x.length} values \u2014 the maximum)`:`Apply filter (${x.length} values)`})]})})})]})}import{Fragment as Xu,jsx as Ot,jsxs as Fn}from"react/jsx-runtime";var Zu=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Lt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Lt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Lt,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:Ss,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Ms,chart:"visit_duration_seconds"}];function Qu({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 Ot("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 fo({summary:e,selected:a,onSelect:s}){return Ot("div",{className:"af-@container",children:Ot("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Zu.map(t=>{let n=t.chart===a,i=s!==void 0,o=Fn(Xu,{children:[Ot("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),Fn("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Ot("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?Ot(Qu,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?Ot("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):Ot("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function Nr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return Fn("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:[Ot("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Ot("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return Ot("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?so(a):"freshness unknown",m=i?" across the whole site, not the current filter,":"",f=s?`${e} current visitors${m} ${o} (not updating)`:`${e} current visitors${m} ${o}`;return Fn("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:f,children:[Ot("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"}),Ot("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Ot("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),Ot("span",{className:"af-sr-only",children:f})]})}import*as mo from"react";import{Fragment as ed,jsx as Bt,jsxs as Hs}from"react/jsx-runtime";function po({rows:e,denominator:a,windowPrecedesCollection:s=!1,coverageUnknown:t=!1,emptyCopy:n="No conversions in this period",maxRows:i=9}){let[o,m]=mo.useState(!1);if(e.length===0)return Bt(Bn,{what:n});let f=Math.max(0,e.length-i),g=o?e:e.slice(0,i);return Hs(ed,{children:[Hs("table",{className:"af-w-full af-text-sm",children:[Bt("thead",{children:Hs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Bt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),Bt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),Bt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total"}),Bt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),Bt("tbody",{children:g.map((r,v)=>Hs("tr",{className:"af-border-t af-border-border",children:[Bt("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:r.goal}),Bt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Lt(r.visitors)}),Bt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Lt(r.events)}),Bt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:r.conversion_rate===null?Bt("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Ss(r.conversion_rate)})]},`${r.goal}-${v}`))})]}),f>0?Bt("button",{type:"button",onClick:()=>m(r=>!r),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}`}):null,Hs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Lt(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),s?Bt("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?Bt("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]})}import{Area as td,AreaChart as ad,CartesianGrid as sd,ResponsiveContainer as nd,Tooltip as rd,XAxis as id,YAxis as od}from"recharts";import{jsx as Ft,jsxs as zs}from"react/jsx-runtime";var Mn={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},_r={visitors:Lt,visits:Lt,pageviews:Lt,views_per_visit:e=>e.toFixed(2),bounce_rate:Ss,visit_duration_seconds:Ms},ld=new Set(["visitors","visits","pageviews"]),cd={..._r,bounce_rate:to,visit_duration_seconds:eo},Sr=[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],dd=[.01,.02,.05,.1,.2,.25,.5,1],fd=[.25,.5,1,2,5,10,25,50],md={visitors:Sr,visits:Sr,pageviews:Sr,views_per_visit:fd,bounce_rate:dd,visit_duration_seconds:ud};function pd({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return zs("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:[Ft("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Mn[t]}),zs("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Ft("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Ft("span",{className:"af-text-muted-foreground",children:ro(String(s))}),Ft("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:_r[t](Number(n[t]??0))})]})]})}function go({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=no(a,e,t),o=_r[s],m=cd[s],f=ao(i.reduce((r,v)=>Math.max(r,Number(v[s]??0)),0),md[s]),g=`${Mn[s]} by day: ${i.map(r=>`${hr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return zs("figure",{"aria-label":`${Mn[s]} over time`,className:"af-m-0",children:[Ft(nd,{width:"100%",height:n,children:zs(ad,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Ft("defs",{children:zs("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Ft("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Ft("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Ft(sd,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Ft(id,{dataKey:"date",tickFormatter:hr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Ft(od,{allowDecimals:!ld.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:r=>m(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Ft(rd,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Ft(pd,{metric:s})}),Ft(td,{type:"monotone",dataKey:s,name:Mn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Ft("figcaption",{className:"af-sr-only",children:g})]})}import{Fragment as Rr,jsx as he,jsxs as Mt}from"react/jsx-runtime";var gd=3e4,vd="2026-08-13",bd=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],yd=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function hd({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[m,f]=qe.useState(30),g=e!==void 0&&a!==void 0,[r,v]=qe.useState(e??[]),{api:h}=ie(),[p,u]=qe.useState(h);p!==h&&(u(h),!g&&r.length>0&&v([]));let l=g?e:r,b=qe.useCallback(E=>{a&&a(E),g||v(E)},[a,g]),x=qe.useCallback((E,te,S)=>{let A=Array.isArray(te)?te:[te];if(A.length===0)return null;let ue=wr(l,{dimension:E,operator:"is",values:A});if(S&&(!S.value||(ue=lo(ue,{dimension:S.dimension,operator:"is",values:[S.value]}),!ue.find(He=>He.dimension===S.dimension&&He.operator!=="is_not")?.values.includes(S.value))))return null;let Ve=ue.find(we=>we.dimension===E&&we.operator!=="is_not");return A.every(we=>Ve?.values.includes(we))?JSON.stringify(ue)===JSON.stringify(l)?null:ue:null},[l]),N=qe.useCallback((E,te,S)=>x(E,te,S)!==null,[x]),I=qe.useCallback((E,te,S)=>{let A=x(E,te,S);A&&b(A)},[x,b]),[O,c]=qe.useState("visitors"),y=Ln(m,{refreshKey:s,breakdowns:yd,filters:l}),T=y.status.data,z=i===!1,L=T!=null&&(!T.collecting||z&&T.first_seen===null&&!T.first_seen_unavailable),R=!L&&T?.collecting===!0&&T.first_seen===null&&!T.first_seen_unavailable,$=T?.collecting===!0&&T.first_seen!==null&&T.first_seen_in_reports===!1,d=R||$,U=On({collecting:R||L?!1:T?.collecting,statusFailed:y.status.error!=null,identity:T?.analytics_id}),se=qe.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Q=qe.useMemo(()=>{let E=y.breakdowns.sources?.data,te={};if(!E||E.status!=="ok")return te;for(let S of E.data){let A=S.source,ue=S.sources;typeof A=="string"&&Array.isArray(ue)&&ue.length>0&&(te[A]=ue)}return te},[y.breakdowns.sources?.data]),oe=qe.useMemo(()=>{let E=(A,ue)=>{let Ve=y.breakdowns[A]?.data;return!Ve||Ve.status!=="ok"?[]:[...new Set(Ve.data.map(we=>we[ue]).filter(we=>typeof we=="string"&&we!==""))]};return{channel:y.channels.data?.status==="ok"?[...new Set(y.channels.data.data.map(A=>A.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")}},[y.breakdowns,y.channels.data]),[ne,J]=qe.useState({}),ee=JSON.stringify(oe),[de,q]=qe.useState(new Map),ve=JSON.stringify(Q);qe.useEffect(()=>{let{suggestions:E,folds:te}=co(se.current,{api:h,period:m},JSON.parse(ee),JSON.parse(ve));J(E),q(te)},[ee,ve,h,m]);let st=qe.useCallback((E,te)=>E!=="source"?te:[...new Set(te.flatMap(S=>{let A=[...de.get(S)??[],...Q[S]??[]];return A.length>0?A:[S]}))],[de,Q]),lt=qe.useMemo(()=>{let E=y.conversions.error;return E instanceof Ht&&E.details?.code==="goals_exceed_report_budget"?E.message:null},[y.conversions.error]),Re=qe.useMemo(()=>{let E=[y.summary,y.timeseries,y.channels,...Object.values(y.breakdowns)];for(let te of E){let S=te?.error;if(S instanceof Ht&&S.details?.code==="filter_unsupported")return S.message}return null},[y.summary,y.timeseries,y.channels,y.breakdowns]),xe=(E,te,S,A,ue,Ve,we,He,et)=>()=>{let ct=y.breakdowns[E];return he(_s,{sourced:ct?.data??null,error:ct?.error,isLoading:ct?.isLoading,what:te,collecting:T?.collecting,onRetry:y.refetch,children:Ut=>{let $t=ae=>He?st(He,[ae]):ae;return he(xr,{rows:Ut,dimension:S,metric:A,metricLabel:ue,secondary:Ve,emptyCopy:l.length>0?"No data for this filter":we,canFilter:He?(ae,Pe)=>N(He,$t(ae),et?{dimension:et,value:Pe}:void 0):()=>!1,onFilter:He?(ae,Pe)=>I(He,$t(ae),et?{dimension:et,value:Pe}:void 0):void 0})}})};qe.useEffect(()=>{if(!d)return;let E,te=()=>{E===void 0&&(E=setInterval(()=>void y.refetchStatus(),gd))},S=()=>{E!==void 0&&(clearInterval(E),E=void 0)},A=()=>{typeof document<"u"&&document.hidden?S():(y.refetchStatus(),te())};return(typeof document>"u"||!document.hidden)&&te(),document?.addEventListener("visibilitychange",A),()=>{S(),document?.removeEventListener("visibilitychange",A)}},[d,y.refetchStatus]);let vt=qe.useRef(void 0);if(qe.useEffect(()=>{if(!T){vt.current=void 0;return}let E=vt.current;vt.current=d,E===!0&&!d&&y.refetch()},[T,d,y.refetch]),L){let E=!!o&&String(o).slice(0,10)<vd;return he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),he("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:z?"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 R?he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),he("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."})]})}):$?he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Mt("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",T?.timezone?` ${T.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),he("div",{className:"af-mt-4 af-flex af-justify-center",children:he(Nr,{currentVisitors:U.currentVisitors,asOf:U.asOf,isStale:U.isStale,isUnreachable:U.isUnreachable||U.error!==null,isInitialLoad:U.isInitialLoad})})]})}):he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Mt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[he("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:bd.map(E=>he("button",{type:"button","aria-pressed":E.value===m,onClick:()=>f(E.value),className:E.value===m?"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))}),he(Nr,{currentVisitors:U.currentVisitors,asOf:U.asOf,isStale:U.isStale,isUnreachable:U.isUnreachable||U.error!==null,isInitialLoad:U.isInitialLoad,scopeIsSiteWide:l.length>0})]}),he(uo,{filters:l,onChange:b,suggestions:ne,expandValues:st,resetKey:h}),Re?Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),he("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:Re}),he("button",{type:"button",onClick:()=>b([]),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,!Re&&T?.timezone_defaulted?he("p",{className:"af-text-xs af-text-muted-foreground",children:"Reports are shown in UTC. Set a timezone to see them in your local days."}):null,Re?null:Mt(Rr,{children:[he(_s,{sourced:y.summary.data,error:y.summary.error,isLoading:y.summary.isLoading,what:"The traffic summary",collecting:T?.collecting,onRetry:y.refetch,children:E=>Mt(Rr,{children:[he(fo,{summary:E,selected:O,onSelect:c}),E.previous_unavailable?Mt("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]})}),he("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:he(_s,{sourced:y.timeseries.data,error:y.timeseries.error,isLoading:y.timeseries.isLoading,what:"The visitors chart",collecting:T?.collecting,onRetry:y.refetch,children:E=>{let te=y.timeseries.data?.status==="ok"?y.timeseries.data.window:{from:"",to:""};return he(go,{rows:E,window:te,metric:O,timeZone:(y.timeseries.data?.status==="ok"?y.timeseries.data.timezone:void 0)??T?.timezone??"UTC"})}})}),Mt("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[he("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:he("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Mt("div",{className:"af-px-3 af-py-2",children:[l.length>0?Mt("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",l.length===1?"filter":"filters"," above."]}):null,lt!==null?Mt("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),he("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:lt})]}):he(_s,{sourced:y.conversions.data,error:y.conversions.error,isLoading:y.conversions.isLoading,what:"Conversions",collecting:T?.collecting,onRetry:y.refetch,children:E=>{let te=y.conversions.data?.status==="ok"?y.conversions.data:null;return he(Rr,{children:he(po,{rows:E,denominator:te?.denominator??0,windowPrecedesCollection:te?.window_precedes_collection??!1,coverageUnknown:te?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]}),Mt("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[he($s,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>he(_s,{sourced:y.channels.data,error:y.channels.error,isLoading:y.channels.isLoading,what:"Channels",collecting:T?.collecting,onRetry:y.refetch,children:E=>he(xr,{rows:E,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:l.length>0?"No data for this filter":"No data for this period",canFilter:te=>N("channel",te),onFilter:te=>I("channel",te)})})},{id:"sources",label:"Sources",render:xe("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:xe("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),he($s,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:xe("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:xe("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:xe("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),he($s,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:xe("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:xe("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:xe("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),he($s,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:xe("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:xe("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:xe("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]})]})]})})}export{Ht as AifeaturesApiError,No as AifeaturesProvider,hd as AnalyticsView,bn as CustomerDetail,hn as CustomersList,an as FormSettings,Qs as FormSubmissions,Gr as FormsDashboard,Ws as FormsList,or as InvoiceDetail,Os as InvoiceLabelBadge,bs as InvoicesList,Qi as InvoicesView,qi as LeadsView,Rs as MAX_ANALYTICS_FILTERS,Ps as MAX_ANALYTICS_FILTER_VALUES,mn as OrderDetail,rs as OrderStatusBadge,ps as OrdersList,ki as OrdersView,Pi as PaymentsDashboard,Sn as PaymentsSetup,ln as ProductSettings,rn as ProductsList,Fi as ProductsView,fs as PromosPanel,yr as REALTIME_FAILURES_BEFORE_ERROR,br as REALTIME_POLL_MS,lr as RetainerStatusBadge,ys as RetainersPanel,Zs as SubmissionDetail,Yi as SubscriptionsView,on as VariantsEditor,Rt as ViewShell,en as WebhookDeliveries,tn as WebhookSettings,ja as chargedTotal,Vn as createApiClient,H as formatPrice,ca as isZeroDecimalCurrency,dt as toMajorUnits,zt as toMinorUnits,ie as useAifeatures,ie as useAifeaturesContext,Ln as useAnalytics,_n as useBusinessSummary,vn as useCustomers,Xs as useEventDestinations,ds as useForms,gs as useInvoices,cn as useOrders,Za as usePaymentsStatus,En as usePeople,In as usePerson,hs as useProducts,On as useRealtimeVisitors,xs as useRetainers,Ys as useSubmissions,An as useSubscriptions};
|
|
2
|
+
import*as Ka from"react";function qs(e,a){let s=new URLSearchParams({period:String(e)});return a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var Ht=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function $n(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 Vn(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 p;try{p=await o.json()}catch{}throw new Ht($n(p?.error,o.status),o.status,p)}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(),p=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(p)},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,p=i.id??i.name,m=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(p)}`,g=await fetch(m,{headers:{Authorization:`Bearer ${e}`}});if(!g.ok){let f;try{f=await g.json()}catch{}throw new Ht($n(f?.error,g.status),g.status,f)}let r=await g.blob(),v=URL.createObjectURL(r),h=document.createElement("a");h.href=v,h.download=o,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(v)},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 p;try{p=await o.json()}catch{}throw new Ht($n(p?.error,o.status),o.status,p)}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(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${qs(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${qs(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${qs(t,n)}`)},async getAnalyticsConversions(t){return s(`/api/v1/analytics/conversions?period=${String(t)}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${qs(n,i)}`)},async getBusinessSummary(t){let n=new URLSearchParams;return n.set("tz_offset_minutes",String(t.tzOffsetMinutes)),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 ks,jsxs as _o}from"react/jsx-runtime";var Lr=Ka.createContext(null);function No(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 So({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Ka.useMemo(()=>No(e),[e]),o=Ka.useMemo(()=>Vn(e,a),[e,a]),p=Ka.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?ks("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:_o("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[ks("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),ks("p",{className:"af-text-sm af-text-destructive",children:i})]})}):ks(Lr.Provider,{value:p,children:ks("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function ie(){let e=Ka.useContext(Lr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as Ya from"react";import{ArrowLeft as Rl,Settings as Pl,Inbox as Cl}from"lucide-react";import*as js from"react";import*as fa from"@radix-ui/react-tabs";import{clsx as Ro}from"clsx";import{extendTailwindMerge as Po}from"tailwind-merge";var Co=Po({prefix:"af-"});function W(...e){return Co(Ro(e))}import{jsx as Hn}from"react/jsx-runtime";var Gs=fa.Root,Es=js.forwardRef(({className:e,...a},s)=>Hn(fa.List,{ref:s,className:W("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...a}));Es.displayName=fa.List.displayName;var ma=js.forwardRef(({className:e,...a},s)=>Hn(fa.Trigger,{ref:s,className:W("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...a}));ma.displayName=fa.Trigger.displayName;var pa=js.forwardRef(({className:e,...a},s)=>Hn(fa.Content,{ref:s,className:W("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...a}));pa.displayName=fa.Content.displayName;import*as Or from"react";import{Slot as To}from"@radix-ui/react-slot";import{cva as ko}from"class-variance-authority";import{jsx as Io}from"react/jsx-runtime";var Eo=ko("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=Or.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>Io(t?To:"button",{className:W(Eo({variant:a,size:s,className:e})),ref:i,...n}));w.displayName="Button";import{Inbox as Br,Settings as Lo}from"lucide-react";import*as Va from"react";import{jsx as $a}from"react/jsx-runtime";var Oe=Va.forwardRef(({className:e,...a},s)=>$a("div",{className:"af-relative af-w-full af-overflow-auto",children:$a("table",{ref:s,className:W("af-w-full af-caption-bottom af-text-sm",e),...a})}));Oe.displayName="Table";var Be=Va.forwardRef(({className:e,...a},s)=>$a("thead",{ref:s,className:W("[&_tr]:af-border-b",e),...a}));Be.displayName="TableHeader";var Fe=Va.forwardRef(({className:e,...a},s)=>$a("tbody",{ref:s,className:W("[&_tr:last-child]:af-border-0",e),...a}));Fe.displayName="TableBody";var Ao=Va.forwardRef(({className:e,...a},s)=>$a("tfoot",{ref:s,className:W("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));Ao.displayName="TableFooter";var pe=Va.forwardRef(({className:e,...a},s)=>$a("tr",{ref:s,className:W("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));pe.displayName="TableRow";var F=Va.forwardRef(({className:e,...a},s)=>$a("th",{ref:s,className:W("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));F.displayName="TableHead";var M=Va.forwardRef(({className:e,...a},s)=>$a("td",{ref:s,className:W("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));M.displayName="TableCell";var Do=Va.forwardRef(({className:e,...a},s)=>$a("caption",{ref:s,className:W("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));Do.displayName="TableCaption";import*as ga from"react";function ds(){let{api:e}=ie(),[a,s]=ga.useState([]),[t,n]=ga.useState(!0),[i,o]=ga.useState(null),p=ga.useCallback(async()=>{try{n(!0),o(null);let v=await e.getForms();s(v)}catch(v){o(v instanceof Error?v:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);ga.useEffect(()=>{p()},[p]);let m=ga.useCallback(async v=>{let h=await e.createForm(v);return s(f=>[...f,h]),h},[e]),g=ga.useCallback(async(v,h)=>{let f=await e.updateForm(v,h);return s(u=>u.map(l=>l.id===v?f:l)),f},[e]),r=ga.useCallback(async v=>{await e.deleteForm(v),s(h=>h.filter(f=>f.id!==v))},[e]);return{forms:a,isLoading:t,error:i,refetch:p,createForm:m,updateForm:g,deleteForm:r}}import{jsx as _t,jsxs as Ha}from"react/jsx-runtime";function Ws({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=ds();return t?_t("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:_t("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?_t("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ha("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?Ha("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[_t(Br,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ha("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",_t("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):_t("div",{className:a,children:Ha(Oe,{children:[_t(Be,{children:Ha(pe,{children:[_t(F,{children:"Name"}),_t(F,{children:"Endpoint"}),_t(F,{className:"af-text-right",children:"Actions"})]})}),_t(Fe,{children:s.map(i=>Ha(pe,{children:[_t(M,{className:"af-font-medium",children:i.name}),_t(M,{children:_t("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","")})}),_t(M,{className:"af-text-right",children:Ha("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ha(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[_t(Br,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ha(w,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[_t(Lo,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as Mo}from"lucide-react";import{cva as Oo}from"class-variance-authority";import{jsx as Fo}from"react/jsx-runtime";var Bo=Oo("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 Z({className:e,variant:a,...s}){return Fo("div",{className:W(Bo({variant:a}),e),...s})}import{jsx as ss,jsxs as Ks}from"react/jsx-runtime";var Uo={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 Js(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 zn(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function $o(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 Is({deliveries:e,label:a="Email needs attention"}){return zn(e)?Ks("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:[ss(Mo,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function Pa({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||zn([n]));return t.length?ss("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=Js(n),o=$o(n);return Ks("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Ks("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[ss("span",{className:"af-font-medium",children:Uo[n.kind]??"Email notification"}),ss(Z,{variant:i.variant,children:i.label})]}),Ks("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&zn([n])&&ss("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&&ss("p",{className:"af-mt-1",children:i.detail}),o&&ss("p",{className:"af-mt-1",children:o})]},n.id)})}):null}import*as As from"react";import{ChevronLeft as el,ChevronRight as tl,Eye as al,Inbox as sl,Paperclip as nl}from"lucide-react";import*as Ja from"react";import*as Ne from"@radix-ui/react-select";import{Check as Vo,ChevronDown as Fr,ChevronUp as Ho}from"lucide-react";import{jsx as kt,jsxs as qn}from"react/jsx-runtime";var na=Ne.Root;var ra=Ne.Value,Yt=Ja.forwardRef(({className:e,children:a,...s},t)=>qn(Ne.Trigger,{ref:t,className:W("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[a,kt(Ne.Icon,{asChild:!0,children:kt(Fr,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Yt.displayName=Ne.Trigger.displayName;var Mr=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.ScrollUpButton,{ref:s,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:kt(Ho,{className:"af-h-4 af-w-4"})}));Mr.displayName=Ne.ScrollUpButton.displayName;var Ur=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.ScrollDownButton,{ref:s,className:W("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:kt(Fr,{className:"af-h-4 af-w-4"})}));Ur.displayName=Ne.ScrollDownButton.displayName;var Zt=Ja.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>kt(Ne.Portal,{children:qn(Ne.Content,{ref:n,className:W("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",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:[kt(Mr,{}),kt(Ne.Viewport,{className:W("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}),kt(Ur,{})]})}));Zt.displayName=Ne.Content.displayName;var zo=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.Label,{ref:s,className:W("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));zo.displayName=Ne.Label.displayName;var ze=Ja.forwardRef(({className:e,children:a,...s},t)=>qn(Ne.Item,{ref:t,className:W("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[kt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:kt(Ne.ItemIndicator,{children:kt(Vo,{className:"af-h-4 af-w-4"})})}),kt(Ne.ItemText,{children:a})]}));ze.displayName=Ne.Item.displayName;var qo=Ja.forwardRef(({className:e,...a},s)=>kt(Ne.Separator,{ref:s,className:W("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));qo.displayName=Ne.Separator.displayName;import*as ia from"react";function Ys({formId:e,initialPageSize:a=25}){let{api:s}=ie(),[t,n]=ia.useState([]),[i,o]=ia.useState(0),[p,m]=ia.useState(!0),[g,r]=ia.useState(null),[v,h]=ia.useState(0),[f,u]=ia.useState(a),l=ia.useCallback(async()=>{if(e)try{m(!0),r(null);let N={limit:f,offset:v*f},I=await s.getSubmissions(e,N);n(I.submissions),o(I.total)}catch(N){r(N instanceof Error?N:new Error("Failed to fetch submissions"))}finally{m(!1)}},[s,e,v,f]);ia.useEffect(()=>{l()},[l]);let b=ia.useCallback(async N=>{await s.deleteSubmission(N),n(I=>I.filter(O=>O.id!==N)),o(I=>I-1)},[s]),x=Math.ceil(i/f);return{submissions:t,total:i,isLoading:p,error:g,page:v,pageSize:f,hasNextPage:v<x-1,hasPreviousPage:v>0,setPage:h,setPageSize:N=>{u(N),h(0)},refetch:l,deleteSubmission:b}}import*as Vr from"react";import{ArrowLeft as jo,Download as Go,Globe as Wo,Clock as Ko,FileText as Jo,Loader2 as Yo,Monitor as Zo,Mail as Qo}from"lucide-react";import{jsx as nt,jsxs as rt}from"react/jsx-runtime";function $r(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Xo(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 Zs({submission:e,onBack:a}){let{api:s}=ie(),[t,n]=Vr.useState(null),i=m=>m.id??m.name,o=async m=>{n(i(m));try{await s.downloadAttachment(e.id,m)}catch(g){console.error("Download failed:",g)}finally{n(null)}},p=Object.entries(e.data).filter(([m])=>!m.startsWith("_"));return rt("div",{children:[rt("div",{className:"af-mb-6",children:[rt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[nt(jo,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),nt("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),rt("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",$r(e.metadata.submitted_at)]})]}),rt("div",{className:"af-space-y-6",children:[nt(Pa,{deliveries:e.email_deliveries}),rt("div",{children:[nt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),rt("div",{className:"af-space-y-3",children:[p.map(([m,g])=>rt("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[nt("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:m.replace(/_/g," ")}),nt("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof g=="string"&&g.includes(`
|
|
3
|
+
`)?nt("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:g}):String(g)})]},m)),p.length===0&&nt("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&rt("div",{children:[nt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),nt("div",{className:"af-space-y-2",children:e.attachments.map((m,g)=>rt("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[rt("div",{className:"af-flex af-items-center af-gap-2",children:[nt(Jo,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),nt("span",{className:"af-text-sm",children:m.name}),rt("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Xo(m.size),")"]})]}),rt(w,{variant:"ghost",size:"sm",onClick:()=>o(m),disabled:t===i(m),children:[t===i(m)?nt(Yo,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):nt(Go,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(m)?"Downloading...":"Download"]})]},g))})]}),rt("div",{children:[nt("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),rt("div",{className:"af-space-y-2 af-text-sm",children:[rt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[nt(Ko,{className:"af-h-4 af-w-4"}),nt("span",{children:$r(e.metadata.submitted_at)})]}),e.metadata.ip_address&&rt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[nt(Wo,{className:"af-h-4 af-w-4"}),rt("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&rt("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[nt(Zo,{className:"af-h-4 af-w-4 af-mt-0.5"}),nt("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&rt("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[nt(Qo,{className:"af-h-4 af-w-4"}),rt("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as Te,jsxs as xt}from"react/jsx-runtime";function rl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function il(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 ol(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 Qs({formId:e,className:a,defaultSubmissionId:s}){let{submissions:t,total:n,isLoading:i,error:o,page:p,pageSize:m,hasNextPage:g,hasPreviousPage:r,setPage:v,setPageSize:h}=Ys({formId:e}),[f,u]=As.useState("list"),[l,b]=As.useState(null);As.useEffect(()=>{if(s&&t.length>0){let c=t.find(y=>y.id===s);c&&(b(c),u("detail"))}},[s,t]);let x=c=>{b(c),u("detail")},N=()=>{u("list"),b(null)};if(f==="detail"&&l)return Te("div",{className:a,children:Te(Zs,{submission:l,onBack:N})});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:xt("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&p===0)return xt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[Te(sl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),xt("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=p*m+1,O=Math.min((p+1)*m,n);return xt("div",{className:a,children:[xt(Oe,{children:[Te(Be,{children:xt(pe,{children:[Te(F,{children:"Email"}),Te(F,{children:"Preview"}),Te(F,{children:"Date"}),Te(F,{className:"af-text-right",children:"Actions"})]})}),Te(Fe,{children:t.map(c=>{let y=il(c.data),T=ol(c.data);return xt(pe,{children:[xt(M,{className:"af-font-medium",children:[xt("div",{className:"af-flex af-items-center af-gap-2",children:[y||Te("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&xt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[Te(nl,{className:"af-h-3 af-w-3"}),Te("span",{className:"af-text-xs",children:c.attachments.length})]})]}),Te(Is,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),Te(M,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:T||Te("span",{className:"af-italic",children:"No preview available"})}),Te(M,{className:"af-text-muted-foreground",children:rl(c.metadata.submitted_at)}),Te(M,{className:"af-text-right",children:Te(w,{variant:"ghost",size:"icon",onClick:()=>x(c),title:"View details",children:Te(al,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),xt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[xt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[xt("span",{children:["Showing ",I,"-",O," of ",n]}),xt(na,{value:String(m),onValueChange:c=>h(Number(c)),children:[Te(Yt,{className:"af-w-[70px] af-h-8",children:Te(ra,{})}),xt(Zt,{children:[Te(ze,{value:"10",children:"10"}),Te(ze,{value:"25",children:"25"}),Te(ze,{value:"50",children:"50"}),Te(ze,{value:"100",children:"100"})]})]}),Te("span",{children:"per page"})]}),xt("div",{className:"af-flex af-items-center af-gap-2",children:[xt(w,{variant:"outline",size:"sm",onClick:()=>v(p-1),disabled:!r,children:[Te(el,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xt(w,{variant:"outline",size:"sm",onClick:()=>v(p+1),disabled:!g,children:["Next",Te(tl,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Xt from"react";import{Plus as wl,X as Nl,Loader2 as Sl,Check as _l}from"lucide-react";import*as Hr from"react";import{jsx as ll}from"react/jsx-runtime";var ge=Hr.forwardRef(({className:e,type:a,...s},t)=>ll("input",{type:a,className:W("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:t,...s}));ge.displayName="Input";import*as zr from"react";import{cva as cl}from"class-variance-authority";import{jsx as dl}from"react/jsx-runtime";var ul=cl("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),be=zr.forwardRef(({className:e,...a},s)=>dl("label",{ref:s,className:W(ul(),e),...a}));be.displayName="Label";import*as la from"react";import{Plus as gl,Loader2 as Gn,Copy as vl,Check as bl,Trash2 as yl,RefreshCw as hl,AlertTriangle as xl}from"lucide-react";import*as Ds from"react";import*as bt from"@radix-ui/react-dialog";import{X as fl}from"lucide-react";import{jsx as za,jsxs as jn}from"react/jsx-runtime";var Ca=bt.Root;var ml=bt.Portal;var qr=Ds.forwardRef(({className:e,...a},s)=>za(bt.Overlay,{ref:s,className:W("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));qr.displayName=bt.Overlay.displayName;var va=Ds.forwardRef(({className:e,children:a,...s},t)=>za(ml,{children:jn("div",{className:"aifeatures-admin",children:[za(qr,{}),jn(bt.Content,{ref:t,className:W("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[a,jn(bt.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(fl,{className:"af-h-4 af-w-4"}),za("span",{className:"af-sr-only",children:"Close"})]})]})]})}));va.displayName=bt.Content.displayName;var ba=({className:e,...a})=>za("div",{className:W("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});ba.displayName="DialogHeader";var ya=({className:e,...a})=>za("div",{className:W("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});ya.displayName="DialogFooter";var ha=Ds.forwardRef(({className:e,...a},s)=>za(bt.Title,{ref:s,className:W("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));ha.displayName=bt.Title.displayName;var xa=Ds.forwardRef(({className:e,...a},s)=>za(bt.Description,{ref:s,className:W("af-text-sm af-text-muted-foreground",e),...a}));xa.displayName=bt.Description.displayName;import*as Qt from"react";function Xs(){let{api:e}=ie(),[a,s]=Qt.useState([]),[t,n]=Qt.useState(!0),[i,o]=Qt.useState(null),p=Qt.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(f){o(f instanceof Error?f:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);Qt.useEffect(()=>{p()},[p]);let m=Qt.useCallback(async f=>{let u=await e.createEventDestination(f);return s(l=>[u,...l]),u},[e]),g=Qt.useCallback(async(f,u)=>{let l=await e.updateEventDestination(f,u);return s(b=>b.map(x=>x.id===f?l:x)),l},[e]),r=Qt.useCallback(async f=>{await e.deleteEventDestination(f),s(u=>u.filter(l=>l.id!==f))},[e]),v=Qt.useCallback(async f=>{let u=await e.rotateEventDestinationSecret(f);return s(l=>l.map(b=>b.id===f?u:b)),u},[e]),h=Qt.useCallback(f=>e.getEventDestinationSecret(f),[e]);return{destinations:a,isLoading:t,error:i,refetch:p,createDestination:m,updateDestination:g,deleteDestination:r,rotateSecret:v,getSecret:h}}import*as qa from"react";import{Loader2 as jr,RotateCw as pl}from"lucide-react";import{jsx as oa,jsxs as Ls}from"react/jsx-runtime";function en({destinationId:e,limit:a=25,className:s}){let{api:t}=ie(),[n,i]=qa.useState([]),[o,p]=qa.useState(!0),[m,g]=qa.useState(null),[r,v]=qa.useState(null),h=qa.useCallback(async()=>{try{p(!0),g(null),i(await t.getEventDeliveries(e,a))}catch(u){g(u instanceof Error?u.message:"Failed to load deliveries")}finally{p(!1)}},[t,e,a]);qa.useEffect(()=>{h()},[h]);let f=async u=>{try{v(u.id),g(null);let l=await t.retryEventDelivery(e,u.id);i(b=>b.map(x=>x.id===u.id?l:x))}catch(l){g(l instanceof Error?l.message:"Retry failed")}finally{v(null)}};return o?Ls("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[oa(jr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):m?oa("div",{className:"af-text-sm af-text-destructive af-py-2",children:m}):n.length===0?oa("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):oa("div",{className:s,children:oa("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let l=u.delivered_at!==null;return Ls("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ls("div",{className:"af-min-w-0",children:[Ls("div",{className:"af-flex af-items-center af-gap-2",children:[l?oa(Z,{variant:"secondary",children:u.last_status??200}):oa(Z,{variant:"destructive",children:u.last_status??"failed"}),oa("span",{className:"af-text-sm af-truncate",children:u.type})]}),Ls("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!l&&u.last_error&&oa("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),oa(w,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>f(u),children:r===u.id?oa(jr,{className:"af-h-4 af-w-4 af-animate-spin"}):oa(pl,{className:"af-h-4 af-w-4"})})]},u.id)})})})}import{jsx as ke,jsxs as ut}from"react/jsx-runtime";function tn({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:p,updateDestination:m,deleteDestination:g,rotateSecret:r,getSecret:v}=Xs(),[h,f]=la.useState(""),[u,l]=la.useState(!1),[b,x]=la.useState(null),[N,I]=la.useState(null),[O,c]=la.useState(null),[y,T]=la.useState(!1),[z,L]=la.useState(null),[R,$]=la.useState(null),[d,U]=la.useState(null),se=la.useMemo(()=>n.filter(q=>q.form_id===e),[n,e]),Q=async()=>{let q=h.trim();if(q){if(!q.startsWith("https://")){x("Webhook URLs must start with https://");return}try{l(!0),x(null),await p({url:q,form_id:e,...a&&a.length>0?{topics:a}:{}}),f("")}catch(ve){x(ve instanceof Error?ve.message:"Failed to add webhook")}finally{l(!1)}}},oe=async q=>{try{$(q.id),x(null),await r(q.id),T(!1),c(await v(q.id))}catch(ve){x(ve instanceof Error?ve.message:"Failed to rotate secret")}finally{$(null)}},ne=async q=>{try{$(q.id),x(null),await m(q.id,{status:"active"})}catch(ve){x(ve instanceof Error?ve.message:"Failed to re-enable")}finally{$(null)}},J=async()=>{if(z)try{$(z.id),await g(z.id),L(null)}catch(q){x(q instanceof Error?q.message:"Failed to delete")}finally{$(null)}},ee=async q=>{if(N===q.id){I(null),c(null);return}try{$(q.id),x(null),T(!1),I(q.id),c(await v(q.id))}catch(ve){I(null),x(ve instanceof Error?ve.message:"Failed to read secret")}finally{$(null)}},de=async()=>{if(O)try{await navigator.clipboard.writeText(O),T(!0)}catch{}};return ut("div",{className:t,children:[ut("div",{className:"af-space-y-1",children:[ke(be,{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."})]}),ut("div",{className:"af-flex af-gap-2 af-mt-4",children:[ke(ge,{value:h,placeholder:"https://hooks.zapier.com/...",onChange:q=>f(q.target.value),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),Q())},disabled:u}),ut(w,{onClick:Q,disabled:u||!h.trim(),children:[u?ke(Gn,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(gl,{className:"af-h-4 af-w-4"}),ke("span",{className:"af-ml-1",children:"Add"})]})]}),(b||o)&&ke("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:b||o?.message}),ut("div",{className:"af-mt-4 af-space-y-2",children:[i&&ut("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ke(Gn,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&se.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."}),se.map(q=>ut("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[ut("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[ut("div",{className:"af-min-w-0",children:[ut("div",{className:"af-flex af-items-center af-gap-2",children:[ke("span",{className:"af-font-mono af-text-sm af-truncate",children:q.url}),q.status==="disabled"?ke(Z,{variant:"destructive",children:"Disabled"}):ke(Z,{variant:"secondary",children:"Active"})]}),ke("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:q.topics.includes("*")?"All events":q.topics.join(", ")})]}),ut("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[ke(w,{variant:"ghost",size:"sm",onClick:()=>U(d===q.id?null:q.id),children:d===q.id?"Hide log":"Deliveries"}),ke(w,{variant:"ghost",size:"sm",onClick:()=>ee(q),disabled:R===q.id,children:N===q.id?"Hide secret":"Show secret"}),ke(w,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:R===q.id,onClick:()=>L(q),children:ke(yl,{className:"af-h-4 af-w-4"})})]})]}),q.status==="disabled"&&ut("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[ke(xl,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),ut("div",{className:"af-text-sm",children:[ut("p",{children:["We stopped sending after repeated failures."," ",q.disabled_reason]}),ke(w,{variant:"outline",size:"sm",className:"af-mt-2",disabled:R===q.id,onClick:()=>ne(q),children:"Re-enable"})]})]}),N===q.id&&O&&ut("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."}),ut("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:de,children:y?ke(bl,{className:"af-h-4 af-w-4"}):ke(vl,{className:"af-h-4 af-w-4"})}),ke(w,{variant:"outline",title:"Rotate signing secret",disabled:R===q.id,onClick:()=>oe(q),children:R===q.id?ke(Gn,{className:"af-h-4 af-w-4 af-animate-spin"}):ke(hl,{className:"af-h-4 af-w-4"})})]})]}),d===q.id&&ke(en,{destinationId:q.id})]},q.id))]}),ke(Ca,{open:!!z,onOpenChange:q=>{!q&&!R&&L(null)},children:ut(va,{children:[ut(ba,{children:[ke(ha,{children:"Delete this webhook?"}),ut(xa,{children:["New submissions will stop being sent to ",z?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),ut(ya,{children:[ke(w,{variant:"outline",onClick:()=>L(null),disabled:!!R,children:"Cancel"}),ke(w,{variant:"destructive",onClick:J,disabled:!!R,children:R?"Deleting...":"Delete"})]})]})})]})}import{jsx as De,jsxs as wa}from"react/jsx-runtime";function an({form:e,onSaved:a,className:s}){let{updateForm:t}=ds(),[n,i]=Xt.useState(!1),[o,p]=Xt.useState(null),[m,g]=Xt.useState(null),[r,v]=Xt.useState(e.name),[h,f]=Xt.useState(e.redirect_url||""),[u,l]=Xt.useState(e.email_recipients),[b,x]=Xt.useState("");Xt.useEffect(()=>{v(e.name),f(e.redirect_url||""),l(e.email_recipients),g(null)},[e]);let N=Xt.useCallback(async T=>{try{i(!0),g(null);let z=await t(e.id,T);p(new Date),a?.(z)}catch(z){g(z instanceof Error?z.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);Xt.useEffect(()=>{if(o){let T=setTimeout(()=>p(null),2e3);return()=>clearTimeout(T)}},[o]);let I=async()=>{let T=b.trim().toLowerCase();if(!T)return;if(!T.includes("@")){g("Please enter a valid email address");return}if(u.includes(T)){g("This email is already added");return}let z=[...u,T];l(z),x(""),g(null),await N({email_recipients:z})},O=async T=>{let z=u.filter(L=>L!==T);l(z),await N({email_recipients:z})},c=async()=>{r!==e.name&&await N({name:r})},y=async()=>{let T=h||null;T!==e.redirect_url&&await N({redirect_url:T})};return wa("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?wa("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(Sl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),De("span",{className:"af-text-sm",children:"Saving..."})]}):wa("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(_l,{className:"af-h-4 af-w-4 af-text-green-600"}),De("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),wa("div",{className:"af-space-y-2",children:[De(be,{htmlFor:"form-name",children:"Form Name"}),De(ge,{id:"form-name",value:r,onChange:T=>v(T.target.value),onBlur:c,placeholder:"Contact Form"}),De("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),wa("div",{className:"af-space-y-2",children:[De(be,{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."}),wa("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(T=>wa(Z,{variant:"secondary",className:"af-gap-1",children:[T,De("button",{type:"button",onClick:()=>O(T),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:De(Nl,{className:"af-h-3 af-w-3"})})]},T)),u.length===0&&De("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),wa("div",{className:"af-flex af-gap-2",children:[De(ge,{type:"email",value:b,onChange:T=>x(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),I())},disabled:n}),De(w,{type:"button",variant:"outline",onClick:I,disabled:!b.trim()||n,children:De(wl,{className:"af-h-4 af-w-4"})})]})]}),wa("div",{className:"af-space-y-2",children:[De(be,{htmlFor:"redirect-url",children:"Redirect URL"}),De(ge,{id:"redirect-url",value:h,onChange:T=>f(T.target.value),onBlur:y,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."})]}),wa("div",{className:"af-space-y-2",children:[De(be,{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."})]}),wa("div",{className:"af-space-y-2",children:[De(be,{children:"Captcha Protection"}),De("div",{className:"af-flex af-items-center af-gap-2",children:De(Z,{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(tn,{formId:e.id}),m&&De("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m})]})}import{jsx as It,jsxs as Ta}from"react/jsx-runtime";function Gr({className:e,submissionId:a}){let{api:s}=ie(),[t,n]=Ya.useState("list"),[i,o]=Ya.useState(null),[p,m]=Ya.useState("submissions"),[g,r]=Ya.useState(a),[v,h]=Ya.useState(!!a);Ya.useEffect(()=>{if(!a)return;async function b(){try{let x=await s.getSubmission(a),N=await s.getForm(x.form_id);o(N),n("detail"),m("submissions"),r(a)}catch(x){console.error("Failed to load submission for deep link:",x)}finally{h(!1)}}b()},[a,s]);let f=(b,x)=>{o(b),n("detail"),m(x),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},l=b=>{o(b)};return v?It("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:It("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Ta("div",{className:e,children:[t==="list"&&Ta("div",{children:[Ta("div",{className:"af-mb-6",children:[It("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),It("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),It(Ws,{onSelectForm:f})]}),t==="detail"&&i&&Ta("div",{children:[Ta("div",{className:"af-mb-6",children:[Ta(w,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[It(Rl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),It("h2",{className:"af-text-lg af-font-semibold",children:i.name}),It("p",{className:"af-text-sm af-text-muted-foreground",children:It("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Ta(Gs,{value:p,onValueChange:b=>m(b),children:[Ta(Es,{className:"af-mb-4",children:[Ta(ma,{value:"submissions",className:"af-gap-2",children:[It(Cl,{className:"af-h-4 af-w-4"}),"Submissions"]}),Ta(ma,{value:"settings",className:"af-gap-2",children:[It(Pl,{className:"af-h-4 af-w-4"}),"Settings"]})]}),It(pa,{value:"submissions",children:It(Qs,{formId:i.id,defaultSubmissionId:g})}),It(pa,{value:"settings",children:It(an,{form:i,onSaved:l})})]})]})]})}import*as Le from"react";import*as ka from"react";function Za(){let{api:e}=ie(),[a,s]=ka.useState(null),[t,n]=ka.useState(!0),[i,o]=ka.useState(null),p=ka.useRef(0),m=ka.useCallback(async()=>{let g=++p.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(g!==p.current)return;s(r)}catch(r){if(g!==p.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{g===p.current&&n(!1)}},[e]);return ka.useEffect(()=>{m()},[m]),{status:a,isLoading:t,error:i,refetch:m}}var Tl=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function ca(e){return Tl.has(e.toLowerCase())}function H(e,a,s){let t=ca(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function ja(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=ca(a)?s:s*100;return Math.round(t)}function dt(e,a){return ca(a)?e:e/100}function sn(e){return e.amount_paid??Math.max(0,ja(e)-(e.credit_applied??0))}import{Fragment as Il,jsx as Ie,jsxs as Ue}from"react/jsx-runtime";function Os(e){return e instanceof Ht&&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 Wr(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${H(e.amount_off,e.currency)} off`:"Discount unavailable"}function fs(){let{api:e,siteToken:a}=ie();return Ie(kl,{api:e},a)}function kl({api:e}){let{status:a,error:s}=Za(),[t,n]=Le.useState([]),[i,o]=Le.useState(null),[p,m]=Le.useState(null),[g,r]=Le.useState(!1),[v,h]=Le.useState(!1),[f,u]=Le.useState(""),[l,b]=Le.useState(null),[x,N]=Le.useState(null),[I,O]=Le.useState(!1),c=Le.useRef(0),y=Le.useCallback(async L=>{let R=++c.current;r(!0),u("");try{let $=await e.getPromos(L);if(R!==c.current)return;n(d=>L?[...d,...$.promos.filter(U=>!d.some(se=>se.id===U.id))]:$.promos),o($.next_cursor),m($.checkout_enabled)}catch($){R===c.current&&u(Os($))}finally{R===c.current&&r(!1)}},[e]);Le.useEffect(()=>(y(),()=>{c.current++}),[y]);async function T(L){let R=++c.current;r(!0),u(""),O(!1);try{let $=await e.getPromo(L);R===c.current&&b($)}catch($){R===c.current&&u(Os($))}finally{R===c.current&&r(!1)}}async function z(){if(l){h(!0),r(!0),u("");try{let L=await e.disablePromo(l.id);if(b(L),!["inactive","expired","exhausted"].includes(L.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");O(!1),await y()}catch(L){u(Os(L))}finally{h(!1),r(!1)}}}return x?Ie(El,{currency:a?.currency??void 0,replaces:x.replaces,onCancel:()=>N(null),onSave:async L=>{let R=x.replaces?await e.replacePromo(x.replaces.id,L):await e.createPromo(L),$=await e.getPromo(R.id);if($.status==="pending"||$.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");b($),N(null),await y()}}):Ue("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[Ue("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:g||!a?.currency,onClick:()=>{u(""),N({})},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."}),p===!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?Os(s):"Connect Stripe and set the payment currency before creating codes."}),f&&Ue("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[f," ",Ie(w,{variant:"outline",disabled:g,onClick:()=>l?void T(l.id):void y(),children:"Refresh"})]}),l?Ue("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[Ie(w,{variant:"ghost",disabled:v,onClick:()=>{b(null),O(!1),y()},children:"Back to codes"}),Ue("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),Ue("p",{children:[Wr(l)," \xB7 ",l.status]}),Ue("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),Ue("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${H(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),Ue("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"}),Ue("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{variant:"outline",disabled:g,onClick:()=>void T(l.id),children:"Refresh details"}),Ie(w,{variant:"outline",disabled:g||l.status==="pending"||l.status==="unavailable"||!a?.currency,onClick:()=>N({replaces:l}),children:"Replace with new code"}),Ie(w,{variant:"outline",disabled:g||!["active","pending","unavailable"].includes(l.status),onClick:()=>O(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),I&&Ue("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[Ue("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:g,onClick:()=>void z(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",Ie(w,{variant:"ghost",disabled:g,onClick:()=>O(!1),children:"Cancel"})]})]}):Ue(Il,{children:[t.map(L=>Ue("button",{type:"button",disabled:g,onClick:()=>void T(L.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:[Ue("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[Ie("span",{className:"af-font-semibold af-break-all",children:L.code}),Ie("span",{className:"af-text-sm",children:L.status})]}),Ue("div",{className:"af-text-sm",children:[Wr(L)," \xB7"," ",L.times_redeemed==null?"Usage unavailable":`${L.times_redeemed} redemptions`]})]},L.id)),!g&&!f&&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."}),g&&Ie("p",{role:"status",children:"Loading promo codes\u2026"}),i&&Ie(w,{variant:"outline",disabled:g,onClick:()=>void y(i),children:"Load more"})]})]})}function El({currency:e,replaces:a,onCancel:s,onSave:t}){let[n,i]=Le.useState(""),[o,p]=Le.useState(a?.name??""),[m,g]=Le.useState(a?.amount_off!=null?"fixed":"percent"),[r,v]=Le.useState(a?.percent_off?.toString()??(a?.amount_off!=null&&e?String(dt(a.amount_off,e)):"")),[h,f]=Le.useState(a?.minimum_amount!=null&&e?String(dt(a.minimum_amount,e)):""),[u,l]=Le.useState(()=>{if(!a?.expires_at)return"";let ne=new Date(a.expires_at);return Number.isFinite(ne.getTime())?new Date(ne.getTime()-ne.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[b,x]=Le.useState(a?.max_redemptions?.toString()??""),[N,I]=Le.useState(a?.duration??"once"),[O,c]=Le.useState(a?.duration_in_months?.toString()??"3"),[y,T]=Le.useState(null),[z,L]=Le.useState(!1),[R,$]=Le.useState(""),d=Le.useRef(!1),U=e&&ca(e)?"1":"0.01";async function se(ne){if(ne.preventDefault(),d.current)return;$("");let J=y;if(!J){if(!e){$("Payment currency is not available.");return}if(a&&n.trim().toUpperCase()===a.code.toUpperCase()){$("Choose a different code for the replacement.");return}let ee=zt(r,e),de=h?zt(h,e):null;if(m==="fixed"&&(!ee||ee>999999999999)||h&&(!de||de>999999999999)){$("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){$("Choose a future expiry.");return}J={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:N,...m==="percent"?{percent_off:Number(r)}:{amount_off:ee,currency:e},...h?{minimum_amount:de,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...b?{max_redemptions:Number(b)}:{},...N==="repeating"?{duration_in_months:Number(O)}:{}},T(J)}d.current=!0,L(!0);try{await t(J)}catch(ee){$(Os(ee)),ee instanceof Ht&&ee.status>=400&&ee.status<500&&ee.details?.retryable!==!0&&T(null)}finally{d.current=!1,L(!1)}}let Q=(ne,J,ee,de={})=>Ue("label",{className:"af-grid af-gap-1 af-text-sm",children:[ne,Ie(ge,{"aria-label":ne,value:J,onChange:q=>ee(q.target.value),...de})]}),oe="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return Ue("form",{onSubmit:se,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."}),Ue("fieldset",{disabled:z||!!y,className:"af-grid af-gap-4",children:[Q("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),Q("Name",o,p,{required:!0,maxLength:40}),Ue("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",Ue("select",{"aria-label":"Discount type",className:oe,value:m,onChange:ne=>g(ne.target.value),children:[Ie("option",{value:"percent",children:"Percentage"}),Ue("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),Q("Discount",r,v,{type:"number",required:!0,min:m==="percent"?"0.01":U,max:m==="percent"?"100":void 0,step:m==="percent"?"0.01":U}),Q("Minimum order amount",h,f,{type:"number",min:U,step:U,placeholder:e?.toUpperCase()}),Ue("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."]}),Q("Expires at (local time)",u,l,{type:"datetime-local",step:1}),Q("Maximum redemptions",b,x,{type:"number",min:1,max:1e6,step:1}),Ue("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",Ue("select",{"aria-label":"Subscription duration",className:oe,value:N,onChange:ne=>I(ne.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"})]})]}),N==="repeating"&&Q("Months",O,c,{type:"number",required:!0,min:1,max:36,step:1})]}),R&&Ie("p",{role:"alert",className:"af-text-sm af-text-destructive",children:R}),y&&!z&&Ue("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:y.request_id})]}),Ue("div",{className:"af-flex af-flex-wrap af-gap-2",children:[Ie(w,{type:"submit",disabled:z,children:z?"Saving\u2026":y?"Retry same request":a?"Create replacement":"Create code"}),Ie(w,{type:"button",variant:"ghost",disabled:z||!!y,onClick:s,children:"Cancel"})]})]})}import*as ws from"react";import{ArrowLeft as Xc,FileText as eu,Package as tu,Receipt as au,Settings as su,Users as nu}from"lucide-react";import*as nn from"react";import{Package as Al,Pencil as Dl,Plus as Kr,Trash2 as Ll}from"lucide-react";import{jsx as Me,jsxs as Et}from"react/jsx-runtime";function Ol(e){if(e.allow_custom_amount){let a=e.min_amount!==null?H(e.min_amount,e.currency):"?",s=e.max_amount!==null?H(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":H(e.unit_amount,e.currency)}function Bl(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function rn({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:p}=e,[m,g]=nn.useState(null),[r,v]=nn.useState(!1),[h,f]=nn.useState(null),u=async()=>{if(m)try{v(!0),f(null),await p(m.id),g(null)}catch(l){f(l instanceof Error?l.message:"Failed to delete product")}finally{v(!1)}};return i?Me("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Me("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?Me("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Et("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Et("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Me(Al,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Et("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",Me("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Et(w,{variant:"outline",onClick:()=>s?.(),children:[Me(Kr,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Et("div",{className:t,children:[Me("div",{className:"af-flex af-justify-end af-mb-4",children:Et(w,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Me(Kr,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Et(Oe,{children:[Me(Be,{children:Et(pe,{children:[Me(F,{children:"Name"}),Me(F,{children:"Price"}),Me(F,{children:"Fulfillment"}),Me(F,{children:"Status"}),Me(F,{className:"af-text-right",children:"Actions"})]})}),Me(Fe,{children:n.map(l=>Et(pe,{children:[Me(M,{className:"af-font-medium",children:l.name}),Me(M,{children:Ol(l)}),Me(M,{className:"af-text-muted-foreground",children:Bl(l)}),Me(M,{children:Me(Z,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),Me(M,{className:"af-text-right",children:Et("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Et(w,{variant:"ghost",size:"sm",onClick:()=>a?.(l),children:[Me(Dl,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Et(w,{variant:"ghost",size:"sm",onClick:()=>{f(null),g(l)},children:[Me(Ll,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),Me(Ca,{open:!!m,onOpenChange:l=>{!l&&!r&&g(null)},children:Et(va,{children:[Et(ba,{children:[Me(ha,{children:"Delete product?"}),Et(xa,{children:['"',m?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),h&&Me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:h}),Et(ya,{children:[Me(w,{variant:"outline",onClick:()=>g(null),disabled:r,children:"Cancel"}),Me(w,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as Ge from"react";import{FileText as Ml,Link2 as Ul,Loader2 as Zr,Plus as $l,Upload as Vl,X as Hl}from"lucide-react";import*as ft from"react";import{Loader2 as Jr,Plus as Wn,Trash2 as Yr,X as Fl}from"lucide-react";import{jsx as j,jsxs as fe}from"react/jsx-runtime";function Kn(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function on({productId:e,currency:a,className:s}){let{api:t}=ie(),n=ca(a)?"1":"0.01",[i,o]=ft.useState(null),[p,m]=ft.useState(!0),[g,r]=ft.useState(null),[v,h]=ft.useState(null),[f,u]=ft.useState(!1),l=ft.useRef(!0);ft.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let b=ft.useCallback(async()=>{try{let S=await t.getProduct(e);if(!l.current)return;o(S)}catch(S){if(!l.current)return;r(S instanceof Error?S.message:"Failed to load product")}finally{l.current&&m(!1)}},[t,e]);ft.useEffect(()=>{b()},[b]);let x=async S=>{h(null),u(!0);try{await S(),await b()}catch(A){l.current&&h(A instanceof Error?A.message:"Something went wrong")}finally{l.current&&u(!1)}},[N,I]=ft.useState(""),[O,c]=ft.useState(""),[y,T]=ft.useState({}),z=()=>x(async()=>{let S=N.trim(),A=O.split(",").map(ue=>ue.trim()).filter(Boolean);if(!S)throw new Error("Option name is required");if(A.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:S,values:A}),l.current&&(I(""),c(""))}),L=S=>x(async()=>{let A=(y[S.id]??"").trim();if(!A)throw new Error("Enter a value");await t.updateOption(S.id,{add_values:[A]}),l.current&&T(ue=>({...ue,[S.id]:""}))}),R=(S,A)=>x(()=>t.updateOption(S.id,{remove_values:[A]})),$=S=>x(()=>t.deleteOption(S.id)),[d,U]=ft.useState(null),[se,Q]=ft.useState(null),[oe,ne]=ft.useState(!1),[J,ee]=ft.useState(null),de=i?.options??[],q=i?.variants??[],ve=()=>{Q(null),U({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(de.map(S=>[S.id,S.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},st=S=>{Q(null);let A=S.inventory?.on_hand??0,ue=A<0?"":String(A);U({variant:S,title:S.title??"",sku:S.sku??"",unitAmount:S.unit_amount!=null?String(dt(S.unit_amount,a)):"",compareAt:S.compare_at_amount!=null?String(dt(S.compare_at_amount,a)):"",active:S.active,optionValues:{},tracked:S.inventory?.tracked??!1,onHand:ue,initialOnHand:ue,allowBackorder:S.inventory?.allow_backorder??!1})},lt=async()=>{if(!d)return;Q(null);let S=d.variant?.allow_custom_amount??!1,A=null,ue=null;if(!S){if(A=zt(d.unitAmount,a),A===null||A<=0){Q("Enter a valid price");return}if(d.compareAt.trim()&&(ue=zt(d.compareAt,a),ue===null||ue<=A)){Q("Compare-at price must be greater than the price");return}}let Ve=d.onHand.trim()!==d.initialOnHand.trim(),we=parseInt(d.onHand,10);if(d.tracked&&Ve&&(!Number.isFinite(we)||we<0)){Q("On-hand quantity must be zero or more");return}try{if(ne(!0),d.variant)await t.updateVariant(d.variant.id,{title:d.title.trim()||null,sku:d.sku.trim()||null,...S?{}:{unit_amount:A,compare_at_amount:ue},active:d.active}),await t.setVariantInventory(d.variant.id,{tracked:d.tracked,on_hand:d.tracked&&Ve?we:void 0,allow_backorder:d.allowBackorder});else{let He={};for(let et of de){let ct=d.optionValues[et.id];if(!ct){Q(`Choose a ${et.title}`),ne(!1);return}He[et.title]=ct}await t.createVariant(e,{title:d.title.trim()||null,sku:d.sku.trim()||null,unit_amount:A,compare_at_amount:ue,active:d.active,option_values:de.length>0?He:void 0,inventory:d.tracked?{tracked:!0,on_hand:we,allow_backorder:d.allowBackorder}:{tracked:!1,allow_backorder:d.allowBackorder}})}await b(),l.current&&U(null)}catch(He){if(l.current&&Q(He instanceof Error?He.message:"Failed to save variant"),d.variant)try{let et=await t.getProduct(e);l.current&&o(et)}catch{}}finally{l.current&&ne(!1)}},Re=()=>x(async()=>{J&&(await t.deleteVariant(J.id),l.current&&ee(null))}),xe=d?.variant?.allow_custom_amount??!1,vt=d?.variant!=null&&d.variant.option_values.length===0&&de.length>0&&!d.variant.active,E=d?.variant?.inventory!=null&&d.variant.inventory.on_hand<0?-d.variant.inventory.on_hand:null;function te(S){let A=S.inventory;if(!A||!A.tracked)return j("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ue=A.available??A.on_hand;return ue<0?fe("span",{children:[-ue," backordered"]}):fe("span",{children:[ue," in stock",A.allow_backorder&&j("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return p?j("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:j(Jr,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):g?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:g})}):fe("div",{className:`af-space-y-6 ${s||""}`,children:[fe("div",{className:"af-space-y-3",children:[fe("div",{children:[j(be,{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."})]}),de.length>0&&j("div",{className:"af-space-y-3",children:de.map(S=>fe("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[fe("div",{className:"af-flex af-items-center af-justify-between",children:[j("span",{className:"af-text-sm af-font-medium",children:S.title}),j(w,{variant:"ghost",size:"sm",onClick:()=>$(S),disabled:f,children:j(Yr,{className:"af-h-4 af-w-4"})})]}),j("div",{className:"af-flex af-flex-wrap af-gap-2",children:S.values.map(A=>fe(Z,{variant:"secondary",className:"af-gap-1",children:[A.value,j("button",{type:"button",onClick:()=>R(S,A.value),className:"af-ml-1 hover:af-text-destructive",disabled:f,title:"Remove value",children:j(Fl,{className:"af-h-3 af-w-3"})})]},A.id))}),fe("div",{className:"af-flex af-gap-2",children:[j(ge,{value:y[S.id]??"",onChange:A=>T(ue=>({...ue,[S.id]:A.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),L(S))},disabled:f}),j(w,{type:"button",variant:"outline",size:"sm",onClick:()=>L(S),disabled:f||!(y[S.id]??"").trim(),children:j(Wn,{className:"af-h-4 af-w-4"})})]})]},S.id))}),fe("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[fe("div",{className:"af-space-y-1",children:[j(be,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),j(ge,{id:"new-option-title",value:N,onChange:S=>I(S.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:f})]}),fe("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[j(be,{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:S=>c(S.target.value),placeholder:"S, M, L",disabled:f})]}),fe(w,{type:"button",variant:"outline",onClick:z,disabled:f||!N.trim()||!O.trim(),children:[j(Wn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),fe("div",{className:"af-space-y-3",children:[fe("div",{className:"af-flex af-items-center af-justify-between",children:[j(be,{children:"Variants"}),fe(w,{type:"button",variant:"outline",size:"sm",onClick:ve,disabled:f||de.length===0,children:[j(Wn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),de.length===0&&j("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),q.length===0?j("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):fe(Oe,{children:[j(Be,{children:fe(pe,{children:[j(F,{children:"Variant"}),j(F,{children:"SKU"}),j(F,{children:"Price"}),j(F,{children:"Stock"}),j(F,{children:"Status"}),j(F,{className:"af-text-right",children:"Actions"})]})}),j(Fe,{children:q.map(S=>fe(pe,{children:[j(M,{className:"af-font-medium",children:Kn(S)}),j(M,{className:"af-text-muted-foreground",children:S.sku||"-"}),j(M,{children:S.unit_amount!=null?fe("span",{children:[S.compare_at_amount!=null&&j("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:H(S.compare_at_amount,S.currency)}),H(S.unit_amount,S.currency)]}):S.allow_custom_amount?j("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),j(M,{children:te(S)}),j(M,{children:j(Z,{variant:S.active?"success":"secondary",children:S.active?"Active":"Inactive"})}),j(M,{className:"af-text-right",children:fe("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[j(w,{variant:"ghost",size:"sm",onClick:()=>st(S),disabled:f,children:"Edit"}),j(w,{variant:"ghost",size:"icon",onClick:()=>ee(S),disabled:f,title:"Delete variant",children:j(Yr,{className:"af-h-4 af-w-4"})})]})})]},S.id))})]})]}),v&&j("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),j(Ca,{open:d!==null,onOpenChange:S=>{!S&&!oe&&U(null)},children:fe(va,{children:[fe(ba,{children:[j(ha,{children:d?.variant?"Edit variant":"Add variant"}),j(xa,{children:"Price, markdown, and stock live on the variant."})]}),d&&fe("div",{className:"af-space-y-3",children:[d.variant?d.variant.option_values.length>0&&fe("div",{className:"af-text-sm",children:[j("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Kn(d.variant)]}):de.map(S=>fe("div",{className:"af-space-y-1",children:[j(be,{className:"af-text-xs af-text-muted-foreground",children:S.title}),fe(na,{value:d.optionValues[S.id]??"",onValueChange:A=>U(ue=>ue&&{...ue,optionValues:{...ue.optionValues,[S.id]:A}}),children:[j(Yt,{children:j(ra,{placeholder:`Choose ${S.title}`})}),j(Zt,{children:S.values.map(A=>j(ze,{value:A.value,children:A.value},A.id))})]})]},S.id)),xe?fe("div",{className:"af-space-y-1",children:[j(be,{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."})]}):fe("div",{className:"af-flex af-gap-3",children:[fe("div",{className:"af-space-y-1",children:[fe(be,{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:d.unitAmount,onChange:S=>U(A=>A&&{...A,unitAmount:S.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),fe("div",{className:"af-space-y-1",children:[j(be,{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:d.compareAt,onChange:S=>U(A=>A&&{...A,compareAt:S.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),fe("div",{className:"af-space-y-1",children:[j(be,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),j(ge,{id:"variant-sku",value:d.sku,onChange:S=>U(A=>A&&{...A,sku:S.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),fe("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[fe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[j("input",{type:"checkbox",checked:d.tracked,onChange:S=>U(A=>A&&{...A,tracked:S.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),d.tracked&&fe("div",{className:"af-space-y-1 af-pl-6",children:[fe("div",{className:"af-flex af-items-end af-gap-3",children:[fe("div",{className:"af-space-y-1",children:[j(be,{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:d.onHand,onChange:S=>U(A=>A&&{...A,onHand:S.target.value}),placeholder:E!=null?"0":void 0,className:"af-w-[100px]"})]}),fe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[j("input",{type:"checkbox",checked:d.allowBackorder,onChange:S=>U(A=>A&&{...A,allowBackorder:S.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),E!=null&&fe("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",E," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),fe("div",{className:"af-space-y-1",children:[fe("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[j("input",{type:"checkbox",checked:d.active,onChange:S=>U(A=>A&&{...A,active:S.target.checked}),className:"af-h-4 af-w-4",disabled:vt}),"Active (buyers can purchase this variant)"]}),vt&&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."})]}),se&&j("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:se})]}),fe(ya,{children:[j(w,{variant:"outline",onClick:()=>U(null),disabled:oe,children:"Cancel"}),fe(w,{onClick:lt,disabled:oe,children:[oe?j(Jr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,d?.variant?"Save":"Add variant"]})]})]})}),j(Ca,{open:J!==null,onOpenChange:S=>{!S&&!f&&ee(null)},children:fe(va,{children:[fe(ba,{children:[j(ha,{children:"Delete variant?"}),j(xa,{children:J&&`"${Kn(J)}" will no longer be purchasable. Past orders are unaffected.`})]}),fe(ya,{children:[j(w,{variant:"outline",onClick:()=>ee(null),disabled:f,children:"Cancel"}),j(w,{variant:"destructive",onClick:Re,disabled:f,children:"Delete"})]})]})})]})}import{Fragment as ql,jsx as me,jsxs as _e}from"react/jsx-runtime";function zl(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 ln({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:p,attachProductFileFromUrl:m}=e,g=!!a,r=a?.currency??s,v=ca(r)?"1":"0.01",h=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[f,u]=Ge.useState(!1),[l,b]=Ge.useState(null),x=Ge.useRef(!0);Ge.useEffect(()=>(x.current=!0,()=>{x.current=!1}),[]);let[N,I]=Ge.useState(a?.name??""),[O,c]=Ge.useState(a?.description??""),[y,T]=Ge.useState(a?.allow_custom_amount?"custom":"fixed"),[z,L]=Ge.useState(a?.unit_amount!=null?String(dt(a.unit_amount,r)):""),[R,$]=Ge.useState(a?.min_amount!=null?String(dt(a.min_amount,r)):""),[d,U]=Ge.useState(a?.max_amount!=null?String(dt(a.max_amount,r)):""),[se,Q]=Ge.useState(String(a?.max_quantity??10)),oe=Ge.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(dt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(dt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(dt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[ne,J]=Ge.useState(a?.collect_shipping_address??!1),[ee,de]=Ge.useState(a?.active??!0),[q,ve]=Ge.useState(a?.images??[]),[st,lt]=Ge.useState(""),[Re,xe]=Ge.useState(a?.fulfillment??null),[vt,E]=Ge.useState(!1),[te,S]=Ge.useState(""),[A,ue]=Ge.useState(null),Ve=Ge.useRef(null),we=f||vt,He=()=>{let ae=st.trim();if(ae){if(q.includes(ae)){b("This image URL is already added");return}ve(Pe=>[...Pe,ae]),lt(""),b(null)}},et=ae=>{ve(Pe=>Pe.filter(Ye=>Ye!==ae))},ct=async()=>{if(b(null),!N.trim()){b("Product name is required");return}let ae=null,Pe=null,Ye=null,Ra=!g||y!==oe.pricingMode||(y==="fixed"?z!==oe.unitAmount:R!==oe.minAmount||d!==oe.maxAmount),sa=!g||se!==oe.maxQuantity,Ua=h||y==="fixed";if(!(h||!Ra))if(y==="fixed"){if(ae=zt(z,r),ae===null||ae<=0){b("Enter a valid price");return}}else{if(Pe=zt(R,r),Ye=zt(d,r),Pe===null||Ye===null){b("Enter valid minimum and maximum amounts");return}if(Ye<Pe){b("Maximum amount must be at least the minimum amount");return}}let tt=parseInt(se,10);if(Ua&&sa&&(!Number.isFinite(tt)||tt<1)){b("Max quantity must be at least 1");return}try{u(!0);let Ze;if(g&&a){let D={name:N.trim(),description:O.trim()||null,images:q,collect_shipping_address:ne,active:ee};!h&&Ra&&(D.allow_custom_amount=y==="custom",y==="fixed"?D.unit_amount=ae:(D.min_amount=Pe,D.max_amount=Ye)),Ua&&sa&&(D.max_quantity=tt),Ze=await o(a.id,D),oe.pricingMode=Ze.allow_custom_amount?"custom":"fixed",oe.unitAmount=Ze.unit_amount!=null?String(dt(Ze.unit_amount,r)):"",oe.minAmount=Ze.min_amount!=null?String(dt(Ze.min_amount,r)):"",oe.maxAmount=Ze.max_amount!=null?String(dt(Ze.max_amount,r)):"",oe.maxQuantity=String(Ze.max_quantity)}else{let D={name:N.trim(),allow_custom_amount:y==="custom",collect_shipping_address:ne,active:ee};O.trim()&&(D.description=O.trim()),q.length>0&&(D.images=q),y==="fixed"?(D.unit_amount=ae,D.max_quantity=tt):(D.min_amount=Pe,D.max_amount=Ye),Ze=await i(D)}if(!x.current)return;xe(Ze.fulfillment),t?.(Ze)}catch(Ze){if(!x.current)return;b(Ze instanceof Error?Ze.message:"Failed to save product")}finally{x.current&&u(!1)}},Ut=async ae=>{let Pe=ae.target.files?.[0];if(!(!Pe||!a))try{E(!0),ue(null);let Ye=await p(a.id,Pe);if(!x.current)return;xe(Ye.fulfillment),t?.(Ye)}catch(Ye){if(!x.current)return;ue(Ye instanceof Error?Ye.message:"Failed to upload file")}finally{x.current&&(E(!1),Ve.current&&(Ve.current.value=""))}},$t=async()=>{let ae=te.trim();if(!(!ae||!a))try{E(!0),ue(null);let Pe=await m(a.id,ae);if(!x.current)return;xe(Pe.fulfillment),S(""),t?.(Pe)}catch(Pe){if(!x.current)return;ue(Pe instanceof Error?Pe.message:"Failed to fetch file")}finally{x.current&&E(!1)}};return _e("div",{className:`af-space-y-6 ${n||""}`,children:[_e("div",{className:"af-space-y-2",children:[me(be,{htmlFor:"product-name",children:"Name"}),me(ge,{id:"product-name",value:N,onChange:ae=>I(ae.target.value),placeholder:"My product"})]}),_e("div",{className:"af-space-y-2",children:[me(be,{htmlFor:"product-description",children:"Description"}),me("textarea",{id:"product-description",value:O,onChange:ae=>c(ae.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:[me(be,{children:"Pricing"}),h?me("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(ql,{children:[_e(na,{value:y,onValueChange:ae=>T(ae),children:[me(Yt,{className:"af-w-[260px]",children:me(ra,{})}),_e(Zt,{children:[me(ze,{value:"fixed",children:"Fixed price"}),me(ze,{value:"custom",children:"Buyer chooses the amount"})]})]}),y==="fixed"?me("div",{className:"af-flex af-items-end af-gap-3",children:_e("div",{className:"af-space-y-1",children:[_e(be,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),me(ge,{id:"product-price",type:"number",min:"0",step:v,value:z,onChange:ae=>L(ae.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(be,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),me(ge,{id:"product-min-amount",type:"number",min:"0",step:v,value:R,onChange:ae=>$(ae.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),_e("div",{className:"af-space-y-1",children:[_e(be,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),me(ge,{id:"product-max-amount",type:"number",min:"0",step:v,value:d,onChange:ae=>U(ae.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),me("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."]})]}),(h||y==="fixed")&&_e("div",{className:"af-space-y-1",children:[me(be,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),me(ge,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:se,onChange:ae=>Q(ae.target.value),className:"af-w-[140px]"})]})]}),_e("div",{className:"af-space-y-2",children:[me(be,{children:"Images"}),me("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:[q.map(ae=>_e(Z,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[me("span",{className:"af-truncate",children:ae}),me("button",{type:"button",onClick:()=>et(ae),className:"af-ml-1 hover:af-text-destructive",disabled:f,children:me(Hl,{className:"af-h-3 af-w-3"})})]},ae)),q.length===0&&me("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),_e("div",{className:"af-flex af-gap-2",children:[me(ge,{type:"url",value:st,onChange:ae=>lt(ae.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),He())},disabled:f}),me(w,{type:"button",variant:"outline",onClick:He,disabled:!st.trim()||f,children:me($l,{className:"af-h-4 af-w-4"})})]})]}),_e("div",{className:"af-space-y-2",children:[me(be,{children:"Digital File"}),me("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."}),g?_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:[me(Ml,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),me("span",{className:"af-text-sm",children:Re.filename}),Re.size!=null&&_e("span",{className:"af-text-xs af-text-muted-foreground",children:["(",zl(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:[me(Ul,{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:[me("input",{ref:Ve,type:"file",onChange:Ut,className:"af-hidden",disabled:we}),_e(w,{type:"button",variant:"outline",size:"sm",onClick:()=>Ve.current?.click(),disabled:we,children:[vt?me(Zr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):me(Vl,{className:"af-h-4 af-w-4 af-mr-1"}),Re?.type==="download"?"Replace file":"Upload file"]}),me("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),me(ge,{type:"url",value:te,onChange:ae=>S(ae.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:vt}),me(w,{type:"button",variant:"outline",size:"sm",onClick:$t,disabled:!te.trim()||we,children:"Fetch from URL"})]}),A&&me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:A})]}):me("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:[me(be,{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:[me("input",{type:"checkbox",checked:ne,onChange:ae=>J(ae.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:[me("input",{type:"checkbox",checked:ee,onChange:ae=>de(ae.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),g&&a&&_e("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[me(be,{children:"Options & Variants"}),me(on,{productId:a.id,currency:r})]}),l&&me("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),me("div",{className:"af-flex af-items-center af-gap-2",children:_e(w,{type:"button",onClick:ct,disabled:we,children:[f?me(Zr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,g?"Save changes":"Create product"]})})]})}import*as wt from"react";import{ChevronLeft as pc,ChevronRight as ui,Loader2 as gc,Receipt as vc,Search as bc,SlidersHorizontal as yc}from"lucide-react";import*as at from"react";var jl=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function cn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=at.useState([]),[i,o]=at.useState(0),[p,m]=at.useState(!0),[g,r]=at.useState(null),[v,h]=at.useState(0),[f,u]=at.useState(e),[l,b]=at.useState(void 0),[x,N]=at.useState(""),[I,O]=at.useState(""),[c,y]=at.useState(""),[T,z]=at.useState(!1),[L,R]=at.useState(!1),[$,d]=at.useState(void 0),U=$?$.join(","):"",se=at.useMemo(()=>{if(!U)return;let J=new Set(U.split(","));return jl.filter(ee=>!J.has(ee))},[U]),Q=at.useRef(0),oe=at.useCallback(async()=>{let J=++Q.current;try{m(!0),r(null);let ee={limit:f,offset:v*f};l?ee.status=l:se?ee.excludeStatus=se:T||(ee.excludeStatus=["pending","expired"]),x.trim()&&(ee.customerEmail=x.trim()),I.trim()&&(ee.from=I.trim()),c.trim()&&(ee.to=c.trim()),L&&(ee.unfulfilledOnly=!0);let de=await s.getOrders(ee);if(J!==Q.current)return;n(de.orders),o(de.total)}catch(ee){if(J!==Q.current)return;r(ee instanceof Error?ee:new Error("Failed to fetch orders"))}finally{J===Q.current&&m(!1)}},[s,v,f,l,se,T,L,x,I,c,a]);at.useEffect(()=>{oe()},[oe]);let ne=Math.ceil(i/f);return{orders:t,total:i,isLoading:p,error:g,page:v,pageSize:f,hasNextPage:v<ne-1,hasPreviousPage:v>0,setPage:h,setPageSize:J=>{u(J),h(0)},status:l,setStatus:J=>{b(J),h(0)},statusIn:$,setStatusIn:J=>{d(J&&J.length>0?J:void 0),h(0)},customerEmail:x,setCustomerEmail:J=>{N(J),h(0)},from:I,setFrom:J=>{O(J),h(0)},to:c,setTo:J=>{y(J),h(0)},showAbandoned:T,setShowAbandoned:J=>{z(J),h(0)},unfulfilledOnly:L,setUnfulfilledOnly:J=>{R(J),h(0)},clearFilters:()=>{b(void 0),d(void 0),z(!1),R(!1),N(""),O(""),y(""),h(0)},refetch:oe}}import*as it from"react";import{ArrowLeft as Kl,Check as ai,ChevronLeft as Jl,ChevronRight as Yl,ClipboardCopy as Zl,Copy as Ql,Download as Xl,Loader2 as dn,Mail as si,MoreHorizontal as ec,Package as tc,RotateCcw as ac,Truck as sc,Undo2 as ni}from"lucide-react";import*as Qr from"react";import*as Ea from"@radix-ui/react-popover";import{jsx as Jn}from"react/jsx-runtime";var Xr=Ea.Root,ei=Ea.Trigger;var Yn=Qr.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>Jn(Ea.Portal,{children:Jn("div",{className:"aifeatures-admin",children:Jn(Ea.Content,{ref:n,align:a,sideOffset:s,className:W("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...t})})}));Yn.displayName=Ea.Content.displayName;import{jsx as un}from"react/jsx-runtime";var Gl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Wl(e){return Gl[e]??e}function ti(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 ns({status:e,className:a}){return un(Z,{variant:ti(e),className:a,children:Wl(e)})}function rs({status:e}){return un(ns,{status:e})}function ms({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?un(Z,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?un(Z,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Ga(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as dc,jsx as P,jsxs as K}from"react/jsx-runtime";var li="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",is="af-text-xs af-text-muted-foreground";function Zn(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 nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ci(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 fn=24,rc=["paid","partially_refunded"],ic=["paid","partially_refunded","disputed"],oc=/^[A-Za-z0-9 _-]*$/,ri=100;function er(e,a,s,t,n){let i=rc.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 ${fn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${fn} 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<fn&&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<fn&&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:p}){if(p)return K("div",{children:[P(Pa,{deliveries:[p]}),o&&P("div",{className:"af-mt-2",children:o})]});let m=er(n,s,t,i,a);return K("div",{children:[K("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[K("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(Z,{variant:m.variant,className:"af-shrink-0",children:m.label})]}),m.detail&&P("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:m.detail}),o&&P("div",{className:"af-mt-2",children:o})]})}function oi(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=nc(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}: ${ci(n)}`)}function lc(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function tr({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=it.useState(!1);if(!lc())return null;let p=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},m=i?P(ai,{className:"af-h-3 af-w-3"}):P(Ql,{className:"af-h-3 af-w-3"});return n==="icon"?P(w,{variant:"ghost",size:"icon",className:W("af-h-6 af-w-6 af-shrink-0",t),onClick:p,title:a,"aria-label":a,children:m}):K(w,{variant:"outline",size:"sm",className:t,onClick:p,"aria-label":a,children:[i?P(ai,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):P(Zl,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Qn({label:e,value:a}){return K("div",{children:[P("div",{className:is,children:e}),K("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(tr,{value:a,label:`Copy ${e}`})]})]})}function cc({src:e}){let[a,s]=it.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(tc,{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 Ia({title:e,action:a,children:s,className:t}){return K("section",{className:W("af-rounded-lg af-border af-p-4",t),children:[K("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[P("h4",{className:li,children:e}),a]}),P("div",{className:"af-mt-3",children:s})]})}function qt({label:e,emphasis:a,divider:s,children:t}){return K("div",{className:W("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":is,children:e}),P("span",{className:W("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function Xn({onSelect:e,disabled:a,icon:s,children:t}){return K(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 uc(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 ${H(sn(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?Js(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?Js(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 ${H(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 mn({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:p=!1,hasNextOrder:m=!1}){let{api:g}=ie(),[r,v]=it.useState(e),[h,f]=it.useState(null),[u,l]=it.useState(null),[b,x]=it.useState(!1),[N,I]=it.useState(!1),[O,c]=it.useState(!1),[y,T]=it.useState(!1),[z,L]=it.useState(""),[R,$]=it.useState(!1),[d,U]=it.useState(null),[se,Q]=it.useState(!1),[oe,ne]=it.useState(""),[J,ee]=it.useState([]),[de,q]=it.useState(!1),[ve,st]=it.useState(!1),[lt,Re]=it.useState(null);it.useEffect(()=>{v(e)},[e]);let xe=k=>{let Ee=k.id===r.id&&k.email_deliveries===void 0?{...k,email_deliveries:r.email_deliveries}:k;v(Ee),t?.(Ee)},vt=Object.entries(r.metadata??{}),E=Math.max(0,sn(r)-r.amount_refunded),te=(r.status==="paid"||r.status==="partially_refunded")&&E>0,S=r.exclusive_tax_total!=null,A=k=>typeof k.amountNet=="number"?k.amountNet+(k.exclusiveTax??0):(typeof k.unitAmount=="number"?k.unitAmount:0)*(typeof k.quantity=="number"&&k.quantity>0?k.quantity:1),ue=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),Ve=J.reduce((k,Ee)=>k+A(r.line_items[Ee]??{}),0)+(de?ue:0),we=r.tax_total??0,He=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((k,Ee)=>k+(Ee.exclusiveTax??0),0)),et=S?de&&ue>0?He:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&we>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,we-(r.tax_refunded??0)),Math.round(we*Ve/(r.amount_total+(r.shipping_total??0)))):0,ct=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(Ve+et,E):Ve+et,Ut=J.length>0||de,$t=Ut?ct:zt(oe,r.currency),ae=ca(r.currency)?"1":"0.01",Pe=async()=>{try{x(!0),f(null),l(null),await g.resendOrderReceipt(r.id);let k=await g.getOrder(r.id);xe(k),l("Receipt email queued.")}catch(k){f(k instanceof Error?k.message:"Failed to resend receipt")}finally{x(!1)}},Ye=async()=>{try{I(!0),f(null),l(null);let k=await g.resetOrderDownloads(r.id);xe(k),c(!1),l("Download count reset.")}catch(k){f(k instanceof Error?k.message:"Failed to reset downloads")}finally{I(!1)}},Ra=r.line_items.some(k=>k.collectShippingAddress===!0&&!k.refunded&&!k.unavailableReason),sa=typeof r.merchant_fulfilled_at=="string",Ua=ic.includes(r.status)||r.status==="refunded"&&r.line_items.some(k=>k.collectShippingAddress===!0&&k.amountNet===0&&!k.refunded&&!k.unavailableReason),tt=z.trim(),Ze=oc.test(tt)&&tt.length<=ri,D=async k=>{try{$(!0),U(null),l(null);let Ee=await g.setOrderFulfillment(r.id,{fulfilled:k,...k&&tt?{trackingNumber:tt}:{}});xe(Ee),L(""),l(k?"Marked as shipped.":"Marked as not shipped.")}catch(Ee){Ee instanceof Ht&&Ee.status===409?U(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):U(Ee instanceof Error?Ee.message:"Failed to update the order")}finally{$(!1)}},je=()=>{Re(null),ne(String(dt(E,r.currency))),ee([]),q(!1),Q(!0)},V=k=>ee(Ee=>Ee.includes(k)?Ee.filter(Vt=>Vt!==k):[...Ee,k]),Tt=async(k,Ee)=>{if(s)try{st(!0),Re(null),await s(r,k,Ee);let Vt=await g.getOrder(r.id);xe(Vt),Q(!1),l("Refund issued.")}catch(Vt){Re(Vt instanceof Error?Vt.message:"Refund failed")}finally{st(!1)}},bo=async()=>{if(Ut){if(ct<=0){Re("The lines you picked were charged nothing");return}if(ct>E){Re(`That selection exceeds the refundable remainder (${H(E,r.currency)})`);return}await Tt(ct,{...J.length>0?{line_items:[...J].sort((Ee,Vt)=>Ee-Vt)}:{},...de?{shipping:!0}:{}});return}let k=zt(oe,r.currency);if(k===null||k<=0){Re("Enter a valid refund amount");return}if(k>E){Re(`Amount exceeds the refundable remainder (${H(E,r.currency)})`);return}await Tt(k,{amount:k})},yo=()=>Tt(E,{full:!0}),Pr=!r.subscription_history_only&&r.fulfillment_type==="download",Cr=!r.subscription_history_only&&n&&Ra,ho=uc(r),xo=r.shipping_address?oi(r.shipping_address).join(`
|
|
4
|
+
`):"",Tr=r.shipping_total!=null,Un=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),kr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-Un):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,Er=Un>0,wo=kr>0,Ir=r.amount_subtotal!=null||Tr||Er||(r.discount_total??0)>0,Ts=[];return r.subscription_history_only||Ts.push(P(Xn,{icon:b?P(dn,{className:"af-h-4 af-w-4 af-animate-spin"}):P(si,{className:"af-h-4 af-w-4"}),disabled:b||r.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Pe()},children:"Resend receipt"},"resend")),Pr&&Ts.push(P(Xn,{icon:P(ac,{className:"af-h-4 af-w-4"}),disabled:N,onSelect:()=>{T(!1),c(!0)},children:"Reset download count"},"reset")),te&&Ts.push(K("div",{children:[P(Xn,{icon:P(ni,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{T(!1),je()},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")),K("div",{children:[K("div",{className:"af-mb-6",children:[K(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[P(Kl,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),K("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[K("div",{className:"af-min-w-0",children:[K("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[P("h3",{className:"af-text-xl af-font-semibold",children:Ga(r)}),P(ns,{status:r.status}),n&&!r.subscription_history_only&&P(ms,{order:r}),r.is_test&&P(Z,{variant:"outline",children:"Test"})]}),K("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Zn(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."})]}),K("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&K("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:!p,"aria-label":"Previous order",children:P(Jl,{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:!m,"aria-label":"Next order",children:P(Yl,{className:"af-h-4 af-w-4"})})]}),Cr&&(sa?K("div",{className:"af-flex af-items-center af-gap-1",children:[K("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${Zn(r.merchant_fulfilled_at)}`:""]}),Ua&&K(w,{variant:"ghost",size:"sm",onClick:()=>D(!1),disabled:R,children:[R?P(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(ni,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Ua?K("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[P(ge,{value:z,onChange:k=>L(k.target.value),placeholder:"Tracking number (optional)",maxLength:ri,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:R}),K(w,{variant:"default",className:"af-shrink-0",onClick:()=>D(!0),disabled:R||!Ze,children:[R?P(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(sc,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ts.length>0&&K(Xr,{open:y,onOpenChange:T,children:[P(ei,{asChild:!0,children:P(w,{variant:"outline",size:"icon","aria-label":"More actions",children:P(ec,{className:"af-h-4 af-w-4"})})}),P(Yn,{children:P("div",{className:"af-space-y-0.5",children:Ts})})]})]})]}),Cr&&!sa&&!Ze&&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."}),d&&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:d}),u&&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:u}),h&&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:h})]}),K("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[K("div",{className:"af-space-y-6",children:[r.line_items.length>0&&P(Ia,{title:"Items",children:P("ul",{className:"af-space-y-3",children:r.line_items.map((k,Ee)=>{let Vt=typeof k.name=="string"&&k.name?k.name:"Item",Ar=typeof k.quantity=="number"&&k.quantity>0?k.quantity:1,Dr=typeof k.unitAmount=="number";return K("li",{className:"af-flex af-items-start af-gap-3",children:[P(cc,{src:typeof k.imageUrl=="string"&&k.imageUrl?k.imageUrl:void 0}),K("div",{className:"af-min-w-0 af-flex-1",children:[K("div",{className:"af-text-sm af-font-medium",children:[Vt,typeof k.variantTitle=="string"&&k.variantTitle&&K("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",k.variantTitle]})]}),K("div",{className:is,children:[Ar," \xD7"," ",Dr?H(k.unitAmount,r.currency):"\u2014"]}),k.unavailableReason==="oversold"&&!k.refunded&&P(Z,{variant:"secondary",className:"af-mt-1",children:k.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),k.refunded===!0&&P(Z,{variant:"secondary",className:"af-mt-1",children:k.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),P("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof k.amountNet=="number"||Dr?H(k.amountNet??k.unitAmount*Ar,r.currency):"\u2014"})]},Ee)})})}),vt.length>0&&P(Ia,{title:"Order details",children:P("dl",{className:"af-space-y-2",children:vt.map(([k,Ee])=>K("div",{children:[P("dt",{className:W(is,"af-capitalize"),children:k.replace(/_/g," ")}),P("dd",{className:"af-text-sm af-break-words",children:ci(Ee)})]},k))})}),P(Ia,{title:"Totals",children:K("div",{className:"af-w-full",children:[Ir&&P(qt,{label:"Subtotal",children:H(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&K(qt,{label:"Discount",children:["\u2212",H(r.discount_total,r.currency)]}),Tr&&P(qt,{label:"Shipping",children:r.shipping_total===0?"Free":H(r.shipping_total??0,r.currency)}),Er&&P(qt,{label:"Tax",children:H(Un,r.currency)}),P(qt,{label:"Total",emphasis:!0,divider:Ir,children:H(ja(r),r.currency)}),(r.credit_applied??0)>0&&K(qt,{label:"Credit applied",children:["\u2212",H(r.credit_applied,r.currency)]}),r.amount_paid!=null&&P(qt,{label:"Amount paid",children:H(r.amount_paid,r.currency)}),wo&&P(qt,{label:"incl. tax",children:H(kr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&K(qt,{label:"Your price",children:[H(r.base_amount_total,r.base_currency),K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&K(dc,{children:[K(qt,{label:"Refunded",children:["\u2212",H(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",H(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),P(qt,{label:"Net",children:P("span",{className:"af-font-medium",children:H(Math.max(0,sn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&K(Ia,{title:"Platform fee",children:[r.application_fee_original!=null&&P(qt,{label:"Collected",children:H(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&P(qt,{label:"Returned",children:H(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&P(qt,{label:"Retained",children:H(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(Ia,{title:"Timeline",children:P("ol",{className:"af-space-y-3",children:ho.map(k=>K("li",{className:"af-flex af-gap-3",children:[P("span",{"aria-hidden":"true",className:W("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",k.tone==="destructive"?"af-bg-destructive":k.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),K("div",{className:"af-min-w-0",children:[P("div",{className:"af-text-sm af-break-words",children:k.text}),k.at&&P("div",{className:"af-text-xs af-text-muted-foreground",children:Zn(k.at)})]})]},k.key))})})]}),K("div",{className:"af-space-y-6",children:[P(Ia,{title:"Customer",children:K("div",{className:"af-space-y-2",children:[K("div",{children:[P("div",{className:is,children:"Email"}),K("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(tr,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&K("div",{children:[P("div",{className:is,children:"Name"}),P("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&K("div",{children:[P("div",{className:is,children:"Customer record"}),K("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(Z,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&P(Ia,{title:"Ship to",action:P(tr,{value:xo,label:"Copy address",size:"sm",children:"Copy address"}),children:P("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:oi(r.shipping_address).map((k,Ee)=>P("div",{children:k},Ee))})}),r.subscription_history_only?P(Ia,{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."})}):K(Ia,{title:"Emails",children:[P(Pa,{deliveries:r.email_deliveries?.filter(k=>!["purchase_receipt","merchant_sale"].includes(k.kind)),problemsOnly:!0,className:"af-mb-4"}),K("div",{className:"af-space-y-4",children:[P(ii,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(k=>k.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:K(w,{variant:"outline",size:"sm",onClick:Pe,disabled:b||r.fulfillment_status!=="fulfilled",children:[b?P(dn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(si,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),P(ii,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(k=>k.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),Pr&&P(Ia,{title:"Download",children:K("div",{className:"af-space-y-2",children:[K("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[P(Xl,{className:"af-h-4 af-w-4"}),K("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"})]})}),K("details",{className:"af-rounded-lg af-border af-p-4",children:[P("summary",{className:W(li,"af-cursor-pointer af-select-none"),children:"Technical details"}),K("div",{className:"af-mt-3 af-space-y-2",children:[P(Qn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&P(Qn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&P(Qn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),P(Ca,{open:O,onOpenChange:k=>{!k&&!N&&c(!1)},children:K(va,{children:[K(ba,{children:[P(ha,{children:"Reset download count?"}),P(xa,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),K(ya,{children:[P(w,{variant:"outline",onClick:()=>c(!1),disabled:N,children:"Cancel"}),P(w,{onClick:Ye,disabled:N,children:N?"Resetting...":"Reset"})]})]})}),P(Ca,{open:se,onOpenChange:k=>{!k&&!ve&&Q(!1)},children:K(va,{children:[K(ba,{children:[P(ha,{children:"Refund order"}),K(xa,{children:["Refund up to ",H(E,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),K("div",{className:"af-space-y-4",children:[(r.line_items.length>0||ue>0)&&K("div",{className:"af-space-y-2",children:[P(be,{children:"Items"}),K("div",{className:"af-space-y-2",children:[r.line_items.map((k,Ee)=>{let Vt=k.refunded===!0;return K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:J.includes(Ee),onChange:()=>V(Ee),disabled:ve||Vt||!!k.unavailableReason||A(k)<=0,className:"af-h-4 af-w-4"}),K("span",{className:Vt?"af-text-muted-foreground af-line-through":void 0,children:[typeof k.name=="string"&&k.name?k.name:"Item",typeof k.variantTitle=="string"&&k.variantTitle?` \u2014 ${k.variantTitle}`:"",typeof k.quantity=="number"&&k.quantity>1?` \xD7 ${k.quantity}`:""]}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:Vt?"Refunded":H(A(k),r.currency)})]},Ee)}),ue>0&&K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:de,onChange:k=>q(k.target.checked),disabled:ve,className:"af-h-4 af-w-4"}),P("span",{children:"Shipping"}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:H(ue,r.currency)})]})]})]}),K("div",{className:"af-space-y-2",children:[K(be,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),P(ge,{id:"refund-amount",type:"number",min:"0",step:ae,value:Ut?String(dt(ct,r.currency)):oe,onChange:k=>ne(k.target.value),disabled:ve||Ut}),Ut&&P("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),lt&&P("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:lt}),K(ya,{children:[P(w,{variant:"outline",onClick:()=>Q(!1),disabled:ve,children:"Cancel"}),P(w,{variant:"outline",onClick:yo,disabled:ve,children:"Refund everything"}),P(w,{variant:"destructive",onClick:bo,disabled:ve,children:ve?"Refunding...":$t!==null&&$t>0?`Refund ${H($t,r.currency)}`:"Refund"})]})]})})]})}import*as pn from"react";import{ArrowLeft as fc,RefreshCw as mc}from"lucide-react";import{jsx as Aa,jsxs as os}from"react/jsx-runtime";function Rt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=pn.useRef(null);return pn.useEffect(()=>{i.current?.focus()},[]),os("div",{className:W("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-justify-between af-gap-2 af-border-b af-bg-background af-px-4 af-py-2",children:[Aa("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&os(w,{type:"button",variant:"outline",size:"sm",onClick:a,children:[Aa(fc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Aa("div",{className:"af-p-4",children:t})]})}function X({className:e}){return Aa("div",{"aria-hidden":"true",className:W("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Qe({label:e,children:a,detail:s,valueClassName:t}){return os("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Aa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Aa("div",{className:W("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&Aa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function ea({message:e,onRetry:a}){return os("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Aa("span",{children:e}),os(w,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[Aa(mc,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Da({icon:e,children:a}){return os("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Aa("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}import{Fragment as xc,jsx as B,jsxs as ye}from"react/jsx-runtime";var hc={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},di={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 gn(e){return e.customer?.name||e.customer_name||null}function ps({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:p}=ie(),m=cn({refreshKey:s}),{orders:g,total:r,isLoading:v,error:h,page:f,pageSize:u,hasNextPage:l,hasPreviousPage:b,setPage:x,setPageSize:N,customerEmail:I,setCustomerEmail:O,setStatusIn:c,from:y,setFrom:T,to:z,setTo:L,showAbandoned:R,setShowAbandoned:$,setUnfulfilledOnly:d,refetch:U}=m,[se,Q]=wt.useState("list"),[oe,ne]=wt.useState(null),[J,ee]=wt.useState(""),[de,q]=wt.useState(""),[ve,st]=wt.useState(n?"needs_shipping":"all"),[lt,Re]=wt.useState(!1),[xe,vt]=wt.useState(!!t),[E,te]=wt.useState(null);wt.useEffect(()=>{if(!t)return;let V=!1;return vt(!0),te(null),p.getOrder(t).then(Tt=>{V||(ne(Tt),Q("detail"))}).catch(()=>{V||te("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{V||vt(!1)}),()=>{V=!0}},[p,t]);let S=wt.useCallback(V=>{st(V);let Tt=di[V];c(Tt.statusIn),d(Tt.unfulfilledOnly)},[c,d]);wt.useEffect(()=>{n&&d(!0)},[]);let A=wt.useRef(!n);wt.useEffect(()=>{A.current||v||(A.current=!0,g.length===0&&S("all"))},[v,g.length,S]);let ue=se==="detail"&&!!oe;wt.useEffect(()=>{o?.(ue)},[ue,o]);let Ve=(y?1:0)+(z?1:0)+(R?1:0),we=Ve>0||!!I||!!de,He=!!y&&!!z&&y>z,et=V=>{ne(V),Q("detail")},ct=()=>{Q("list"),ne(null),U()},Ut=V=>{let Tt=V.trim();if(!Tt){q(""),I&&O("");return}if(Tt.startsWith("#")||/^\d+$/.test(Tt)){q(Tt),I&&O("");return}q(""),O(Tt)},$t=()=>{ee(""),q(""),O(""),T(""),L(""),$(!1),Re(!1)},ae=de.replace(/^#/,"").toLowerCase(),Pe=ae?g.filter(V=>String(V.order_number??"")===ae||V.id.toLowerCase().startsWith(ae)):g,Ye=oe?g.findIndex(V=>V.id===oe.id):-1,Ra=Ye>0,sa=Ye>=0&&Ye<g.length-1;if(xe)return B("div",{className:a,children:B("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:B(gc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(se==="detail"&&oe)return B("div",{className:a,children:B(mn,{order:oe,onBack:ct,onRefund:e,onOrderUpdated:V=>ne(V),allowFulfillment:n,onPrevOrder:Ra?()=>ne(g[Ye-1]):void 0,onNextOrder:sa?()=>ne(g[Ye+1]):void 0,hasPrevOrder:Ra,hasNextOrder:sa},oe.id)});let tt=ye("div",{className:"af-mb-4 af-space-y-3",children:[E&&B("p",{className:"af-text-xs af-text-muted-foreground",children:E}),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":ve===V,onClick:()=>S(V),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",ve===V?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:hc[V]},V))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[B(bc,{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:J,onChange:V=>ee(V.target.value),onBlur:()=>Ut(J),onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),Ut(J))},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:Ve>0?"secondary":"ghost",size:"sm",onClick:()=>Re(V=>!V),"aria-expanded":lt,children:[B(yc,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ve>0&&B(Z,{variant:"secondary",className:"af-ml-2",children:Ve})]}),we&&B(w,{type:"button",variant:"ghost",size:"sm",onClick:$t,children:"Clear filters"})]}),(lt||!!y||!!z)&&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(be,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),B(ge,{id:"orders-from",type:"date",value:y,max:z||void 0,onChange:V=>T(V.target.value),className:"af-w-[170px]"}),B(be,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),B(ge,{id:"orders-to",type:"date",value:z,min:y||void 0,onChange:V=>L(V.target.value),className:"af-w-[170px]"}),!di[ve].statusIn&&B(w,{type:"button",variant:R?"secondary":"ghost",size:"sm",onClick:()=>$(!R),"aria-pressed":R,children:R?"Hide abandoned":"Show abandoned"})]}),He&&B("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(v)return ye("div",{className:a,children:[tt,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(X,{className:"af-h-4 af-w-16"}),B(X,{className:"af-h-4 af-w-14"})]}),B(X,{className:"af-mt-2 af-h-3 af-w-40"}),B(X,{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(Oe,{children:[B(Be,{children:ye(pe,{children:[B(F,{children:"Order"}),B(F,{children:"Date"}),B(F,{children:"Customer"}),B(F,{children:"Items"}),B(F,{className:"af-text-right",children:"Total"}),B(F,{children:"Status"}),B(F,{className:"af-w-8"})]})}),B(Fe,{"aria-hidden":"true",children:[0,1,2,3,4].map(V=>ye(pe,{children:[B(M,{children:B(X,{className:"af-h-4 af-w-14"})}),B(M,{children:B(X,{className:"af-h-4 af-w-24"})}),B(M,{children:B(X,{className:"af-h-4 af-w-40"})}),B(M,{children:B(X,{className:"af-h-4 af-w-32"})}),B(M,{children:B(X,{className:"af-ml-auto af-h-4 af-w-16"})}),B(M,{children:B(X,{className:"af-h-5 af-w-16"})}),B(M,{})]},V))})]})}),B("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(h)return ye("div",{className:a,children:[tt,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:()=>U(),children:"Try again"})]})]});let Ze=ve!=="all";if(Pe.length===0&&f===0)return ye("div",{className:a,children:[(we||Ze)&&tt,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[B(vc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),B("p",{className:"af-text-muted-foreground af-text-center",children:we||Ze?"No orders match these filters.":i??ye(xc,{children:["No orders yet.",B("br",{}),"Orders will appear here when someone buys from your website."]})}),!we&&!Ze&&B(w,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>$(!0),children:"Show abandoned checkouts"})]})]});let D=f*u+1,je=Math.min((f+1)*u,r);return ye("div",{className:a,children:[tt,B("div",{className:"af-space-y-3 lg:af-hidden",children:Pe.map(V=>ye("button",{type:"button",onClick:()=>et(V),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left 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:Ga(V)}),B("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:H(ja(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"}),gn(V)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",gn(V)]})]}),B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:mi(V)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(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(ns,{status:V.status}),B(Is,{deliveries:V.email_deliveries}),V.is_test&&B(Z,{variant:"outline",children:"Test"}),n&&B(ms,{order:V}),B("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:fi(V.created_at)})]})]},V.id))}),B("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Oe,{children:[B(Be,{children:ye(pe,{children:[B(F,{children:"Order"}),B(F,{children:"Date"}),B(F,{children:"Customer"}),B(F,{children:"Items"}),B(F,{className:"af-text-right",children:"Total"}),B(F,{children:"Status"}),B(F,{className:"af-w-8"})]})}),B(Fe,{children:Pe.map(V=>ye(pe,{onClick:()=>et(V),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[ye(M,{className:"af-whitespace-nowrap af-font-medium",children:[B("button",{type:"button",onClick:Tt=>{Tt.stopPropagation(),et(V)},"aria-label":`Open order ${Ga(V)}`,className:"af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ga(V)}),V.is_test&&B(Z,{variant:"outline",className:"af-ml-2",children:"Test"})]}),B(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:fi(V.created_at)}),ye(M,{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"})}),gn(V)&&B("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:gn(V)})]}),B(M,{className:"af-max-w-[220px]",children:B("div",{className:"af-truncate af-text-muted-foreground",children:mi(V)})}),ye(M,{className:"af-whitespace-nowrap af-text-right",children:[B("div",{className:"af-font-medium af-tabular-nums",children:H(ja(V),V.currency)}),V.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(V.amount_refunded,V.currency)," ","refunded"]})]}),B(M,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[B(ns,{status:V.status}),B(Is,{deliveries:V.email_deliveries}),n&&B(ms,{order:V})]})}),B(M,{className:"af-w-8 af-text-right",children:B(ui,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},V.id))})]})}),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:ae?`${Pe.length} matching this page`:`Showing ${D}-${je} of ${r}`}),ye(na,{value:String(u),onValueChange:V=>N(Number(V)),children:[B(Yt,{className:"af-w-[70px] af-h-8",children:B(ra,{})}),ye(Zt,{children:[B(ze,{value:"10",children:"10"}),B(ze,{value:"25",children:"25"}),B(ze,{value:"50",children:"50"}),B(ze,{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:()=>x(f-1),disabled:!b,children:[B(pc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ye(w,{variant:"outline",size:"sm",onClick:()=>x(f+1),disabled:!l,children:["Next",B(ui,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as yn from"react";import{ChevronLeft as _c,ChevronRight as Rc,Eye as Pc,Search as Cc,Users as Tc}from"lucide-react";import*as jt from"react";function vn({initialPageSize:e=25}={}){let{api:a}=ie(),[s,t]=jt.useState([]),[n,i]=jt.useState(0),[o,p]=jt.useState(!0),[m,g]=jt.useState(null),[r,v]=jt.useState(0),[h,f]=jt.useState(e),[u,l]=jt.useState(""),b=jt.useRef(0),x=jt.useCallback(async()=>{let I=++b.current;try{p(!0),g(null);let O={limit:h,offset:r*h};u.trim()&&(O.email=u.trim());let c=await a.getCustomers(O);if(I!==b.current)return;t(c.customers),i(c.total)}catch(O){if(I!==b.current)return;g(O instanceof Error?O:new Error("Failed to fetch customers"))}finally{I===b.current&&p(!1)}},[a,r,h,u]);jt.useEffect(()=>{x()},[x]);let N=Math.ceil(n/h);return{customers:s,total:n,isLoading:o,error:m,page:r,pageSize:h,hasNextPage:r<N-1,hasPreviousPage:r>0,setPage:v,setPageSize:I=>{f(I),v(0)},email:u,setEmail:I=>{l(I),v(0)},refetch:x}}import*as ls from"react";import{ArrowLeft as wc,Loader2 as Nc}from"lucide-react";import{jsx as Ae,jsxs as Pt}from"react/jsx-runtime";function pi(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 Sc(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 bn({customer:e,onBack:a,className:s}){let{api:t}=ie(),[n,i]=ls.useState(null),[o,p]=ls.useState([]),[m,g]=ls.useState(!0),[r,v]=ls.useState(null);ls.useEffect(()=>{let u=!1;return g(!0),v(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,b])=>{u||(i(l),p(b.orders))}).catch(l=>{u||v(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{u||g(!1)}),()=>{u=!0}},[t,e.id,e.email]);let h=n?.addresses??[],f=n?.order_count??o.length;return Pt("div",{className:s,children:[Pt("div",{className:"af-mb-6",children:[Pt(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[Ae(wc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Ae("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Pt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",pi(e.created_at)]})]}),m?Ae("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ae(Nc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?Ae("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):Pt("div",{className:"af-space-y-6",children:[Ae(Pa,{deliveries:n?.email_deliveries}),Pt("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Pt("div",{className:"af-space-y-1 af-text-sm",children:[Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Ae("span",{children:e.email})]}),e.name&&Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Ae("span",{children:e.name})]}),e.phone&&Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Ae("span",{children:e.phone})]}),Pt("div",{className:"af-flex af-gap-2",children:[Ae("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Ae("span",{children:f})]})]})]}),h.length>0&&Pt("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Ae("div",{className:"af-flex af-flex-wrap af-gap-3",children:h.map(u=>Pt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&Ae(Z,{variant:"secondary",className:"af-mb-1",children:"Default"}),Sc(u).map((l,b)=>Ae("div",{children:l},b))]},u.id))})]}),Pt("div",{children:[Ae("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Ae("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Pt(Oe,{children:[Ae(Be,{children:Pt(pe,{children:[Ae(F,{children:"Date"}),Ae(F,{children:"Amount"}),Ae(F,{children:"Status"})]})}),Ae(Fe,{children:o.map(u=>Pt(pe,{children:[Ae(M,{className:"af-text-muted-foreground",children:pi(u.created_at)}),Ae(M,{children:H(ja(u),u.currency)}),Ae(M,{children:Ae(rs,{status:u.status})})]},u.id))})]})]})]})]})}import{Fragment as Ec,jsx as Ce,jsxs as mt}from"react/jsx-runtime";function kc(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 hn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:p,hasPreviousPage:m,setPage:g,setPageSize:r,email:v,setEmail:h,refetch:f}=vn(),[u,l]=yn.useState("list"),[b,x]=yn.useState(null),[N,I]=yn.useState(""),O=L=>{x(L),l("detail")},c=()=>{l("list"),x(null),f()};if(u==="detail"&&b)return Ce("div",{className:e,children:Ce(bn,{customer:b,onBack:c})});let y=mt("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Ce(ge,{type:"email",value:N,onChange:L=>I(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),h(N.trim()))}}),mt(w,{type:"button",variant:"outline",size:"sm",onClick:()=>h(N.trim()),children:[Ce(Cc,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),v&&Ce(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{I(""),h("")},children:"Clear"})]});if(t)return mt("div",{className:e,children:[y,Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ce("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return mt("div",{className:e,children:[y,Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:mt("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return mt("div",{className:e,children:[v&&y,mt("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Ce(Tc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ce("p",{className:"af-text-muted-foreground af-text-center",children:v?"No customers match that email.":mt(Ec,{children:["No customers yet.",Ce("br",{}),"Customers appear here after their first purchase."]})})]})]});let T=i*o+1,z=Math.min((i+1)*o,s);return mt("div",{className:e,children:[y,mt(Oe,{children:[Ce(Be,{children:mt(pe,{children:[Ce(F,{children:"Email"}),Ce(F,{children:"Name"}),Ce(F,{children:"Customer since"}),Ce(F,{className:"af-text-right",children:"Actions"})]})}),Ce(Fe,{children:a.map(L=>mt(pe,{children:[Ce(M,{className:"af-font-medium",children:L.email}),Ce(M,{children:L.name||Ce("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Ce(M,{className:"af-text-muted-foreground",children:kc(L.created_at)}),Ce(M,{className:"af-text-right",children:Ce(w,{variant:"ghost",size:"icon",onClick:()=>O(L),title:"View customer",children:Ce(Pc,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),mt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[mt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[mt("span",{children:["Showing ",T,"-",z," of ",s]}),mt(na,{value:String(o),onValueChange:L=>r(Number(L)),children:[Ce(Yt,{className:"af-w-[70px] af-h-8",children:Ce(ra,{})}),mt(Zt,{children:[Ce(ze,{value:"10",children:"10"}),Ce(ze,{value:"25",children:"25"}),Ce(ze,{value:"50",children:"50"}),Ce(ze,{value:"100",children:"100"})]})]}),Ce("span",{children:"per page"})]}),mt("div",{className:"af-flex af-items-center af-gap-2",children:[mt(w,{variant:"outline",size:"sm",onClick:()=>g(i-1),disabled:!m,children:[Ce(_c,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),mt(w,{variant:"outline",size:"sm",onClick:()=>g(i+1),disabled:!p,children:["Next",Ce(Rc,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Se from"react";import{ArrowLeft as Ic,ChevronLeft as Ac,ChevronRight as gi,Copy as Dc,Download as Lc,ExternalLink as Oc,FileText as yi,Loader2 as Bc,Search as Fc}from"lucide-react";import*as pt from"react";function gs({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=ie(),[n,i]=pt.useState([]),[o,p]=pt.useState(0),[m,g]=pt.useState(null),[r,v]=pt.useState(!0),[h,f]=pt.useState(null),[u,l]=pt.useState(0),[b,x]=pt.useState(e),[N,I]=pt.useState(void 0),[O,c]=pt.useState(""),[y,T]=pt.useState(""),[z,L]=pt.useState(""),[R,$]=pt.useState(""),[d,U]=pt.useState(""),se=N?N.join(","):"",Q=pt.useRef(0),oe=pt.useCallback(async()=>{let J=++Q.current;v(!0),f(null);try{let ee={labels:se?se.split(","):void 0,customerEmail:O||void 0,q:y||void 0,from:z||void 0,to:R||void 0,retainerId:d||void 0,includeAggregates:s,limit:b,offset:u*b},de=await t.getInvoices(ee);if(J!==Q.current)return;if(u>0&&u*b>=de.total){l(Math.max(0,Math.ceil(de.total/b)-1));return}i(de.invoices),p(de.total),s&&g(de.aggregates??null)}catch(ee){if(J!==Q.current)return;f(ee instanceof Error?ee:new Error("Failed to fetch invoices"))}finally{J===Q.current&&v(!1)}},[t,se,O,y,z,R,d,u,b,s]);pt.useEffect(()=>{oe()},[oe,a]);let ne=J=>ee=>{l(0),J(ee)};return{invoices:n,total:o,aggregates:m,isLoading:r,error:h,page:u,pageSize:b,hasNextPage:(u+1)*b<o,hasPreviousPage:u>0,setPage:l,setPageSize:ne(x),labels:N,setLabels:ne(I),customerEmail:O,setCustomerEmail:ne(c),q:y,setQ:ne(T),from:z,setFrom:ne(L),to:R,setTo:ne($),retainerId:d,setRetainerId:ne(U),clearFilters:()=>{l(0),I(void 0),c(""),T(""),L(""),$(""),U("")},refetch:oe}}import{Fragment as qc,jsx as C,jsxs as G}from"react/jsx-runtime";var Mc={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 ir(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Mc[e.label]??e.label}function Uc(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 rr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},$c={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Bs({invoice:e,className:a}){return G("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[C(Z,{variant:Uc(e.label),className:a,children:ir(e)}),e.collection_method==="charge_automatically"&&C(Z,{variant:"secondary",children:"Managed in Stripe"})]})}function wn({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(Z,{variant:s,className:a,children:rr[e.state]??e.state})}function vs(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function da(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 vi={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},ar={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 Vc(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 sr=100,nr=5e3;async function Hc(e,a){let s=[],t=0;for(let n=0;n<nr;n+=sr){let i=await e.getInvoices({...a,limit:sr,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<sr||s.length>=t)break}return{invoices:s.slice(0,nr),total:t,truncated:t>s.length||t>nr}}function hi(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,vs(t),ir(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),H(t.amount_subtotal,t.currency),H(t.tax_total,t.currency),H(t.amount_total,t.currency),t.amount_due===null?"":H(t.amount_due,t.currency),t.amount_paid===null?"":H(t.amount_paid,t.currency),H(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?"":H(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(Vc).join(",")).join(`
|
|
5
|
+
`)}function zc(e){if(typeof document>"u")return;let a=new Blob([hi(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 bs({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:p=null,onClearRetainerFilter:m}){let{api:g}=ie(),{invoices:r,total:v,isLoading:h,error:f,page:u,pageSize:l,hasNextPage:b,hasPreviousPage:x,setPage:N,labels:I,setLabels:O,customerEmail:c,setCustomerEmail:y,q:T,setQ:z,from:L,setFrom:R,to:$,setTo:d,retainerId:U,setRetainerId:se,refetch:Q}=gs({refreshKey:a}),[oe,ne]=Se.useState("open"),[J,ee]=Se.useState(""),[de,q]=Se.useState(null),ve=Se.useRef(0),st=Se.useCallback(D=>{ve.current++,Re(!1),q(D)},[]),[lt,Re]=Se.useState(!1),[xe,vt]=Se.useState(0),[E,te]=Se.useState(null),[S,A]=Se.useState(!1),[ue,Ve]=Se.useState(0);Se.useEffect(()=>{q(D=>{if(!D)return D;let je=r.find(V=>V.id===D.id);return je&&je!==D?je:D})},[r]);let[we,He]=Se.useState(!1),[et,ct]=Se.useState(null),Ut=async()=>{if(!we){He(!0),ct(null);try{let{invoices:D,total:je,truncated:V}=await Hc(g,{labels:I,customerEmail:c,q:T,from:L,to:$,retainerId:U});zc(D),ct(V?`Exported the first ${D.length.toLocaleString()} of ${je.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{ct("Couldn't export \u2014 try again.")}finally{He(!1)}}},$t=!c&&!T&&!L&&!$&&!U,[ae,Pe]=Se.useState(null);Se.useEffect(()=>{if(h||v>0||!$t||oe!=="open")return;let D=!1;return g.getInvoices({limit:1}).then(je=>{D||Pe(je.total>0)}).catch(()=>{D||Pe(!0)}),()=>{D=!0}},[g,h,v,$t,oe,a]),Se.useEffect(()=>{O(ar.open)},[]),Se.useEffect(()=>{let D=p?.id??"";D!==U&&(se(D),D&&(ne("all"),O(ar.all),y(""),z(""),ee(""),R(""),d("")))},[p?.id]),Se.useEffect(()=>{let D=!1;return A(!1),g.getInvoiceSettings().then(je=>{D||te({payments_active:je.payments_active,blocked:je.blocked})}).catch(()=>{D||A(!0)}),()=>{D=!0}},[g,a,ue]),Se.useEffect(()=>{if(!s)return;let D=!1,je=ve.current;return Re(!1),g.getInvoice(s).then(V=>{!D&&je===ve.current&&q(V)}).catch(()=>{!D&&je===ve.current&&Re(!0)}),()=>{D=!0}},[g,s,xe]),Se.useEffect(()=>{t?.(de!==null)},[de,t]);let Ye=D=>{ne(D),O(ar[D])},Ra=D=>{let je=D.trim();if(!je){T&&z(""),c&&y("");return}if(je.includes("@")){T&&z(""),y(je);return}c&&y(""),z(je.replace(/^#/,""))},sa=r,Ua=lt&&G("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:()=>vt(D=>D+1),children:"Retry opening invoice"})]});if(de)return G("div",{className:e,children:[Ua,C(or,{invoice:de,refreshKey:a,onBack:()=>{st(null),Q()}},de.id)]});let tt=G("div",{className:"af-mb-4 af-space-y-3",children:[S&&G("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:()=>Ve(D=>D+1),children:"Retry setup check"})]}),Ua,E?.blocked&&G("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."]}),p&&G("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[G(Z,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",p.label]}),m&&C(w,{type:"button",variant:"link",size:"sm",onClick:m,children:"Clear schedule filter"})]}),G("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(vi).map(D=>C("button",{type:"button","aria-pressed":oe===D,onClick:()=>Ye(D),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",oe===D?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:vi[D]},D))}),G("div",{className:"af-relative af-w-full af-max-w-xs",children:[C(Fc,{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:J,onChange:D=>ee(D.target.value),onBlur:()=>Ra(J),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),Ra(J))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),G("div",{className:"af-flex af-items-center af-gap-2",children:[C(be,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),C(ge,{id:"invoices-from",type:"date",value:L,max:$||void 0,onChange:D=>R(D.target.value),className:"af-invoice-date af-w-[150px]"})]}),G("div",{className:"af-flex af-items-center af-gap-2",children:[C(be,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),C(ge,{id:"invoices-to",type:"date",value:$,min:L||void 0,onChange:D=>d(D.target.value),className:"af-invoice-date af-w-[150px]"})]}),G(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Ut(),disabled:we||h||!!f||v===0,"aria-busy":we,children:[C(Lc,{className:"af-h-4 af-w-4 af-mr-1"}),we?"Exporting\u2026":"Export CSV (all matching)"]})]}),et&&C("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:et})]});return h?G("div",{className:e,children:[tt,C("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(D=>G("div",{className:"af-rounded-md af-border af-p-3",children:[G("div",{className:"af-flex af-items-center af-justify-between",children:[C(X,{className:"af-h-4 af-w-20"}),C(X,{className:"af-h-4 af-w-16"})]}),C(X,{className:"af-mt-2 af-h-3 af-w-40"})]},D))})]}):f?G("div",{className:e,children:[tt,G("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 Q(),children:"Retry"})]})]}):v===0&&$t&&ae===!1&&oe==="open"?E?.blocked?G("div",{className:e,children:[tt,C(xn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?G("div",{className:e,children:[tt,C(xn,{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?G("div",{className:e,children:[tt,C(xn,{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})]}):G("div",{className:e,children:[tt,C(xn,{heading:"No invoices yet",body:!E||S?"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."})]}):G("div",{className:e,children:[tt,sa.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."}):G(qc,{children:[C("div",{className:"af-space-y-3 lg:af-hidden",children:sa.map(D=>G("button",{type:"button",onClick:()=>st(D),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[G("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[C("span",{className:"af-font-medium",children:vs(D)}),C(Bs,{invoice:D})]}),C("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:D.customer_name??D.customer_email??"\u2014"}),D.delivery&&C("div",{className:"af-mt-1",children:C(wn,{delivery:D.delivery})}),G("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:D.collection_method==="charge_automatically"?"Automatic collection":D.due_at?`Due ${da(D.due_at)}`:"Due on receipt"}),C("span",{className:"af-font-medium af-tabular-nums",children:H(D.amount_due??D.amount_total,D.currency)})]})]},D.id))}),C("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:G(Oe,{children:[C(Be,{children:G(pe,{children:[C(F,{children:"Invoice"}),C(F,{children:"Created"}),C(F,{children:"Customer"}),C(F,{children:"Due"}),C(F,{className:"af-text-right",children:"Amount"}),C(F,{children:"Status"}),C(F,{children:"Delivery"}),C(F,{className:"af-w-8"})]})}),C(Fe,{children:sa.map(D=>G(pe,{className:"af-cursor-pointer",onClick:()=>st(D),children:[C(M,{className:"af-font-medium",children:C("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:je=>{je.stopPropagation(),st(D)},"aria-label":`Open invoice ${vs(D)}`,children:vs(D)})}),C(M,{children:da(D.created_at)}),G(M,{children:[C("div",{children:D.customer_name??"\u2014"}),C("div",{className:"af-text-xs af-text-muted-foreground",children:D.customer_email})]}),C(M,{children:D.collection_method==="charge_automatically"?"Automatic":D.due_at?da(D.due_at):"On receipt"}),C(M,{className:"af-text-right af-tabular-nums",children:H(D.amount_due??D.amount_total,D.currency)}),C(M,{children:C(Bs,{invoice:D})}),C(M,{children:C(wn,{delivery:D.delivery})}),C(M,{children:C(gi,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},D.id))})]})}),G("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[G("span",{children:[v," invoice",v===1?"":"s"]}),G("div",{className:"af-flex af-items-center af-gap-1",children:[C(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>N(u-1),disabled:!x,"aria-label":"Previous page",children:C(Ac,{className:"af-h-4 af-w-4"})}),G("span",{className:"af-tabular-nums",children:[u*l+1,"\u2013",Math.min((u+1)*l,v)]}),C(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>N(u+1),disabled:!b,"aria-label":"Next page",children:C(gi,{className:"af-h-4 af-w-4"})})]})]})]})]})}function xn({heading:e,body:a,action:s}){return G("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[C(yi,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),C("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),C("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&C(w,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var Wa="af-text-xs af-text-muted-foreground";function bi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function or({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=ie(),i=Se.useRef(null);Se.useEffect(()=>{i.current?.focus()},[e.id]);let[o,p]=Se.useState(!1),[m,g]=Se.useState(null),[r,v]=Se.useState(!1),[h,f]=Se.useState(!1),u=Se.useRef(0),[l,b]=Se.useState(null),[x,N]=Se.useState(!1),[I,O]=Se.useState(0);Se.useEffect(()=>{let d=!1;return N(!1),n.getInvoice(e.id).then(U=>{d||b({source:e,value:U})}).catch(()=>{d||N(!0)}),()=>{d=!0}},[n,e,s,I]);let c=l?.source===e?l.value:e,y=c.collection_method==="charge_automatically";Se.useEffect(()=>(u.current++,g(null),v(!1),f(!1),p(!1),()=>{u.current++}),[n,c,s]);let T=d=>d==null?"\u2014":H(d,c.currency),z=async()=>{if(!(!c.pay_url||!bi()))try{await navigator.clipboard.writeText(c.pay_url),p(!0),setTimeout(()=>p(!1),1500)}catch{}},L=async()=>{if(m){g(null);return}let d=++u.current;f(!1),v(!0);try{let U=await n.getInvoicePreview(c.id);d===u.current&&g(U)}catch{d===u.current&&f(!0)}finally{d===u.current&&v(!1)}},R=c.bill_to,$=R?[R.company,R.name,R.address?.line1,R.address?.line2,[R.address?.city,R.address?.state,R.address?.postal_code].filter(Boolean).join(", "),R.address?.country,R.tax_id?`${R.tax_id.value}`:null,R.po_number?`PO ${R.po_number}`:null,R.service_period?`Service period: ${R.service_period}`:null].filter(d=>!!d&&d.length>0):[];return G("div",{className:t,children:[G("div",{className:"af-mb-4",children:[G(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[C(Ic,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),G("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[G("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",vs(c)]}),C(Bs,{invoice:c}),C(wn,{delivery:c.delivery})]}),G("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),x&&G("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(d=>d+1),children:"Retry details"})]}),c.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."}),c.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."}),G("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[G("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[G("section",{className:"af-rounded-md af-border af-p-4",children:[G(Oe,{children:[C(Be,{children:G(pe,{children:[C(F,{children:"Description"}),C(F,{className:"af-text-right",children:"Qty"}),C(F,{className:"af-text-right",children:"Amount"})]})}),C(Fe,{children:c.line_items.map((d,U)=>G(pe,{children:[C(M,{style:{overflowWrap:"anywhere"},children:d.description}),C(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:d.quantity}),C(M,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(d.amount)})]},U))})]}),G("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[C(Qa,{label:"Subtotal",value:T(c.amount_subtotal)}),(c.discount_total??0)>0&&C(Qa,{label:"Discount",value:`-${T(c.discount_total)}`}),c.tax_total>0&&C(Qa,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(c.tax_total)}),C(Qa,{label:"Total",value:T(c.amount_total),strong:!0}),c.credit_applied>0&&C(Qa,{label:"Credit applied",value:`-${T(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&C(Qa,{label:"Amount due",value:T(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&C(Qa,{label:"Amount paid",value:T(c.amount_paid)}),c.amount_refunded>0&&C(Qa,{label:"Refunded",value:T(c.amount_refunded)})]}),c.credit_notes?.length>0&&G("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[C("div",{className:Wa,children:"Credit notes"}),c.credit_notes.map(d=>G("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[G("span",{className:"af-text-muted-foreground",children:[da(d.created_at)," \xB7 ",d.origin==="dashboard"?"issued in Stripe":"refund",d.stripe_credit_note_id?"":" \xB7 being created"]}),G("span",{className:"af-tabular-nums",children:["-",H(d.amount,d.currency)]})]},d.id))]})]}),(c.note||c.footer)&&G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&G("div",{children:[C("div",{className:Wa,children:"Note"}),C("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&G("div",{children:[C("div",{className:Wa,children:"Footer"}),C("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),m&&!y&&G("section",{className:"af-rounded-md af-border af-p-4",children:[G("div",{className:W(Wa,"af-break-words"),children:["Email preview \u2014 ",m.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:m.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),G("div",{className:"af-min-w-0 af-space-y-4",children:[G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C(ua,{label:"Created",value:da(c.created_at)}),C(ua,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?da(c.due_at):"On receipt"}),c.paid_at&&C(ua,{label:"Paid",value:da(c.paid_at)}),c.payment_method&&C(ua,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&C(ua,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&C(ua,{label:"Delivery",value:`${rr[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&C(ua,{label:"Written off",value:da(c.marked_uncollectible_at)}),c.correction_reason&&C(ua,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&C(ua,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?C(ua,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&C(ua,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&C(ua,{label:"Replaces",value:c.replaces_order_id})]}),G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C("div",{className:Wa,children:"Reminders"}),y?C("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?C("div",{children:"Off for this invoice."}):c.reminders.paused_until?G("div",{children:["Paused until ",da(c.reminders.paused_until),"."]}):c.reminders.next_at?G("div",{children:["Next on ",da(c.reminders.next_at),"."]}):c.reminders.final_sent_at?G("div",{children:["Final reminder sent ",da(c.reminders.final_sent_at),"."]}):C("div",{children:"None scheduled."}),!y&&G("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(d=>d<0?`${-d}d before`:d===0?"due day":`${d}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[C("div",{className:Wa,children:"Email delivery history"}),c.communications.map(d=>G("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[G("span",{className:"af-min-w-0 af-break-words",children:[$c[d.kind]??d.kind,d.kind==="reminder"&&d.slot!==null?` #${d.slot}`:"",G("span",{className:"af-text-muted-foreground",children:[" \xB7 ",d.recipient]})]}),G("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[rr[d.state]??d.state," \xB7 ",da(d.state_at??d.created_at)]})]},d.id))]}),$.length>0&&G("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[C("div",{className:Wa,children:"Bill to"}),$.map((d,U)=>C("div",{className:"af-break-words",children:d},U))]}),G("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&G(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void z(),disabled:!bi(),children:[C(Dc,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":y?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&C(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:G("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[C(Oc,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!y&&G(w,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void L(),disabled:r,children:[r?C(Bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):C(yi,{className:"af-h-4 af-w-4 af-mr-1"}),m?"Hide email preview":h?"Retry email preview":"Show email preview"]}),h&&!y&&C("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&C("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),C("p",{className:"af-text-xs af-text-muted-foreground",children:y?"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 ua({label:e,value:a}){return G("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[C("span",{className:W(Wa,"af-shrink-0"),children:e}),C("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function Qa({label:e,value:a,strong:s}){return G("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[C("dt",{className:W(Wa,s&&"af-font-medium af-text-foreground"),children:e}),C("dd",{className:W("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as jc}from"lucide-react";import{jsx as gt,jsxs as Na}from"react/jsx-runtime";var Gc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},xi={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Wc(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 wi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>xi[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>xi[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Gc[e.status]}function Ni(e){let a=e.interval==="year"?"every year":"every month";return`${H(e.amount,e.currency)} ${a}`}function Kc(e){return e.status==="canceled"?`Ended ${Nn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Nn(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 ${Nn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Nn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Nn(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 lr({retainer:e,className:a}){return gt(Z,{variant:Wc(e.status),className:W("af-max-w-full af-whitespace-normal af-break-words",a),children:wi(e)})}function ys({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:p=0,isLoadingMore:m=!1,onLoadMore:g,includeEnded:r=!1,onIncludeEndedChange:v,className:h}){let f=!!v;if(!a&&!s&&e.length===0&&!(f&&(r||p>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return Na("section",{className:W("af-mb-6",h),"aria-label":"Recurring invoices",children:[Na("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[gt(jc,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),gt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),gt("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."}),f&>(w,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>v?.(!r),children:r?"Hide ended recurring invoices":p>0&&e.length===0?`Show ended recurring invoices (${p})`:"Show ended recurring invoices"})]}),s?Na("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",gt(w,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?gt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>Na("div",{className:"af-rounded-md af-border af-p-3",children:[gt(X,{className:"af-h-4 af-w-48"}),gt(X,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?gt("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."}):gt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let b=i===l.id;return Na("li",{className:W("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[Na("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[Na("div",{className:"af-min-w-0",children:[gt("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),gt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),gt(lr,{retainer:l})]}),l.collection_method==="charge_automatically"?Na("div",{className:"af-mt-2 af-space-y-1",children:[gt(Z,{variant:"secondary",children:"Managed in Stripe"}),gt("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."})]}):gt("div",{className:"af-mt-2 af-text-sm",children:Ni(l)}),Na("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:[Na("span",{children:[Kc(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&>(w,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&Na("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!a&&!s&&u>0&&g&>("div",{className:"af-mt-2",children:gt(w,{type:"button",variant:"outline",size:"sm",onClick:g,disabled:m,children:m?"Loading\u2026":`Load more (${u} more)`})})]})}import*as _i from"react";import{AlertTriangle as Si,CheckCircle2 as Jc,CreditCard as cr,Loader2 as Yc,RefreshCw as Zc}from"lucide-react";import{jsx as Xe,jsxs as Nt}from"react/jsx-runtime";function Sn({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=Za(),[p,m]=_i.useState(!1),g=async()=>{m(!0);try{await o()}finally{m(!1)}};return n&&!t?Xe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Xe("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?Xe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Nt("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?Xe("div",{className:s,children:Nt("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:[Xe(Jc,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),Nt("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."]})]})]})}):Nt("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&Nt("div",{className:"af-space-y-3",children:[Nt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Xe(cr,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Xe("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?Nt(w,{onClick:e,children:[Xe(cr,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):Xe("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"&&Nt("div",{className:"af-space-y-3",children:[Nt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Xe(Si,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Xe("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?Xe(w,{onClick:a,children:"Upgrade plan"}):Xe("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&Nt("div",{className:"af-space-y-3",children:[Nt("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:[Xe(Si,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),Nt("div",{children:[Xe("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?Xe("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."}):Xe("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."})]})]}),Nt("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&Nt(w,{onClick:e,children:[Xe(cr,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),Nt(w,{variant:"outline",onClick:g,disabled:p,children:[p?Xe(Yc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Xe(Zc,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as At from"react";function ur(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function hs({includeStats:e=!1,refreshKey:a}={}){let{api:s}=ie(),[t,n]=At.useState([]),[i,o]=At.useState(!0),[p,m]=At.useState(null),g=At.useRef(0),r=At.useCallback(async()=>{let b=++g.current;try{o(!0),m(null);let x=await s.getProducts(e?{include:"stats"}:{});if(b!==g.current)return;n(x)}catch(x){if(b!==g.current)return;m(x instanceof Error?x:new Error("Failed to fetch products"))}finally{b===g.current&&o(!1)}},[s,e,a]);At.useEffect(()=>{r()},[r]);let v=At.useCallback(async b=>{let x=await s.createProduct(b);return n(N=>[x,...N]),x},[s]),h=At.useCallback(async(b,x)=>{let N=await s.updateProduct(b,x);return n(I=>ur(I,b,N)),N},[s]),f=At.useCallback(async b=>{await s.deleteProduct(b),n(x=>x.filter(N=>N.id!==b))},[s]),u=At.useCallback(async(b,x)=>{let N=await s.attachProductFile(b,x);return n(I=>ur(I,b,N)),N},[s]),l=At.useCallback(async(b,x)=>{let N=await s.attachProductFileFromUrl(b,x);return n(I=>ur(I,b,N)),N},[s]);return{products:t,isLoading:i,error:p,refetch:r,createProduct:v,updateProduct:h,deleteProduct:f,attachProductFile:u,attachProductFileFromUrl:l}}import*as Dt from"react";var Ri=["creating","active","paused","canceling"],Qc=["canceled","failed"];function xs({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=ie(),[n,i]=Dt.useState([]),[o,p]=Dt.useState(0),[m,g]=Dt.useState(0),[r,v]=Dt.useState(!0),[h,f]=Dt.useState(!1),[u,l]=Dt.useState(null),[b,x]=Dt.useState(a),N=Dt.useRef(0),I=Dt.useCallback(async()=>{let c=++N.current;v(!0),f(!1),l(null);try{let y=await t.getRetainers({statuses:b?void 0:Ri,limit:s,offset:0});if(c!==N.current)return;if(i(y.retainers),p(y.total),!b&&y.total===0){let T=await t.getRetainers({statuses:Qc,limit:1,offset:0});if(c!==N.current)return;g(T.total)}else g(0)}catch(y){if(c!==N.current)return;l(y instanceof Error?y:new Error("Failed to fetch retainers"))}finally{c===N.current&&v(!1)}},[t,b,s]);Dt.useEffect(()=>{I()},[I,e]);let O=Dt.useCallback(async()=>{if(r||h||n.length>=o)return;let c=N.current;f(!0);try{let y=await t.getRetainers({statuses:b?void 0:Ri,limit:s,offset:n.length});if(c!==N.current)return;i(T=>{let z=new Set(T.map(L=>L.id));return[...T,...y.retainers.filter(L=>!z.has(L.id))]}),p(y.total)}catch(y){if(c!==N.current)return;l(y instanceof Error?y:new Error("Failed to fetch retainers"))}finally{c===N.current&&f(!1)}},[t,b,s,r,h,n.length,o]);return{retainers:n,total:o,endedTotal:m,hasMore:n.length<o,isLoading:r,isLoadingMore:h,error:u,includeEnded:b,setIncludeEnded:x,loadMore:O,refetch:I}}import{Fragment as iu,jsx as $e,jsxs as Gt}from"react/jsx-runtime";function Pi({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=ws.useState(a),[p,m]=ws.useState("list"),[g,r]=ws.useState(null),v=hs(),{status:h,error:f}=Za(),u=h?.currency,l=I=>{r(I),m("edit")},b=()=>{r(null),m("create")},x=()=>{m("list"),r(null)},N=I=>{r(I),m("edit")};return Gt("div",{className:e,children:[Gt("div",{className:"af-mb-6",children:[$e("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),$e("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Gt(Gs,{value:i,onValueChange:I=>o(I),children:[Gt(Es,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Gt(ma,{value:"products",className:"af-gap-2",children:[$e(tu,{className:"af-h-4 af-w-4"}),"Products"]}),Gt(ma,{value:"orders",className:"af-gap-2",children:[$e(au,{className:"af-h-4 af-w-4"}),"Orders"]}),Gt(ma,{value:"invoices",className:"af-gap-2",children:[$e(eu,{className:"af-h-4 af-w-4"}),"Invoices"]}),Gt(ma,{value:"customers",className:"af-gap-2",children:[$e(nu,{className:"af-h-4 af-w-4"}),"Customers"]}),$e(ma,{value:"promos",children:"Promo codes"}),Gt(ma,{value:"setup",className:"af-gap-2",children:[$e(su,{className:"af-h-4 af-w-4"}),"Setup"]})]}),$e(pa,{value:"products",children:p==="list"?$e(rn,{productsState:v,onSelectProduct:l,onCreateProduct:b}):Gt("div",{children:[Gt("div",{className:"af-mb-6",children:[Gt(w,{variant:"ghost",size:"sm",onClick:x,className:"af-mb-2 af--ml-2",children:[$e(Xc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),$e("h3",{className:"af-text-lg af-font-semibold",children:p==="create"?"New Product":g?.name})]}),p==="create"&&!u?$e("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:f?Gt("div",{className:"af-text-destructive",children:["Error: ",f.message]}):$e("div",{className:"af-text-muted-foreground",children:"Loading..."})}):$e(ln,{productsState:v,product:p==="edit"?g:null,currency:u??"usd",onSaved:N},p==="edit"?g?.id??"edit":"new")]})}),$e(pa,{value:"orders",children:$e(ps,{onRefund:t})}),$e(pa,{value:"invoices",children:$e(ru,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:h?.reason==="needs_paid_plan"})}),$e(pa,{value:"customers",children:$e(hn,{})}),$e(pa,{value:"promos",children:$e(fs,{})}),$e(pa,{value:"setup",children:$e(Sn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function ru({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=xs(),[n,i]=ws.useState(null),[o,p]=ws.useState(!1);return Gt(iu,{children:[!o&&$e(ys,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:m=>i(g=>g?.id===m.id?null:m),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),$e(bs,{onDetailOpenChange:p,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 Ti from"react";import*as La from"react";function _n({refreshKey:e}={}){let{api:a}=ie(),[s,t]=La.useState(null),[n,i]=La.useState(!0),[o,p]=La.useState(null),m=La.useRef(0),g=La.useCallback(async()=>{let r=++m.current;try{i(!0),p(null);let v=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==m.current)return;t(v)}catch(v){if(r!==m.current)return;p(v instanceof Error?v:new Error("Failed to fetch summary"))}finally{r===m.current&&i(!1)}},[a,e]);return La.useEffect(()=>{g()},[g]),{summary:s,isLoading:n,error:o,refetch:g}}import{Fragment as dr,jsx as St,jsxs as fr}from"react/jsx-runtime";function Ci(e,a){if(e.settled.complete)return{headline:H(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:H(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${H(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:H(0,a),extra:[]}}function ki({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:p,error:m,refetch:g}=_n({refreshKey:e}),[r,v]=Ti.useState(!1),h=St("div",{className:"af-mb-6",children:m&&!o?St(ea,{message:"Couldn't load your revenue summary.",onRetry:()=>g()}):St("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:p||!o?fr(dr,{children:[St(Qe,{label:"This week",children:St(X,{className:"af-h-6 af-w-24"})}),St(Qe,{label:"Today",children:St(X,{className:"af-h-6 af-w-24"})}),St(Qe,{label:"Needs attention",children:St(X,{className:"af-h-6 af-w-10"})})]}):St(dr,{children:(()=>{let f=Ci(o.revenue.d7,o.currency),u=Ci(o.revenue.today,o.currency);return fr(dr,{children:[St(Qe,{label:"This week",detail:f.extra.length>0?St("div",{children:f.extra.map(l=>St("div",{children:l},l))}):void 0,children:f.headline}),St(Qe,{label:"Today",detail:u.extra.length>0?St("div",{children:u.extra.map(l=>St("div",{children:l},l))}):void 0,children:u.headline}),St(Qe,{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 fr(Rt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[h,St(ps,{refreshKey:e,initialOrderId:a,onDetailOpenChange:v,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as Ba from"react";import{ImageOff as du,Package as fu,Search as mu}from"lucide-react";import*as Oa from"react";import{ArrowLeft as cu,ImageOff as uu}from"lucide-react";import{jsx as Sa,jsxs as Fs}from"react/jsx-runtime";var Ei="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Xa="af-text-xs af-text-muted-foreground",Rn="af-text-sm af-font-medium af-tabular-nums",ou=3;function lu(e){let a=e.pricing,s=a?.currency??e.currency;if(a?.custom_amount??e.allow_custom_amount){let m=e.min_amount??a?.min_amount??null,g=e.max_amount??a?.max_amount??null;return m!==null&&g!==null?{text:`Buyer chooses (${H(m,s)} \u2013 ${H(g,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?H(n,s):`${H(n,s)} \u2013 ${H(i,s)}`,p=a?.compare_at_amount??null;return{text:o,compareAt:p!==null&&p>i?H(p,s):null}}function Pn({product:e,className:a}){let s=lu(e);return Fs("div",{className:a,children:[Sa("span",{className:Rn,children:s.text}),s.compareAt&&Sa("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Cn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?Sa(Z,{variant:"destructive",children:"Out of stock"}):a.low_stock?Fs(Z,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?Sa(Z,{variant:"secondary",children:"Backorder"}):a.available===null?null:Fs(Z,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?Sa(Z,{variant:"warning",children:"Low stock"}):null}function Tn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function kn(e){return e.map(a=>H(a.amount,a.currency)).join(" + ")}function Ii(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${H(e.min_amount,e.currency)} \u2013 ${H(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":H(e.unit_amount,e.currency)}function Ai({variant:e}){let a=e.inventory;if(!a||!a.tracked)return Sa("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?Fs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Sa("span",{className:"af-tabular-nums",children:Math.max(0,s)}),Sa(Z,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?Sa(Z,{variant:"destructive",children:"Out of stock"}):Fs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Sa("span",{className:"af-tabular-nums",children:s}),s<=ou&&Sa(Z,{variant:"warning",children:"Low"})]})}import{jsx as ce,jsxs as We}from"react/jsx-runtime";function Ms({title:e,children:a,className:s}){return We("section",{className:W("af-rounded-lg af-border af-p-4",s),children:[ce("h4",{className:Ei,children:e}),ce("div",{className:"af-mt-3",children:a})]})}function Di({src:e,className:a}){let[s,t]=Oa.useState(!1);return Oa.useEffect(()=>t(!1),[e]),!e||s?ce("div",{"aria-hidden":"true",className:W("af-flex af-items-center af-justify-center af-bg-muted",a),children:ce(uu,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):ce("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:W("af-object-cover",a)})}function Li({product:e,showStats:a=!1,onBack:s}){let{api:t}=ie(),[n,i]=Oa.useState(null),[o,p]=Oa.useState(!0),[m,g]=Oa.useState(null),[r,v]=Oa.useState(0),[h,f]=Oa.useState(0);Oa.useEffect(()=>{let c=!1;return p(!0),g(null),t.getProduct(e.id).then(y=>{c||i(y)}).catch(y=>{c||g(y instanceof Error?y:new Error("Failed to load product"))}).finally(()=>{c||p(!1)}),()=>{c=!0}},[t,e.id,r]);let u=n?{...e,...n}:e,l=u.images.length>0?u.images:e.images,b=l[h]??l[0],x=Tn(u),N=a?u.stats:void 0,I=n?.variants??[],O=I.length>1;return We("div",{children:[We("div",{className:"af-mb-6",children:[We(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[ce(cu,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),We("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ce("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),ce(Z,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),ce(Cn,{product:u})]}),ce(Pn,{product:u,className:"af-mt-1"}),!u.active&&ce("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),We("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[We("div",{className:"af-space-y-2",children:[ce(Di,{src:b,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&ce("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((c,y)=>ce("button",{type:"button",onClick:()=>f(y),"aria-label":`Show photo ${y+1} of ${l.length}`,"aria-pressed":y===h,className:W("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",y===h?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:ce(Di,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${y}`))})]}),We("div",{className:"af-space-y-6",children:[u.description&&ce(Ms,{title:"Description",children:ce("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?We(Ms,{title:"Variants",children:[ce("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>We("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[ce(X,{className:"af-h-4 af-w-28"}),ce(X,{className:"af-h-4 af-w-20"}),ce(X,{className:"af-h-4 af-w-16"})]},c))}),ce("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):m?ce(ea,{message:"Couldn't load this product's variants.",onRetry:()=>v(c=>c+1)}):O?ce(Ms,{title:`Variants \xB7 ${I.length}`,children:ce("div",{className:"af-overflow-x-auto",children:We(Oe,{children:[ce(Be,{children:We(pe,{children:[ce(F,{children:"Variant"}),ce(F,{children:"SKU"}),ce(F,{className:"af-text-right",children:"Price"}),ce(F,{children:"Stock"})]})}),ce(Fe,{children:I.map(c=>We(pe,{children:[We(M,{className:"af-font-medium",children:[c.title||c.option_values.map(y=>y.value).join(" / ")||"\u2014",!c.active&&ce(Z,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),ce(M,{className:"af-text-muted-foreground",children:c.sku?ce("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),We(M,{className:"af-whitespace-nowrap af-text-right",children:[ce("div",{className:Rn,children:Ii(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&ce("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:H(c.compare_at_amount,c.currency)})]}),ce(M,{className:"af-text-sm",children:ce(Ai,{variant:c})})]},c.id))})]})})}):null,ce(Ms,{title:"Details",children:We("dl",{className:"af-space-y-2",children:[We("div",{children:[ce("dt",{className:Xa,children:"Delivery"}),ce("dd",{className:"af-text-sm",children:x==="Digital download"?u.fulfillment.filename??"Digital download":x??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&We("div",{children:[ce("dt",{className:Xa,children:"Sends buyers to"}),ce("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),We("div",{children:[ce("dt",{className:Xa,children:"Shipping address"}),ce("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),We("div",{children:[ce("dt",{className:Xa,children:"Most one buyer can order"}),ce("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),N&&ce(Ms,{title:"Last 30 days",children:We("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[We("div",{children:[ce("dt",{className:Xa,children:"Units sold"}),ce("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:N.units_sold})]}),We("div",{children:[ce("dt",{className:Xa,children:"Orders"}),ce("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:N.orders})]}),We("div",{children:[ce("dt",{className:Xa,children:"Gross"}),ce("dd",{className:Rn,children:N.gross.length>0?kn(N.gross):"\u2014"})]})]})}),ce("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 es,jsx as re,jsxs as Ke}from"react/jsx-runtime";var pu={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},gu=["all","active","draft","low_stock","out_of_stock"];function Oi(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function Bi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function vu(e){return e.inventory?.out_of_stock??!1}function bu(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Bi(e);case"out_of_stock":return vu(e);default:return!0}}function yu({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=Tn(e),o=e.variant_count??0;return Ke("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(du,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ke("div",{className:"af-space-y-2 af-p-3",children:[Ke("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ke("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(Pn,{product:e,className:"af-mt-0.5"})]}),!e.active&&re(Z,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ke("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[re(Cn,{product:e}),o>1&&Ke(Z,{variant:"outline",children:[o," variants"]}),i&&re(Z,{variant:"outline",children:i})]}),n&&Ke("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${kn(n.gross)}`:""," ",re("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function hu(){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=>Ke("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"}),Ke("div",{className:"af-space-y-2 af-p-3",children:[re(X,{className:"af-w-32"}),re(X,{className:"af-w-16"}),re(X,{className:"af-h-5 af-w-24"})]})]},e))})}function Fi({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:p}=hs({includeStats:a,refreshKey:e}),[m,g]=Ba.useState(!1),[r,v]=Ba.useState(null),[h,f]=Ba.useState("all"),[u,l]=Ba.useState(""),[b,x]=Ba.useState("newest"),N=Ba.useMemo(()=>{if(!a)return null;let d=null;for(let U of n)!U.stats||U.stats.units_sold===0||(!d||U.stats.units_sold>(d.stats?.units_sold??0))&&(d=U);return d},[n,a]),I=Ba.useMemo(()=>n.filter(Bi).length,[n]),O=u.trim().toLowerCase(),c=Ba.useMemo(()=>{let U=[...n.filter(se=>bu(se,h)&&(!O||se.name.toLowerCase().includes(O)))];return b==="name"?U.sort((se,Q)=>se.name.localeCompare(Q.name)):b==="best_selling"?U.sort((se,Q)=>(Q.stats?.units_sold??0)-(se.stats?.units_sold??0)):U.sort((se,Q)=>Oi(Q.created_at)-Oi(se.created_at)),U},[n,h,O,b]),y=h!=="all"||!!O,T=()=>{f("all"),l("")},z=i||o!==null&&n.length===0,L=re("div",{className:"af-mb-6",children:re("div",{className:W("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:z?Ke(es,{children:[re(Qe,{label:"Products",children:re(X,{className:"af-h-6 af-w-10"})}),a?Ke(es,{children:[re(Qe,{label:"Best seller",children:re(X,{className:"af-h-6 af-w-28"})}),re(Qe,{label:"Low stock",children:re(X,{className:"af-h-6 af-w-10"})})]}):re(Qe,{label:"Active",children:re(X,{className:"af-h-6 af-w-10"})})]}):Ke(es,{children:[re(Qe,{label:"Products",children:n.length}),a?Ke(es,{children:[re(Qe,{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?re("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:N.name}):re("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),re(Qe,{label:"Low stock",children:I})]}):re(Qe,{label:"Active",children:n.filter(d=>d.active).length})]})})}),R=Ke("div",{className:"af-mb-4 af-space-y-3",children:[Ke("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:gu.map(d=>re("button",{type:"button","aria-pressed":h===d,onClick:()=>f(d),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",h===d?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:pu[d]},d))}),Ke("div",{className:"af-relative af-w-full af-max-w-xs",children:[re(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"}),re(ge,{type:"text",value:u,onChange:d=>l(d.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ke(na,{value:b,onValueChange:d=>x(d),children:[re(Yt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:re(ra,{})}),Ke(Zt,{children:[re(ze,{value:"newest",children:"Newest"}),re(ze,{value:"name",children:"Name A\u2013Z"}),a&&re(ze,{value:"best_selling",children:"Best selling"})]})]}),y&&re(w,{type:"button",variant:"ghost",size:"sm",onClick:T,children:"Clear filters"})]}),i&&n.length===0?re(X,{className:"af-h-4 af-w-28"}):re("p",{className:"af-text-sm af-text-muted-foreground",children:y?`${c.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${I>0?` \xB7 ${I} low stock`:""}`})]}),$;return r?$=re(Li,{product:r,showStats:a,onBack:()=>{v(null),p()}},r.id):i&&n.length===0?$=Ke(es,{children:[R,re(hu,{}),re("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?$=re("div",{className:"af-flex af-justify-center af-py-8",children:re(ea,{message:"Couldn't load your products.",onRetry:()=>p()})}):n.length===0?$=Ke(Da,{icon:re(fu,{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."]}):$=Ke(es,{children:[R,o&&re("div",{className:"af-mb-4",children:re(ea,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>p()})}),c.length===0?Ke(Da,{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:c.map(d=>re(yu,{product:d,showStats:a,onOpen:()=>v(d)},d.id))})]}),re(Rt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:t,children:m?Ke(es,{children:[re(w,{variant:"ghost",onClick:()=>g(!1),children:"Back to products"}),re(fs,{})]}):Ke(es,{children:[!r&&re("div",{className:"af-mb-4 af-flex af-justify-end",children:re(w,{variant:"outline",onClick:()=>g(!0),children:"Promo codes"})}),!r&&L,$]})})}import*as _a from"react";import{ArrowLeft as Hi,Check as xu,ChevronLeft as Mi,ChevronRight as Ui,ClipboardCopy as wu,Mail as pr,Search as Nu,Users as Su}from"lucide-react";import*as ta from"react";function En({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=ta.useState([]),[i,o]=ta.useState(!0),[p,m]=ta.useState(null),[g,r]=ta.useState(0),[v]=ta.useState(e),[h,f]=ta.useState(""),u=ta.useRef(0),l=ta.useCallback(async()=>{let b=++u.current;try{o(!0),m(null);let x={limit:v,offset:g*v};h.trim()&&(x.q=h.trim());let N=await s.getPeople(x);if(b!==u.current)return;n(N.people)}catch(x){if(b!==u.current)return;m(x instanceof Error?x:new Error("Failed to fetch people"))}finally{b===u.current&&o(!1)}},[s,g,v,h,a]);return ta.useEffect(()=>{l()},[l]),{people:t,isLoading:i,error:p,page:g,pageSize:v,hasNextPage:t.length===v,hasPreviousPage:g>0,setPage:r,q:h,setQ:b=>{f(b),r(0)},refetch:l}}import*as Fa from"react";function In(e,{refreshKey:a}={}){let{api:s}=ie(),[t,n]=Fa.useState(null),[i,o]=Fa.useState(e!==null),[p,m]=Fa.useState(null),g=Fa.useRef(0),r=Fa.useCallback(async()=>{if(e===null){n(null),o(!1),m(null);return}let v=++g.current;try{o(!0),m(null);let h=await s.getPerson(e);if(v!==g.current)return;n(h)}catch(h){if(v!==g.current)return;m(h instanceof Error?h:new Error("Failed to fetch person"))}finally{v===g.current&&o(!1)}},[s,e,a]);return Fa.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:p,refetch:r}}import{jsx as _,jsxs as le}from"react/jsx-runtime";var mr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",_u="af-text-xs af-text-muted-foreground";function Ns(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 gr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Ru(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Pu({value:e,label:a}){let[s,t]=_a.useState(!1);return Ru()?le(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?_(xu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):_(wu,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function $i(e){return le("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&le(Z,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&_(Z,{variant:"secondary",children:"Contact form"})]})}function Vi(e){return e.name?e.name:e.email?e.email:_("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Cu=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Tu=40;function ku(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>Cu.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=Tu).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 Eu(e){return e.replace(/_/g," ")}function Iu(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Au({data:e}){let{message:a,rest:s}=ku(e);return a===null&&s.length===0?_("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):le("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])=>le("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[_("dt",{className:W(_u,"af-w-28 af-shrink-0 af-capitalize"),children:Eu(t)}),_("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:Iu(n)})]},t))})]})}function zi({formName:e,createdAt:a,data:s}){return le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[_(Z,{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:Ns(a)})]}),_(Au,{data:s})]})}function Du(e){return e.charged_total??e.amount_total}function Lu({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=In(e,{refreshKey:a}),p=gr(e,t?.submissions[0]?.form_name);return le("div",{children:[le("div",{className:"af-mb-6",children:[le(w,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[_(Hi,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),le("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[le("div",{className:"af-min-w-0",children:[n?_(X,{className:"af-h-7 af-w-48"}):_("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),le("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}),_(Pu,{value:e,label:"Copy email address"})]})]}),_(w,{asChild:!0,children:le("a",{href:p,children:[_(pr,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?le("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(m=>le("div",{className:"af-rounded-md af-border af-p-3",children:[_(X,{className:"af-w-40"}),_(X,{className:"af-mt-2 af-w-64"})]},m)),_("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?_("div",{className:"af-flex af-justify-center af-py-8",children:_(ea,{message:"Couldn't load this person.",onRetry:()=>o()})}):le("div",{className:"af-space-y-6",children:[t.customer&&le("div",{children:[_("h4",{className:W(mr,"af-mb-3"),children:"Customer"}),le("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&le("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&&le("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})]}),le("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:Ns(t.customer.created_at)})]})]})]}),t.orders.length>0&&le("div",{children:[_("h4",{className:W(mr,"af-mb-3"),children:"Purchases"}),_("div",{className:"af-overflow-x-auto",children:le(Oe,{children:[_(Be,{children:le(pe,{children:[_(F,{children:"Order"}),_(F,{children:"Date"}),_(F,{className:"af-text-right",children:"Total"}),_(F,{children:"Status"})]})}),_(Fe,{children:t.orders.map(m=>le(pe,{children:[_(M,{className:"af-whitespace-nowrap af-font-medium",children:Ga(m)}),_(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ns(m.created_at)}),_(M,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:H(Du(m),m.currency)}),_(M,{children:_(rs,{status:m.status})})]},m.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&&le("div",{children:[_("h4",{className:W(mr,"af-mb-3"),children:"Messages"}),_("div",{className:"af-space-y-3",children:t.submissions.map(m=>_(zi,{formName:m.form_name,createdAt:m.created_at,data:m.data},m.id))})]})]})]})}function Ou({submissionId:e,onBack:a}){let{api:s}=ie(),[t,n]=_a.useState(null),[i,o]=_a.useState(!0),[p,m]=_a.useState(null),[g,r]=_a.useState(0);return _a.useEffect(()=>{let v=!1;return o(!0),m(null),s.getSubmission(e).then(h=>{v||n(h)}).catch(h=>{v||m(h instanceof Error?h:new Error("Failed to load submission"))}).finally(()=>{v||o(!1)}),()=>{v=!0}},[s,e,g]),le("div",{children:[le("div",{className:"af-mb-6",children:[le(w,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[_(Hi,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),_("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?_(X,{className:"af-mt-1 af-h-4 af-w-32"}):t&&_("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Ns(t.metadata.submitted_at)})]}),i?le("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[_(X,{className:"af-w-40"}),_(X,{className:"af-mt-2 af-w-64"}),_(X,{className:"af-mt-2 af-w-52"}),_("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):p||!t?_("div",{className:"af-flex af-justify-center af-py-8",children:_(ea,{message:"Couldn't load this submission.",onRetry:()=>r(v=>v+1)})}):le("div",{className:"af-space-y-3",children:[_(zi,{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 Bu={all:"All",customers:"Customers",leads:"Leads"},Fu=["all","customers","leads"];function Mu(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function qi({refreshKey:e,onBackToWebsite:a,className:s}){let{people:t,isLoading:n,error:i,page:o,pageSize:p,hasNextPage:m,hasPreviousPage:g,setPage:r,q:v,setQ:h,refetch:f}=En({refreshKey:e}),[u,l]=_a.useState({kind:"list"}),[b,x]=_a.useState(""),[N,I]=_a.useState("all"),O=L=>{L.email?l({kind:"person",email:L.email}):L.submission_id&&l({kind:"submission",submissionId:L.submission_id})},c=()=>{l({kind:"list"}),f()},y=L=>{let R=L.trim();R!==v&&h(R)},T=t.filter(L=>Mu(L,N)),z;if(u.kind==="person")z=_(Lu,{email:u.email,refreshKey:e,onBack:c});else if(u.kind==="submission")z=_(Ou,{submissionId:u.submissionId,onBack:c});else{let L=le("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:Fu.map(R=>_("button",{type:"button","aria-pressed":N===R,onClick:()=>I(R),className:W("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===R?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Bu[R]},R))}),le("div",{className:"af-relative af-w-full af-max-w-xs",children:[_(Nu,{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:b,onChange:R=>x(R.target.value),onBlur:()=>y(b),onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),y(b))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),v&&_(w,{type:"button",variant:"ghost",size:"sm",onClick:()=>{x(""),h("")},children:"Clear search"})]});if(n)z=le("div",{children:[L,_("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(R=>le("div",{className:"af-rounded-md af-border af-p-3",children:[le("div",{className:"af-flex af-items-center af-justify-between",children:[_(X,{className:"af-h-4 af-w-32"}),_(X,{className:"af-h-4 af-w-16"})]}),_(X,{className:"af-mt-2 af-h-5 af-w-28"}),_(X,{className:"af-mt-2 af-h-3 af-w-56"})]},R))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le(Oe,{children:[_(Be,{children:le(pe,{children:[_(F,{children:"Person"}),_(F,{children:"Came from"}),_(F,{children:"Latest message"}),_(F,{children:"Last activity"}),_(F,{className:"af-w-8"}),_(F,{className:"af-w-8"})]})}),_(Fe,{"aria-hidden":"true",children:[0,1,2,3,4].map(R=>le(pe,{children:[_(M,{children:_(X,{className:"af-h-4 af-w-40"})}),_(M,{children:_(X,{className:"af-h-5 af-w-24"})}),_(M,{children:_(X,{className:"af-h-4 af-w-56"})}),_(M,{children:_(X,{className:"af-h-4 af-w-24"})}),_(M,{}),_(M,{})]},R))})]})}),_("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)z=le("div",{children:[L,_("div",{className:"af-flex af-justify-center af-py-8",children:_(ea,{message:"Couldn't load your leads.",onRetry:()=>f()})})]});else if(T.length===0&&o===0){let R=!!v||N!=="all";z=le("div",{children:[R&&L,R?_(Da,{children:v?"Nobody matches that search.":N==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):_(Da,{icon:_(Su,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Form submissions and customers will show up here."})]})}else if(t.length===0)z=le("div",{children:[L,_(Da,{children:"No more results."}),_("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:le(w,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[_(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let R=o*p+1,$=o*p+t.length;z=le("div",{children:[L,_("div",{className:"af-space-y-3 lg:af-hidden",children:T.map((d,U)=>le("div",{onClick:()=>O(d),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[le("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[le("div",{className:"af-min-w-0",children:[_("button",{type:"button",onClick:se=>{se.stopPropagation(),O(d)},"aria-label":`Open ${d.name||d.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 hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Vi(d)}),d.name&&d.email&&_("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:d.email})]}),le("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[_("span",{className:"af-text-xs af-text-muted-foreground",children:Ns(d.last_activity_at)}),d.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:gr(d.email),onClick:se=>se.stopPropagation(),"aria-label":`Email ${d.email}`,children:_(pr,{className:"af-h-4 af-w-4"})})})]})]}),_("div",{className:"af-mt-2",children:$i(d)}),d.latest_message_excerpt&&_("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:d.latest_message_excerpt})]},d.email??d.submission_id??U))}),_("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:le(Oe,{children:[_(Be,{children:le(pe,{children:[_(F,{children:"Person"}),_(F,{children:"Came from"}),_(F,{children:"Latest message"}),_(F,{children:"Last activity"}),_(F,{className:"af-w-8",children:_("span",{className:"af-sr-only",children:"Reply"})}),_(F,{className:"af-w-8"})]})}),_(Fe,{children:T.map((d,U)=>le(pe,{onClick:()=>O(d),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[le(M,{className:"af-max-w-[260px] af-font-medium",children:[_("button",{type:"button",onClick:se=>{se.stopPropagation(),O(d)},"aria-label":`Open ${d.name||d.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Vi(d)}),d.name&&d.email&&_("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:d.email})]}),_(M,{children:$i(d)}),_(M,{className:"af-max-w-[320px]",children:d.latest_message_excerpt?_("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:d.latest_message_excerpt}):_("span",{className:"af-text-muted-foreground",children:"\u2014"})}),_(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ns(d.last_activity_at)}),_(M,{className:"af-w-8",children:d.email&&_(w,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:_("a",{href:gr(d.email),onClick:se=>se.stopPropagation(),"aria-label":`Email ${d.email}`,children:_(pr,{className:"af-h-4 af-w-4"})})})}),_(M,{className:"af-w-8 af-text-right",children:_(Ui,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},d.email??d.submission_id??U))})]})}),le("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:N==="all"?`Showing ${R}-${$}`:`${T.length} of ${t.length} on this page`}),le("div",{className:"af-flex af-items-center af-gap-2",children:[le(w,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!g,children:[_(Mi,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),le(w,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!m,children:["Next",_(Ui,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return _(Rt,{title:"Leads",onBackToWebsite:a,hideBackButton:u.kind!=="list",className:s,children:z})}import{ChevronLeft as ji,ChevronRight as Uu,Repeat as $u}from"lucide-react";import*as Wt from"react";function An({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ie(),[t,n]=Wt.useState([]),[i,o]=Wt.useState(0),[p,m]=Wt.useState(!0),[g,r]=Wt.useState(null),[v,h]=Wt.useState(0),[f,u]=Wt.useState(e),[l,b]=Wt.useState(void 0),x=Wt.useRef(0),N=Wt.useCallback(async()=>{let O=++x.current;try{m(!0),r(null);let c={limit:f,offset:v*f};l&&(c.status=l);let y=await s.getSubscriptions(c);if(O!==x.current)return;n(y.subscriptions),o(y.total)}catch(c){if(O!==x.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{O===x.current&&m(!1)}},[s,v,f,l,a]);Wt.useEffect(()=>{N()},[N]);let I=Math.ceil(i/f);return{subscriptions:t,total:i,isLoading:p,error:g,page:v,pageSize:f,hasNextPage:v<I-1,hasPreviousPage:v>0,setPage:h,setPageSize:O=>{u(O),h(0)},status:l,setStatus:O=>{b(O),h(0)},refetch:N}}import{jsx as Y,jsxs as Je}from"react/jsx-runtime";function Gi(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 Wi({sub:e}){return e.status==="canceled"?Y(Z,{variant:"outline",children:"Canceled"}):e.status==="past_due"?Y(Z,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?Y(Z,{variant:"warning",children:"Scheduled to cancel"}):Y(Z,{variant:"success",children:"Active"}):Y(Z,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Vu(e,a){let s=H(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ki({sub:e}){let a=e.current_amount!==e.plan_amount;return Je("div",{children:[Y("div",{className:"af-font-medium af-tabular-nums",children:Vu(e,e.current_amount)}),a&&Je("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",H(e.plan_amount,e.currency)]})]})}function Ji(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Gi(e.current_period_end)}`:"Ends at period end":e.current_period_end?Gi(e.current_period_end):"\u2014"}function Yi({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:p,pageSize:m,hasNextPage:g,hasPreviousPage:r,setPage:v,refetch:h}=An({refreshKey:e}),f;if(i)f=Je("div",{children:[Y("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>Je("div",{className:"af-rounded-md af-border af-p-3",children:[Je("div",{className:"af-flex af-items-center af-justify-between",children:[Y(X,{className:"af-h-4 af-w-40"}),Y(X,{className:"af-h-4 af-w-20"})]}),Y(X,{className:"af-mt-2 af-h-3 af-w-32"}),Y(X,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),Y("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Je(Oe,{children:[Y(Be,{children:Je(pe,{children:[Y(F,{children:"Subscriber"}),Y(F,{children:"Plan"}),Y(F,{className:"af-text-right",children:"Amount"}),Y(F,{children:"Renews"}),Y(F,{children:"Status"})]})}),Y(Fe,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>Je(pe,{children:[Y(M,{children:Y(X,{className:"af-h-4 af-w-44"})}),Y(M,{children:Y(X,{className:"af-h-4 af-w-32"})}),Y(M,{className:"af-text-right",children:Y(X,{className:"af-ml-auto af-h-4 af-w-24"})}),Y(M,{children:Y(X,{className:"af-h-4 af-w-24"})}),Y(M,{children:Y(X,{className:"af-h-5 af-w-20"})})]},u))})]})}),Y("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)f=Y("div",{className:"af-flex af-justify-center af-py-8",children:Y(ea,{message:"Couldn't load your subscriptions.",onRetry:()=>h()})});else if(t.length===0&&p===0)f=Y(Da,{icon:Y($u,{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)f=Je("div",{children:[Y(Da,{children:"No more results."}),Y("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Je(w,{variant:"outline",size:"sm",onClick:()=>v(p-1),children:[Y(ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=p*m+1,l=p*m+t.length;f=Je("div",{children:[Y("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(b=>Je("div",{className:"af-rounded-md af-border af-p-3",children:[Je("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Je("div",{className:"af-min-w-0",children:[Y("div",{className:"af-truncate af-text-sm af-font-medium",children:b.customer_email||Y("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Y("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:b.plan_title||"Untitled plan"})]}),Y("div",{className:"af-shrink-0 af-text-right",children:Y(Ki,{sub:b})})]}),Je("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[Y(Wi,{sub:b}),b.is_test&&Y(Z,{variant:"outline",children:"Test"}),Y("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ji(b)})]}),Y(Pa,{deliveries:b.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},b.id))}),Y("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Je(Oe,{children:[Y(Be,{children:Je(pe,{children:[Y(F,{children:"Subscriber"}),Y(F,{children:"Plan"}),Y(F,{className:"af-text-right",children:"Amount"}),Y(F,{children:"Renews"}),Y(F,{children:"Status"})]})}),Y(Fe,{children:t.map(b=>Je(pe,{children:[Y(M,{className:"af-max-w-[240px]",children:Y("div",{className:"af-truncate af-font-medium",children:b.customer_email||Y("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),Y(M,{className:"af-max-w-[220px]",children:Y("div",{className:"af-truncate",children:b.plan_title||Y("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),Y(M,{className:"af-whitespace-nowrap af-text-right",children:Y(Ki,{sub:b})}),Y(M,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ji(b)}),Je(M,{children:[Je("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[Y(Wi,{sub:b}),b.is_test&&Y(Z,{variant:"outline",children:"Test"})]}),Y(Pa,{deliveries:b.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},b.id))})]})}),Je("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[Y("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${u}-${l} of ${n}`}),Je("div",{className:"af-flex af-items-center af-gap-2",children:[Je(w,{variant:"outline",size:"sm",onClick:()=>v(p-1),disabled:!r,children:[Y(ji,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Je(w,{variant:"outline",size:"sm",onClick:()=>v(p+1),disabled:!g,children:["Next",Y(Uu,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return Y(Rt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:f})}import*as vr from"react";import{Fragment as Zi,jsx as aa,jsxs as Dn}from"react/jsx-runtime";function Qi({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:p,isLoading:m,error:g,refetch:r}=gs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),v=xs({refreshKey:e}),[h,f]=vr.useState(!1),[u,l]=vr.useState(null),b=aa("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!m&&!p?Dn("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. ",aa(w,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):m||!p?Dn(Zi,{children:[aa(Qe,{label:"Outstanding",children:aa(X,{className:"af-h-6 af-w-24"})}),aa(Qe,{label:"Overdue",children:aa(X,{className:"af-h-6 af-w-24"})}),aa(Qe,{label:"Paid this month",children:aa(X,{className:"af-h-6 af-w-24"})})]}):Dn(Zi,{children:[aa(Qe,{label:"Outstanding",detail:`${p.outstanding.count} open`,children:H(p.outstanding.amount,p.currency)}),aa(Qe,{label:"Overdue",detail:p.overdue.count===0?"Nothing overdue":`${p.overdue.count} overdue`,valueClassName:p.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:H(p.overdue.amount,p.currency)}),aa(Qe,{label:"Paid this month",detail:`${p.paid_this_month.count} paid`,children:H(p.paid_this_month.amount,p.currency)})]})});return Dn(Rt,{title:"Invoices",onBackToWebsite:s,hideBackButton:h,className:o,children:[b,!h&&aa(ys,{retainers:v.retainers,isLoading:v.isLoading,error:v.error,onRetry:()=>void v.refetch(),activeRetainerId:u?.id??null,onShowCycles:x=>l(N=>N?.id===x.id?null:x),total:v.total,endedTotal:v.endedTotal,isLoadingMore:v.isLoadingMore,onLoadMore:()=>void v.loadMore(),includeEnded:v.includeEnded,onIncludeEndedChange:v.setIncludeEnded}),aa(bs,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:f,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:u?{id:u.id,label:`${u.customer_name??u.customer_email??"Recurring invoices"} \u2014 ${u.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}import*as yt from"react";var Hu=2e3,Ct=()=>({data:null,error:null,isLoading:!0});function Ln(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=ie(),[i,o]=yt.useState(Ct),[p,m]=yt.useState(Ct),[g,r]=yt.useState(Ct),[v,h]=yt.useState(Ct),[f,u]=yt.useState(Ct),l=ne=>Object.fromEntries(ne.map(J=>[J,Ct()])),[b,x]=yt.useState(()=>l(s)),N=yt.useRef(0),I=yt.useRef(0),O=yt.useRef("idle"),c=s.join(","),y=JSON.stringify(t),T=`${e}:${c}:${y}`,[z,L]=yt.useState({api:n,fetchIdentity:T});(z.api!==n||z.fetchIdentity!==T)&&(L({api:n,fetchIdentity:T}),N.current+=1,o(Ct),m(Ct),r(Ct),h(Ct),x(l(c?c.split(","):[])));let R=`${e}:${String(a??"")}`,[$,d]=yt.useState({api:n,conversionsIdentity:R});($.api!==n||$.conversionsIdentity!==R)&&(d({api:n,conversionsIdentity:R}),I.current+=1,O.current="idle",u(Ct));let U=yt.useCallback(async ne=>{let J=++N.current,ee=c?c.split(","):[];o(Ct),m(Ct),r(Ct),h(Ct),x(Object.fromEntries(ee.map(E=>[E,Ct()])));let de=O.current!=="pending"&&(ne?.force===!0||O.current==="idle"),q=(E,te)=>te.then(S=>{J===N.current&&E({data:S,error:null,isLoading:!1})},S=>{J===N.current&&E({data:null,error:S instanceof Error?S:new Error("Failed to fetch report"),isLoading:!1})}),ve=n.getAnalyticsStatus(),st=q(o,ve),lt=Symbol("status-timeout"),Re,xe=await Promise.race([ve.then(E=>E,()=>null),new Promise(E=>{Re=setTimeout(()=>E(lt),Hu)})]);if(clearTimeout(Re),J!==N.current)return;if(xe===lt&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),xe!==null&&xe!==lt&&(xe.collecting!==!0||xe.first_seen===null&&!xe.first_seen_unavailable||xe.first_seen!==null&&xe.first_seen_in_reports===!1)){let E={data:null,error:null,isLoading:!1};m(E),r(E),h(E),x(Object.fromEntries(ee.map(te=>[te,{...E}]))),de&&(u(E),O.current="done"),await st;return}await Promise.all([xe===lt?Promise.resolve():st,q(m,n.getAnalyticsSummary(e,t)),q(r,n.getAnalyticsTimeseries(e,t)),q(h,n.getAnalyticsChannels(e,t)),de?(()=>{O.current="pending";let E=++I.current;return u(Ct),n.getAnalyticsConversions(e).then(te=>{E===I.current&&(u({data:te,error:null,isLoading:!1}),O.current="done")},te=>{E===I.current&&(u({data:null,error:te instanceof Error?te:new Error("Failed to fetch report"),isLoading:!1}),O.current="done")})})():Promise.resolve(),...ee.map(E=>n.getAnalyticsBreakdown(E,e,t).then(te=>{J===N.current&&x(S=>({...S,[E]:{data:te,error:null,isLoading:!1}}))},te=>{J===N.current&&x(S=>({...S,[E]:{data:null,error:te instanceof Error?te:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,c,y,R]),se=yt.useCallback(async()=>{let ne=N.current;try{let J=await n.getAnalyticsStatus();if(ne!==N.current)return;o({data:J,error:null,isLoading:!1})}catch(J){if(ne!==N.current)return;o(ee=>({data:ee.data,error:J instanceof Error?J:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),Q=yt.useCallback(()=>U({force:!0}),[U]);yt.useEffect(()=>{U()},[U,a]);let oe=i.isLoading||p.isLoading||g.isLoading||v.isLoading||f.isLoading||Object.values(b).some(ne=>ne.isLoading);return{status:i,summary:p,timeseries:g,channels:v,conversions:f,breakdowns:b,isLoading:oe,refetch:Q,refetchStatus:se}}import*as ht from"react";var br=3e4,yr=3;function On(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=ie(),[o,p]=ht.useState(null),[m,g]=ht.useState(null),[r,v]=ht.useState(!1),[h,f]=ht.useState(null),[u,l]=ht.useState(!1),[b,x]=ht.useState(!0),[N,I]=ht.useState(0),O=ht.useRef(0),c=ht.useRef(0),y=ht.useRef(void 0);s!==void 0&&(y.current=s);let T=a?y.current===!0||y.current===void 0&&t:!0,[z,L]=ht.useState({api:i,identity:n}),R=n!==void 0&&n!==z.identity;(z.api!==i||R)&&(y.current=void 0,L({api:i,identity:n}),c.current+=1,O.current=0,p(null),g(null),v(!1),f(null),l(!1),x(!0),I(0));let $=ht.useRef(()=>{}),d=ht.useRef(null),U=ht.useCallback(async()=>{if(d.current!==null&&d.current===c.current)return;let se=++c.current;d.current=se;try{let Q=await i.getAnalyticsRealtime();if(se!==c.current)return;if(Q.status==="unreachable"){l(!0),v(!0),x(!1),I(oe=>oe+1);return}O.current=0,l(!1),p(Q.data.current_visitors),g(Q.as_of),v(!1),f(null),x(!1),I(oe=>oe+1)}catch(Q){if(se!==c.current)return;O.current+=1,x(!1),I(oe=>oe+1),v(!0),O.current>=yr&&f(Q instanceof Error?Q:new Error("Realtime unavailable"))}finally{d.current===se&&(d.current=null)}},[i]);return $.current=()=>void U(),ht.useEffect(()=>{let se,Q=()=>{se===void 0&&(se=setInterval(()=>$.current(),br))},oe=()=>{se!==void 0&&(clearInterval(se),se=void 0)},ne=()=>{typeof document<"u"&&document.hidden?oe():($.current(),Q())};return T?((typeof document>"u"||!document.hidden)&&($.current(),Q()),document?.addEventListener("visibilitychange",ne),()=>{oe(),document?.removeEventListener("visibilitychange",ne),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",ne)}},[z.api,z.identity,T]),{currentVisitors:o,asOf:m,isStale:r,error:h,isUnreachable:u,isInitialLoad:b,polls:N}}import*as qe from"react";import*as us from"react";var zu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Lt(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?Lt(o*t):`${o}${n}`}return String(e)}function Ss(e){return`${(e*100).toFixed(1)}%`}function Us(e){let a=Math.max(0,Math.round(e));if(a<60)return`${a}s`;let s=Math.floor(a/60);return s<60?`${s}m ${a%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function eo(e){let a=Math.max(0,Math.round(e));return a>=3600&&a%3600===0?`${a/3600}h`:a>=60&&a%60===0?`${a/60}m`:Us(a)}function to(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function ao(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 $s(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function so(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 hr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${zu[a-1]} ${s}`}function Xi(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function qu(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function no(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=Xi(e.to,s);for(let o=Xi(e.from,s);o<i;o=qu(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 ro(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 Gu,jsx as ts,jsxs as ju}from"react/jsx-runtime";function io({what:e="This report",onRetry:a,collecting:s}){return ju("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:[ts("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),ts("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?ts("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 Bn({what:e="No data"}){return ts("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 _s({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?ts("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?ts(io,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?ts(io,{what:t,onRetry:n,collecting:i}):ts(Gu,{children:o(e.data)})}import{Fragment as Wu,jsx as Kt,jsxs as cs}from"react/jsx-runtime";function xr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:p,maxRows:m=9}){let[g,r]=us.useState(!1);if(e.length===0)return Kt(Bn,{what:i});let v=e.reduce((u,l)=>Math.max(u,Number(l[s]??0)),0)||1,h=Math.max(0,e.length-m),f=g?e:e.slice(0,m);return cs(Wu,{children:[cs("table",{className:"af-w-full af-text-sm",children:[Kt("thead",{children:cs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Kt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),Kt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),Kt("tbody",{children:f.map((u,l)=>{let b=Number(u[s]??0),x=u[a]??null,N=$s(x),I=n?u[n]:null,O=x!==null&&(p?p(x,I):!0);return cs("tr",{className:"af-border-t af-border-border",children:[cs("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Kt("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,b/v*100)}%`}}),x!==null&&o&&O?Kt("button",{type:"button",onClick:()=>o(x,I),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}):Kt("span",{className:"af-relative af-break-words af-text-foreground",children:N}),I?Kt("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:I}):null]}),Kt("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Lt(b)})]},`${N}-${I??""}-${l}`)})})]}),h>0?Kt("button",{type:"button",onClick:()=>r(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:g?"Show fewer":`Show all ${e.length}`}):null]})}function Vs({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=us.useState(s),o=a.find(f=>f.id===n)??a[0],p=us.useId(),m=f=>`${p}-tab-${f}`,g=f=>`${p}-panel-${f}`,r=us.useRef(null),v=(f,u)=>{f.preventDefault();let l=(u+a.length)%a.length;i(a[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return cs("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[cs("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:[Kt("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:f=>{let u=a.findIndex(l=>l.id===n);f.key==="ArrowRight"&&v(f,u+1),f.key==="ArrowLeft"&&v(f,u-1),f.key==="Home"&&v(f,0),f.key==="End"&&v(f,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(f=>Kt("button",{id:m(f.id),role:"tab",type:"button","aria-selected":f.id===n,"aria-controls":g(f.id),tabIndex:f.id===n?0:-1,onClick:()=>i(f.id),className:f.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:f.label},f.id))}),t]}),o?Kt("div",{id:g(o.id),role:"tabpanel","aria-labelledby":m(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}import*as Jt from"react";import*as as from"@radix-ui/react-popover";var Rs=3,Ps=100;import{jsx as ot,jsxs as Ma}from"react/jsx-runtime";var Hs={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"},Ku=Object.keys(Hs);function oo(e){let a=Hs[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>$s(n)).join(" or ");return`${a} ${s} ${t}`}function wr(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function Ju(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 lo(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 Yu(e){return{dimension:e,operator:"is",search:"",picked:[]}}function co(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=Ju(e.byDimension,s);for(let[i,o]of Object.entries(t)){let p=e.foldsByLabel.get(i)??new Set;for(let m of o)p.add(m);e.foldsByLabel.set(i,p)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function uo(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Jt.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]),Ma("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>Ma("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:[ot("span",{className:"af-text-foreground",children:oo(n)}),ot("button",{type:"button","aria-label":`Remove filter ${oo(n)}`,onClick:()=>s(a.filter((o,p)=>p!==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"}`)),ot(Zu,{...e,disabled:t}),a.length>0?ot("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 Zu({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,p]=Jt.useState(!1),m=Jt.useRef(null),[g,r]=Jt.useState(null);Jt.useEffect(()=>{r(m.current?.closest(".aifeatures-admin")??null)},[]);let[v,h]=Jt.useState(null),[f,u]=Jt.useState("is"),[l,b]=Jt.useState(""),[x,N]=Jt.useState([]);Jt.useEffect(()=>{o||(h(null),u("is"),b(""),N([]))},[o]);let I=Jt.useRef(t);I.current!==t&&(I.current=t,o&&p(!1),v!==null&&h(null),x.length>0&&N([]),l!==""&&b(""),f!=="is"&&u("is"));let O=R=>{let $=Yu(R);h($.dimension),N($.picked),b($.search),u($.operator)},y=(v?s[v]??[]:[]).filter(R=>R.toLowerCase().includes(l.trim().toLowerCase())),T=v===null||x.length===0?null:wr(e,{dimension:v,operator:f,values:i?i(v,x):x}),z=T!==null&&T!==e,L=()=>{let R=T;!R||R===e||(a(R),p(!1))};return Ma(as.Root,{open:o,onOpenChange:p,children:[ot(as.Trigger,{asChild:!0,children:ot("button",{ref:m,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"})}),ot(as.Portal,{container:g,children:ot(as.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:v===null?Ma("div",{children:[ot("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),ot("div",{className:"af-max-h-96 af-overflow-y-auto",children:Ku.filter(R=>s[R]!==void 0).map(R=>{let $=s[R]?.length??0,d=!e.some(U=>U.dimension===R)&&e.length>=3;return Ma("button",{type:"button",onClick:()=>O(R),disabled:$===0||d,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:[ot("span",{children:Hs[R]}),ot("span",{className:"af-text-muted-foreground",children:$===0?"no data":d?"no room":$})]},R)})})]}):Ma("div",{children:[Ma("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[ot("button",{type:"button",onClick:()=>O(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),ot("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Hs[v]}),Ma("select",{"aria-label":"Operator",value:f,onChange:R=>u(R.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:[ot("option",{value:"is",children:"is"}),ot("option",{value:"is_not",children:"is not"})]})]}),ot("input",{type:"text",value:l,onChange:R=>b(R.target.value),placeholder:"Search\u2026","aria-label":`Search ${Hs[v]}`,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"}),ot("div",{className:"af-max-h-48 af-overflow-y-auto",children:y.length===0?Ma("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):y.map(R=>Ma("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:[ot("input",{type:"checkbox",checked:x.includes(R),disabled:!x.includes(R)&&x.length>=100,onChange:$=>N(d=>$.target.checked?[...d,R]:d.filter(U=>U!==R))}),ot("span",{className:"af-break-all",children:$s(R)})]},R))}),ot("button",{type:"button",onClick:L,disabled:!z,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:x.length<=1?"Apply filter":x.length>=100?`Apply filter (${x.length} values \u2014 the maximum)`:`Apply filter (${x.length} values)`})]})})})]})}import{Fragment as ed,jsx as Ot,jsxs as Fn}from"react/jsx-runtime";var Qu=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Lt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Lt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Lt,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:Ss,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Us,chart:"visit_duration_seconds"}];function Xu({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 Ot("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 fo({summary:e,selected:a,onSelect:s}){return Ot("div",{className:"af-@container",children:Ot("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Qu.map(t=>{let n=t.chart===a,i=s!==void 0,o=Fn(ed,{children:[Ot("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),Fn("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Ot("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?Ot(Xu,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?Ot("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):Ot("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function Nr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return Fn("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:[Ot("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Ot("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return Ot("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?so(a):"freshness unknown",p=i?" across the whole site, not the current filter,":"",m=s?`${e} current visitors${p} ${o} (not updating)`:`${e} current visitors${p} ${o}`;return Fn("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:m,children:[Ot("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"}),Ot("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Ot("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),Ot("span",{className:"af-sr-only",children:m})]})}import*as po from"react";import{Fragment as mo,jsx as Bt,jsxs as Cs}from"react/jsx-runtime";function go({rows:e,denominator:a,windowPrecedesCollection:s=!1,coverageUnknown:t=!1,emptyCopy:n="No conversions in this period",maxRows:i=9}){let[o,p]=po.useState(!1),m=e.filter(f=>!f.implicit||f.visitors>0||f.events>0),g=s?Bt("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?Bt("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(m.length===0)return Cs(mo,{children:[Bt(Bn,{what:n}),g]});let r=m.slice(0,i),v=o?e:r,h=Math.max(0,e.length-r.length);return Cs(mo,{children:[Cs("table",{className:"af-w-full af-text-sm",children:[Bt("thead",{children:Cs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Bt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),Bt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),Bt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),Bt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),Bt("tbody",{children:v.map((f,u)=>Cs("tr",{className:"af-border-t af-border-border",children:[Bt("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:f.goal}),Bt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Lt(f.visitors)}),Bt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Lt(f.events)}),Bt("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:f.conversion_rate===null?Bt("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Ss(f.conversion_rate)})]},`${f.goal}-${u}`))})]}),h>0?Bt("button",{type:"button",onClick:()=>p(f=>!f),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,Cs("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Lt(a)," ",a===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),g]})}import{Area as td,AreaChart as ad,CartesianGrid as sd,ResponsiveContainer as nd,Tooltip as rd,XAxis as id,YAxis as od}from"recharts";import{jsx as Ft,jsxs as zs}from"react/jsx-runtime";var Mn={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},_r={visitors:Lt,visits:Lt,pageviews:Lt,views_per_visit:e=>e.toFixed(2),bounce_rate:Ss,visit_duration_seconds:Us},ld=new Set(["visitors","visits","pageviews"]),cd={..._r,bounce_rate:to,visit_duration_seconds:eo},Sr=[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],dd=[.01,.02,.05,.1,.2,.25,.5,1],fd=[.25,.5,1,2,5,10,25,50],md={visitors:Sr,visits:Sr,pageviews:Sr,views_per_visit:fd,bounce_rate:dd,visit_duration_seconds:ud};function pd({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return zs("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:[Ft("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Mn[t]}),zs("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Ft("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Ft("span",{className:"af-text-muted-foreground",children:ro(String(s))}),Ft("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:_r[t](Number(n[t]??0))})]})]})}function vo({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=no(a,e,t),o=_r[s],p=cd[s],m=ao(i.reduce((r,v)=>Math.max(r,Number(v[s]??0)),0),md[s]),g=`${Mn[s]} by day: ${i.map(r=>`${hr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return zs("figure",{"aria-label":`${Mn[s]} over time`,className:"af-m-0",children:[Ft(nd,{width:"100%",height:n,children:zs(ad,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Ft("defs",{children:zs("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Ft("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Ft("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Ft(sd,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Ft(id,{dataKey:"date",tickFormatter:hr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Ft(od,{allowDecimals:!ld.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...m?{ticks:m,domain:[0,m[m.length-1]]}:{},tickFormatter:r=>p(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Ft(rd,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Ft(pd,{metric:s})}),Ft(td,{type:"monotone",dataKey:s,name:Mn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Ft("figcaption",{className:"af-sr-only",children:g})]})}import{Fragment as Rr,jsx as he,jsxs as Mt}from"react/jsx-runtime";var gd=3e4,vd="2026-08-13",bd=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],yd=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function hd({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[p,m]=qe.useState(30),g=e!==void 0&&a!==void 0,[r,v]=qe.useState(e??[]),{api:h}=ie(),[f,u]=qe.useState(h);f!==h&&(u(h),!g&&r.length>0&&v([]));let l=g?e:r,b=qe.useCallback(E=>{a&&a(E),g||v(E)},[a,g]),x=qe.useCallback((E,te,S)=>{let A=Array.isArray(te)?te:[te];if(A.length===0)return null;let ue=wr(l,{dimension:E,operator:"is",values:A});if(S&&(!S.value||(ue=lo(ue,{dimension:S.dimension,operator:"is",values:[S.value]}),!ue.find(He=>He.dimension===S.dimension&&He.operator!=="is_not")?.values.includes(S.value))))return null;let Ve=ue.find(we=>we.dimension===E&&we.operator!=="is_not");return A.every(we=>Ve?.values.includes(we))?JSON.stringify(ue)===JSON.stringify(l)?null:ue:null},[l]),N=qe.useCallback((E,te,S)=>x(E,te,S)!==null,[x]),I=qe.useCallback((E,te,S)=>{let A=x(E,te,S);A&&b(A)},[x,b]),[O,c]=qe.useState("visitors"),y=Ln(p,{refreshKey:s,breakdowns:yd,filters:l}),T=y.status.data,z=i===!1,L=T!=null&&(!T.collecting||z&&T.first_seen===null&&!T.first_seen_unavailable),R=!L&&T?.collecting===!0&&T.first_seen===null&&!T.first_seen_unavailable,$=T?.collecting===!0&&T.first_seen!==null&&T.first_seen_in_reports===!1,d=R||$,U=On({collecting:R||L?!1:T?.collecting,statusFailed:y.status.error!=null,identity:T?.analytics_id}),se=qe.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Q=qe.useMemo(()=>{let E=y.breakdowns.sources?.data,te={};if(!E||E.status!=="ok")return te;for(let S of E.data){let A=S.source,ue=S.sources;typeof A=="string"&&Array.isArray(ue)&&ue.length>0&&(te[A]=ue)}return te},[y.breakdowns.sources?.data]),oe=qe.useMemo(()=>{let E=(A,ue)=>{let Ve=y.breakdowns[A]?.data;return!Ve||Ve.status!=="ok"?[]:[...new Set(Ve.data.map(we=>we[ue]).filter(we=>typeof we=="string"&&we!==""))]};return{channel:y.channels.data?.status==="ok"?[...new Set(y.channels.data.data.map(A=>A.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")}},[y.breakdowns,y.channels.data]),[ne,J]=qe.useState({}),ee=JSON.stringify(oe),[de,q]=qe.useState(new Map),ve=JSON.stringify(Q);qe.useEffect(()=>{let{suggestions:E,folds:te}=co(se.current,{api:h,period:p},JSON.parse(ee),JSON.parse(ve));J(E),q(te)},[ee,ve,h,p]);let st=qe.useCallback((E,te)=>E!=="source"?te:[...new Set(te.flatMap(S=>{let A=[...de.get(S)??[],...Q[S]??[]];return A.length>0?A:[S]}))],[de,Q]),lt=qe.useMemo(()=>{let E=y.conversions.error;return E instanceof Ht&&E.details?.code==="goals_exceed_report_budget"?E.message:null},[y.conversions.error]),Re=qe.useMemo(()=>{let E=[y.summary,y.timeseries,y.channels,...Object.values(y.breakdowns)];for(let te of E){let S=te?.error;if(S instanceof Ht&&S.details?.code==="filter_unsupported")return S.message}return null},[y.summary,y.timeseries,y.channels,y.breakdowns]),xe=(E,te,S,A,ue,Ve,we,He,et)=>()=>{let ct=y.breakdowns[E];return he(_s,{sourced:ct?.data??null,error:ct?.error,isLoading:ct?.isLoading,what:te,collecting:T?.collecting,onRetry:y.refetch,children:Ut=>{let $t=ae=>He?st(He,[ae]):ae;return he(xr,{rows:Ut,dimension:S,metric:A,metricLabel:ue,secondary:Ve,emptyCopy:l.length>0?"No data for this filter":we,canFilter:He?(ae,Pe)=>N(He,$t(ae),et?{dimension:et,value:Pe}:void 0):()=>!1,onFilter:He?(ae,Pe)=>I(He,$t(ae),et?{dimension:et,value:Pe}:void 0):void 0})}})};qe.useEffect(()=>{if(!d)return;let E,te=()=>{E===void 0&&(E=setInterval(()=>void y.refetchStatus(),gd))},S=()=>{E!==void 0&&(clearInterval(E),E=void 0)},A=()=>{typeof document<"u"&&document.hidden?S():(y.refetchStatus(),te())};return(typeof document>"u"||!document.hidden)&&te(),document?.addEventListener("visibilitychange",A),()=>{S(),document?.removeEventListener("visibilitychange",A)}},[d,y.refetchStatus]);let vt=qe.useRef(void 0);if(qe.useEffect(()=>{if(!T){vt.current=void 0;return}let E=vt.current;vt.current=d,E===!0&&!d&&y.refetch()},[T,d,y.refetch]),L){let E=!!o&&String(o).slice(0,10)<vd;return he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),he("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:z?"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 R?he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),he("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."})]})}):$?he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),Mt("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",T?.timezone?` ${T.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),he("div",{className:"af-mt-4 af-flex af-justify-center",children:he(Nr,{currentVisitors:U.currentVisitors,asOf:U.asOf,isStale:U.isStale,isUnreachable:U.isUnreachable||U.error!==null,isInitialLoad:U.isInitialLoad})})]})}):he(Rt,{title:"Analytics",onBackToWebsite:t,className:n,children:Mt("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[Mt("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[he("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:bd.map(E=>he("button",{type:"button","aria-pressed":E.value===p,onClick:()=>m(E.value),className:E.value===p?"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))}),he(Nr,{currentVisitors:U.currentVisitors,asOf:U.asOf,isStale:U.isStale,isUnreachable:U.isUnreachable||U.error!==null,isInitialLoad:U.isInitialLoad,scopeIsSiteWide:l.length>0})]}),he(uo,{filters:l,onChange:b,suggestions:ne,expandValues:st,resetKey:h}),Re?Mt("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),he("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:Re}),he("button",{type:"button",onClick:()=>b([]),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,!Re&&T?.timezone_defaulted?he("p",{className:"af-text-xs af-text-muted-foreground",children:"Reports are shown in UTC. Set a timezone to see them in your local days."}):null,Re?null:Mt(Rr,{children:[he(_s,{sourced:y.summary.data,error:y.summary.error,isLoading:y.summary.isLoading,what:"The traffic summary",collecting:T?.collecting,onRetry:y.refetch,children:E=>Mt(Rr,{children:[he(fo,{summary:E,selected:O,onSelect:c}),E.previous_unavailable?Mt("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]})}),he("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:he(_s,{sourced:y.timeseries.data,error:y.timeseries.error,isLoading:y.timeseries.isLoading,what:"The visitors chart",collecting:T?.collecting,onRetry:y.refetch,children:E=>{let te=y.timeseries.data?.status==="ok"?y.timeseries.data.window:{from:"",to:""};return he(vo,{rows:E,window:te,metric:O,timeZone:(y.timeseries.data?.status==="ok"?y.timeseries.data.timezone:void 0)??T?.timezone??"UTC"})}})}),Mt("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[he(Vs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>he(_s,{sourced:y.channels.data,error:y.channels.error,isLoading:y.channels.isLoading,what:"Channels",collecting:T?.collecting,onRetry:y.refetch,children:E=>he(xr,{rows:E,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:l.length>0?"No data for this filter":"No data for this period",canFilter:te=>N("channel",te),onFilter:te=>I("channel",te)})})},{id:"sources",label:"Sources",render:xe("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:xe("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),he(Vs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:xe("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:xe("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:xe("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),he(Vs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:xe("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:xe("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:xe("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),he(Vs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:xe("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:xe("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:xe("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),Mt("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[he("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:he("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),Mt("div",{className:"af-px-3 af-py-2",children:[l.length>0?Mt("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",l.length===1?"filter":"filters"," above."]}):null,lt!==null?Mt("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[he("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),he("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:lt})]}):he(_s,{sourced:y.conversions.data,error:y.conversions.error,isLoading:y.conversions.isLoading,what:"Conversions",collecting:T?.collecting,onRetry:y.refetch,children:E=>{let te=y.conversions.data?.status==="ok"?y.conversions.data:null;return he(Rr,{children:he(go,{rows:E,denominator:te?.denominator??0,windowPrecedesCollection:te?.window_precedes_collection??!1,coverageUnknown:te?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}export{Ht as AifeaturesApiError,So as AifeaturesProvider,hd as AnalyticsView,bn as CustomerDetail,hn as CustomersList,an as FormSettings,Qs as FormSubmissions,Gr as FormsDashboard,Ws as FormsList,or as InvoiceDetail,Bs as InvoiceLabelBadge,bs as InvoicesList,Qi as InvoicesView,qi as LeadsView,Rs as MAX_ANALYTICS_FILTERS,Ps as MAX_ANALYTICS_FILTER_VALUES,mn as OrderDetail,rs as OrderStatusBadge,ps as OrdersList,ki as OrdersView,Pi as PaymentsDashboard,Sn as PaymentsSetup,ln as ProductSettings,rn as ProductsList,Fi as ProductsView,fs as PromosPanel,yr as REALTIME_FAILURES_BEFORE_ERROR,br as REALTIME_POLL_MS,lr as RetainerStatusBadge,ys as RetainersPanel,Zs as SubmissionDetail,Yi as SubscriptionsView,on as VariantsEditor,Rt as ViewShell,en as WebhookDeliveries,tn as WebhookSettings,ja as chargedTotal,Vn as createApiClient,H as formatPrice,ca as isZeroDecimalCurrency,dt as toMajorUnits,zt as toMinorUnits,ie as useAifeatures,ie as useAifeaturesContext,Ln as useAnalytics,_n as useBusinessSummary,vn as useCustomers,Xs as useEventDestinations,ds as useForms,gs as useInvoices,cn as useOrders,Za as usePaymentsStatus,En as usePeople,In as usePerson,hs as useProducts,On as useRealtimeVisitors,xs as useRetainers,Ys as useSubmissions,An as useSubscriptions};
|