@aifeatures/admin-react 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import*as Ha from"react";function Bs(e,a){let s=new URLSearchParams({period:String(e)});return a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var ya=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function En(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 In(e,a="https://aifeatures.dev"){async function s(t,n={}){let i=`${a}${t}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let f;try{f=await o.json()}catch{}throw new ya(En(f?.error,o.status),o.status,f)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(t){return s(`/api/v1/forms/${t}`)},async createForm(t){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(t)})},async updateForm(t,n){return s(`/api/v1/forms/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(t){await s(`/api/v1/forms/${t}`,{method:"DELETE"})},async getSubmissions(t,n={}){let i=new URLSearchParams;n.limit!==void 0&&i.set("limit",String(n.limit)),n.offset!==void 0&&i.set("offset",String(n.offset));let o=i.toString(),f=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(f)},async getSubmission(t){return s(`/api/v1/submissions/${t}`)},async deleteSubmission(t){await s(`/api/v1/submissions/${t}`,{method:"DELETE"})},async downloadAttachment(t,n){let i=typeof n=="string"?{name:n}:n,o=i.name,f=i.id??i.name,m=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(f)}`,v=await fetch(m,{headers:{Authorization:`Bearer ${e}`}});if(!v.ok){let u;try{u=await v.json()}catch{}throw new ya(En(u?.error,v.status),v.status,u)}let r=await v.blob(),p=URL.createObjectURL(r),y=document.createElement("a");y.href=p,y.download=o,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(p)},async getPaymentsStatus(){return s("/api/v1/payments/status")},async getProducts(t={}){let n=new URLSearchParams;t.include&&n.set("include",t.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(t){return s(`/api/v1/products/${t}`)},async createProduct(t){return s("/api/v1/products",{method:"POST",body:JSON.stringify(t)})},async updateProduct(t,n){return s(`/api/v1/products/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(t){await s(`/api/v1/products/${t}`,{method:"DELETE"})},async attachProductFile(t,n){let i=new FormData;i.append("file",n);let o=await fetch(`${a}/api/v1/products/${t}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let f;try{f=await o.json()}catch{}throw new ya(En(f?.error,o.status),o.status,f)}return o.json()},async attachProductFileFromUrl(t,n){return s(`/api/v1/products/${t}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(t,n){return s(`/api/v1/products/${t}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(t,n){return s(`/api/v1/options/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(t){await s(`/api/v1/options/${t}`,{method:"DELETE"})},async createVariant(t,n){return s(`/api/v1/products/${t}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(t,n){return s(`/api/v1/variants/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(t){await s(`/api/v1/variants/${t}`,{method:"DELETE"})},async setVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(t={}){let n=new URLSearchParams;t.email?n.set("email",t.email):t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(t){return s(`/api/v1/customers/${t}`)},async getOrders(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.source&&n.set("source",t.source),t.excludeStatus?.length&&n.set("exclude_status",t.excludeStatus.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.unfulfilledOnly&&n.set("unfulfilled_only","true"),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(t){return s(`/api/v1/orders/${t}`)},async getInvoices(t={}){let n=new URLSearchParams;t.labels?.length&&n.set("label",t.labels.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.customerId&&n.set("customer_id",t.customerId),t.q&&n.set("q",t.q),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.includeAggregates&&n.set("include","aggregates"),t.retainerId&&n.set("retainer_id",t.retainerId),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(t){return s(`/api/v1/invoices/${t}`)},async getInvoicePreview(t){return s(`/api/v1/invoices/${t}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(t={}){let n=new URLSearchParams;t.statuses?.length&&n.set("status",t.statuses.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(t){return s(`/api/v1/retainers/${t}`)},async resendOrderReceipt(t){await s(`/api/v1/orders/${t}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(t){return s(`/api/v1/orders/${t}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(t,n){return s(`/api/v1/orders/${t}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${Bs(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${Bs(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${Bs(t,n)}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${Bs(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 ws,jsxs as oo}from"react/jsx-runtime";var Nr=Ha.createContext(null);function ro(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 io({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Ha.useMemo(()=>ro(e),[e]),o=Ha.useMemo(()=>In(e,a),[e,a]),f=Ha.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?ws("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:oo("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[ws("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),ws("p",{className:"af-text-sm af-text-destructive",children:i})]})}):ws(Nr.Provider,{value:f,children:ws("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function ee(){let e=Ha.useContext(Nr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as qa from"react";import{ArrowLeft as cl,Settings as dl,Inbox as ul}from"lucide-react";import*as Fs from"react";import*as aa from"@radix-ui/react-tabs";import{clsx as lo}from"clsx";import{extendTailwindMerge as co}from"tailwind-merge";var uo=co({prefix:"af-"});function z(...e){return uo(lo(e))}import{jsx as An}from"react/jsx-runtime";var Ms=aa.Root,Ns=Fs.forwardRef(({className:e,...a},s)=>An(aa.List,{ref:s,className:z("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...a}));Ns.displayName=aa.List.displayName;var ha=Fs.forwardRef(({className:e,...a},s)=>An(aa.Trigger,{ref:s,className:z("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...a}));ha.displayName=aa.Trigger.displayName;var xa=Fs.forwardRef(({className:e,...a},s)=>An(aa.Content,{ref:s,className:z("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...a}));xa.displayName=aa.Content.displayName;import*as Sr from"react";import{Slot as fo}from"@radix-ui/react-slot";import{cva as mo}from"class-variance-authority";import{jsx as go}from"react/jsx-runtime";var po=mo("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),S=Sr.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>go(t?fo:"button",{className:z(po({variant:a,size:s,className:e})),ref:i,...n}));S.displayName="Button";import{Inbox as Rr,Settings as yo}from"lucide-react";import*as Oa from"react";import{jsx as La}from"react/jsx-runtime";var Ae=Oa.forwardRef(({className:e,...a},s)=>La("div",{className:"af-relative af-w-full af-overflow-auto",children:La("table",{ref:s,className:z("af-w-full af-caption-bottom af-text-sm",e),...a})}));Ae.displayName="Table";var De=Oa.forwardRef(({className:e,...a},s)=>La("thead",{ref:s,className:z("[&_tr]:af-border-b",e),...a}));De.displayName="TableHeader";var Le=Oa.forwardRef(({className:e,...a},s)=>La("tbody",{ref:s,className:z("[&_tr:last-child]:af-border-0",e),...a}));Le.displayName="TableBody";var vo=Oa.forwardRef(({className:e,...a},s)=>La("tfoot",{ref:s,className:z("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));vo.displayName="TableFooter";var pe=Oa.forwardRef(({className:e,...a},s)=>La("tr",{ref:s,className:z("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));pe.displayName="TableRow";var O=Oa.forwardRef(({className:e,...a},s)=>La("th",{ref:s,className:z("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));O.displayName="TableHead";var B=Oa.forwardRef(({className:e,...a},s)=>La("td",{ref:s,className:z("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));B.displayName="TableCell";var bo=Oa.forwardRef(({className:e,...a},s)=>La("caption",{ref:s,className:z("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));bo.displayName="TableCaption";import*as sa from"react";function ss(){let{api:e}=ee(),[a,s]=sa.useState([]),[t,n]=sa.useState(!0),[i,o]=sa.useState(null),f=sa.useCallback(async()=>{try{n(!0),o(null);let p=await e.getForms();s(p)}catch(p){o(p instanceof Error?p:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);sa.useEffect(()=>{f()},[f]);let m=sa.useCallback(async p=>{let y=await e.createForm(p);return s(u=>[...u,y]),y},[e]),v=sa.useCallback(async(p,y)=>{let u=await e.updateForm(p,y);return s(c=>c.map(d=>d.id===p?u:d)),u},[e]),r=sa.useCallback(async p=>{await e.deleteForm(p),s(y=>y.filter(u=>u.id!==p))},[e]);return{forms:a,isLoading:t,error:i,refetch:f,createForm:m,updateForm:v,deleteForm:r}}import{jsx as yt,jsxs as Ba}from"react/jsx-runtime";function Us({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=ss();return t?yt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:yt("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?yt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ba("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?Ba("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[yt(Rr,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ba("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",yt("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):yt("div",{className:a,children:Ba(Ae,{children:[yt(De,{children:Ba(pe,{children:[yt(O,{children:"Name"}),yt(O,{children:"Endpoint"}),yt(O,{className:"af-text-right",children:"Actions"})]})}),yt(Le,{children:s.map(i=>Ba(pe,{children:[yt(B,{className:"af-font-medium",children:i.name}),yt(B,{children:yt("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","")})}),yt(B,{className:"af-text-right",children:Ba("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ba(S,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[yt(Rr,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ba(S,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[yt(yo,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as No}from"lucide-react";import{cva as ho}from"class-variance-authority";import{jsx as wo}from"react/jsx-runtime";var xo=ho("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 Y({className:e,variant:a,...s}){return wo("div",{className:z(xo({variant:a}),e),...s})}import{jsx as Za,jsxs as Vs}from"react/jsx-runtime";var So={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 $s(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 Dn(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function Ro(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 Ss({deliveries:e,label:a="Email needs attention"}){return Dn(e)?Vs("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:[Za(No,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function wa({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||Dn([n]));return t.length?Za("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=$s(n),o=Ro(n);return Vs("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Vs("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Za("span",{className:"af-font-medium",children:So[n.kind]??"Email notification"}),Za(Y,{variant:i.variant,children:i.label})]}),Vs("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&Dn([n])&&Za("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&&Za("p",{className:"af-mt-1",children:i.detail}),o&&Za("p",{className:"af-mt-1",children:o})]},n.id)})}):null}import*as Rs from"react";import{ChevronLeft as Mo,ChevronRight as Uo,Eye as Vo,Inbox as $o,Paperclip as Ho}from"lucide-react";import*as za from"react";import*as we from"@radix-ui/react-select";import{Check as _o,ChevronDown as _r,ChevronUp as Po}from"lucide-react";import{jsx as St,jsxs as Ln}from"react/jsx-runtime";var Kt=we.Root;var Jt=we.Value,Ut=za.forwardRef(({className:e,children:a,...s},t)=>Ln(we.Trigger,{ref:t,className:z("af-flex af-h-9 af-w-full af-items-center af-justify-between af-whitespace-nowrap af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm af-ring-offset-background placeholder:af-text-muted-foreground focus:af-outline-none focus:af-ring-1 focus:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50 [&>span]:af-line-clamp-1",e),...s,children:[a,St(we.Icon,{asChild:!0,children:St(_r,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Ut.displayName=we.Trigger.displayName;var Pr=za.forwardRef(({className:e,...a},s)=>St(we.ScrollUpButton,{ref:s,className:z("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:St(Po,{className:"af-h-4 af-w-4"})}));Pr.displayName=we.ScrollUpButton.displayName;var Tr=za.forwardRef(({className:e,...a},s)=>St(we.ScrollDownButton,{ref:s,className:z("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:St(_r,{className:"af-h-4 af-w-4"})}));Tr.displayName=we.ScrollDownButton.displayName;var Vt=za.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>St(we.Portal,{children:Ln(we.Content,{ref:n,className:z("af-relative af-z-50 af-max-h-96 af-min-w-[8rem] af-overflow-hidden af-rounded-md af-border af-bg-popover af-text-popover-foreground af-shadow-md data-[state=open]:af-animate-in data-[state=closed]:af-animate-out data-[state=closed]:af-fade-out-0 data-[state=open]:af-fade-in-0 data-[state=closed]:af-zoom-out-95 data-[state=open]:af-zoom-in-95 data-[side=bottom]:af-slide-in-from-top-2 data-[side=left]:af-slide-in-from-right-2 data-[side=right]:af-slide-in-from-left-2 data-[side=top]:af-slide-in-from-bottom-2",s==="popper"&&"data-[side=bottom]:af-translate-y-1 data-[side=left]:af--translate-x-1 data-[side=right]:af-translate-x-1 data-[side=top]:af--translate-y-1",e),position:s,...t,children:[St(Pr,{}),St(we.Viewport,{className:z("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:a}),St(Tr,{})]})}));Vt.displayName=we.Content.displayName;var To=za.forwardRef(({className:e,...a},s)=>St(we.Label,{ref:s,className:z("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));To.displayName=we.Label.displayName;var Ve=za.forwardRef(({className:e,children:a,...s},t)=>Ln(we.Item,{ref:t,className:z("af-relative af-flex af-w-full af-cursor-default af-select-none af-items-center af-rounded-sm af-py-1.5 af-pl-2 af-pr-8 af-text-sm af-outline-none focus:af-bg-accent focus:af-text-accent-foreground data-[disabled]:af-pointer-events-none data-[disabled]:af-opacity-50",e),...s,children:[St("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:St(we.ItemIndicator,{children:St(_o,{className:"af-h-4 af-w-4"})})}),St(we.ItemText,{children:a})]}));Ve.displayName=we.Item.displayName;var Co=za.forwardRef(({className:e,...a},s)=>St(we.Separator,{ref:s,className:z("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));Co.displayName=we.Separator.displayName;import*as Yt from"react";function Hs({formId:e,initialPageSize:a=25}){let{api:s}=ee(),[t,n]=Yt.useState([]),[i,o]=Yt.useState(0),[f,m]=Yt.useState(!0),[v,r]=Yt.useState(null),[p,y]=Yt.useState(0),[u,c]=Yt.useState(a),d=Yt.useCallback(async()=>{if(e)try{m(!0),r(null);let _={limit:u,offset:p*u},D=await s.getSubmissions(e,_);n(D.submissions),o(D.total)}catch(_){r(_ instanceof Error?_:new Error("Failed to fetch submissions"))}finally{m(!1)}},[s,e,p,u]);Yt.useEffect(()=>{d()},[d]);let b=Yt.useCallback(async _=>{await s.deleteSubmission(_),n(D=>D.filter(U=>U.id!==_)),o(D=>D-1)},[s]),h=Math.ceil(i/u);return{submissions:t,total:i,isLoading:f,error:v,page:p,pageSize:u,hasNextPage:p<h-1,hasPreviousPage:p>0,setPage:y,setPageSize:_=>{c(_),y(0)},refetch:d,deleteSubmission:b}}import*as kr from"react";import{ArrowLeft as ko,Download as Eo,Globe as Io,Clock as Ao,FileText as Do,Loader2 as Lo,Monitor as Oo,Mail as Bo}from"lucide-react";import{jsx as at,jsxs as st}from"react/jsx-runtime";function Cr(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Fo(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}=ee(),[t,n]=kr.useState(null),i=m=>m.id??m.name,o=async m=>{n(i(m));try{await s.downloadAttachment(e.id,m)}catch(v){console.error("Download failed:",v)}finally{n(null)}},f=Object.entries(e.data).filter(([m])=>!m.startsWith("_"));return st("div",{children:[st("div",{className:"af-mb-6",children:[st(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[at(ko,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),at("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),st("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Cr(e.metadata.submitted_at)]})]}),st("div",{className:"af-space-y-6",children:[at(wa,{deliveries:e.email_deliveries}),st("div",{children:[at("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),st("div",{className:"af-space-y-3",children:[f.map(([m,v])=>st("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[at("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:m.replace(/_/g," ")}),at("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof v=="string"&&v.includes(`
3
- `)?at("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:v}):String(v)})]},m)),f.length===0&&at("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&st("div",{children:[at("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),at("div",{className:"af-space-y-2",children:e.attachments.map((m,v)=>st("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[st("div",{className:"af-flex af-items-center af-gap-2",children:[at(Do,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),at("span",{className:"af-text-sm",children:m.name}),st("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Fo(m.size),")"]})]}),st(S,{variant:"ghost",size:"sm",onClick:()=>o(m),disabled:t===i(m),children:[t===i(m)?at(Lo,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):at(Eo,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(m)?"Downloading...":"Download"]})]},v))})]}),st("div",{children:[at("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),st("div",{className:"af-space-y-2 af-text-sm",children:[st("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[at(Ao,{className:"af-h-4 af-w-4"}),at("span",{children:Cr(e.metadata.submitted_at)})]}),e.metadata.ip_address&&st("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[at(Io,{className:"af-h-4 af-w-4"}),st("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&st("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[at(Oo,{className:"af-h-4 af-w-4 af-mt-0.5"}),at("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&st("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[at(Bo,{className:"af-h-4 af-w-4"}),st("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as _e,jsxs as pt}from"react/jsx-runtime";function zo(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qo(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 jo(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:f,pageSize:m,hasNextPage:v,hasPreviousPage:r,setPage:p,setPageSize:y}=Hs({formId:e}),[u,c]=Rs.useState("list"),[d,b]=Rs.useState(null);Rs.useEffect(()=>{if(s&&t.length>0){let l=t.find(x=>x.id===s);l&&(b(l),c("detail"))}},[s,t]);let h=l=>{b(l),c("detail")},_=()=>{c("list"),b(null)};if(u==="detail"&&d)return _e("div",{className:a,children:_e(zs,{submission:d,onBack:_})});if(i)return _e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:_e("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return _e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:pt("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&f===0)return pt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[_e($o,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),pt("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",_e("br",{}),"Submissions will appear here when visitors use your form."]})]});let D=f*m+1,U=Math.min((f+1)*m,n);return pt("div",{className:a,children:[pt(Ae,{children:[_e(De,{children:pt(pe,{children:[_e(O,{children:"Email"}),_e(O,{children:"Preview"}),_e(O,{children:"Date"}),_e(O,{className:"af-text-right",children:"Actions"})]})}),_e(Le,{children:t.map(l=>{let x=qo(l.data),C=jo(l.data);return pt(pe,{children:[pt(B,{className:"af-font-medium",children:[pt("div",{className:"af-flex af-items-center af-gap-2",children:[x||_e("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),l.attachments.length>0&&pt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${l.attachments.length} attachment(s)`,children:[_e(Ho,{className:"af-h-3 af-w-3"}),_e("span",{className:"af-text-xs",children:l.attachments.length})]})]}),_e(Ss,{deliveries:l.email_deliveries,label:"Notification email needs attention"})]}),_e(B,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:C||_e("span",{className:"af-italic",children:"No preview available"})}),_e(B,{className:"af-text-muted-foreground",children:zo(l.metadata.submitted_at)}),_e(B,{className:"af-text-right",children:_e(S,{variant:"ghost",size:"icon",onClick:()=>h(l),title:"View details",children:_e(Vo,{className:"af-h-4 af-w-4"})})})]},l.id)})})]}),pt("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[pt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[pt("span",{children:["Showing ",D,"-",U," of ",n]}),pt(Kt,{value:String(m),onValueChange:l=>y(Number(l)),children:[_e(Ut,{className:"af-w-[70px] af-h-8",children:_e(Jt,{})}),pt(Vt,{children:[_e(Ve,{value:"10",children:"10"}),_e(Ve,{value:"25",children:"25"}),_e(Ve,{value:"50",children:"50"}),_e(Ve,{value:"100",children:"100"})]})]}),_e("span",{children:"per page"})]}),pt("div",{className:"af-flex af-items-center af-gap-2",children:[pt(S,{variant:"outline",size:"sm",onClick:()=>p(f-1),disabled:!r,children:[_e(Mo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),pt(S,{variant:"outline",size:"sm",onClick:()=>p(f+1),disabled:!v,children:["Next",_e(Uo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ht from"react";import{Plus as rl,X as il,Loader2 as ol,Check as ll}from"lucide-react";import*as Er from"react";import{jsx as Go}from"react/jsx-runtime";var ve=Er.forwardRef(({className:e,type:a,...s},t)=>Go("input",{type:a,className:z("af-flex af-h-9 af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-1 af-text-sm af-shadow-sm af-transition-colors file:af-border-0 file:af-bg-transparent file:af-text-sm file:af-font-medium file:af-text-foreground placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-cursor-not-allowed disabled:af-opacity-50",e),ref:t,...s}));ve.displayName="Input";import*as Ir from"react";import{cva as Wo}from"class-variance-authority";import{jsx as Jo}from"react/jsx-runtime";var Ko=Wo("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),be=Ir.forwardRef(({className:e,...a},s)=>Jo("label",{ref:s,className:z(Ko(),e),...a}));be.displayName="Label";import*as Qt from"react";import{Plus as Xo,Loader2 as Bn,Copy as el,Check as tl,Trash2 as al,RefreshCw as sl,AlertTriangle as nl}from"lucide-react";import*as _s from"react";import*as ft from"@radix-ui/react-dialog";import{X as Yo}from"lucide-react";import{jsx as Fa,jsxs as On}from"react/jsx-runtime";var Na=ft.Root;var Zo=ft.Portal;var Ar=_s.forwardRef(({className:e,...a},s)=>Fa(ft.Overlay,{ref:s,className:z("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));Ar.displayName=ft.Overlay.displayName;var na=_s.forwardRef(({className:e,children:a,...s},t)=>Fa(Zo,{children:On("div",{className:"aifeatures-admin",children:[Fa(Ar,{}),On(ft.Content,{ref:t,className:z("aifeatures-dialog-content af-fixed af-left-[50%] af-top-[50%] af-z-50 af-grid af-w-full af-max-w-lg af-translate-x-[-50%] af-translate-y-[-50%] af-gap-4 af-border af-bg-background af-p-6 af-shadow-lg sm:af-rounded-lg",e),...s,children:[a,On(ft.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:[Fa(Yo,{className:"af-h-4 af-w-4"}),Fa("span",{className:"af-sr-only",children:"Close"})]})]})]})}));na.displayName=ft.Content.displayName;var ra=({className:e,...a})=>Fa("div",{className:z("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});ra.displayName="DialogHeader";var ia=({className:e,...a})=>Fa("div",{className:z("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});ia.displayName="DialogFooter";var oa=_s.forwardRef(({className:e,...a},s)=>Fa(ft.Title,{ref:s,className:z("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));oa.displayName=ft.Title.displayName;var la=_s.forwardRef(({className:e,...a},s)=>Fa(ft.Description,{ref:s,className:z("af-text-sm af-text-muted-foreground",e),...a}));la.displayName=ft.Description.displayName;import*as $t from"react";function js(){let{api:e}=ee(),[a,s]=$t.useState([]),[t,n]=$t.useState(!0),[i,o]=$t.useState(null),f=$t.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(u){o(u instanceof Error?u:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);$t.useEffect(()=>{f()},[f]);let m=$t.useCallback(async u=>{let c=await e.createEventDestination(u);return s(d=>[c,...d]),c},[e]),v=$t.useCallback(async(u,c)=>{let d=await e.updateEventDestination(u,c);return s(b=>b.map(h=>h.id===u?d:h)),d},[e]),r=$t.useCallback(async u=>{await e.deleteEventDestination(u),s(c=>c.filter(d=>d.id!==u))},[e]),p=$t.useCallback(async u=>{let c=await e.rotateEventDestinationSecret(u);return s(d=>d.map(b=>b.id===u?c:b)),c},[e]),y=$t.useCallback(u=>e.getEventDestinationSecret(u),[e]);return{destinations:a,isLoading:t,error:i,refetch:f,createDestination:m,updateDestination:v,deleteDestination:r,rotateSecret:p,getSecret:y}}import*as Ma from"react";import{Loader2 as Dr,RotateCw as Qo}from"lucide-react";import{jsx as Zt,jsxs as Ps}from"react/jsx-runtime";function Gs({destinationId:e,limit:a=25,className:s}){let{api:t}=ee(),[n,i]=Ma.useState([]),[o,f]=Ma.useState(!0),[m,v]=Ma.useState(null),[r,p]=Ma.useState(null),y=Ma.useCallback(async()=>{try{f(!0),v(null),i(await t.getEventDeliveries(e,a))}catch(c){v(c instanceof Error?c.message:"Failed to load deliveries")}finally{f(!1)}},[t,e,a]);Ma.useEffect(()=>{y()},[y]);let u=async c=>{try{p(c.id),v(null);let d=await t.retryEventDelivery(e,c.id);i(b=>b.map(h=>h.id===c.id?d:h))}catch(d){v(d instanceof Error?d.message:"Retry failed")}finally{p(null)}};return o?Ps("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[Zt(Dr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):m?Zt("div",{className:"af-text-sm af-text-destructive af-py-2",children:m}):n.length===0?Zt("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):Zt("div",{className:s,children:Zt("div",{className:"af-divide-y af-border af-rounded",children:n.map(c=>{let d=c.delivered_at!==null;return Ps("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ps("div",{className:"af-min-w-0",children:[Ps("div",{className:"af-flex af-items-center af-gap-2",children:[d?Zt(Y,{variant:"secondary",children:c.last_status??200}):Zt(Y,{variant:"destructive",children:c.last_status??"failed"}),Zt("span",{className:"af-text-sm af-truncate",children:c.type})]}),Ps("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[c.event_id," \xB7 ",c.created_at,c.attempts>0&&` \xB7 ${c.attempts} failed ${c.attempts===1?"attempt":"attempts"}`]}),!d&&c.last_error&&Zt("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),Zt(S,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===c.id,onClick:()=>u(c),children:r===c.id?Zt(Dr,{className:"af-h-4 af-w-4 af-animate-spin"}):Zt(Qo,{className:"af-h-4 af-w-4"})})]},c.id)})})})}import{jsx as Pe,jsxs as ot}from"react/jsx-runtime";function Ws({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:f,updateDestination:m,deleteDestination:v,rotateSecret:r,getSecret:p}=js(),[y,u]=Qt.useState(""),[c,d]=Qt.useState(!1),[b,h]=Qt.useState(null),[_,D]=Qt.useState(null),[U,l]=Qt.useState(null),[x,C]=Qt.useState(!1),[G,L]=Qt.useState(null),[w,M]=Qt.useState(null),[g,Z]=Qt.useState(null),ie=Qt.useMemo(()=>n.filter(q=>q.form_id===e),[n,e]),oe=async()=>{let q=y.trim();if(q){if(!q.startsWith("https://")){h("Webhook URLs must start with https://");return}try{d(!0),h(null),await f({url:q,form_id:e,...a&&a.length>0?{topics:a}:{}}),u("")}catch(he){h(he instanceof Error?he.message:"Failed to add webhook")}finally{d(!1)}}},X=async q=>{try{M(q.id),h(null),await r(q.id),C(!1),l(await p(q.id))}catch(he){h(he instanceof Error?he.message:"Failed to rotate secret")}finally{M(null)}},ye=async q=>{try{M(q.id),h(null),await m(q.id,{status:"active"})}catch(he){h(he instanceof Error?he.message:"Failed to re-enable")}finally{M(null)}},W=async()=>{if(G)try{M(G.id),await v(G.id),L(null)}catch(q){h(q instanceof Error?q.message:"Failed to delete")}finally{M(null)}},re=async q=>{if(_===q.id){D(null),l(null);return}try{M(q.id),h(null),C(!1),D(q.id),l(await p(q.id))}catch(he){D(null),h(he instanceof Error?he.message:"Failed to read secret")}finally{M(null)}},ce=async()=>{if(U)try{await navigator.clipboard.writeText(U),C(!0)}catch{}};return ot("div",{className:t,children:[ot("div",{className:"af-space-y-1",children:[Pe(be,{children:"Webhooks"}),Pe("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."})]}),ot("div",{className:"af-flex af-gap-2 af-mt-4",children:[Pe(ve,{value:y,placeholder:"https://hooks.zapier.com/...",onChange:q=>u(q.target.value),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),oe())},disabled:c}),ot(S,{onClick:oe,disabled:c||!y.trim(),children:[c?Pe(Bn,{className:"af-h-4 af-w-4 af-animate-spin"}):Pe(Xo,{className:"af-h-4 af-w-4"}),Pe("span",{className:"af-ml-1",children:"Add"})]})]}),(b||o)&&Pe("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:b||o?.message}),ot("div",{className:"af-mt-4 af-space-y-2",children:[i&&ot("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Pe(Bn,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&ie.length===0&&Pe("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),ie.map(q=>ot("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[ot("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[ot("div",{className:"af-min-w-0",children:[ot("div",{className:"af-flex af-items-center af-gap-2",children:[Pe("span",{className:"af-font-mono af-text-sm af-truncate",children:q.url}),q.status==="disabled"?Pe(Y,{variant:"destructive",children:"Disabled"}):Pe(Y,{variant:"secondary",children:"Active"})]}),Pe("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:q.topics.includes("*")?"All events":q.topics.join(", ")})]}),ot("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[Pe(S,{variant:"ghost",size:"sm",onClick:()=>Z(g===q.id?null:q.id),children:g===q.id?"Hide log":"Deliveries"}),Pe(S,{variant:"ghost",size:"sm",onClick:()=>re(q),disabled:w===q.id,children:_===q.id?"Hide secret":"Show secret"}),Pe(S,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:w===q.id,onClick:()=>L(q),children:Pe(al,{className:"af-h-4 af-w-4"})})]})]}),q.status==="disabled"&&ot("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[Pe(nl,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),ot("div",{className:"af-text-sm",children:[ot("p",{children:["We stopped sending after repeated failures."," ",q.disabled_reason]}),Pe(S,{variant:"outline",size:"sm",className:"af-mt-2",disabled:w===q.id,onClick:()=>ye(q),children:"Re-enable"})]})]}),_===q.id&&U&&ot("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Pe("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."}),ot("div",{className:"af-flex af-gap-2",children:[Pe(ve,{readOnly:!0,value:U,className:"af-font-mono"}),Pe(S,{variant:"outline",title:"Copy signing secret",onClick:ce,children:x?Pe(tl,{className:"af-h-4 af-w-4"}):Pe(el,{className:"af-h-4 af-w-4"})}),Pe(S,{variant:"outline",title:"Rotate signing secret",disabled:w===q.id,onClick:()=>X(q),children:w===q.id?Pe(Bn,{className:"af-h-4 af-w-4 af-animate-spin"}):Pe(sl,{className:"af-h-4 af-w-4"})})]})]}),g===q.id&&Pe(Gs,{destinationId:q.id})]},q.id))]}),Pe(Na,{open:!!G,onOpenChange:q=>{!q&&!w&&L(null)},children:ot(na,{children:[ot(ra,{children:[Pe(oa,{children:"Delete this webhook?"}),ot(la,{children:["New submissions will stop being sent to ",G?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),ot(ia,{children:[Pe(S,{variant:"outline",onClick:()=>L(null),disabled:!!w,children:"Cancel"}),Pe(S,{variant:"destructive",onClick:W,disabled:!!w,children:w?"Deleting...":"Delete"})]})]})})]})}import{jsx as Ee,jsxs as ca}from"react/jsx-runtime";function Ks({form:e,onSaved:a,className:s}){let{updateForm:t}=ss(),[n,i]=Ht.useState(!1),[o,f]=Ht.useState(null),[m,v]=Ht.useState(null),[r,p]=Ht.useState(e.name),[y,u]=Ht.useState(e.redirect_url||""),[c,d]=Ht.useState(e.email_recipients),[b,h]=Ht.useState("");Ht.useEffect(()=>{p(e.name),u(e.redirect_url||""),d(e.email_recipients),v(null)},[e]);let _=Ht.useCallback(async C=>{try{i(!0),v(null);let G=await t(e.id,C);f(new Date),a?.(G)}catch(G){v(G instanceof Error?G.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);Ht.useEffect(()=>{if(o){let C=setTimeout(()=>f(null),2e3);return()=>clearTimeout(C)}},[o]);let D=async()=>{let C=b.trim().toLowerCase();if(!C)return;if(!C.includes("@")){v("Please enter a valid email address");return}if(c.includes(C)){v("This email is already added");return}let G=[...c,C];d(G),h(""),v(null),await _({email_recipients:G})},U=async C=>{let G=c.filter(L=>L!==C);d(G),await _({email_recipients:G})},l=async()=>{r!==e.name&&await _({name:r})},x=async()=>{let C=y||null;C!==e.redirect_url&&await _({redirect_url:C})};return ca("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&Ee("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?ca("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:[Ee(ol,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),Ee("span",{className:"af-text-sm",children:"Saving..."})]}):ca("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:[Ee(ll,{className:"af-h-4 af-w-4 af-text-green-600"}),Ee("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),ca("div",{className:"af-space-y-2",children:[Ee(be,{htmlFor:"form-name",children:"Form Name"}),Ee(ve,{id:"form-name",value:r,onChange:C=>p(C.target.value),onBlur:l,placeholder:"Contact Form"}),Ee("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),ca("div",{className:"af-space-y-2",children:[Ee(be,{children:"Email Recipients"}),Ee("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),ca("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(C=>ca(Y,{variant:"secondary",className:"af-gap-1",children:[C,Ee("button",{type:"button",onClick:()=>U(C),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:Ee(il,{className:"af-h-3 af-w-3"})})]},C)),c.length===0&&Ee("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),ca("div",{className:"af-flex af-gap-2",children:[Ee(ve,{type:"email",value:b,onChange:C=>h(C.target.value),placeholder:"Add email address",onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),D())},disabled:n}),Ee(S,{type:"button",variant:"outline",onClick:D,disabled:!b.trim()||n,children:Ee(rl,{className:"af-h-4 af-w-4"})})]})]}),ca("div",{className:"af-space-y-2",children:[Ee(be,{htmlFor:"redirect-url",children:"Redirect URL"}),Ee(ve,{id:"redirect-url",value:y,onChange:C=>u(C.target.value),onBlur:x,placeholder:"/thank-you"}),Ee("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."})]}),ca("div",{className:"af-space-y-2",children:[Ee(be,{children:"Form Endpoint"}),Ee("div",{className:"af-flex af-items-center af-gap-2",children:Ee("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})}),Ee("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),ca("div",{className:"af-space-y-2",children:[Ee(be,{children:"Captcha Protection"}),Ee("div",{className:"af-flex af-items-center af-gap-2",children:Ee(Y,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),Ee("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),Ee(Ws,{formId:e.id}),m&&Ee("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m})]})}import{jsx as _t,jsxs as Sa}from"react/jsx-runtime";function Lr({className:e,submissionId:a}){let{api:s}=ee(),[t,n]=qa.useState("list"),[i,o]=qa.useState(null),[f,m]=qa.useState("submissions"),[v,r]=qa.useState(a),[p,y]=qa.useState(!!a);qa.useEffect(()=>{if(!a)return;async function b(){try{let h=await s.getSubmission(a),_=await s.getForm(h.form_id);o(_),n("detail"),m("submissions"),r(a)}catch(h){console.error("Failed to load submission for deep link:",h)}finally{y(!1)}}b()},[a,s]);let u=(b,h)=>{o(b),n("detail"),m(h),r(void 0)},c=()=>{n("list"),o(null),r(void 0)},d=b=>{o(b)};return p?_t("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:_t("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Sa("div",{className:e,children:[t==="list"&&Sa("div",{children:[Sa("div",{className:"af-mb-6",children:[_t("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),_t("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),_t(Us,{onSelectForm:u})]}),t==="detail"&&i&&Sa("div",{children:[Sa("div",{className:"af-mb-6",children:[Sa(S,{variant:"ghost",size:"sm",onClick:c,className:"af-mb-2 af--ml-2",children:[_t(cl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),_t("h2",{className:"af-text-lg af-font-semibold",children:i.name}),_t("p",{className:"af-text-sm af-text-muted-foreground",children:_t("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Sa(Ms,{value:f,onValueChange:b=>m(b),children:[Sa(Ns,{className:"af-mb-4",children:[Sa(ha,{value:"submissions",className:"af-gap-2",children:[_t(ul,{className:"af-h-4 af-w-4"}),"Submissions"]}),Sa(ha,{value:"settings",className:"af-gap-2",children:[_t(dl,{className:"af-h-4 af-w-4"}),"Settings"]})]}),_t(xa,{value:"submissions",children:_t(qs,{formId:i.id,defaultSubmissionId:v})}),_t(xa,{value:"settings",children:_t(Ks,{form:i,onSaved:d})})]})]})]})}import*as ms from"react";import{ArrowLeft as Lc,FileText as Oc,Package as Bc,Receipt as Fc,Settings as Mc,Users as Uc}from"lucide-react";import*as Js from"react";import{Package as ml,Pencil as pl,Plus as Or,Trash2 as gl}from"lucide-react";var fl=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Ra(e){return fl.has(e.toLowerCase())}function j(e,a,s){let t=Ra(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function da(e){let a=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+a}function ua(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=Ra(a)?s:s*100;return Math.round(t)}function ht(e,a){return Ra(a)?e:e/100}import{jsx as Oe,jsxs as Rt}from"react/jsx-runtime";function vl(e){if(e.allow_custom_amount){let a=e.min_amount!==null?j(e.min_amount,e.currency):"?",s=e.max_amount!==null?j(e.max_amount,e.currency):"?";return`Buyer chooses (${a} - ${s})`}return e.unit_amount===null?"Varies by variant":j(e.unit_amount,e.currency)}function bl(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Ys({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:f}=e,[m,v]=Js.useState(null),[r,p]=Js.useState(!1),[y,u]=Js.useState(null),c=async()=>{if(m)try{p(!0),u(null),await f(m.id),v(null)}catch(d){u(d instanceof Error?d.message:"Failed to delete product")}finally{p(!1)}};return i?Oe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Oe("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?Oe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Rt("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?Rt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Oe(ml,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Rt("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",Oe("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),Rt(S,{variant:"outline",onClick:()=>s?.(),children:[Oe(Or,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):Rt("div",{className:t,children:[Oe("div",{className:"af-flex af-justify-end af-mb-4",children:Rt(S,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Oe(Or,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),Rt(Ae,{children:[Oe(De,{children:Rt(pe,{children:[Oe(O,{children:"Name"}),Oe(O,{children:"Price"}),Oe(O,{children:"Fulfillment"}),Oe(O,{children:"Status"}),Oe(O,{className:"af-text-right",children:"Actions"})]})}),Oe(Le,{children:n.map(d=>Rt(pe,{children:[Oe(B,{className:"af-font-medium",children:d.name}),Oe(B,{children:vl(d)}),Oe(B,{className:"af-text-muted-foreground",children:bl(d)}),Oe(B,{children:Oe(Y,{variant:d.active?"success":"secondary",children:d.active?"Active":"Inactive"})}),Oe(B,{className:"af-text-right",children:Rt("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Rt(S,{variant:"ghost",size:"sm",onClick:()=>a?.(d),children:[Oe(pl,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),Rt(S,{variant:"ghost",size:"sm",onClick:()=>{u(null),v(d)},children:[Oe(gl,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},d.id))})]}),Oe(Na,{open:!!m,onOpenChange:d=>{!d&&!r&&v(null)},children:Rt(na,{children:[Rt(ra,{children:[Oe(oa,{children:"Delete product?"}),Rt(la,{children:['"',m?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),y&&Oe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y}),Rt(ia,{children:[Oe(S,{variant:"outline",onClick:()=>v(null),disabled:r,children:"Cancel"}),Oe(S,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as He from"react";import{FileText as hl,Link2 as xl,Loader2 as Mr,Plus as wl,Upload as Nl,X as Sl}from"lucide-react";import*as lt from"react";import{Loader2 as Br,Plus as Fn,Trash2 as Fr,X as yl}from"lucide-react";import{jsx as $,jsxs as ue}from"react/jsx-runtime";function Mn(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function Zs({productId:e,currency:a,className:s}){let{api:t}=ee(),n=Ra(a)?"1":"0.01",[i,o]=lt.useState(null),[f,m]=lt.useState(!0),[v,r]=lt.useState(null),[p,y]=lt.useState(null),[u,c]=lt.useState(!1),d=lt.useRef(!0);lt.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);let b=lt.useCallback(async()=>{try{let T=await t.getProduct(e);if(!d.current)return;o(T)}catch(T){if(!d.current)return;r(T instanceof Error?T.message:"Failed to load product")}finally{d.current&&m(!1)}},[t,e]);lt.useEffect(()=>{b()},[b]);let h=async T=>{y(null),c(!0);try{await T(),await b()}catch(A){d.current&&y(A instanceof Error?A.message:"Something went wrong")}finally{d.current&&c(!1)}},[_,D]=lt.useState(""),[U,l]=lt.useState(""),[x,C]=lt.useState({}),G=()=>h(async()=>{let T=_.trim(),A=U.split(",").map(me=>me.trim()).filter(Boolean);if(!T)throw new Error("Option name is required");if(A.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:T,values:A}),d.current&&(D(""),l(""))}),L=T=>h(async()=>{let A=(x[T.id]??"").trim();if(!A)throw new Error("Enter a value");await t.updateOption(T.id,{add_values:[A]}),d.current&&C(me=>({...me,[T.id]:""}))}),w=(T,A)=>h(()=>t.updateOption(T.id,{remove_values:[A]})),M=T=>h(()=>t.deleteOption(T.id)),[g,Z]=lt.useState(null),[ie,oe]=lt.useState(null),[X,ye]=lt.useState(!1),[W,re]=lt.useState(null),ce=i?.options??[],q=i?.variants??[],he=()=>{oe(null),Z({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ce.map(T=>[T.id,T.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Be=T=>{oe(null);let A=T.inventory?.on_hand??0,me=A<0?"":String(A);Z({variant:T,title:T.title??"",sku:T.sku??"",unitAmount:T.unit_amount!=null?String(ht(T.unit_amount,a)):"",compareAt:T.compare_at_amount!=null?String(ht(T.compare_at_amount,a)):"",active:T.active,optionValues:{},tracked:T.inventory?.tracked??!1,onHand:me,initialOnHand:me,allowBackorder:T.inventory?.allow_backorder??!1})},Nt=async()=>{if(!g)return;oe(null);let T=g.variant?.allow_custom_amount??!1,A=null,me=null;if(!T){if(A=ua(g.unitAmount,a),A===null||A<=0){oe("Enter a valid price");return}if(g.compareAt.trim()&&(me=ua(g.compareAt,a),me===null||me<=A)){oe("Compare-at price must be greater than the price");return}}let We=g.onHand.trim()!==g.initialOnHand.trim(),Ue=parseInt(g.onHand,10);if(g.tracked&&We&&(!Number.isFinite(Ue)||Ue<0)){oe("On-hand quantity must be zero or more");return}try{if(ye(!0),g.variant)await t.updateVariant(g.variant.id,{title:g.title.trim()||null,sku:g.sku.trim()||null,...T?{}:{unit_amount:A,compare_at_amount:me},active:g.active}),await t.setVariantInventory(g.variant.id,{tracked:g.tracked,on_hand:g.tracked&&We?Ue:void 0,allow_backorder:g.allowBackorder});else{let et={};for(let Ke of ce){let tt=g.optionValues[Ke.id];if(!tt){oe(`Choose a ${Ke.title}`),ye(!1);return}et[Ke.title]=tt}await t.createVariant(e,{title:g.title.trim()||null,sku:g.sku.trim()||null,unit_amount:A,compare_at_amount:me,active:g.active,option_values:ce.length>0?et:void 0,inventory:g.tracked?{tracked:!0,on_hand:Ue,allow_backorder:g.allowBackorder}:{tracked:!1,allow_backorder:g.allowBackorder}})}await b(),d.current&&Z(null)}catch(et){if(d.current&&oe(et instanceof Error?et.message:"Failed to save variant"),g.variant)try{let Ke=await t.getProduct(e);d.current&&o(Ke)}catch{}}finally{d.current&&ye(!1)}},V=()=>h(async()=>{W&&(await t.deleteVariant(W.id),d.current&&re(null))}),de=g?.variant?.allow_custom_amount??!1,ge=g?.variant!=null&&g.variant.option_values.length===0&&ce.length>0&&!g.variant.active,le=g?.variant?.inventory!=null&&g.variant.inventory.on_hand<0?-g.variant.inventory.on_hand:null;function Fe(T){let A=T.inventory;if(!A||!A.tracked)return $("span",{className:"af-text-muted-foreground",children:"Unlimited"});let me=A.available??A.on_hand;return me<0?ue("span",{children:[-me," backordered"]}):ue("span",{children:[me," in stock",A.allow_backorder&&$("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return f?$("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:$(Br,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):v?$("div",{className:s,children:$("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v})}):ue("div",{className:`af-space-y-6 ${s||""}`,children:[ue("div",{className:"af-space-y-3",children:[ue("div",{children:[$(be,{children:"Options"}),$("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."})]}),ce.length>0&&$("div",{className:"af-space-y-3",children:ce.map(T=>ue("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[ue("div",{className:"af-flex af-items-center af-justify-between",children:[$("span",{className:"af-text-sm af-font-medium",children:T.title}),$(S,{variant:"ghost",size:"sm",onClick:()=>M(T),disabled:u,children:$(Fr,{className:"af-h-4 af-w-4"})})]}),$("div",{className:"af-flex af-flex-wrap af-gap-2",children:T.values.map(A=>ue(Y,{variant:"secondary",className:"af-gap-1",children:[A.value,$("button",{type:"button",onClick:()=>w(T,A.value),className:"af-ml-1 hover:af-text-destructive",disabled:u,title:"Remove value",children:$(yl,{className:"af-h-3 af-w-3"})})]},A.id))}),ue("div",{className:"af-flex af-gap-2",children:[$(ve,{value:x[T.id]??"",onChange:A=>C(me=>({...me,[T.id]:A.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),L(T))},disabled:u}),$(S,{type:"button",variant:"outline",size:"sm",onClick:()=>L(T),disabled:u||!(x[T.id]??"").trim(),children:$(Fn,{className:"af-h-4 af-w-4"})})]})]},T.id))}),ue("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[ue("div",{className:"af-space-y-1",children:[$(be,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),$(ve,{id:"new-option-title",value:_,onChange:T=>D(T.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:u})]}),ue("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[$(be,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),$(ve,{id:"new-option-values",value:U,onChange:T=>l(T.target.value),placeholder:"S, M, L",disabled:u})]}),ue(S,{type:"button",variant:"outline",onClick:G,disabled:u||!_.trim()||!U.trim(),children:[$(Fn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),ue("div",{className:"af-space-y-3",children:[ue("div",{className:"af-flex af-items-center af-justify-between",children:[$(be,{children:"Variants"}),ue(S,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:u||ce.length===0,children:[$(Fn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ce.length===0&&$("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),q.length===0?$("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):ue(Ae,{children:[$(De,{children:ue(pe,{children:[$(O,{children:"Variant"}),$(O,{children:"SKU"}),$(O,{children:"Price"}),$(O,{children:"Stock"}),$(O,{children:"Status"}),$(O,{className:"af-text-right",children:"Actions"})]})}),$(Le,{children:q.map(T=>ue(pe,{children:[$(B,{className:"af-font-medium",children:Mn(T)}),$(B,{className:"af-text-muted-foreground",children:T.sku||"-"}),$(B,{children:T.unit_amount!=null?ue("span",{children:[T.compare_at_amount!=null&&$("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(T.compare_at_amount,T.currency)}),j(T.unit_amount,T.currency)]}):T.allow_custom_amount?$("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),$(B,{children:Fe(T)}),$(B,{children:$(Y,{variant:T.active?"success":"secondary",children:T.active?"Active":"Inactive"})}),$(B,{className:"af-text-right",children:ue("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[$(S,{variant:"ghost",size:"sm",onClick:()=>Be(T),disabled:u,children:"Edit"}),$(S,{variant:"ghost",size:"icon",onClick:()=>re(T),disabled:u,title:"Delete variant",children:$(Fr,{className:"af-h-4 af-w-4"})})]})})]},T.id))})]})]}),p&&$("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:p}),$(Na,{open:g!==null,onOpenChange:T=>{!T&&!X&&Z(null)},children:ue(na,{children:[ue(ra,{children:[$(oa,{children:g?.variant?"Edit variant":"Add variant"}),$(la,{children:"Price, markdown, and stock live on the variant."})]}),g&&ue("div",{className:"af-space-y-3",children:[g.variant?g.variant.option_values.length>0&&ue("div",{className:"af-text-sm",children:[$("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Mn(g.variant)]}):ce.map(T=>ue("div",{className:"af-space-y-1",children:[$(be,{className:"af-text-xs af-text-muted-foreground",children:T.title}),ue(Kt,{value:g.optionValues[T.id]??"",onValueChange:A=>Z(me=>me&&{...me,optionValues:{...me.optionValues,[T.id]:A}}),children:[$(Ut,{children:$(Jt,{placeholder:`Choose ${T.title}`})}),$(Vt,{children:T.values.map(A=>$(Ve,{value:A.value,children:A.value},A.id))})]})]},T.id)),de?ue("div",{className:"af-space-y-1",children:[$(be,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),$("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):ue("div",{className:"af-flex af-gap-3",children:[ue("div",{className:"af-space-y-1",children:[ue(be,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),$(ve,{id:"variant-price",type:"number",min:"0",step:n,value:g.unitAmount,onChange:T=>Z(A=>A&&{...A,unitAmount:T.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),ue("div",{className:"af-space-y-1",children:[$(be,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),$(ve,{id:"variant-compare",type:"number",min:"0",step:n,value:g.compareAt,onChange:T=>Z(A=>A&&{...A,compareAt:T.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),ue("div",{className:"af-space-y-1",children:[$(be,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),$(ve,{id:"variant-sku",value:g.sku,onChange:T=>Z(A=>A&&{...A,sku:T.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),ue("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[ue("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[$("input",{type:"checkbox",checked:g.tracked,onChange:T=>Z(A=>A&&{...A,tracked:T.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),g.tracked&&ue("div",{className:"af-space-y-1 af-pl-6",children:[ue("div",{className:"af-flex af-items-end af-gap-3",children:[ue("div",{className:"af-space-y-1",children:[$(be,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),$(ve,{id:"variant-onhand",type:"number",min:"0",step:"1",value:g.onHand,onChange:T=>Z(A=>A&&{...A,onHand:T.target.value}),placeholder:le!=null?"0":void 0,className:"af-w-[100px]"})]}),ue("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[$("input",{type:"checkbox",checked:g.allowBackorder,onChange:T=>Z(A=>A&&{...A,allowBackorder:T.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),le!=null&&ue("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",le," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),ue("div",{className:"af-space-y-1",children:[ue("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[$("input",{type:"checkbox",checked:g.active,onChange:T=>Z(A=>A&&{...A,active:T.target.checked}),className:"af-h-4 af-w-4",disabled:ge}),"Active (buyers can purchase this variant)"]}),ge&&$("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."})]}),ie&&$("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:ie})]}),ue(ia,{children:[$(S,{variant:"outline",onClick:()=>Z(null),disabled:X,children:"Cancel"}),ue(S,{onClick:Nt,disabled:X,children:[X?$(Br,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,g?.variant?"Save":"Add variant"]})]})]})}),$(Na,{open:W!==null,onOpenChange:T=>{!T&&!u&&re(null)},children:ue(na,{children:[ue(ra,{children:[$(oa,{children:"Delete variant?"}),$(la,{children:W&&`"${Mn(W)}" will no longer be purchasable. Past orders are unaffected.`})]}),ue(ia,{children:[$(S,{variant:"outline",onClick:()=>re(null),disabled:u,children:"Cancel"}),$(S,{variant:"destructive",onClick:V,disabled:u,children:"Delete"})]})]})})]})}import{Fragment as _l,jsx as fe,jsxs as Se}from"react/jsx-runtime";function Rl(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 Qs({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:f,attachProductFileFromUrl:m}=e,v=!!a,r=a?.currency??s,p=Ra(r)?"1":"0.01",y=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[u,c]=He.useState(!1),[d,b]=He.useState(null),h=He.useRef(!0);He.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);let[_,D]=He.useState(a?.name??""),[U,l]=He.useState(a?.description??""),[x,C]=He.useState(a?.allow_custom_amount?"custom":"fixed"),[G,L]=He.useState(a?.unit_amount!=null?String(ht(a.unit_amount,r)):""),[w,M]=He.useState(a?.min_amount!=null?String(ht(a.min_amount,r)):""),[g,Z]=He.useState(a?.max_amount!=null?String(ht(a.max_amount,r)):""),[ie,oe]=He.useState(String(a?.max_quantity??10)),X=He.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(ht(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(ht(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(ht(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[ye,W]=He.useState(a?.collect_shipping_address??!1),[re,ce]=He.useState(a?.active??!0),[q,he]=He.useState(a?.images??[]),[Be,Nt]=He.useState(""),[V,de]=He.useState(a?.fulfillment??null),[ge,le]=He.useState(!1),[Fe,T]=He.useState(""),[A,me]=He.useState(null),We=He.useRef(null),Ue=u||ge,et=()=>{let ne=Be.trim();if(ne){if(q.includes(ne)){b("This image URL is already added");return}he(Ie=>[...Ie,ne]),Nt(""),b(null)}},Ke=ne=>{he(Ie=>Ie.filter($e=>$e!==ne))},tt=async()=>{if(b(null),!_.trim()){b("Product name is required");return}let ne=null,Ie=null,$e=null,ta=!v||x!==X.pricingMode||(x==="fixed"?G!==X.unitAmount:w!==X.minAmount||g!==X.maxAmount),Et=!v||ie!==X.maxQuantity,Da=y||x==="fixed";if(!(y||!ta))if(x==="fixed"){if(ne=ua(G,r),ne===null||ne<=0){b("Enter a valid price");return}}else{if(Ie=ua(w,r),$e=ua(g,r),Ie===null||$e===null){b("Enter valid minimum and maximum amounts");return}if($e<Ie){b("Maximum amount must be at least the minimum amount");return}}let it=parseInt(ie,10);if(Da&&Et&&(!Number.isFinite(it)||it<1)){b("Max quantity must be at least 1");return}try{c(!0);let Qe;if(v&&a){let k={name:_.trim(),description:U.trim()||null,images:q,collect_shipping_address:ye,active:re};!y&&ta&&(k.allow_custom_amount=x==="custom",x==="fixed"?k.unit_amount=ne:(k.min_amount=Ie,k.max_amount=$e)),Da&&Et&&(k.max_quantity=it),Qe=await o(a.id,k),X.pricingMode=Qe.allow_custom_amount?"custom":"fixed",X.unitAmount=Qe.unit_amount!=null?String(ht(Qe.unit_amount,r)):"",X.minAmount=Qe.min_amount!=null?String(ht(Qe.min_amount,r)):"",X.maxAmount=Qe.max_amount!=null?String(ht(Qe.max_amount,r)):"",X.maxQuantity=String(Qe.max_quantity)}else{let k={name:_.trim(),allow_custom_amount:x==="custom",collect_shipping_address:ye,active:re};U.trim()&&(k.description=U.trim()),q.length>0&&(k.images=q),x==="fixed"?(k.unit_amount=ne,k.max_quantity=it):(k.min_amount=Ie,k.max_amount=$e),Qe=await i(k)}if(!h.current)return;de(Qe.fulfillment),t?.(Qe)}catch(Qe){if(!h.current)return;b(Qe instanceof Error?Qe.message:"Failed to save product")}finally{h.current&&c(!1)}},Wt=async ne=>{let Ie=ne.target.files?.[0];if(!(!Ie||!a))try{le(!0),me(null);let $e=await f(a.id,Ie);if(!h.current)return;de($e.fulfillment),t?.($e)}catch($e){if(!h.current)return;me($e instanceof Error?$e.message:"Failed to upload file")}finally{h.current&&(le(!1),We.current&&(We.current.value=""))}},ba=async()=>{let ne=Fe.trim();if(!(!ne||!a))try{le(!0),me(null);let Ie=await m(a.id,ne);if(!h.current)return;de(Ie.fulfillment),T(""),t?.(Ie)}catch(Ie){if(!h.current)return;me(Ie instanceof Error?Ie.message:"Failed to fetch file")}finally{h.current&&le(!1)}};return Se("div",{className:`af-space-y-6 ${n||""}`,children:[Se("div",{className:"af-space-y-2",children:[fe(be,{htmlFor:"product-name",children:"Name"}),fe(ve,{id:"product-name",value:_,onChange:ne=>D(ne.target.value),placeholder:"My product"})]}),Se("div",{className:"af-space-y-2",children:[fe(be,{htmlFor:"product-description",children:"Description"}),fe("textarea",{id:"product-description",value:U,onChange:ne=>l(ne.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),Se("div",{className:"af-space-y-2",children:[fe(be,{children:"Pricing"}),y?fe("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Se(_l,{children:[Se(Kt,{value:x,onValueChange:ne=>C(ne),children:[fe(Ut,{className:"af-w-[260px]",children:fe(Jt,{})}),Se(Vt,{children:[fe(Ve,{value:"fixed",children:"Fixed price"}),fe(Ve,{value:"custom",children:"Buyer chooses the amount"})]})]}),x==="fixed"?fe("div",{className:"af-flex af-items-end af-gap-3",children:Se("div",{className:"af-space-y-1",children:[Se(be,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),fe(ve,{id:"product-price",type:"number",min:"0",step:p,value:G,onChange:ne=>L(ne.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Se("div",{className:"af-space-y-1",children:[Se("div",{className:"af-flex af-items-end af-gap-3",children:[Se("div",{className:"af-space-y-1",children:[Se(be,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),fe(ve,{id:"product-min-amount",type:"number",min:"0",step:p,value:w,onChange:ne=>M(ne.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Se("div",{className:"af-space-y-1",children:[Se(be,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),fe(ve,{id:"product-max-amount",type:"number",min:"0",step:p,value:g,onChange:ne=>Z(ne.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),fe("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),Se("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",r.toUpperCase(),"), which follows the country of your payment account."]})]}),(y||x==="fixed")&&Se("div",{className:"af-space-y-1",children:[fe(be,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),fe(ve,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:ie,onChange:ne=>oe(ne.target.value),className:"af-w-[140px]"})]})]}),Se("div",{className:"af-space-y-2",children:[fe(be,{children:"Images"}),fe("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Se("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[q.map(ne=>Se(Y,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[fe("span",{className:"af-truncate",children:ne}),fe("button",{type:"button",onClick:()=>Ke(ne),className:"af-ml-1 hover:af-text-destructive",disabled:u,children:fe(Sl,{className:"af-h-3 af-w-3"})})]},ne)),q.length===0&&fe("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Se("div",{className:"af-flex af-gap-2",children:[fe(ve,{type:"url",value:Be,onChange:ne=>Nt(ne.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),et())},disabled:u}),fe(S,{type:"button",variant:"outline",onClick:et,disabled:!Be.trim()||u,children:fe(wl,{className:"af-h-4 af-w-4"})})]})]}),Se("div",{className:"af-space-y-2",children:[fe(be,{children:"Digital File"}),fe("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),v?Se("div",{className:"af-space-y-3",children:[V?.type==="download"&&Se("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[fe(hl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),fe("span",{className:"af-text-sm",children:V.filename}),V.size!=null&&Se("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Rl(V.size),")"]})]}),V?.type==="redirect"&&V.url&&Se("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[fe(xl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Se("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",V.url]})]}),Se("div",{className:"af-flex af-items-center af-gap-2",children:[fe("input",{ref:We,type:"file",onChange:Wt,className:"af-hidden",disabled:Ue}),Se(S,{type:"button",variant:"outline",size:"sm",onClick:()=>We.current?.click(),disabled:Ue,children:[ge?fe(Mr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):fe(Nl,{className:"af-h-4 af-w-4 af-mr-1"}),V?.type==="download"?"Replace file":"Upload file"]}),fe("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),fe(ve,{type:"url",value:Fe,onChange:ne=>T(ne.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:ge}),fe(S,{type:"button",variant:"outline",size:"sm",onClick:ba,disabled:!Fe.trim()||Ue,children:"Fetch from URL"})]}),A&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:A})]}):fe("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Se("div",{className:"af-space-y-2",children:[fe(be,{children:"Settings"}),Se("div",{className:"af-space-y-2",children:[Se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[fe("input",{type:"checkbox",checked:ye,onChange:ne=>W(ne.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[fe("input",{type:"checkbox",checked:re,onChange:ne=>ce(ne.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),v&&a&&Se("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[fe(be,{children:"Options & Variants"}),fe(Zs,{productId:a.id,currency:r})]}),d&&fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d}),fe("div",{className:"af-flex af-items-center af-gap-2",children:Se(S,{type:"button",onClick:tt,disabled:Ue,children:[u?fe(Mr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,v?"Save changes":"Create product"]})})]})}import*as gt from"react";import{ChevronLeft as Jl,ChevronRight as Zr,Loader2 as Yl,Receipt as Zl,Search as Ql,SlidersHorizontal as Xl}from"lucide-react";import*as Xe from"react";var Pl=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Xs({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ee(),[t,n]=Xe.useState([]),[i,o]=Xe.useState(0),[f,m]=Xe.useState(!0),[v,r]=Xe.useState(null),[p,y]=Xe.useState(0),[u,c]=Xe.useState(e),[d,b]=Xe.useState(void 0),[h,_]=Xe.useState(""),[D,U]=Xe.useState(""),[l,x]=Xe.useState(""),[C,G]=Xe.useState(!1),[L,w]=Xe.useState(!1),[M,g]=Xe.useState(void 0),Z=M?M.join(","):"",ie=Xe.useMemo(()=>{if(!Z)return;let W=new Set(Z.split(","));return Pl.filter(re=>!W.has(re))},[Z]),oe=Xe.useRef(0),X=Xe.useCallback(async()=>{let W=++oe.current;try{m(!0),r(null);let re={limit:u,offset:p*u};d?re.status=d:ie?re.excludeStatus=ie:C||(re.excludeStatus=["pending","expired"]),h.trim()&&(re.customerEmail=h.trim()),D.trim()&&(re.from=D.trim()),l.trim()&&(re.to=l.trim()),L&&(re.unfulfilledOnly=!0);let ce=await s.getOrders(re);if(W!==oe.current)return;n(ce.orders),o(ce.total)}catch(re){if(W!==oe.current)return;r(re instanceof Error?re:new Error("Failed to fetch orders"))}finally{W===oe.current&&m(!1)}},[s,p,u,d,ie,C,L,h,D,l,a]);Xe.useEffect(()=>{X()},[X]);let ye=Math.ceil(i/u);return{orders:t,total:i,isLoading:f,error:v,page:p,pageSize:u,hasNextPage:p<ye-1,hasPreviousPage:p>0,setPage:y,setPageSize:W=>{c(W),y(0)},status:d,setStatus:W=>{b(W),y(0)},statusIn:M,setStatusIn:W=>{g(W&&W.length>0?W:void 0),y(0)},customerEmail:h,setCustomerEmail:W=>{_(W),y(0)},from:D,setFrom:W=>{U(W),y(0)},to:l,setTo:W=>{x(W),y(0)},showAbandoned:C,setShowAbandoned:W=>{G(W),y(0)},unfulfilledOnly:L,setUnfulfilledOnly:W=>{w(W),y(0)},clearFilters:()=>{b(void 0),g(void 0),G(!1),w(!1),_(""),U(""),x(""),y(0)},refetch:X}}import*as nt from"react";import{ArrowLeft as kl,Check as zr,ChevronLeft as El,ChevronRight as Il,ClipboardCopy as Al,Copy as Dl,Download as Ll,Loader2 as tn,Mail as qr,MoreHorizontal as Ol,Package as Bl,RotateCcw as Fl,Truck as Ml,Undo2 as jr}from"lucide-react";import*as Ur from"react";import*as _a from"@radix-ui/react-popover";import{jsx as Un}from"react/jsx-runtime";var Vr=_a.Root,$r=_a.Trigger;var Vn=Ur.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>Un(_a.Portal,{children:Un("div",{className:"aifeatures-admin",children:Un(_a.Content,{ref:n,align:a,sideOffset:s,className:z("af-z-50 af-w-64 af-rounded-md af-border af-bg-popover af-p-1 af-text-popover-foreground af-shadow-md af-outline-none",e),...t})})}));Vn.displayName=_a.Content.displayName;import{jsx as en}from"react/jsx-runtime";var Tl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Cl(e){return Tl[e]??e}function Hr(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 Qa({status:e,className:a}){return en(Y,{variant:Hr(e),className:a,children:Cl(e)})}function Xa({status:e}){return en(Qa,{status:e})}function ns({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?en(Y,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?en(Y,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Ua(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as Gl,jsx as P,jsxs as K}from"react/jsx-runtime";var Jr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",es="af-text-xs af-text-muted-foreground";function $n(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 Ul(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yr(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 an=24,Vl=["paid","partially_refunded"],$l=["paid","partially_refunded","disputed"],Hl=/^[A-Za-z0-9 _-]*$/,Gr=100;function qn(e,a,s,t,n){let i=Vl.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${an} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${an} 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<an&&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<an&&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 Wr({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:f}){if(f)return K("div",{children:[P(wa,{deliveries:[f]}),o&&P("div",{className:"af-mt-2",children:o})]});let m=qn(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(Y,{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 Kr(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=Ul(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}: ${Yr(n)}`)}function zl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function jn({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=nt.useState(!1);if(!zl())return null;let f=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},m=i?P(zr,{className:"af-h-3 af-w-3"}):P(Dl,{className:"af-h-3 af-w-3"});return n==="icon"?P(S,{variant:"ghost",size:"icon",className:z("af-h-6 af-w-6 af-shrink-0",t),onClick:f,title:a,"aria-label":a,children:m}):K(S,{variant:"outline",size:"sm",className:t,onClick:f,"aria-label":a,children:[i?P(zr,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):P(Al,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Hn({label:e,value:a}){return K("div",{children:[P("div",{className:es,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(jn,{value:a,label:`Copy ${e}`})]})]})}function ql({src:e}){let[a,s]=nt.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(Bl,{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 ja({title:e,action:a,children:s,className:t}){return K("section",{className:z("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:Jr,children:e}),a]}),P("div",{className:"af-mt-3",children:s})]})}function Ga({label:e,emphasis:a,divider:s,children:t}){return K("div",{className:z("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[P("span",{className:a?"af-text-base af-font-semibold":es,children:e}),P("span",{className:z("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function zn({onSelect:e,disabled:a,icon:s,children:t}){return K(S,{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 jl(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${j(da(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?$s(s):qn("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?$s(s):qn("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);a.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${t.label.toLowerCase()}`,at:null,tone:t.variant==="destructive"?"destructive":t.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&a.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&a.push({key:"refunded",text:`Refunded ${j(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&a.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),a}function sn({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:f=!1,hasNextOrder:m=!1}){let{api:v}=ee(),[r,p]=nt.useState(e),[y,u]=nt.useState(null),[c,d]=nt.useState(null),[b,h]=nt.useState(!1),[_,D]=nt.useState(!1),[U,l]=nt.useState(!1),[x,C]=nt.useState(!1),[G,L]=nt.useState(""),[w,M]=nt.useState(!1),[g,Z]=nt.useState(null),[ie,oe]=nt.useState(!1),[X,ye]=nt.useState(""),[W,re]=nt.useState([]),[ce,q]=nt.useState(!1),[he,Be]=nt.useState(!1),[Nt,V]=nt.useState(null);nt.useEffect(()=>{p(e)},[e]);let de=I=>{let ke=I.id===r.id&&I.email_deliveries===void 0?{...I,email_deliveries:r.email_deliveries}:I;p(ke),t?.(ke)},ge=Object.entries(r.metadata??{}),le=da(r)-r.amount_refunded,Fe=(r.status==="paid"||r.status==="partially_refunded")&&le>0,T=I=>(typeof I.unitAmount=="number"?I.unitAmount:0)*(typeof I.quantity=="number"&&I.quantity>0?I.quantity:1),A=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),me=W.reduce((I,ke)=>I+T(r.line_items[ke]??{}),0)+(ce?A:0),We=r.tax_total??0,Ue=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*me/(r.amount_total+(r.shipping_total??0)))):0,et=me+Ue,Ke=W.length>0||ce,tt=Ke?et:ua(X,r.currency),Wt=Ra(r.currency)?"1":"0.01",ba=async()=>{try{h(!0),u(null),d(null),await v.resendOrderReceipt(r.id);let I=await v.getOrder(r.id);de(I),d("Receipt email queued.")}catch(I){u(I instanceof Error?I.message:"Failed to resend receipt")}finally{h(!1)}},ne=async()=>{try{D(!0),u(null),d(null);let I=await v.resetOrderDownloads(r.id);de(I),l(!1),d("Download count reset.")}catch(I){u(I instanceof Error?I.message:"Failed to reset downloads")}finally{D(!1)}},Ie=r.line_items.some(I=>I.collectShippingAddress===!0),$e=typeof r.merchant_fulfilled_at=="string",ta=$l.includes(r.status),Et=G.trim(),Da=Hl.test(Et)&&Et.length<=Gr,it=async I=>{try{M(!0),Z(null),d(null);let ke=await v.setOrderFulfillment(r.id,{fulfilled:I,...I&&Et?{trackingNumber:Et}:{}});de(ke),L(""),d(I?"Marked as shipped.":"Marked as not shipped.")}catch(ke){ke instanceof ya&&ke.status===409?Z(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Z(ke instanceof Error?ke.message:"Failed to update the order")}finally{M(!1)}},Qe=()=>{V(null),ye(String(ht(le,r.currency))),re([]),q(!1),oe(!0)},k=I=>re(ke=>ke.includes(I)?ke.filter(At=>At!==I):[...ke,I]),Me=async(I,ke)=>{if(s)try{Be(!0),V(null),await s(r,I,ke);let At=await v.getOrder(r.id);de(At),oe(!1),d("Refund issued.")}catch(At){V(At instanceof Error?At.message:"Refund failed")}finally{Be(!1)}},F=async()=>{if(Ke){if(et<=0){V("The lines you picked were charged nothing");return}if(et>le){V(`That selection exceeds the refundable remainder (${j(le,r.currency)})`);return}await Me(et,{...W.length>0?{line_items:[...W].sort((ke,At)=>ke-At)}:{},...ce?{shipping:!0}:{}});return}let I=ua(X,r.currency);if(I===null||I<=0){V("Enter a valid refund amount");return}if(I>le){V(`Amount exceeds the refundable remainder (${j(le,r.currency)})`);return}await Me(I,{amount:I})},It=()=>Me(le,{full:!0}),gr=r.fulfillment_type==="download",vr=n&&Ie,ao=jl(r),so=r.shipping_address?Kr(r.shipping_address).join(`
4
- `):"",br=r.shipping_total!=null,yr=!!r.automatic_tax&&r.tax_behavior==="exclusive"&&(r.tax_total??0)>0,no=!(r.automatic_tax&&r.tax_behavior==="exclusive")&&(r.tax_total??0)>0,hr=br||yr,xs=[];return xs.push(P(zn,{icon:b?P(tn,{className:"af-h-4 af-w-4 af-animate-spin"}):P(qr,{className:"af-h-4 af-w-4"}),disabled:b||r.fulfillment_status!=="fulfilled",onSelect:()=>{C(!1),ba()},children:"Resend receipt"},"resend")),gr&&xs.push(P(zn,{icon:P(Fl,{className:"af-h-4 af-w-4"}),disabled:_,onSelect:()=>{C(!1),l(!0)},children:"Reset download count"},"reset")),Fe&&xs.push(K("div",{children:[P(zn,{icon:P(jr,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{C(!1),Qe()},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(S,{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:Ua(r)}),P(Qa,{status:r.status}),n&&P(ns,{order:r}),r.is_test&&P(Y,{variant:"outline",children:"Test"})]}),K("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",$n(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(S,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!f,"aria-label":"Previous order",children:P(El,{className:"af-h-4 af-w-4"})}),P(S,{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(Il,{className:"af-h-4 af-w-4"})})]}),vr&&($e?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 ${$n(r.merchant_fulfilled_at)}`:""]}),ta&&K(S,{variant:"ghost",size:"sm",onClick:()=>it(!1),disabled:w,children:[w?P(tn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(jr,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):ta?K("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[P(ve,{value:G,onChange:I=>L(I.target.value),placeholder:"Tracking number (optional)",maxLength:Gr,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:w}),K(S,{variant:"default",className:"af-shrink-0",onClick:()=>it(!0),disabled:w||!Da,children:[w?P(tn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(Ml,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),xs.length>0&&K(Vr,{open:x,onOpenChange:C,children:[P($r,{asChild:!0,children:P(S,{variant:"outline",size:"icon","aria-label":"More actions",children:P(Ol,{className:"af-h-4 af-w-4"})})}),P(Vn,{children:P("div",{className:"af-space-y-0.5",children:xs})})]})]})]}),vr&&!$e&&!Da&&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."}),g&&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:g}),c&&P("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:c}),y&&P("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:y})]}),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(ja,{title:"Items",children:P("ul",{className:"af-space-y-3",children:r.line_items.map((I,ke)=>{let At=typeof I.name=="string"&&I.name?I.name:"Item",xr=typeof I.quantity=="number"&&I.quantity>0?I.quantity:1,wr=typeof I.unitAmount=="number";return K("li",{className:"af-flex af-items-start af-gap-3",children:[P(ql,{src:typeof I.imageUrl=="string"&&I.imageUrl?I.imageUrl:void 0}),K("div",{className:"af-min-w-0 af-flex-1",children:[K("div",{className:"af-text-sm af-font-medium",children:[At,typeof I.variantTitle=="string"&&I.variantTitle&&K("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",I.variantTitle]})]}),K("div",{className:es,children:[xr," \xD7"," ",wr?j(I.unitAmount,r.currency):"\u2014"]}),I.refunded===!0&&P(Y,{variant:"secondary",className:"af-mt-1",children:I.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),P("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:wr?j(I.unitAmount*xr,r.currency):"\u2014"})]},ke)})})}),ge.length>0&&P(ja,{title:"Order details",children:P("dl",{className:"af-space-y-2",children:ge.map(([I,ke])=>K("div",{children:[P("dt",{className:z(es,"af-capitalize"),children:I.replace(/_/g," ")}),P("dd",{className:"af-text-sm af-break-words",children:Yr(ke)})]},I))})}),P(ja,{title:"Totals",children:K("div",{className:"af-w-full",children:[hr&&P(Ga,{label:"Subtotal",children:j(r.amount_total,r.currency)}),br&&P(Ga,{label:"Shipping",children:r.shipping_total===0?"Free":j(r.shipping_total??0,r.currency)}),yr&&P(Ga,{label:"Tax",children:j(r.tax_total??0,r.currency)}),P(Ga,{label:"Total",emphasis:!0,divider:hr,children:j(da(r),r.currency)}),no&&P(Ga,{label:"incl. tax",children:j(r.tax_total??0,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&K(Ga,{label:"Your price",children:[j(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(Gl,{children:[K(Ga,{label:"Refunded",children:["\u2212",j(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&K("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",j(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),P(Ga,{label:"Net",children:P("span",{className:"af-font-medium",children:j(Math.max(0,da(r)-r.amount_refunded),r.currency)})})]})]})}),P(ja,{title:"Timeline",children:P("ol",{className:"af-space-y-3",children:ao.map(I=>K("li",{className:"af-flex af-gap-3",children:[P("span",{"aria-hidden":"true",className:z("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",I.tone==="destructive"?"af-bg-destructive":I.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:I.text}),I.at&&P("div",{className:"af-text-xs af-text-muted-foreground",children:$n(I.at)})]})]},I.key))})})]}),K("div",{className:"af-space-y-6",children:[P(ja,{title:"Customer",children:K("div",{className:"af-space-y-2",children:[K("div",{children:[P("div",{className:es,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(jn,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&K("div",{children:[P("div",{className:es,children:"Name"}),P("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&K("div",{children:[P("div",{className:es,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(Y,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&P(ja,{title:"Ship to",action:P(jn,{value:so,label:"Copy address",size:"sm",children:"Copy address"}),children:P("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Kr(r.shipping_address).map((I,ke)=>P("div",{children:I},ke))})}),K(ja,{title:"Emails",children:[P(wa,{deliveries:r.email_deliveries?.filter(I=>!["purchase_receipt","merchant_sale"].includes(I.kind)),problemsOnly:!0,className:"af-mb-4"}),K("div",{className:"af-space-y-4",children:[P(Wr,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(I=>I.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:K(S,{variant:"outline",size:"sm",onClick:ba,disabled:b||r.fulfillment_status!=="fulfilled",children:[b?P(tn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(qr,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),P(Wr,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(I=>I.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),gr&&P(ja,{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(Ll,{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:z(Jr,"af-cursor-pointer af-select-none"),children:"Technical details"}),K("div",{className:"af-mt-3 af-space-y-2",children:[P(Hn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&P(Hn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&P(Hn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),P(Na,{open:U,onOpenChange:I=>{!I&&!_&&l(!1)},children:K(na,{children:[K(ra,{children:[P(oa,{children:"Reset download count?"}),P(la,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),K(ia,{children:[P(S,{variant:"outline",onClick:()=>l(!1),disabled:_,children:"Cancel"}),P(S,{onClick:ne,disabled:_,children:_?"Resetting...":"Reset"})]})]})}),P(Na,{open:ie,onOpenChange:I=>{!I&&!he&&oe(!1)},children:K(na,{children:[K(ra,{children:[P(oa,{children:"Refund order"}),K(la,{children:["Refund up to ",j(le,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||A>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((I,ke)=>{let At=I.refunded===!0;return K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:W.includes(ke),onChange:()=>k(ke),disabled:he||At,className:"af-h-4 af-w-4"}),K("span",{className:At?"af-text-muted-foreground af-line-through":void 0,children:[typeof I.name=="string"&&I.name?I.name:"Item",typeof I.variantTitle=="string"&&I.variantTitle?` \u2014 ${I.variantTitle}`:"",typeof I.quantity=="number"&&I.quantity>1?` \xD7 ${I.quantity}`:""]}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:At?"Refunded":j(T(I),r.currency)})]},ke)}),A>0&&K("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[P("input",{type:"checkbox",checked:ce,onChange:I=>q(I.target.checked),disabled:he,className:"af-h-4 af-w-4"}),P("span",{children:"Shipping"}),P("span",{className:"af-ml-auto af-text-muted-foreground",children:j(A,r.currency)})]})]})]}),K("div",{className:"af-space-y-2",children:[K(be,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),P(ve,{id:"refund-amount",type:"number",min:"0",step:Wt,value:Ke?String(ht(et,r.currency)):X,onChange:I=>ye(I.target.value),disabled:he||Ke}),Ke&&P("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),Nt&&P("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:Nt}),K(ia,{children:[P(S,{variant:"outline",onClick:()=>oe(!1),disabled:he,children:"Cancel"}),P(S,{variant:"outline",onClick:It,disabled:he,children:"Refund everything"}),P(S,{variant:"destructive",onClick:F,disabled:he,children:he?"Refunding...":tt!==null&&tt>0?`Refund ${j(tt,r.currency)}`:"Refund"})]})]})})]})}import*as nn from"react";import{ArrowLeft as Wl,RefreshCw as Kl}from"lucide-react";import{jsx as Pa,jsxs as ts}from"react/jsx-runtime";function xt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=nn.useRef(null);return nn.useEffect(()=>{i.current?.focus()},[]),ts("div",{className:z("af-bg-background",n),children:[ts("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:[Pa("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&ts(S,{type:"button",variant:"outline",size:"sm",onClick:a,children:[Pa(Wl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Pa("div",{className:"af-p-4",children:t})]})}function Q({className:e}){return Pa("div",{"aria-hidden":"true",className:z("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Je({label:e,children:a,detail:s,valueClassName:t}){return ts("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Pa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Pa("div",{className:z("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&Pa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function zt({message:e,onRetry:a}){return ts("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Pa("span",{children:e}),ts(S,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[Pa(Kl,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ta({icon:e,children:a}){return ts("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Pa("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}import{Fragment as tc,jsx as E,jsxs as xe}from"react/jsx-runtime";var ec={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Qr={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Xr(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 ei(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 rn(e){return e.customer?.name||e.customer_name||null}function rs({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:f}=ee(),m=Xs({refreshKey:s}),{orders:v,total:r,isLoading:p,error:y,page:u,pageSize:c,hasNextPage:d,hasPreviousPage:b,setPage:h,setPageSize:_,customerEmail:D,setCustomerEmail:U,setStatusIn:l,from:x,setFrom:C,to:G,setTo:L,showAbandoned:w,setShowAbandoned:M,setUnfulfilledOnly:g,refetch:Z}=m,[ie,oe]=gt.useState("list"),[X,ye]=gt.useState(null),[W,re]=gt.useState(""),[ce,q]=gt.useState(""),[he,Be]=gt.useState(n?"needs_shipping":"all"),[Nt,V]=gt.useState(!1),[de,ge]=gt.useState(!!t),[le,Fe]=gt.useState(null);gt.useEffect(()=>{if(!t)return;let F=!1;return ge(!0),Fe(null),f.getOrder(t).then(It=>{F||(ye(It),oe("detail"))}).catch(()=>{F||Fe("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{F||ge(!1)}),()=>{F=!0}},[f,t]);let T=gt.useCallback(F=>{Be(F);let It=Qr[F];l(It.statusIn),g(It.unfulfilledOnly)},[l,g]);gt.useEffect(()=>{n&&g(!0)},[]);let A=gt.useRef(!n);gt.useEffect(()=>{A.current||p||(A.current=!0,v.length===0&&T("all"))},[p,v.length,T]);let me=ie==="detail"&&!!X;gt.useEffect(()=>{o?.(me)},[me,o]);let We=(x?1:0)+(G?1:0)+(w?1:0),Ue=We>0||!!D||!!ce,et=!!x&&!!G&&x>G,Ke=F=>{ye(F),oe("detail")},tt=()=>{oe("list"),ye(null),Z()},Wt=F=>{let It=F.trim();if(!It){q(""),D&&U("");return}if(It.startsWith("#")||/^\d+$/.test(It)){q(It),D&&U("");return}q(""),U(It)},ba=()=>{re(""),q(""),U(""),C(""),L(""),M(!1),V(!1)},ne=ce.replace(/^#/,"").toLowerCase(),Ie=ne?v.filter(F=>String(F.order_number??"")===ne||F.id.toLowerCase().startsWith(ne)):v,$e=X?v.findIndex(F=>F.id===X.id):-1,ta=$e>0,Et=$e>=0&&$e<v.length-1;if(de)return E("div",{className:a,children:E("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:E(Yl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(ie==="detail"&&X)return E("div",{className:a,children:E(sn,{order:X,onBack:tt,onRefund:e,onOrderUpdated:F=>ye(F),allowFulfillment:n,onPrevOrder:ta?()=>ye(v[$e-1]):void 0,onNextOrder:Et?()=>ye(v[$e+1]):void 0,hasPrevOrder:ta,hasNextOrder:Et},X.id)});let it=xe("div",{className:"af-mb-4 af-space-y-3",children:[le&&E("p",{className:"af-text-xs af-text-muted-foreground",children:le}),xe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[E("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(F=>E("button",{type:"button","aria-pressed":he===F,onClick:()=>T(F),className:z("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",he===F?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:ec[F]},F))}),xe("div",{className:"af-relative af-w-full af-max-w-xs",children:[E(Ql,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),E(ve,{type:"text",value:W,onChange:F=>re(F.target.value),onBlur:()=>Wt(W),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),Wt(W))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),xe(S,{type:"button",variant:We>0?"secondary":"ghost",size:"sm",onClick:()=>V(F=>!F),"aria-expanded":Nt,children:[E(Xl,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",We>0&&E(Y,{variant:"secondary",className:"af-ml-2",children:We})]}),Ue&&E(S,{type:"button",variant:"ghost",size:"sm",onClick:ba,children:"Clear filters"})]}),(Nt||!!x||!!G)&&xe("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:[E(be,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),E(ve,{id:"orders-from",type:"date",value:x,max:G||void 0,onChange:F=>C(F.target.value),className:"af-w-[170px]"}),E(be,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),E(ve,{id:"orders-to",type:"date",value:G,min:x||void 0,onChange:F=>L(F.target.value),className:"af-w-[170px]"}),!Qr[he].statusIn&&E(S,{type:"button",variant:w?"secondary":"ghost",size:"sm",onClick:()=>M(!w),"aria-pressed":w,children:w?"Hide abandoned":"Show abandoned"})]}),et&&E("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(p)return xe("div",{className:a,children:[it,E("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(F=>xe("div",{className:"af-rounded-md af-border af-p-3",children:[xe("div",{className:"af-flex af-items-center af-justify-between",children:[E(Q,{className:"af-h-4 af-w-16"}),E(Q,{className:"af-h-4 af-w-14"})]}),E(Q,{className:"af-mt-2 af-h-3 af-w-40"}),E(Q,{className:"af-mt-2 af-h-3 af-w-24"})]},F))}),E("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(Ae,{children:[E(De,{children:xe(pe,{children:[E(O,{children:"Order"}),E(O,{children:"Date"}),E(O,{children:"Customer"}),E(O,{children:"Items"}),E(O,{className:"af-text-right",children:"Total"}),E(O,{children:"Status"}),E(O,{className:"af-w-8"})]})}),E(Le,{"aria-hidden":"true",children:[0,1,2,3,4].map(F=>xe(pe,{children:[E(B,{children:E(Q,{className:"af-h-4 af-w-14"})}),E(B,{children:E(Q,{className:"af-h-4 af-w-24"})}),E(B,{children:E(Q,{className:"af-h-4 af-w-40"})}),E(B,{children:E(Q,{className:"af-h-4 af-w-32"})}),E(B,{children:E(Q,{className:"af-ml-auto af-h-4 af-w-16"})}),E(B,{children:E(Q,{className:"af-h-5 af-w-16"})}),E(B,{})]},F))})]})}),E("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(y)return xe("div",{className:a,children:[it,xe("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[E("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),E(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>Z(),children:"Try again"})]})]});let Qe=he!=="all";if(Ie.length===0&&u===0)return xe("div",{className:a,children:[(Ue||Qe)&&it,xe("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[E(Zl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),E("p",{className:"af-text-muted-foreground af-text-center",children:Ue||Qe?"No orders match these filters.":i??xe(tc,{children:["No orders yet.",E("br",{}),"Orders will appear here when someone buys from your website."]})}),!Ue&&!Qe&&E(S,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>M(!0),children:"Show abandoned checkouts"})]})]});let k=u*c+1,Me=Math.min((u+1)*c,r);return xe("div",{className:a,children:[it,E("div",{className:"af-space-y-3 lg:af-hidden",children:Ie.map(F=>xe("button",{type:"button",onClick:()=>Ke(F),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[xe("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[E("span",{className:"af-font-medium",children:Ua(F)}),E("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(da(F),F.currency)})]}),xe("div",{className:"af-mt-1 af-min-w-0",children:[xe("div",{className:"af-truncate af-text-sm",children:[F.customer_email||E("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),rn(F)&&xe("span",{className:"af-text-muted-foreground",children:[" \xB7 ",rn(F)]})]}),E("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ei(F)}),F.amount_refunded>0&&xe("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(F.amount_refunded,F.currency)," refunded"]})]}),xe("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[E(Qa,{status:F.status}),E(Ss,{deliveries:F.email_deliveries}),F.is_test&&E(Y,{variant:"outline",children:"Test"}),n&&E(ns,{order:F}),E("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Xr(F.created_at)})]})]},F.id))}),E("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:xe(Ae,{children:[E(De,{children:xe(pe,{children:[E(O,{children:"Order"}),E(O,{children:"Date"}),E(O,{children:"Customer"}),E(O,{children:"Items"}),E(O,{className:"af-text-right",children:"Total"}),E(O,{children:"Status"}),E(O,{className:"af-w-8"})]})}),E(Le,{children:Ie.map(F=>xe(pe,{onClick:()=>Ke(F),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[xe(B,{className:"af-whitespace-nowrap af-font-medium",children:[E("button",{type:"button",onClick:It=>{It.stopPropagation(),Ke(F)},"aria-label":`Open order ${Ua(F)}`,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:Ua(F)}),F.is_test&&E(Y,{variant:"outline",className:"af-ml-2",children:"Test"})]}),E(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Xr(F.created_at)}),xe(B,{className:"af-max-w-[220px]",children:[E("div",{className:"af-truncate",children:F.customer_email||E("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),rn(F)&&E("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:rn(F)})]}),E(B,{className:"af-max-w-[220px]",children:E("div",{className:"af-truncate af-text-muted-foreground",children:ei(F)})}),xe(B,{className:"af-whitespace-nowrap af-text-right",children:[E("div",{className:"af-font-medium af-tabular-nums",children:j(da(F),F.currency)}),F.amount_refunded>0&&xe("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(F.amount_refunded,F.currency)," ","refunded"]})]}),E(B,{children:xe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[E(Qa,{status:F.status}),E(Ss,{deliveries:F.email_deliveries}),n&&E(ns,{order:F})]})}),E(B,{className:"af-w-8 af-text-right",children:E(Zr,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},F.id))})]})}),xe("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[xe("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[E("span",{children:ne?`${Ie.length} matching this page`:`Showing ${k}-${Me} of ${r}`}),xe(Kt,{value:String(c),onValueChange:F=>_(Number(F)),children:[E(Ut,{className:"af-w-[70px] af-h-8",children:E(Jt,{})}),xe(Vt,{children:[E(Ve,{value:"10",children:"10"}),E(Ve,{value:"25",children:"25"}),E(Ve,{value:"50",children:"50"}),E(Ve,{value:"100",children:"100"})]})]}),E("span",{children:"per page"})]}),xe("div",{className:"af-flex af-items-center af-gap-2",children:[xe(S,{variant:"outline",size:"sm",onClick:()=>h(u-1),disabled:!b,children:[E(Jl,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),xe(S,{variant:"outline",size:"sm",onClick:()=>h(u+1),disabled:!d,children:["Next",E(Zr,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as cn from"react";import{ChevronLeft as rc,ChevronRight as ic,Eye as oc,Search as lc,Users as cc}from"lucide-react";import*as Dt from"react";function on({initialPageSize:e=25}={}){let{api:a}=ee(),[s,t]=Dt.useState([]),[n,i]=Dt.useState(0),[o,f]=Dt.useState(!0),[m,v]=Dt.useState(null),[r,p]=Dt.useState(0),[y,u]=Dt.useState(e),[c,d]=Dt.useState(""),b=Dt.useRef(0),h=Dt.useCallback(async()=>{let D=++b.current;try{f(!0),v(null);let U={limit:y,offset:r*y};c.trim()&&(U.email=c.trim());let l=await a.getCustomers(U);if(D!==b.current)return;t(l.customers),i(l.total)}catch(U){if(D!==b.current)return;v(U instanceof Error?U:new Error("Failed to fetch customers"))}finally{D===b.current&&f(!1)}},[a,r,y,c]);Dt.useEffect(()=>{h()},[h]);let _=Math.ceil(n/y);return{customers:s,total:n,isLoading:o,error:m,page:r,pageSize:y,hasNextPage:r<_-1,hasPreviousPage:r>0,setPage:p,setPageSize:D=>{u(D),p(0)},email:c,setEmail:D=>{d(D),p(0)},refetch:h}}import*as as from"react";import{ArrowLeft as ac,Loader2 as sc}from"lucide-react";import{jsx as Ce,jsxs as wt}from"react/jsx-runtime";function ti(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 ln({customer:e,onBack:a,className:s}){let{api:t}=ee(),[n,i]=as.useState(null),[o,f]=as.useState([]),[m,v]=as.useState(!0),[r,p]=as.useState(null);as.useEffect(()=>{let c=!1;return v(!0),p(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([d,b])=>{c||(i(d),f(b.orders))}).catch(d=>{c||p(d instanceof Error?d.message:"Failed to load customer")}).finally(()=>{c||v(!1)}),()=>{c=!0}},[t,e.id,e.email]);let y=n?.addresses??[],u=n?.order_count??o.length;return wt("div",{className:s,children:[wt("div",{className:"af-mb-6",children:[wt(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[Ce(ac,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Ce("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),wt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",ti(e.created_at)]})]}),m?Ce("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ce(sc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?Ce("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):wt("div",{className:"af-space-y-6",children:[Ce(wa,{deliveries:n?.email_deliveries}),wt("div",{children:[Ce("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),wt("div",{className:"af-space-y-1 af-text-sm",children:[wt("div",{className:"af-flex af-gap-2",children:[Ce("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Ce("span",{children:e.email})]}),e.name&&wt("div",{className:"af-flex af-gap-2",children:[Ce("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Ce("span",{children:e.name})]}),e.phone&&wt("div",{className:"af-flex af-gap-2",children:[Ce("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Ce("span",{children:e.phone})]}),wt("div",{className:"af-flex af-gap-2",children:[Ce("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Ce("span",{children:u})]})]})]}),y.length>0&&wt("div",{children:[Ce("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Ce("div",{className:"af-flex af-flex-wrap af-gap-3",children:y.map(c=>wt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&Ce(Y,{variant:"secondary",className:"af-mb-1",children:"Default"}),nc(c).map((d,b)=>Ce("div",{children:d},b))]},c.id))})]}),wt("div",{children:[Ce("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Ce("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):wt(Ae,{children:[Ce(De,{children:wt(pe,{children:[Ce(O,{children:"Date"}),Ce(O,{children:"Amount"}),Ce(O,{children:"Status"})]})}),Ce(Le,{children:o.map(c=>wt(pe,{children:[Ce(B,{className:"af-text-muted-foreground",children:ti(c.created_at)}),Ce(B,{children:j(da(c),c.currency)}),Ce(B,{children:Ce(Xa,{status:c.status})})]},c.id))})]})]})]})]})}import{Fragment as uc,jsx as Re,jsxs as ct}from"react/jsx-runtime";function dc(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function dn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:f,hasPreviousPage:m,setPage:v,setPageSize:r,email:p,setEmail:y,refetch:u}=on(),[c,d]=cn.useState("list"),[b,h]=cn.useState(null),[_,D]=cn.useState(""),U=L=>{h(L),d("detail")},l=()=>{d("list"),h(null),u()};if(c==="detail"&&b)return Re("div",{className:e,children:Re(ln,{customer:b,onBack:l})});let x=ct("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Re(ve,{type:"email",value:_,onChange:L=>D(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),y(_.trim()))}}),ct(S,{type:"button",variant:"outline",size:"sm",onClick:()=>y(_.trim()),children:[Re(lc,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),p&&Re(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>{D(""),y("")},children:"Clear"})]});if(t)return ct("div",{className:e,children:[x,Re("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Re("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return ct("div",{className:e,children:[x,Re("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:ct("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return ct("div",{className:e,children:[p&&x,ct("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Re(cc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Re("p",{className:"af-text-muted-foreground af-text-center",children:p?"No customers match that email.":ct(uc,{children:["No customers yet.",Re("br",{}),"Customers appear here after their first purchase."]})})]})]});let C=i*o+1,G=Math.min((i+1)*o,s);return ct("div",{className:e,children:[x,ct(Ae,{children:[Re(De,{children:ct(pe,{children:[Re(O,{children:"Email"}),Re(O,{children:"Name"}),Re(O,{children:"Customer since"}),Re(O,{className:"af-text-right",children:"Actions"})]})}),Re(Le,{children:a.map(L=>ct(pe,{children:[Re(B,{className:"af-font-medium",children:L.email}),Re(B,{children:L.name||Re("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Re(B,{className:"af-text-muted-foreground",children:dc(L.created_at)}),Re(B,{className:"af-text-right",children:Re(S,{variant:"ghost",size:"icon",onClick:()=>U(L),title:"View customer",children:Re(oc,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),ct("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[ct("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[ct("span",{children:["Showing ",C,"-",G," of ",s]}),ct(Kt,{value:String(o),onValueChange:L=>r(Number(L)),children:[Re(Ut,{className:"af-w-[70px] af-h-8",children:Re(Jt,{})}),ct(Vt,{children:[Re(Ve,{value:"10",children:"10"}),Re(Ve,{value:"25",children:"25"}),Re(Ve,{value:"50",children:"50"}),Re(Ve,{value:"100",children:"100"})]})]}),Re("span",{children:"per page"})]}),ct("div",{className:"af-flex af-items-center af-gap-2",children:[ct(S,{variant:"outline",size:"sm",onClick:()=>v(i-1),disabled:!m,children:[Re(rc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ct(S,{variant:"outline",size:"sm",onClick:()=>v(i+1),disabled:!f,children:["Next",Re(ic,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ne from"react";import{ArrowLeft as fc,ChevronLeft as mc,ChevronRight as ai,Copy as pc,Download as gc,ExternalLink as vc,FileText as ri,Loader2 as bc,Search as yc}from"lucide-react";import*as dt from"react";function is({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=ee(),[n,i]=dt.useState([]),[o,f]=dt.useState(0),[m,v]=dt.useState(null),[r,p]=dt.useState(!0),[y,u]=dt.useState(null),[c,d]=dt.useState(0),[b,h]=dt.useState(e),[_,D]=dt.useState(void 0),[U,l]=dt.useState(""),[x,C]=dt.useState(""),[G,L]=dt.useState(""),[w,M]=dt.useState(""),[g,Z]=dt.useState(""),ie=_?_.join(","):"",oe=dt.useRef(0),X=dt.useCallback(async()=>{let W=++oe.current;p(!0),u(null);try{let re={labels:ie?ie.split(","):void 0,customerEmail:U||void 0,q:x||void 0,from:G||void 0,to:w||void 0,retainerId:g||void 0,includeAggregates:s,limit:b,offset:c*b},ce=await t.getInvoices(re);if(W!==oe.current)return;if(c>0&&c*b>=ce.total){d(Math.max(0,Math.ceil(ce.total/b)-1));return}i(ce.invoices),f(ce.total),s&&v(ce.aggregates??null)}catch(re){if(W!==oe.current)return;u(re instanceof Error?re:new Error("Failed to fetch invoices"))}finally{W===oe.current&&p(!1)}},[t,ie,U,x,G,w,g,c,b,s]);dt.useEffect(()=>{X()},[X,a]);let ye=W=>re=>{d(0),W(re)};return{invoices:n,total:o,aggregates:m,isLoading:r,error:y,page:c,pageSize:b,hasNextPage:(c+1)*b<o,hasPreviousPage:c>0,setPage:d,setPageSize:ye(h),labels:_,setLabels:ye(D),customerEmail:U,setCustomerEmail:ye(l),q:x,setQ:ye(C),from:G,setFrom:ye(L),to:w,setTo:ye(M),retainerId:g,setRetainerId:ye(Z),clearFilters:()=>{d(0),D(void 0),l(""),C(""),L(""),M(""),Z("")},refetch:X}}import{Fragment as _c,jsx as R,jsxs as H}from"react/jsx-runtime";var hc={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 Yn(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:hc[e.label]??e.label}function xc(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 Jn={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},wc={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ts({invoice:e,className:a}){return H("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[R(Y,{variant:xc(e.label),className:a,children:Yn(e)}),e.collection_method==="charge_automatically"&&R(Y,{variant:"secondary",children:"Managed in Stripe"})]})}function fn({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 R(Y,{variant:s,className:a,children:Jn[e.state]??e.state})}function os(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ea(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 si={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Gn={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 Nc(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 Wn=100,Kn=5e3;async function Sc(e,a){let s=[],t=0;for(let n=0;n<Kn;n+=Wn){let i=await e.getInvoices({...a,limit:Wn,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<Wn||s.length>=t)break}return{invoices:s.slice(0,Kn),total:t,truncated:t>s.length||t>Kn}}function ii(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,os(t),Yn(t),t.customer_name??"",t.customer_email??"",t.created_at,t.due_at??"",t.paid_at??"",t.currency.toUpperCase(),j(t.amount_subtotal,t.currency),j(t.tax_total,t.currency),j(t.amount_total,t.currency),t.amount_due===null?"":j(t.amount_due,t.currency),t.amount_paid===null?"":j(t.amount_paid,t.currency),j(t.amount_refunded,t.currency),t.payment_method??"",t.pay_url??"",t.retainer_id??"",t.replaces_order_id??"",t.replaced_by_order_id??"",t.tax_behavior??"",t.discount_total===void 0?"":j(t.discount_total,t.currency),t.collection_method??""]);return[a,...s].map(t=>t.map(Nc).join(",")).join(`
5
- `)}function Rc(e){if(typeof document>"u")return;let a=new Blob([ii(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 ls({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:f=null,onClearRetainerFilter:m}){let{api:v}=ee(),{invoices:r,total:p,isLoading:y,error:u,page:c,pageSize:d,hasNextPage:b,hasPreviousPage:h,setPage:_,labels:D,setLabels:U,customerEmail:l,setCustomerEmail:x,q:C,setQ:G,from:L,setFrom:w,to:M,setTo:g,retainerId:Z,setRetainerId:ie,refetch:oe}=is({refreshKey:a}),[X,ye]=Ne.useState("open"),[W,re]=Ne.useState(""),[ce,q]=Ne.useState(null),he=Ne.useRef(0),Be=Ne.useCallback(k=>{he.current++,V(!1),q(k)},[]),[Nt,V]=Ne.useState(!1),[de,ge]=Ne.useState(0),[le,Fe]=Ne.useState(null),[T,A]=Ne.useState(!1),[me,We]=Ne.useState(0);Ne.useEffect(()=>{q(k=>{if(!k)return k;let Me=r.find(F=>F.id===k.id);return Me&&Me!==k?Me:k})},[r]);let[Ue,et]=Ne.useState(!1),[Ke,tt]=Ne.useState(null),Wt=async()=>{if(!Ue){et(!0),tt(null);try{let{invoices:k,total:Me,truncated:F}=await Sc(v,{labels:D,customerEmail:l,q:C,from:L,to:M,retainerId:Z});Rc(k),tt(F?`Exported the first ${k.length.toLocaleString()} of ${Me.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{tt("Couldn't export \u2014 try again.")}finally{et(!1)}}},ba=!l&&!C&&!L&&!M&&!Z,[ne,Ie]=Ne.useState(null);Ne.useEffect(()=>{if(y||p>0||!ba||X!=="open")return;let k=!1;return v.getInvoices({limit:1}).then(Me=>{k||Ie(Me.total>0)}).catch(()=>{k||Ie(!0)}),()=>{k=!0}},[v,y,p,ba,X,a]),Ne.useEffect(()=>{U(Gn.open)},[]),Ne.useEffect(()=>{let k=f?.id??"";k!==Z&&(ie(k),k&&(ye("all"),U(Gn.all),x(""),G(""),re(""),w(""),g("")))},[f?.id]),Ne.useEffect(()=>{let k=!1;return A(!1),v.getInvoiceSettings().then(Me=>{k||Fe({payments_active:Me.payments_active,blocked:Me.blocked})}).catch(()=>{k||A(!0)}),()=>{k=!0}},[v,a,me]),Ne.useEffect(()=>{if(!s)return;let k=!1,Me=he.current;return V(!1),v.getInvoice(s).then(F=>{!k&&Me===he.current&&q(F)}).catch(()=>{!k&&Me===he.current&&V(!0)}),()=>{k=!0}},[v,s,de]),Ne.useEffect(()=>{t?.(ce!==null)},[ce,t]);let $e=k=>{ye(k),U(Gn[k])},ta=k=>{let Me=k.trim();if(!Me){C&&G(""),l&&x("");return}if(Me.includes("@")){C&&G(""),x(Me);return}l&&x(""),G(Me.replace(/^#/,""))},Et=r,Da=Nt&&H("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. ",R(S,{type:"button",variant:"link",size:"sm",onClick:()=>ge(k=>k+1),children:"Retry opening invoice"})]});if(ce)return H("div",{className:e,children:[Da,R(Zn,{invoice:ce,refreshKey:a,onBack:()=>{Be(null),oe()}},ce.id)]});let it=H("div",{className:"af-mb-4 af-space-y-3",children:[T&&H("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",R(S,{type:"button",variant:"link",size:"sm",onClick:()=>We(k=>k+1),children:"Retry setup check"})]}),Da,le?.blocked&&H("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",le.blocked.reason?`: ${le.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),f&&H("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[H(Y,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",f.label]}),m&&R(S,{type:"button",variant:"link",size:"sm",onClick:m,children:"Clear schedule filter"})]}),H("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[R("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(si).map(k=>R("button",{type:"button","aria-pressed":X===k,onClick:()=>$e(k),className:z("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",X===k?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:si[k]},k))}),H("div",{className:"af-relative af-w-full af-max-w-xs",children:[R(yc,{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"}),R(ve,{type:"text",value:W,onChange:k=>re(k.target.value),onBlur:()=>ta(W),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),ta(W))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),H("div",{className:"af-flex af-items-center af-gap-2",children:[R(be,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),R(ve,{id:"invoices-from",type:"date",value:L,max:M||void 0,onChange:k=>w(k.target.value),className:"af-invoice-date af-w-[150px]"})]}),H("div",{className:"af-flex af-items-center af-gap-2",children:[R(be,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),R(ve,{id:"invoices-to",type:"date",value:M,min:L||void 0,onChange:k=>g(k.target.value),className:"af-invoice-date af-w-[150px]"})]}),H(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Wt(),disabled:Ue||y||!!u||p===0,"aria-busy":Ue,children:[R(gc,{className:"af-h-4 af-w-4 af-mr-1"}),Ue?"Exporting\u2026":"Export CSV (all matching)"]})]}),Ke&&R("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:Ke})]});return y?H("div",{className:e,children:[it,R("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(k=>H("div",{className:"af-rounded-md af-border af-p-3",children:[H("div",{className:"af-flex af-items-center af-justify-between",children:[R(Q,{className:"af-h-4 af-w-20"}),R(Q,{className:"af-h-4 af-w-16"})]}),R(Q,{className:"af-mt-2 af-h-3 af-w-40"})]},k))})]}):u?H("div",{className:e,children:[it,H("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",R(S,{type:"button",variant:"link",size:"sm",onClick:()=>void oe(),children:"Retry"})]})]}):p===0&&ba&&ne===!1&&X==="open"?le?.blocked?H("div",{className:e,children:[it,R(un,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?H("div",{className:e,children:[it,R(un,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):le&&!le.payments_active?H("div",{className:e,children:[it,R(un,{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})]}):H("div",{className:e,children:[it,R(un,{heading:"No invoices yet",body:!le||T?"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."})]}):H("div",{className:e,children:[it,Et.length===0?R("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."}):H(_c,{children:[R("div",{className:"af-space-y-3 lg:af-hidden",children:Et.map(k=>H("button",{type:"button",onClick:()=>Be(k),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[H("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[R("span",{className:"af-font-medium",children:os(k)}),R(Ts,{invoice:k})]}),R("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:k.customer_name??k.customer_email??"\u2014"}),k.delivery&&R("div",{className:"af-mt-1",children:R(fn,{delivery:k.delivery})}),H("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[R("span",{children:k.collection_method==="charge_automatically"?"Automatic collection":k.due_at?`Due ${ea(k.due_at)}`:"Due on receipt"}),R("span",{className:"af-font-medium af-tabular-nums",children:j(k.amount_due??k.amount_total,k.currency)})]})]},k.id))}),R("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:H(Ae,{children:[R(De,{children:H(pe,{children:[R(O,{children:"Invoice"}),R(O,{children:"Created"}),R(O,{children:"Customer"}),R(O,{children:"Due"}),R(O,{className:"af-text-right",children:"Amount"}),R(O,{children:"Status"}),R(O,{children:"Delivery"}),R(O,{className:"af-w-8"})]})}),R(Le,{children:Et.map(k=>H(pe,{className:"af-cursor-pointer",onClick:()=>Be(k),children:[R(B,{className:"af-font-medium",children:R("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:Me=>{Me.stopPropagation(),Be(k)},"aria-label":`Open invoice ${os(k)}`,children:os(k)})}),R(B,{children:ea(k.created_at)}),H(B,{children:[R("div",{children:k.customer_name??"\u2014"}),R("div",{className:"af-text-xs af-text-muted-foreground",children:k.customer_email})]}),R(B,{children:k.collection_method==="charge_automatically"?"Automatic":k.due_at?ea(k.due_at):"On receipt"}),R(B,{className:"af-text-right af-tabular-nums",children:j(k.amount_due??k.amount_total,k.currency)}),R(B,{children:R(Ts,{invoice:k})}),R(B,{children:R(fn,{delivery:k.delivery})}),R(B,{children:R(ai,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},k.id))})]})}),H("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[H("span",{children:[p," invoice",p===1?"":"s"]}),H("div",{className:"af-flex af-items-center af-gap-1",children:[R(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>_(c-1),disabled:!h,"aria-label":"Previous page",children:R(mc,{className:"af-h-4 af-w-4"})}),H("span",{className:"af-tabular-nums",children:[c*d+1,"\u2013",Math.min((c+1)*d,p)]}),R(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>_(c+1),disabled:!b,"aria-label":"Next page",children:R(ai,{className:"af-h-4 af-w-4"})})]})]})]})]})}function un({heading:e,body:a,action:s}){return H("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[R(ri,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),R("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),R("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&R(S,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var Va="af-text-xs af-text-muted-foreground";function ni(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Zn({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=ee(),i=Ne.useRef(null);Ne.useEffect(()=>{i.current?.focus()},[e.id]);let[o,f]=Ne.useState(!1),[m,v]=Ne.useState(null),[r,p]=Ne.useState(!1),[y,u]=Ne.useState(!1),c=Ne.useRef(0),[d,b]=Ne.useState(null),[h,_]=Ne.useState(!1),[D,U]=Ne.useState(0);Ne.useEffect(()=>{let g=!1;return _(!1),n.getInvoice(e.id).then(Z=>{g||b({source:e,value:Z})}).catch(()=>{g||_(!0)}),()=>{g=!0}},[n,e,s,D]);let l=d?.source===e?d.value:e,x=l.collection_method==="charge_automatically";Ne.useEffect(()=>(c.current++,v(null),p(!1),u(!1),f(!1),()=>{c.current++}),[n,l,s]);let C=g=>g==null?"\u2014":j(g,l.currency),G=async()=>{if(!(!l.pay_url||!ni()))try{await navigator.clipboard.writeText(l.pay_url),f(!0),setTimeout(()=>f(!1),1500)}catch{}},L=async()=>{if(m){v(null);return}let g=++c.current;u(!1),p(!0);try{let Z=await n.getInvoicePreview(l.id);g===c.current&&v(Z)}catch{g===c.current&&u(!0)}finally{g===c.current&&p(!1)}},w=l.bill_to,M=w?[w.company,w.name,w.address?.line1,w.address?.line2,[w.address?.city,w.address?.state,w.address?.postal_code].filter(Boolean).join(", "),w.address?.country,w.tax_id?`${w.tax_id.value}`:null,w.po_number?`PO ${w.po_number}`:null,w.service_period?`Service period: ${w.service_period}`:null].filter(g=>!!g&&g.length>0):[];return H("div",{className:t,children:[H("div",{className:"af-mb-4",children:[H(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[R(fc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),H("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[H("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",os(l)]}),R(Ts,{invoice:l}),R(fn,{delivery:l.delivery})]}),H("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[l.customer_name??l.customer_email,l.customer_name&&l.customer_email?` \xB7 ${l.customer_email}`:""]})]}),h&&H("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. ",R(S,{type:"button",variant:"link",size:"sm",onClick:()=>U(g=>g+1),children:"Retry details"})]}),l.label==="failed"&&R("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."}),l.label==="creating"&&R("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."}),H("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[H("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[H("section",{className:"af-rounded-md af-border af-p-4",children:[H(Ae,{children:[R(De,{children:H(pe,{children:[R(O,{children:"Description"}),R(O,{className:"af-text-right",children:"Qty"}),R(O,{className:"af-text-right",children:"Amount"})]})}),R(Le,{children:l.line_items.map((g,Z)=>H(pe,{children:[R(B,{style:{overflowWrap:"anywhere"},children:g.description}),R(B,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:g.quantity}),R(B,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C(g.amount)})]},Z))})]}),H("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[R(Wa,{label:"Subtotal",value:C(l.amount_subtotal)}),(l.discount_total??0)>0&&R(Wa,{label:"Discount",value:`-${C(l.discount_total)}`}),l.tax_total>0&&R(Wa,{label:l.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:C(l.tax_total)}),R(Wa,{label:"Total",value:C(l.amount_total),strong:!0}),l.credit_applied>0&&R(Wa,{label:"Credit applied",value:`-${C(l.credit_applied)}`}),l.amount_due!==null&&l.amount_due!==l.amount_total&&R(Wa,{label:"Amount due",value:C(l.amount_due),strong:!0}),l.amount_paid!==null&&l.amount_paid>0&&R(Wa,{label:"Amount paid",value:C(l.amount_paid)}),l.amount_refunded>0&&R(Wa,{label:"Refunded",value:C(l.amount_refunded)})]}),l.credit_notes?.length>0&&H("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[R("div",{className:Va,children:"Credit notes"}),l.credit_notes.map(g=>H("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[H("span",{className:"af-text-muted-foreground",children:[ea(g.created_at)," \xB7 ",g.origin==="dashboard"?"issued in Stripe":"refund",g.stripe_credit_note_id?"":" \xB7 being created"]}),H("span",{className:"af-tabular-nums",children:["-",j(g.amount,g.currency)]})]},g.id))]})]}),(l.note||l.footer)&&H("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[l.note&&H("div",{children:[R("div",{className:Va,children:"Note"}),R("div",{className:"af-whitespace-pre-wrap af-break-words",children:l.note})]}),l.footer&&H("div",{children:[R("div",{className:Va,children:"Footer"}),R("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:l.footer})]})]}),m&&!x&&H("section",{className:"af-rounded-md af-border af-p-4",children:[H("div",{className:z(Va,"af-break-words"),children:["Email preview \u2014 ",m.subject]}),R("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),R("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"})]})]}),H("div",{className:"af-min-w-0 af-space-y-4",children:[H("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[R(Xt,{label:"Created",value:ea(l.created_at)}),R(Xt,{label:"Due",value:l.collection_method==="charge_automatically"?"Managed in Stripe":l.due_at?ea(l.due_at):"On receipt"}),l.paid_at&&R(Xt,{label:"Paid",value:ea(l.paid_at)}),l.payment_method&&R(Xt,{label:"Paid by",value:l.paid_out_of_band?`${l.payment_method} (recorded outside Stripe)`:l.payment_method}),l.payment_state!=="none"&&R(Xt,{label:"Payment",value:l.payment_state==="processing"?"Processing":l.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),l.delivery&&R(Xt,{label:"Delivery",value:`${Jn[l.delivery.state]} \xB7 ${l.delivery.recipient}`}),l.marked_uncollectible_at&&R(Xt,{label:"Written off",value:ea(l.marked_uncollectible_at)}),l.correction_reason&&R(Xt,{label:"Correction",value:l.correction_reason}),l.replaced_by_order_id&&R(Xt,{label:"Replaced by",value:l.replaced_by_order_id}),l.collection_method==="charge_automatically"?R(Xt,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):l.retainer_id&&R(Xt,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),l.replaces_order_id&&R(Xt,{label:"Replaces",value:l.replaces_order_id})]}),H("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[R("div",{className:Va,children:"Reminders"}),x?R("div",{children:"View automatic payment reminders in Stripe."}):l.reminders.disabled?R("div",{children:"Off for this invoice."}):l.reminders.paused_until?H("div",{children:["Paused until ",ea(l.reminders.paused_until),"."]}):l.reminders.next_at?H("div",{children:["Next on ",ea(l.reminders.next_at),"."]}):l.reminders.final_sent_at?H("div",{children:["Final reminder sent ",ea(l.reminders.final_sent_at),"."]}):R("div",{children:"None scheduled."}),!x&&H("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",l.reminders.schedule.length===0?"none":l.reminders.schedule.map(g=>g<0?`${-g}d before`:g===0?"due day":`${g}d after`).join(", ")]})]}),l.communications&&l.communications.length>0&&H("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[R("div",{className:Va,children:"Email delivery history"}),l.communications.map(g=>H("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[H("span",{className:"af-min-w-0 af-break-words",children:[wc[g.kind]??g.kind,g.kind==="reminder"&&g.slot!==null?` #${g.slot}`:"",H("span",{className:"af-text-muted-foreground",children:[" \xB7 ",g.recipient]})]}),H("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Jn[g.state]??g.state," \xB7 ",ea(g.state_at??g.created_at)]})]},g.id))]}),M.length>0&&H("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[R("div",{className:Va,children:"Bill to"}),M.map((g,Z)=>R("div",{className:"af-break-words",children:g},Z))]}),H("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[l.pay_url&&H(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void G(),disabled:!ni(),children:[R(pc,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":x?"Copy invoice link":"Copy pay link"]}),l.pdf_url&&R(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:H("a",{href:l.pdf_url,target:"_blank",rel:"noreferrer",children:[R(vc,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!x&&H(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void L(),disabled:r,children:[r?R(bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):R(ri,{className:"af-h-4 af-w-4 af-mr-1"}),m?"Hide email preview":y?"Retry email preview":"Show email preview"]}),y&&!x&&R("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),l.pay_url&&R("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:l.pay_url}),R("p",{className:"af-text-xs af-text-muted-foreground",children:x?"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 Xt({label:e,value:a}){return H("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[R("span",{className:z(Va,"af-shrink-0"),children:e}),R("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function Wa({label:e,value:a,strong:s}){return H("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[R("dt",{className:z(Va,s&&"af-font-medium af-text-foreground"),children:e}),R("dd",{className:z("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as Pc}from"lucide-react";import{jsx as ut,jsxs as fa}from"react/jsx-runtime";var Tc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},oi={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Cc(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 li(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>oi[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>oi[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Tc[e.status]}function ci(e){let a=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${a}`}function kc(e){return e.status==="canceled"?`Ended ${mn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${mn(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 ${mn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${mn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function mn(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 Qn({retainer:e,className:a}){return ut(Y,{variant:Cc(e.status),className:z("af-max-w-full af-whitespace-normal af-break-words",a),children:li(e)})}function cs({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:f=0,isLoadingMore:m=!1,onLoadMore:v,includeEnded:r=!1,onIncludeEndedChange:p,className:y}){let u=!!p;if(!a&&!s&&e.length===0&&!(u&&(r||f>0)))return null;let c=o!==void 0?Math.max(0,o-e.length):0;return fa("section",{className:z("af-mb-6",y),"aria-label":"Recurring invoices",children:[fa("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[ut(Pc,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),ut("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),ut("span",{className:"af-text-xs af-text-muted-foreground",children:"Send invoices on a schedule \u2014 change, skip, pause or end them from the chat."}),u&&ut(S,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>p?.(!r),children:r?"Hide ended recurring invoices":f>0&&e.length===0?`Show ended recurring invoices (${f})`:"Show ended recurring invoices"})]}),s?fa("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",ut(S,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?ut("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(d=>fa("div",{className:"af-rounded-md af-border af-p-3",children:[ut(Q,{className:"af-h-4 af-w-48"}),ut(Q,{className:"af-mt-2 af-h-3 af-w-32"})]},d))}):e.length===0?ut("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."}):ut("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(d=>{let b=i===d.id;return fa("li",{className:z("af-rounded-md af-border af-p-3",b&&"af-border-primary af-bg-muted/40"),children:[fa("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[fa("div",{className:"af-min-w-0",children:[ut("div",{className:"af-truncate af-font-medium",children:d.customer_name??d.customer_email??"\u2014"}),ut("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:d.description})]}),ut(Qn,{retainer:d})]}),d.collection_method==="charge_automatically"?fa("div",{className:"af-mt-2 af-space-y-1",children:[ut(Y,{variant:"secondary",children:"Managed in Stripe"}),ut("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."})]}):ut("div",{className:"af-mt-2 af-text-sm",children:ci(d)}),fa("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:[fa("span",{children:[kc(d)," \xB7 ",d.cycles.count===0?"no invoices yet":`${d.cycles.paid} paid${d.cycles.open>0?`, ${d.cycles.open} open`:""}`]}),d.cycles.count>0&&ut(S,{type:"button",variant:b?"secondary":"ghost",size:"sm",onClick:()=>n(d),"aria-pressed":b,children:b?"Showing invoices":"View invoices"})]}),d.status==="failed"&&d.operation?.last_error&&fa("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",d.operation.last_error,". Ask in the chat to try again."]})]},d.id)})}),!a&&!s&&c>0&&v&&ut("div",{className:"af-mt-2",children:ut(S,{type:"button",variant:"outline",size:"sm",onClick:v,disabled:m,children:m?"Loading\u2026":`Load more (${c} more)`})})]})}import*as ui from"react";import{AlertTriangle as di,CheckCircle2 as Ec,CreditCard as Xn,Loader2 as Ic,RefreshCw as Ac}from"lucide-react";import*as Ca from"react";function ds(){let{api:e}=ee(),[a,s]=Ca.useState(null),[t,n]=Ca.useState(!0),[i,o]=Ca.useState(null),f=Ca.useRef(0),m=Ca.useCallback(async()=>{let v=++f.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(v!==f.current)return;s(r)}catch(r){if(v!==f.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{v===f.current&&n(!1)}},[e]);return Ca.useEffect(()=>{m()},[m]),{status:a,isLoading:t,error:i,refetch:m}}import{jsx as Ye,jsxs as vt}from"react/jsx-runtime";function pn({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=ds(),[f,m]=ui.useState(!1),v=async()=>{m(!0);try{await o()}finally{m(!1)}};return n&&!t?Ye("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Ye("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?Ye("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:vt("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?Ye("div",{className:s,children:vt("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:[Ye(Ec,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),vt("div",{children:[Ye("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),vt("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."]})]})]})}):vt("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&vt("div",{className:"af-space-y-3",children:[vt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Ye(Xn,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),vt("div",{children:[Ye("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Ye("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?vt(S,{onClick:e,children:[Ye(Xn,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):Ye("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"&&vt("div",{className:"af-space-y-3",children:[vt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Ye(di,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),vt("div",{children:[Ye("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Ye("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?Ye(S,{onClick:a,children:"Upgrade plan"}):Ye("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&vt("div",{className:"af-space-y-3",children:[vt("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:[Ye(di,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),vt("div",{children:[Ye("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?Ye("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."}):Ye("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."})]})]}),vt("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&vt(S,{onClick:e,children:[Ye(Xn,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),vt(S,{variant:"outline",onClick:v,disabled:f,children:[f?Ye(Ic,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Ye(Ac,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Pt from"react";function er(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function us({includeStats:e=!1,refreshKey:a}={}){let{api:s}=ee(),[t,n]=Pt.useState([]),[i,o]=Pt.useState(!0),[f,m]=Pt.useState(null),v=Pt.useRef(0),r=Pt.useCallback(async()=>{let b=++v.current;try{o(!0),m(null);let h=await s.getProducts(e?{include:"stats"}:{});if(b!==v.current)return;n(h)}catch(h){if(b!==v.current)return;m(h instanceof Error?h:new Error("Failed to fetch products"))}finally{b===v.current&&o(!1)}},[s,e,a]);Pt.useEffect(()=>{r()},[r]);let p=Pt.useCallback(async b=>{let h=await s.createProduct(b);return n(_=>[h,..._]),h},[s]),y=Pt.useCallback(async(b,h)=>{let _=await s.updateProduct(b,h);return n(D=>er(D,b,_)),_},[s]),u=Pt.useCallback(async b=>{await s.deleteProduct(b),n(h=>h.filter(_=>_.id!==b))},[s]),c=Pt.useCallback(async(b,h)=>{let _=await s.attachProductFile(b,h);return n(D=>er(D,b,_)),_},[s]),d=Pt.useCallback(async(b,h)=>{let _=await s.attachProductFileFromUrl(b,h);return n(D=>er(D,b,_)),_},[s]);return{products:t,isLoading:i,error:f,refetch:r,createProduct:p,updateProduct:y,deleteProduct:u,attachProductFile:c,attachProductFileFromUrl:d}}import*as Tt from"react";var fi=["creating","active","paused","canceling"],Dc=["canceled","failed"];function fs({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=ee(),[n,i]=Tt.useState([]),[o,f]=Tt.useState(0),[m,v]=Tt.useState(0),[r,p]=Tt.useState(!0),[y,u]=Tt.useState(!1),[c,d]=Tt.useState(null),[b,h]=Tt.useState(a),_=Tt.useRef(0),D=Tt.useCallback(async()=>{let l=++_.current;p(!0),u(!1),d(null);try{let x=await t.getRetainers({statuses:b?void 0:fi,limit:s,offset:0});if(l!==_.current)return;if(i(x.retainers),f(x.total),!b&&x.total===0){let C=await t.getRetainers({statuses:Dc,limit:1,offset:0});if(l!==_.current)return;v(C.total)}else v(0)}catch(x){if(l!==_.current)return;d(x instanceof Error?x:new Error("Failed to fetch retainers"))}finally{l===_.current&&p(!1)}},[t,b,s]);Tt.useEffect(()=>{D()},[D,e]);let U=Tt.useCallback(async()=>{if(r||y||n.length>=o)return;let l=_.current;u(!0);try{let x=await t.getRetainers({statuses:b?void 0:fi,limit:s,offset:n.length});if(l!==_.current)return;i(C=>{let G=new Set(C.map(L=>L.id));return[...C,...x.retainers.filter(L=>!G.has(L.id))]}),f(x.total)}catch(x){if(l!==_.current)return;d(x instanceof Error?x:new Error("Failed to fetch retainers"))}finally{l===_.current&&u(!1)}},[t,b,s,r,y,n.length,o]);return{retainers:n,total:o,endedTotal:m,hasMore:n.length<o,isLoading:r,isLoadingMore:y,error:c,includeEnded:b,setIncludeEnded:h,loadMore:U,refetch:D}}import{Fragment as $c,jsx as ze,jsxs as Lt}from"react/jsx-runtime";function mi({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=ms.useState(a),[f,m]=ms.useState("list"),[v,r]=ms.useState(null),p=us(),{status:y,error:u}=ds(),c=y?.currency,d=D=>{r(D),m("edit")},b=()=>{r(null),m("create")},h=()=>{m("list"),r(null)},_=D=>{r(D),m("edit")};return Lt("div",{className:e,children:[Lt("div",{className:"af-mb-6",children:[ze("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),ze("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Lt(Ms,{value:i,onValueChange:D=>o(D),children:[Lt(Ns,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Lt(ha,{value:"products",className:"af-gap-2",children:[ze(Bc,{className:"af-h-4 af-w-4"}),"Products"]}),Lt(ha,{value:"orders",className:"af-gap-2",children:[ze(Fc,{className:"af-h-4 af-w-4"}),"Orders"]}),Lt(ha,{value:"invoices",className:"af-gap-2",children:[ze(Oc,{className:"af-h-4 af-w-4"}),"Invoices"]}),Lt(ha,{value:"customers",className:"af-gap-2",children:[ze(Uc,{className:"af-h-4 af-w-4"}),"Customers"]}),Lt(ha,{value:"setup",className:"af-gap-2",children:[ze(Mc,{className:"af-h-4 af-w-4"}),"Setup"]})]}),ze(xa,{value:"products",children:f==="list"?ze(Ys,{productsState:p,onSelectProduct:d,onCreateProduct:b}):Lt("div",{children:[Lt("div",{className:"af-mb-6",children:[Lt(S,{variant:"ghost",size:"sm",onClick:h,className:"af-mb-2 af--ml-2",children:[ze(Lc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),ze("h3",{className:"af-text-lg af-font-semibold",children:f==="create"?"New Product":v?.name})]}),f==="create"&&!c?ze("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:u?Lt("div",{className:"af-text-destructive",children:["Error: ",u.message]}):ze("div",{className:"af-text-muted-foreground",children:"Loading..."})}):ze(Qs,{productsState:p,product:f==="edit"?v:null,currency:c??"usd",onSaved:_},f==="edit"?v?.id??"edit":"new")]})}),ze(xa,{value:"orders",children:ze(rs,{onRefund:t})}),ze(xa,{value:"invoices",children:ze(Vc,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:y?.reason==="needs_paid_plan"})}),ze(xa,{value:"customers",children:ze(dn,{})}),ze(xa,{value:"setup",children:ze(pn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Vc({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=fs(),[n,i]=ms.useState(null),[o,f]=ms.useState(!1);return Lt($c,{children:[!o&&ze(cs,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:m=>i(v=>v?.id===m.id?null:m),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),ze(ls,{onDetailOpenChange:f,onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}import*as gi from"react";import*as ka from"react";function gn({refreshKey:e}={}){let{api:a}=ee(),[s,t]=ka.useState(null),[n,i]=ka.useState(!0),[o,f]=ka.useState(null),m=ka.useRef(0),v=ka.useCallback(async()=>{let r=++m.current;try{i(!0),f(null);let p=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==m.current)return;t(p)}catch(p){if(r!==m.current)return;f(p instanceof Error?p:new Error("Failed to fetch summary"))}finally{r===m.current&&i(!1)}},[a,e]);return ka.useEffect(()=>{v()},[v]),{summary:s,isLoading:n,error:o,refetch:v}}import{Fragment as tr,jsx as bt,jsxs as ar}from"react/jsx-runtime";function pi(e,a){if(e.settled.complete)return{headline:j(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:j(s.gross,s.currency),extra:e.totals.slice(1).map(t=>`+ ${j(t.gross,t.currency)} in ${t.currency.toUpperCase()}`)}:{headline:j(0,a),extra:[]}}function vi({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:f,error:m,refetch:v}=gn({refreshKey:e}),[r,p]=gi.useState(!1),y=bt("div",{className:"af-mb-6",children:m&&!o?bt(zt,{message:"Couldn't load your revenue summary.",onRetry:()=>v()}):bt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!o?ar(tr,{children:[bt(Je,{label:"This week",children:bt(Q,{className:"af-h-6 af-w-24"})}),bt(Je,{label:"Today",children:bt(Q,{className:"af-h-6 af-w-24"})}),bt(Je,{label:"Needs attention",children:bt(Q,{className:"af-h-6 af-w-10"})})]}):bt(tr,{children:(()=>{let u=pi(o.revenue.d7,o.currency),c=pi(o.revenue.today,o.currency);return ar(tr,{children:[bt(Je,{label:"This week",detail:u.extra.length>0?bt("div",{children:u.extra.map(d=>bt("div",{children:d},d))}):void 0,children:u.headline}),bt(Je,{label:"Today",detail:c.extra.length>0?bt("div",{children:c.extra.map(d=>bt("div",{children:d},d))}):void 0,children:c.headline}),bt(Je,{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 ar(xt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[y,bt(rs,{refreshKey:e,initialOrderId:a,onDetailOpenChange:p,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as $a from"react";import{ImageOff as Gc,Package as Wc,Search as Kc}from"lucide-react";import*as Ea from"react";import{ArrowLeft as qc,ImageOff as jc}from"lucide-react";import{jsx as ma,jsxs as Cs}from"react/jsx-runtime";var bi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ka="af-text-xs af-text-muted-foreground",vn="af-text-sm af-font-medium af-tabular-nums",Hc=3;function zc(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,v=e.max_amount??a?.max_amount??null;return m!==null&&v!==null?{text:`Buyer chooses (${j(m,s)} \u2013 ${j(v,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=a?.min_amount??e.unit_amount,i=a?.max_amount??e.unit_amount;if(n===null||i===null)return{text:"Varies by variant",compareAt:null};let o=n===i?j(n,s):`${j(n,s)} \u2013 ${j(i,s)}`,f=a?.compare_at_amount??null;return{text:o,compareAt:f!==null&&f>i?j(f,s):null}}function bn({product:e,className:a}){let s=zc(e);return Cs("div",{className:a,children:[ma("span",{className:vn,children:s.text}),s.compareAt&&ma("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function yn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?ma(Y,{variant:"destructive",children:"Out of stock"}):a.low_stock?Cs(Y,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?ma(Y,{variant:"secondary",children:"Backorder"}):a.available===null?null:Cs(Y,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?ma(Y,{variant:"warning",children:"Low stock"}):null}function hn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function xn(e){return e.map(a=>j(a.amount,a.currency)).join(" + ")}function yi(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${j(e.min_amount,e.currency)} \u2013 ${j(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":j(e.unit_amount,e.currency)}function hi({variant:e}){let a=e.inventory;if(!a||!a.tracked)return ma("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?Cs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ma("span",{className:"af-tabular-nums",children:Math.max(0,s)}),ma(Y,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?ma(Y,{variant:"destructive",children:"Out of stock"}):Cs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[ma("span",{className:"af-tabular-nums",children:s}),s<=Hc&&ma(Y,{variant:"warning",children:"Low"})]})}import{jsx as ae,jsxs as qe}from"react/jsx-runtime";function ks({title:e,children:a,className:s}){return qe("section",{className:z("af-rounded-lg af-border af-p-4",s),children:[ae("h4",{className:bi,children:e}),ae("div",{className:"af-mt-3",children:a})]})}function xi({src:e,className:a}){let[s,t]=Ea.useState(!1);return Ea.useEffect(()=>t(!1),[e]),!e||s?ae("div",{"aria-hidden":"true",className:z("af-flex af-items-center af-justify-center af-bg-muted",a),children:ae(jc,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):ae("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:z("af-object-cover",a)})}function wi({product:e,showStats:a=!1,onBack:s}){let{api:t}=ee(),[n,i]=Ea.useState(null),[o,f]=Ea.useState(!0),[m,v]=Ea.useState(null),[r,p]=Ea.useState(0),[y,u]=Ea.useState(0);Ea.useEffect(()=>{let l=!1;return f(!0),v(null),t.getProduct(e.id).then(x=>{l||i(x)}).catch(x=>{l||v(x instanceof Error?x:new Error("Failed to load product"))}).finally(()=>{l||f(!1)}),()=>{l=!0}},[t,e.id,r]);let c=n?{...e,...n}:e,d=c.images.length>0?c.images:e.images,b=d[y]??d[0],h=hn(c),_=a?c.stats:void 0,D=n?.variants??[],U=D.length>1;return qe("div",{children:[qe("div",{className:"af-mb-6",children:[qe(S,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[ae(qc,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),qe("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ae("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),ae(Y,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),ae(yn,{product:c})]}),ae(bn,{product:c,className:"af-mt-1"}),!c.active&&ae("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),qe("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[qe("div",{className:"af-space-y-2",children:[ae(xi,{src:b,className:"af-h-48 af-w-full af-rounded-md af-border"}),d.length>1&&ae("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map((l,x)=>ae("button",{type:"button",onClick:()=>u(x),"aria-label":`Show photo ${x+1} of ${d.length}`,"aria-pressed":x===y,className:z("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",x===y?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:ae(xi,{src:l,className:"af-h-12 af-w-12 af-rounded-md"})},`${l}-${x}`))})]}),qe("div",{className:"af-space-y-6",children:[c.description&&ae(ks,{title:"Description",children:ae("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?qe(ks,{title:"Variants",children:[ae("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(l=>qe("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[ae(Q,{className:"af-h-4 af-w-28"}),ae(Q,{className:"af-h-4 af-w-20"}),ae(Q,{className:"af-h-4 af-w-16"})]},l))}),ae("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):m?ae(zt,{message:"Couldn't load this product's variants.",onRetry:()=>p(l=>l+1)}):U?ae(ks,{title:`Variants \xB7 ${D.length}`,children:ae("div",{className:"af-overflow-x-auto",children:qe(Ae,{children:[ae(De,{children:qe(pe,{children:[ae(O,{children:"Variant"}),ae(O,{children:"SKU"}),ae(O,{className:"af-text-right",children:"Price"}),ae(O,{children:"Stock"})]})}),ae(Le,{children:D.map(l=>qe(pe,{children:[qe(B,{className:"af-font-medium",children:[l.title||l.option_values.map(x=>x.value).join(" / ")||"\u2014",!l.active&&ae(Y,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),ae(B,{className:"af-text-muted-foreground",children:l.sku?ae("code",{className:"af-font-mono af-text-xs af-break-all",children:l.sku}):"\u2014"}),qe(B,{className:"af-whitespace-nowrap af-text-right",children:[ae("div",{className:vn,children:yi(l)}),l.compare_at_amount!==null&&l.unit_amount!==null&&l.compare_at_amount>l.unit_amount&&ae("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(l.compare_at_amount,l.currency)})]}),ae(B,{className:"af-text-sm",children:ae(hi,{variant:l})})]},l.id))})]})})}):null,ae(ks,{title:"Details",children:qe("dl",{className:"af-space-y-2",children:[qe("div",{children:[ae("dt",{className:Ka,children:"Delivery"}),ae("dd",{className:"af-text-sm",children:h==="Digital download"?c.fulfillment.filename??"Digital download":h??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&qe("div",{children:[ae("dt",{className:Ka,children:"Sends buyers to"}),ae("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),qe("div",{children:[ae("dt",{className:Ka,children:"Shipping address"}),ae("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),qe("div",{children:[ae("dt",{className:Ka,children:"Most one buyer can order"}),ae("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),_&&ae(ks,{title:"Last 30 days",children:qe("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[qe("div",{children:[ae("dt",{className:Ka,children:"Units sold"}),ae("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:_.units_sold})]}),qe("div",{children:[ae("dt",{className:Ka,children:"Orders"}),ae("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:_.orders})]}),qe("div",{children:[ae("dt",{className:Ka,children:"Gross"}),ae("dd",{className:vn,children:_.gross.length>0?xn(_.gross):"\u2014"})]})]})}),ae("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 ps,jsx as se,jsxs as Ze}from"react/jsx-runtime";var Jc={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Yc=["all","active","draft","low_stock","out_of_stock"];function Ni(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function Si(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Zc(e){return e.inventory?.out_of_stock??!1}function Qc(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Si(e);case"out_of_stock":return Zc(e);default:return!0}}function Xc({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=hn(e),o=e.variant_count??0;return Ze("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[t?se("img",{src:t,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):se("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:se(Gc,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ze("div",{className:"af-space-y-2 af-p-3",children:[Ze("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ze("div",{className:"af-min-w-0",children:[se("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),se(bn,{product:e,className:"af-mt-0.5"})]}),!e.active&&se(Y,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ze("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[se(yn,{product:e}),o>1&&Ze(Y,{variant:"outline",children:[o," variants"]}),i&&se(Y,{variant:"outline",children:i})]}),n&&Ze("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${xn(n.gross)}`:""," ",se("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function ed(){return se("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:[0,1,2,3,4,5].map(e=>Ze("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[se("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),Ze("div",{className:"af-space-y-2 af-p-3",children:[se(Q,{className:"af-w-32"}),se(Q,{className:"af-w-16"}),se(Q,{className:"af-h-5 af-w-24"})]})]},e))})}function Ri({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:f}=us({includeStats:a,refreshKey:e}),[m,v]=$a.useState(null),[r,p]=$a.useState("all"),[y,u]=$a.useState(""),[c,d]=$a.useState("newest"),b=$a.useMemo(()=>{if(!a)return null;let w=null;for(let M of n)!M.stats||M.stats.units_sold===0||(!w||M.stats.units_sold>(w.stats?.units_sold??0))&&(w=M);return w},[n,a]),h=$a.useMemo(()=>n.filter(Si).length,[n]),_=y.trim().toLowerCase(),D=$a.useMemo(()=>{let M=[...n.filter(g=>Qc(g,r)&&(!_||g.name.toLowerCase().includes(_)))];return c==="name"?M.sort((g,Z)=>g.name.localeCompare(Z.name)):c==="best_selling"?M.sort((g,Z)=>(Z.stats?.units_sold??0)-(g.stats?.units_sold??0)):M.sort((g,Z)=>Ni(Z.created_at)-Ni(g.created_at)),M},[n,r,_,c]),U=r!=="all"||!!_,l=()=>{p("all"),u("")},x=i||o!==null&&n.length===0,C=se("div",{className:"af-mb-6",children:se("div",{className:z("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:x?Ze(ps,{children:[se(Je,{label:"Products",children:se(Q,{className:"af-h-6 af-w-10"})}),a?Ze(ps,{children:[se(Je,{label:"Best seller",children:se(Q,{className:"af-h-6 af-w-28"})}),se(Je,{label:"Low stock",children:se(Q,{className:"af-h-6 af-w-10"})})]}):se(Je,{label:"Active",children:se(Q,{className:"af-h-6 af-w-10"})})]}):Ze(ps,{children:[se(Je,{label:"Products",children:n.length}),a?Ze(ps,{children:[se(Je,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:b?`${b.stats?.units_sold??0} sold, last 30 days`:void 0,children:b?se("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:b.name}):se("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),se(Je,{label:"Low stock",children:h})]}):se(Je,{label:"Active",children:n.filter(w=>w.active).length})]})})}),G=Ze("div",{className:"af-mb-4 af-space-y-3",children:[Ze("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[se("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Yc.map(w=>se("button",{type:"button","aria-pressed":r===w,onClick:()=>p(w),className:z("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",r===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Jc[w]},w))}),Ze("div",{className:"af-relative af-w-full af-max-w-xs",children:[se(Kc,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),se(ve,{type:"text",value:y,onChange:w=>u(w.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ze(Kt,{value:c,onValueChange:w=>d(w),children:[se(Ut,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:se(Jt,{})}),Ze(Vt,{children:[se(Ve,{value:"newest",children:"Newest"}),se(Ve,{value:"name",children:"Name A\u2013Z"}),a&&se(Ve,{value:"best_selling",children:"Best selling"})]})]}),U&&se(S,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Clear filters"})]}),i&&n.length===0?se(Q,{className:"af-h-4 af-w-28"}):se("p",{className:"af-text-sm af-text-muted-foreground",children:U?`${D.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),L;return m?L=se(wi,{product:m,showStats:a,onBack:()=>{v(null),f()}},m.id):i&&n.length===0?L=Ze(ps,{children:[G,se(ed,{}),se("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?L=se("div",{className:"af-flex af-justify-center af-py-8",children:se(zt,{message:"Couldn't load your products.",onRetry:()=>f()})}):n.length===0?L=Ze(Ta,{icon:se(Wc,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",se("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):L=Ze(ps,{children:[G,o&&se("div",{className:"af-mb-4",children:se(zt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>f()})}),D.length===0?Ze(Ta,{children:["No products match these filters.",se("br",{}),se(S,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:l,children:"Show all products"})]}):se("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:D.map(w=>se(Xc,{product:w,showStats:a,onOpen:()=>v(w)},w.id))})]}),Ze(xt,{title:"Products",onBackToWebsite:s,hideBackButton:!!m,className:t,children:[!m&&C,L]})}import*as pa from"react";import{ArrowLeft as ki,Check as td,ChevronLeft as _i,ChevronRight as Pi,ClipboardCopy as ad,Mail as nr,Search as sd,Users as nd}from"lucide-react";import*as qt from"react";function wn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ee(),[t,n]=qt.useState([]),[i,o]=qt.useState(!0),[f,m]=qt.useState(null),[v,r]=qt.useState(0),[p]=qt.useState(e),[y,u]=qt.useState(""),c=qt.useRef(0),d=qt.useCallback(async()=>{let b=++c.current;try{o(!0),m(null);let h={limit:p,offset:v*p};y.trim()&&(h.q=y.trim());let _=await s.getPeople(h);if(b!==c.current)return;n(_.people)}catch(h){if(b!==c.current)return;m(h instanceof Error?h:new Error("Failed to fetch people"))}finally{b===c.current&&o(!1)}},[s,v,p,y,a]);return qt.useEffect(()=>{d()},[d]),{people:t,isLoading:i,error:f,page:v,pageSize:p,hasNextPage:t.length===p,hasPreviousPage:v>0,setPage:r,q:y,setQ:b=>{u(b),r(0)},refetch:d}}import*as Ia from"react";function Nn(e,{refreshKey:a}={}){let{api:s}=ee(),[t,n]=Ia.useState(null),[i,o]=Ia.useState(e!==null),[f,m]=Ia.useState(null),v=Ia.useRef(0),r=Ia.useCallback(async()=>{if(e===null){n(null),o(!1),m(null);return}let p=++v.current;try{o(!0),m(null);let y=await s.getPerson(e);if(p!==v.current)return;n(y)}catch(y){if(p!==v.current)return;m(y instanceof Error?y:new Error("Failed to fetch person"))}finally{p===v.current&&o(!1)}},[s,e,a]);return Ia.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:f,refetch:r}}import{jsx as N,jsxs as te}from"react/jsx-runtime";var sr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",rd="af-text-xs af-text-muted-foreground";function gs(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 rr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function id(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function od({value:e,label:a}){let[s,t]=pa.useState(!1);return id()?te(S,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),t(!0),setTimeout(()=>t(!1),1500)}catch{}},"aria-label":a,className:"af-shrink-0",children:[s?N(td,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):N(ad,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function Ti(e){return te("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&te(Y,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&N(Y,{variant:"secondary",children:"Contact form"})]})}function Ci(e){return e.name?e.name:e.email?e.email:N("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var ld=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,cd=40;function dd(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>ld.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=cd).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 ud(e){return e.replace(/_/g," ")}function fd(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function md({data:e}){let{message:a,rest:s}=dd(e);return a===null&&s.length===0?N("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):te("div",{className:"af-space-y-3",children:[a!==null&&N("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&N("dl",{className:"af-space-y-1",children:s.map(([t,n])=>te("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[N("dt",{className:z(rd,"af-w-28 af-shrink-0 af-capitalize"),children:ud(t)}),N("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:fd(n)})]},t))})]})}function Ei({formName:e,createdAt:a,data:s}){return te("div",{className:"af-rounded-md af-border af-p-3",children:[te("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[N(Y,{variant:"outline",children:"Form submission (unverified)"}),e&&N("span",{className:"af-text-xs af-text-muted-foreground",children:e}),N("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:gs(a)})]}),N(md,{data:s})]})}function pd(e){return e.charged_total??e.amount_total}function gd({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=Nn(e,{refreshKey:a}),f=rr(e,t?.submissions[0]?.form_name);return te("div",{children:[te("div",{className:"af-mb-6",children:[te(S,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[N(ki,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),te("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[te("div",{className:"af-min-w-0",children:[n?N(Q,{className:"af-h-7 af-w-48"}):N("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),te("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[N("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),N(od,{value:e,label:"Copy email address"})]})]}),N(S,{asChild:!0,children:te("a",{href:f,children:[N(nr,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?te("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(m=>te("div",{className:"af-rounded-md af-border af-p-3",children:[N(Q,{className:"af-w-40"}),N(Q,{className:"af-mt-2 af-w-64"})]},m)),N("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?N("div",{className:"af-flex af-justify-center af-py-8",children:N(zt,{message:"Couldn't load this person.",onRetry:()=>o()})}):te("div",{className:"af-space-y-6",children:[t.customer&&te("div",{children:[N("h4",{className:z(sr,"af-mb-3"),children:"Customer"}),te("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&te("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),N("dd",{children:t.customer.name})]}),t.customer.phone&&te("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),N("dd",{children:t.customer.phone})]}),te("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),N("dd",{children:gs(t.customer.created_at)})]})]})]}),t.orders.length>0&&te("div",{children:[N("h4",{className:z(sr,"af-mb-3"),children:"Purchases"}),N("div",{className:"af-overflow-x-auto",children:te(Ae,{children:[N(De,{children:te(pe,{children:[N(O,{children:"Order"}),N(O,{children:"Date"}),N(O,{className:"af-text-right",children:"Total"}),N(O,{children:"Status"})]})}),N(Le,{children:t.orders.map(m=>te(pe,{children:[N(B,{className:"af-whitespace-nowrap af-font-medium",children:Ua(m)}),N(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:gs(m.created_at)}),N(B,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(pd(m),m.currency)}),N(B,{children:N(Xa,{status:m.status})})]},m.id))})]})}),N("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),t.submissions.length>0&&te("div",{children:[N("h4",{className:z(sr,"af-mb-3"),children:"Messages"}),N("div",{className:"af-space-y-3",children:t.submissions.map(m=>N(Ei,{formName:m.form_name,createdAt:m.created_at,data:m.data},m.id))})]})]})]})}function vd({submissionId:e,onBack:a}){let{api:s}=ee(),[t,n]=pa.useState(null),[i,o]=pa.useState(!0),[f,m]=pa.useState(null),[v,r]=pa.useState(0);return pa.useEffect(()=>{let p=!1;return o(!0),m(null),s.getSubmission(e).then(y=>{p||n(y)}).catch(y=>{p||m(y instanceof Error?y:new Error("Failed to load submission"))}).finally(()=>{p||o(!1)}),()=>{p=!0}},[s,e,v]),te("div",{children:[te("div",{className:"af-mb-6",children:[te(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[N(ki,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),N("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?N(Q,{className:"af-mt-1 af-h-4 af-w-32"}):t&&N("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:gs(t.metadata.submitted_at)})]}),i?te("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[N(Q,{className:"af-w-40"}),N(Q,{className:"af-mt-2 af-w-64"}),N(Q,{className:"af-mt-2 af-w-52"}),N("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):f||!t?N("div",{className:"af-flex af-justify-center af-py-8",children:N(zt,{message:"Couldn't load this submission.",onRetry:()=>r(p=>p+1)})}):te("div",{className:"af-space-y-3",children:[N(Ei,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),N("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var bd={all:"All",customers:"Customers",leads:"Leads"},yd=["all","customers","leads"];function hd(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function Ii({refreshKey:e,onBackToWebsite:a,className:s}){let{people:t,isLoading:n,error:i,page:o,pageSize:f,hasNextPage:m,hasPreviousPage:v,setPage:r,q:p,setQ:y,refetch:u}=wn({refreshKey:e}),[c,d]=pa.useState({kind:"list"}),[b,h]=pa.useState(""),[_,D]=pa.useState("all"),U=L=>{L.email?d({kind:"person",email:L.email}):L.submission_id&&d({kind:"submission",submissionId:L.submission_id})},l=()=>{d({kind:"list"}),u()},x=L=>{let w=L.trim();w!==p&&y(w)},C=t.filter(L=>hd(L,_)),G;if(c.kind==="person")G=N(gd,{email:c.email,refreshKey:e,onBack:l});else if(c.kind==="submission")G=N(vd,{submissionId:c.submissionId,onBack:l});else{let L=te("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[N("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:yd.map(w=>N("button",{type:"button","aria-pressed":_===w,onClick:()=>D(w),className:z("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",_===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:bd[w]},w))}),te("div",{className:"af-relative af-w-full af-max-w-xs",children:[N(sd,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),N(ve,{type:"text",value:b,onChange:w=>h(w.target.value),onBlur:()=>x(b),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),x(b))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),p&&N(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),y("")},children:"Clear search"})]});if(n)G=te("div",{children:[L,N("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(w=>te("div",{className:"af-rounded-md af-border af-p-3",children:[te("div",{className:"af-flex af-items-center af-justify-between",children:[N(Q,{className:"af-h-4 af-w-32"}),N(Q,{className:"af-h-4 af-w-16"})]}),N(Q,{className:"af-mt-2 af-h-5 af-w-28"}),N(Q,{className:"af-mt-2 af-h-3 af-w-56"})]},w))}),N("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:te(Ae,{children:[N(De,{children:te(pe,{children:[N(O,{children:"Person"}),N(O,{children:"Came from"}),N(O,{children:"Latest message"}),N(O,{children:"Last activity"}),N(O,{className:"af-w-8"}),N(O,{className:"af-w-8"})]})}),N(Le,{"aria-hidden":"true",children:[0,1,2,3,4].map(w=>te(pe,{children:[N(B,{children:N(Q,{className:"af-h-4 af-w-40"})}),N(B,{children:N(Q,{className:"af-h-5 af-w-24"})}),N(B,{children:N(Q,{className:"af-h-4 af-w-56"})}),N(B,{children:N(Q,{className:"af-h-4 af-w-24"})}),N(B,{}),N(B,{})]},w))})]})}),N("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)G=te("div",{children:[L,N("div",{className:"af-flex af-justify-center af-py-8",children:N(zt,{message:"Couldn't load your leads.",onRetry:()=>u()})})]});else if(C.length===0&&o===0){let w=!!p||_!=="all";G=te("div",{children:[w&&L,w?N(Ta,{children:p?"Nobody matches that search.":_==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):N(Ta,{icon:N(nd,{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)G=te("div",{children:[L,N(Ta,{children:"No more results."}),N("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:te(S,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[N(_i,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let w=o*f+1,M=o*f+t.length;G=te("div",{children:[L,N("div",{className:"af-space-y-3 lg:af-hidden",children:C.map((g,Z)=>te("div",{onClick:()=>U(g),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[te("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[te("div",{className:"af-min-w-0",children:[N("button",{type:"button",onClick:ie=>{ie.stopPropagation(),U(g)},"aria-label":`Open ${g.name||g.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ci(g)}),g.name&&g.email&&N("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:g.email})]}),te("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[N("span",{className:"af-text-xs af-text-muted-foreground",children:gs(g.last_activity_at)}),g.email&&N(S,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:N("a",{href:rr(g.email),onClick:ie=>ie.stopPropagation(),"aria-label":`Email ${g.email}`,children:N(nr,{className:"af-h-4 af-w-4"})})})]})]}),N("div",{className:"af-mt-2",children:Ti(g)}),g.latest_message_excerpt&&N("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:g.latest_message_excerpt})]},g.email??g.submission_id??Z))}),N("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:te(Ae,{children:[N(De,{children:te(pe,{children:[N(O,{children:"Person"}),N(O,{children:"Came from"}),N(O,{children:"Latest message"}),N(O,{children:"Last activity"}),N(O,{className:"af-w-8",children:N("span",{className:"af-sr-only",children:"Reply"})}),N(O,{className:"af-w-8"})]})}),N(Le,{children:C.map((g,Z)=>te(pe,{onClick:()=>U(g),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[te(B,{className:"af-max-w-[260px] af-font-medium",children:[N("button",{type:"button",onClick:ie=>{ie.stopPropagation(),U(g)},"aria-label":`Open ${g.name||g.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ci(g)}),g.name&&g.email&&N("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:g.email})]}),N(B,{children:Ti(g)}),N(B,{className:"af-max-w-[320px]",children:g.latest_message_excerpt?N("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:g.latest_message_excerpt}):N("span",{className:"af-text-muted-foreground",children:"\u2014"})}),N(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:gs(g.last_activity_at)}),N(B,{className:"af-w-8",children:g.email&&N(S,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:N("a",{href:rr(g.email),onClick:ie=>ie.stopPropagation(),"aria-label":`Email ${g.email}`,children:N(nr,{className:"af-h-4 af-w-4"})})})}),N(B,{className:"af-w-8 af-text-right",children:N(Pi,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},g.email??g.submission_id??Z))})]})}),te("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[N("span",{className:"af-text-sm af-text-muted-foreground",children:_==="all"?`Showing ${w}-${M}`:`${C.length} of ${t.length} on this page`}),te("div",{className:"af-flex af-items-center af-gap-2",children:[te(S,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!v,children:[N(_i,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),te(S,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!m,children:["Next",N(Pi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return N(xt,{title:"Leads",onBackToWebsite:a,hideBackButton:c.kind!=="list",className:s,children:G})}import{ChevronLeft as Ai,ChevronRight as xd,Repeat as wd}from"lucide-react";import*as Ot from"react";function Sn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ee(),[t,n]=Ot.useState([]),[i,o]=Ot.useState(0),[f,m]=Ot.useState(!0),[v,r]=Ot.useState(null),[p,y]=Ot.useState(0),[u,c]=Ot.useState(e),[d,b]=Ot.useState(void 0),h=Ot.useRef(0),_=Ot.useCallback(async()=>{let U=++h.current;try{m(!0),r(null);let l={limit:u,offset:p*u};d&&(l.status=d);let x=await s.getSubscriptions(l);if(U!==h.current)return;n(x.subscriptions),o(x.total)}catch(l){if(U!==h.current)return;r(l instanceof Error?l:new Error("Failed to fetch subscriptions"))}finally{U===h.current&&m(!1)}},[s,p,u,d,a]);Ot.useEffect(()=>{_()},[_]);let D=Math.ceil(i/u);return{subscriptions:t,total:i,isLoading:f,error:v,page:p,pageSize:u,hasNextPage:p<D-1,hasPreviousPage:p>0,setPage:y,setPageSize:U=>{c(U),y(0)},status:d,setStatus:U=>{b(U),y(0)},refetch:_}}import{jsx as J,jsxs as je}from"react/jsx-runtime";function Di(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 Li({sub:e}){return e.status==="canceled"?J(Y,{variant:"outline",children:"Canceled"}):e.status==="past_due"?J(Y,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?J(Y,{variant:"warning",children:"Scheduled to cancel"}):J(Y,{variant:"success",children:"Active"}):J(Y,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Nd(e,a){let s=j(a,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function Oi({sub:e}){let a=e.current_amount!==e.plan_amount;return je("div",{children:[J("div",{className:"af-font-medium af-tabular-nums",children:Nd(e,e.current_amount)}),a&&je("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function Bi(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Di(e.current_period_end)}`:"Ends at period end":e.current_period_end?Di(e.current_period_end):"\u2014"}function Fi({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:f,pageSize:m,hasNextPage:v,hasPreviousPage:r,setPage:p,refetch:y}=Sn({refreshKey:e}),u;if(i)u=je("div",{children:[J("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(c=>je("div",{className:"af-rounded-md af-border af-p-3",children:[je("div",{className:"af-flex af-items-center af-justify-between",children:[J(Q,{className:"af-h-4 af-w-40"}),J(Q,{className:"af-h-4 af-w-20"})]}),J(Q,{className:"af-mt-2 af-h-3 af-w-32"}),J(Q,{className:"af-mt-2 af-h-5 af-w-24"})]},c))}),J("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:je(Ae,{children:[J(De,{children:je(pe,{children:[J(O,{children:"Subscriber"}),J(O,{children:"Plan"}),J(O,{className:"af-text-right",children:"Amount"}),J(O,{children:"Renews"}),J(O,{children:"Status"})]})}),J(Le,{"aria-hidden":"true",children:[0,1,2,3,4].map(c=>je(pe,{children:[J(B,{children:J(Q,{className:"af-h-4 af-w-44"})}),J(B,{children:J(Q,{className:"af-h-4 af-w-32"})}),J(B,{className:"af-text-right",children:J(Q,{className:"af-ml-auto af-h-4 af-w-24"})}),J(B,{children:J(Q,{className:"af-h-4 af-w-24"})}),J(B,{children:J(Q,{className:"af-h-5 af-w-20"})})]},c))})]})}),J("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)u=J("div",{className:"af-flex af-justify-center af-py-8",children:J(zt,{message:"Couldn't load your subscriptions.",onRetry:()=>y()})});else if(t.length===0&&f===0)u=J(Ta,{icon:J(wd,{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)u=je("div",{children:[J(Ta,{children:"No more results."}),J("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:je(S,{variant:"outline",size:"sm",onClick:()=>p(f-1),children:[J(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=f*m+1,d=f*m+t.length;u=je("div",{children:[J("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:[J("div",{className:"af-truncate af-text-sm af-font-medium",children:b.customer_email||J("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),J("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:b.plan_title||"Untitled plan"})]}),J("div",{className:"af-shrink-0 af-text-right",children:J(Oi,{sub:b})})]}),je("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[J(Li,{sub:b}),b.is_test&&J(Y,{variant:"outline",children:"Test"}),J("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Bi(b)})]}),J(wa,{deliveries:b.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},b.id))}),J("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:je(Ae,{children:[J(De,{children:je(pe,{children:[J(O,{children:"Subscriber"}),J(O,{children:"Plan"}),J(O,{className:"af-text-right",children:"Amount"}),J(O,{children:"Renews"}),J(O,{children:"Status"})]})}),J(Le,{children:t.map(b=>je(pe,{children:[J(B,{className:"af-max-w-[240px]",children:J("div",{className:"af-truncate af-font-medium",children:b.customer_email||J("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),J(B,{className:"af-max-w-[220px]",children:J("div",{className:"af-truncate",children:b.plan_title||J("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),J(B,{className:"af-whitespace-nowrap af-text-right",children:J(Oi,{sub:b})}),J(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bi(b)}),je(B,{children:[je("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[J(Li,{sub:b}),b.is_test&&J(Y,{variant:"outline",children:"Test"})]}),J(wa,{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:[J("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${c}-${d} of ${n}`}),je("div",{className:"af-flex af-items-center af-gap-2",children:[je(S,{variant:"outline",size:"sm",onClick:()=>p(f-1),disabled:!r,children:[J(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),je(S,{variant:"outline",size:"sm",onClick:()=>p(f+1),disabled:!v,children:["Next",J(xd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return J(xt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:u})}import*as ir from"react";import{Fragment as Mi,jsx as jt,jsxs as Rn}from"react/jsx-runtime";function Ui({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:f,isLoading:m,error:v,refetch:r}=is({refreshKey:e,initialPageSize:1,includeAggregates:!0}),p=fs({refreshKey:e}),[y,u]=ir.useState(!1),[c,d]=ir.useState(null),b=jt("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:v||!m&&!f?Rn("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. ",jt(S,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):m||!f?Rn(Mi,{children:[jt(Je,{label:"Outstanding",children:jt(Q,{className:"af-h-6 af-w-24"})}),jt(Je,{label:"Overdue",children:jt(Q,{className:"af-h-6 af-w-24"})}),jt(Je,{label:"Paid this month",children:jt(Q,{className:"af-h-6 af-w-24"})})]}):Rn(Mi,{children:[jt(Je,{label:"Outstanding",detail:`${f.outstanding.count} open`,children:j(f.outstanding.amount,f.currency)}),jt(Je,{label:"Overdue",detail:f.overdue.count===0?"Nothing overdue":`${f.overdue.count} overdue`,valueClassName:f.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:j(f.overdue.amount,f.currency)}),jt(Je,{label:"Paid this month",detail:`${f.paid_this_month.count} paid`,children:j(f.paid_this_month.amount,f.currency)})]})});return Rn(xt,{title:"Invoices",onBackToWebsite:s,hideBackButton:y,className:o,children:[b,!y&&jt(cs,{retainers:p.retainers,isLoading:p.isLoading,error:p.error,onRetry:()=>void p.refetch(),activeRetainerId:c?.id??null,onShowCycles:h=>d(_=>_?.id===h.id?null:h),total:p.total,endedTotal:p.endedTotal,isLoadingMore:p.isLoadingMore,onLoadMore:()=>void p.loadMore(),includeEnded:p.includeEnded,onIncludeEndedChange:p.setIncludeEnded}),jt(ls,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:u,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:c?{id:c.id,label:`${c.customer_name??c.customer_email??"Recurring invoices"} \u2014 ${c.description}`}:null,onClearRetainerFilter:()=>d(null)})]})}import*as Ft from"react";var Sd=2e3,Bt=()=>({data:null,error:null,isLoading:!0});function _n(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=ee(),[i,o]=Ft.useState(Bt),[f,m]=Ft.useState(Bt),[v,r]=Ft.useState(Bt),[p,y]=Ft.useState(Bt),u=L=>Object.fromEntries(L.map(w=>[w,Bt()])),[c,d]=Ft.useState(()=>u(s)),b=Ft.useRef(0),h=s.join(","),_=JSON.stringify(t),D=`${e}:${h}:${_}`,[U,l]=Ft.useState({api:n,fetchIdentity:D});(U.api!==n||U.fetchIdentity!==D)&&(l({api:n,fetchIdentity:D}),b.current+=1,o(Bt),m(Bt),r(Bt),y(Bt),d(u(h?h.split(","):[])));let x=Ft.useCallback(async()=>{let L=++b.current,w=h?h.split(","):[];o(Bt),m(Bt),r(Bt),y(Bt),d(Object.fromEntries(w.map(W=>[W,Bt()])));let M=(W,re)=>re.then(ce=>{L===b.current&&W({data:ce,error:null,isLoading:!1})},ce=>{L===b.current&&W({data:null,error:ce instanceof Error?ce:new Error("Failed to fetch report"),isLoading:!1})}),g=n.getAnalyticsStatus(),Z=M(o,g),ie=Symbol("status-timeout"),oe,X=await Promise.race([g.then(W=>W,()=>null),new Promise(W=>{oe=setTimeout(()=>W(ie),Sd)})]);if(clearTimeout(oe),L!==b.current)return;if(X===ie&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),X!==null&&X!==ie&&(X.collecting!==!0||X.first_seen===null&&!X.first_seen_unavailable||X.first_seen!==null&&X.first_seen_in_reports===!1)){let W={data:null,error:null,isLoading:!1};m(W),r(W),y(W),d(Object.fromEntries(w.map(re=>[re,{...W}]))),await Z;return}await Promise.all([X===ie?Promise.resolve():Z,M(m,n.getAnalyticsSummary(e,t)),M(r,n.getAnalyticsTimeseries(e,t)),M(y,n.getAnalyticsChannels(e,t)),...w.map(W=>n.getAnalyticsBreakdown(W,e,t).then(re=>{L===b.current&&d(ce=>({...ce,[W]:{data:re,error:null,isLoading:!1}}))},re=>{L===b.current&&d(ce=>({...ce,[W]:{data:null,error:re instanceof Error?re:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,_]),C=Ft.useCallback(async()=>{let L=b.current;try{let w=await n.getAnalyticsStatus();if(L!==b.current)return;o({data:w,error:null,isLoading:!1})}catch(w){if(L!==b.current)return;o(M=>({data:M.data,error:w instanceof Error?w:new Error("Failed to fetch status"),isLoading:!1}))}},[n]);Ft.useEffect(()=>{x()},[x,a]);let G=i.isLoading||f.isLoading||v.isLoading||p.isLoading||Object.values(c).some(L=>L.isLoading);return{status:i,summary:f,timeseries:v,channels:p,breakdowns:c,isLoading:G,refetch:x,refetchStatus:C}}import*as mt from"react";var or=3e4,lr=3;function Pn(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=ee(),[o,f]=mt.useState(null),[m,v]=mt.useState(null),[r,p]=mt.useState(!1),[y,u]=mt.useState(null),[c,d]=mt.useState(!1),[b,h]=mt.useState(!0),[_,D]=mt.useState(0),U=mt.useRef(0),l=mt.useRef(0),x=mt.useRef(void 0);s!==void 0&&(x.current=s);let C=a?x.current===!0||x.current===void 0&&t:!0,[G,L]=mt.useState({api:i,identity:n}),w=n!==void 0&&n!==G.identity;(G.api!==i||w)&&(x.current=void 0,L({api:i,identity:n}),l.current+=1,U.current=0,f(null),v(null),p(!1),u(null),d(!1),h(!0),D(0));let M=mt.useRef(()=>{}),g=mt.useRef(null),Z=mt.useCallback(async()=>{if(g.current!==null&&g.current===l.current)return;let ie=++l.current;g.current=ie;try{let oe=await i.getAnalyticsRealtime();if(ie!==l.current)return;if(oe.status==="unreachable"){d(!0),p(!0),h(!1),D(X=>X+1);return}U.current=0,d(!1),f(oe.data.current_visitors),v(oe.as_of),p(!1),u(null),h(!1),D(X=>X+1)}catch(oe){if(ie!==l.current)return;U.current+=1,h(!1),D(X=>X+1),p(!0),U.current>=lr&&u(oe instanceof Error?oe:new Error("Realtime unavailable"))}finally{g.current===ie&&(g.current=null)}},[i]);return M.current=()=>void Z(),mt.useEffect(()=>{let ie,oe=()=>{ie===void 0&&(ie=setInterval(()=>M.current(),or))},X=()=>{ie!==void 0&&(clearInterval(ie),ie=void 0)},ye=()=>{typeof document<"u"&&document.hidden?X():(M.current(),oe())};return C?((typeof document>"u"||!document.hidden)&&(M.current(),oe()),document?.addEventListener("visibilitychange",ye),()=>{X(),document?.removeEventListener("visibilitychange",ye),l.current+=1}):()=>{document?.removeEventListener("visibilitychange",ye)}},[G.api,G.identity,C]),{currentVisitors:o,asOf:m,isStale:r,error:y,isUnreachable:c,isInitialLoad:b,polls:_}}import*as Ge from"react";import*as bs from"react";var Rd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ga(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?ga(o*t):`${o}${n}`}return String(e)}function Tn(e){return`${(e*100).toFixed(1)}%`}function Es(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 $i(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`:Es(a)}function Hi(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function zi(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 Is(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function qi(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 cr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${Rd[a-1]} ${s}`}function Vi(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function _d(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function ji(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=Vi(e.to,s);for(let o=Vi(e.from,s);o<i;o=_d(o))n.push(t.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Gi(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 Td,jsx as Ja,jsxs as Pd}from"react/jsx-runtime";function Wi({what:e="This report",onRetry:a,collecting:s}){return Pd("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:[Ja("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),Ja("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?Ja("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 Ki({what:e="No data"}){return Ja("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 As({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?Ja("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?Ja(Wi,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?Ja(Wi,{what:t,onRetry:n,collecting:i}):Ja(Td,{children:o(e.data)})}import{jsx as Gt,jsxs as vs}from"react/jsx-runtime";function dr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:f}){if(e.length===0)return Gt(Ki,{what:i});let m=e.reduce((v,r)=>Math.max(v,Number(r[s]??0)),0)||1;return vs("table",{className:"af-w-full af-text-sm",children:[Gt("thead",{children:vs("tr",{className:"af-text-xs af-text-muted-foreground",children:[Gt("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),Gt("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),Gt("tbody",{children:e.map((v,r)=>{let p=Number(v[s]??0),y=v[a]??null,u=Is(y),c=n?v[n]:null,d=y!==null&&(f?f(y,c):!0);return vs("tr",{className:"af-border-t af-border-border",children:[vs("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Gt("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,p/m*100)}%`}}),y!==null&&o&&d?Gt("button",{type:"button",onClick:()=>o(y,c),title:`Filter by ${u}`,"aria-label":`Filter by ${u}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:u}):Gt("span",{className:"af-relative af-break-words af-text-foreground",children:u}),c?Gt("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:c}):null]}),Gt("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:ga(p)})]},`${u}-${c??""}-${r}`)})})]})}function Ds({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=bs.useState(s),o=a.find(u=>u.id===n)??a[0],f=bs.useId(),m=u=>`${f}-tab-${u}`,v=u=>`${f}-panel-${u}`,r=bs.useRef(null),p=(u,c)=>{u.preventDefault();let d=(c+a.length)%a.length;i(a[d].id),r.current?.querySelectorAll('[role="tab"]')?.[d]?.focus()};return vs("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[vs("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:[Gt("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:u=>{let c=a.findIndex(d=>d.id===n);u.key==="ArrowRight"&&p(u,c+1),u.key==="ArrowLeft"&&p(u,c-1),u.key==="Home"&&p(u,0),u.key==="End"&&p(u,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(u=>Gt("button",{id:m(u.id),role:"tab",type:"button","aria-selected":u.id===n,"aria-controls":v(u.id),tabIndex:u.id===n?0:-1,onClick:()=>i(u.id),className:u.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:u.label},u.id))}),t]}),o?Gt("div",{id:v(o.id),role:"tabpanel","aria-labelledby":m(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()}):null]})}import*as Mt from"react";import*as Ya from"@radix-ui/react-popover";var ys=3,hs=100;import{jsx as rt,jsxs as Aa}from"react/jsx-runtime";var Ls={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},Cd=Object.keys(Ls);function Ji(e){let a=Ls[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>Is(n)).join(" or ");return`${a} ${s} ${t}`}function ur(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));if(s>=0){let t=[...new Set([...e[s].values,...a.values])];return t.length>100||t.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:t}:n)}return a.values.length>100||e.length>=3?e:[...e,a]}function kd(e,a){let s={};for(let[t,n]of Object.entries(a)){let i=e.get(t)??new Set;for(let o of n)i.add(o);e.set(t,i),s[t]=[...i]}return s}function Yi(e,a){let s=e.findIndex(t=>t.dimension===a.dimension&&(t.operator??"is")===(a.operator??"is"));return s>=0?e.map((t,n)=>n===s?a:t):a.values.length>100||e.length>=3?e:[...e,a]}function Ed(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Zi(e,a,s,t={}){if(e.api!==a.api||e.period!==a.period)return e.api=a.api,e.period=a.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=kd(e.byDimension,s);for(let[i,o]of Object.entries(t)){let f=e.foldsByLabel.get(i)??new Set;for(let m of o)f.add(m);e.foldsByLabel.set(i,f)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Qi(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Mt.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]),Aa("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>Aa("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:[rt("span",{className:"af-text-foreground",children:Ji(n)}),rt("button",{type:"button","aria-label":`Remove filter ${Ji(n)}`,onClick:()=>s(a.filter((o,f)=>f!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),rt(Id,{...e,disabled:t}),a.length>0?rt("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 Id({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,f]=Mt.useState(!1),m=Mt.useRef(null),[v,r]=Mt.useState(null);Mt.useEffect(()=>{r(m.current?.closest(".aifeatures-admin")??null)},[]);let[p,y]=Mt.useState(null),[u,c]=Mt.useState("is"),[d,b]=Mt.useState(""),[h,_]=Mt.useState([]);Mt.useEffect(()=>{o||(y(null),c("is"),b(""),_([]))},[o]);let D=Mt.useRef(t);D.current!==t&&(D.current=t,o&&f(!1),p!==null&&y(null),h.length>0&&_([]),d!==""&&b(""),u!=="is"&&c("is"));let U=w=>{let M=Ed(w);y(M.dimension),_(M.picked),b(M.search),c(M.operator)},x=(p?s[p]??[]:[]).filter(w=>w.toLowerCase().includes(d.trim().toLowerCase())),C=p===null||h.length===0?null:ur(e,{dimension:p,operator:u,values:i?i(p,h):h}),G=C!==null&&C!==e,L=()=>{let w=C;!w||w===e||(a(w),f(!1))};return Aa(Ya.Root,{open:o,onOpenChange:f,children:[rt(Ya.Trigger,{asChild:!0,children:rt("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"})}),rt(Ya.Portal,{container:v,children:rt(Ya.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:p===null?Aa("div",{children:[rt("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),rt("div",{className:"af-max-h-96 af-overflow-y-auto",children:Cd.filter(w=>s[w]!==void 0).map(w=>{let M=s[w]?.length??0,g=!e.some(Z=>Z.dimension===w)&&e.length>=3;return Aa("button",{type:"button",onClick:()=>U(w),disabled:M===0||g,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:[rt("span",{children:Ls[w]}),rt("span",{className:"af-text-muted-foreground",children:M===0?"no data":g?"no room":M})]},w)})})]}):Aa("div",{children:[Aa("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[rt("button",{type:"button",onClick:()=>U(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),rt("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Ls[p]}),Aa("select",{"aria-label":"Operator",value:u,onChange:w=>c(w.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:[rt("option",{value:"is",children:"is"}),rt("option",{value:"is_not",children:"is not"})]})]}),rt("input",{type:"text",value:d,onChange:w=>b(w.target.value),placeholder:"Search\u2026","aria-label":`Search ${Ls[p]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),rt("div",{className:"af-max-h-48 af-overflow-y-auto",children:x.length===0?Aa("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",d,"\u201D."]}):x.map(w=>Aa("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:[rt("input",{type:"checkbox",checked:h.includes(w),disabled:!h.includes(w)&&h.length>=100,onChange:M=>_(g=>M.target.checked?[...g,w]:g.filter(Z=>Z!==w))}),rt("span",{className:"af-break-all",children:Is(w)})]},w))}),rt("button",{type:"button",onClick:L,disabled:!G,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:h.length<=1?"Apply filter":h.length>=100?`Apply filter (${h.length} values \u2014 the maximum)`:`Apply filter (${h.length} values)`})]})})})]})}import{Fragment as Ld,jsx as Ct,jsxs as Cn}from"react/jsx-runtime";var Ad=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:ga,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:ga,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:ga,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:Tn,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Es,chart:"visit_duration_seconds"}];function Dd({current:e,previous:a,downIsGood:s}){if(a===0)return null;let t=(e-a)/a;if(Math.abs(t)<5e-4)return null;let n=t>0,i=s?!n:n,o=`${n?"+":""}${(t*100).toFixed(1)}%`;return Ct("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 Xi({summary:e,selected:a,onSelect:s}){return Ct("div",{className:"af-@container",children:Ct("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Ad.map(t=>{let n=t.chart===a,i=s!==void 0,o=Cn(Ld,{children:[Ct("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),Cn("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[Ct("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?Ct(Dd,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?Ct("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):Ct("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function fr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return Cn("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:[Ct("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),Ct("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return Ct("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?qi(a):"freshness unknown",f=i?" across the whole site, not the current filter,":"",m=s?`${e} current visitors${f} ${o} (not updating)`:`${e} current visitors${f} ${o}`;return Cn("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:[Ct("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"}),Ct("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),Ct("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),Ct("span",{className:"af-sr-only",children:m})]})}import{Area as Od,AreaChart as Bd,CartesianGrid as Fd,ResponsiveContainer as Md,Tooltip as Ud,XAxis as Vd,YAxis as $d}from"recharts";import{jsx as kt,jsxs as Os}from"react/jsx-runtime";var kn={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},pr={visitors:ga,visits:ga,pageviews:ga,views_per_visit:e=>e.toFixed(2),bounce_rate:Tn,visit_duration_seconds:Es},Hd=new Set(["visitors","visits","pageviews"]),zd={...pr,bounce_rate:Hi,visit_duration_seconds:$i},mr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],qd=[5,10,15,30,60,120,300,600,900,1800,3600,7200],jd=[.01,.02,.05,.1,.2,.25,.5,1],Gd=[.25,.5,1,2,5,10,25,50],Wd={visitors:mr,visits:mr,pageviews:mr,views_per_visit:Gd,bounce_rate:jd,visit_duration_seconds:qd};function Kd({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return Os("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[kt("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:kn[t]}),Os("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[kt("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),kt("span",{className:"af-text-muted-foreground",children:Gi(String(s))}),kt("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:pr[t](Number(n[t]??0))})]})]})}function eo({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=ji(a,e,t),o=pr[s],f=zd[s],m=zi(i.reduce((r,p)=>Math.max(r,Number(p[s]??0)),0),Wd[s]),v=`${kn[s]} by day: ${i.map(r=>`${cr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return Os("figure",{"aria-label":`${kn[s]} over time`,className:"af-m-0",children:[kt(Md,{width:"100%",height:n,children:Os(Bd,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[kt("defs",{children:Os("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[kt("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),kt("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),kt(Fd,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),kt(Vd,{dataKey:"date",tickFormatter:cr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),kt($d,{allowDecimals:!Hd.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...m?{ticks:m,domain:[0,m[m.length-1]]}:{},tickFormatter:r=>f(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),kt(Ud,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:kt(Kd,{metric:s})}),kt(Od,{type:"monotone",dataKey:s,name:kn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),kt("figcaption",{className:"af-sr-only",children:v})]})}import{Fragment as to,jsx as Te,jsxs as va}from"react/jsx-runtime";var Jd=3e4,Yd="2026-08-13",Zd=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Qd=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Xd({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[f,m]=Ge.useState(30),v=e!==void 0&&a!==void 0,[r,p]=Ge.useState(e??[]),{api:y}=ee(),[u,c]=Ge.useState(y);u!==y&&(c(y),!v&&r.length>0&&p([]));let d=v?e:r,b=Ge.useCallback(V=>{a&&a(V),v||p(V)},[a,v]),h=Ge.useCallback((V,de,ge)=>{let le=Array.isArray(de)?de:[de];if(le.length===0)return null;let Fe=ur(d,{dimension:V,operator:"is",values:le});if(ge&&(!ge.value||(Fe=Yi(Fe,{dimension:ge.dimension,operator:"is",values:[ge.value]}),!Fe.find(me=>me.dimension===ge.dimension&&me.operator!=="is_not")?.values.includes(ge.value))))return null;let T=Fe.find(A=>A.dimension===V&&A.operator!=="is_not");return le.every(A=>T?.values.includes(A))?JSON.stringify(Fe)===JSON.stringify(d)?null:Fe:null},[d]),_=Ge.useCallback((V,de,ge)=>h(V,de,ge)!==null,[h]),D=Ge.useCallback((V,de,ge)=>{let le=h(V,de,ge);le&&b(le)},[h,b]),[U,l]=Ge.useState("visitors"),x=_n(f,{refreshKey:s,breakdowns:Qd,filters:d}),C=x.status.data,G=C?.collecting===!0&&C.first_seen===null&&!C.first_seen_unavailable,L=C?.collecting===!0&&C.first_seen!==null&&C.first_seen_in_reports===!1,w=G||L,M=Pn({collecting:G?!1:C?.collecting,statusFailed:x.status.error!=null,identity:C?.analytics_id}),g=Ge.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),Z=Ge.useMemo(()=>{let V=x.breakdowns.sources?.data,de={};if(!V||V.status!=="ok")return de;for(let ge of V.data){let le=ge.source,Fe=ge.sources;typeof le=="string"&&Array.isArray(Fe)&&Fe.length>0&&(de[le]=Fe)}return de},[x.breakdowns.sources?.data]),ie=Ge.useMemo(()=>{let V=(le,Fe)=>{let T=x.breakdowns[le]?.data;return!T||T.status!=="ok"?[]:[...new Set(T.data.map(A=>A[Fe]).filter(A=>typeof A=="string"&&A!==""))]};return{channel:x.channels.data?.status==="ok"?[...new Set(x.channels.data.data.map(le=>le.channel))]:[],source:V("sources","source"),campaign:V("utm/campaign","campaign"),page:V("pages","pathname"),entry_page:V("entry-pages","pathname"),exit_page:V("exit-pages","pathname"),country:V("countries","country"),browser:V("browsers","browser"),os:V("operating-systems","os"),device:V("devices","device")}},[x.breakdowns,x.channels.data]),[oe,X]=Ge.useState({}),ye=JSON.stringify(ie),[W,re]=Ge.useState(new Map),ce=JSON.stringify(Z);Ge.useEffect(()=>{let{suggestions:V,folds:de}=Zi(g.current,{api:y,period:f},JSON.parse(ye),JSON.parse(ce));X(V),re(de)},[ye,ce,y,f]);let q=Ge.useCallback((V,de)=>V!=="source"?de:[...new Set(de.flatMap(ge=>{let le=[...W.get(ge)??[],...Z[ge]??[]];return le.length>0?le:[ge]}))],[W,Z]),he=Ge.useMemo(()=>{let V=[x.summary,x.timeseries,x.channels,...Object.values(x.breakdowns)];for(let de of V){let ge=de?.error;if(ge instanceof ya&&ge.details?.code==="filter_unsupported")return ge.message}return null},[x.summary,x.timeseries,x.channels,x.breakdowns]),Be=(V,de,ge,le,Fe,T,A,me,We)=>()=>{let Ue=x.breakdowns[V];return Te(As,{sourced:Ue?.data??null,error:Ue?.error,isLoading:Ue?.isLoading,what:de,collecting:C?.collecting,onRetry:x.refetch,children:et=>{let Ke=tt=>me?q(me,[tt]):tt;return Te(dr,{rows:et,dimension:ge,metric:le,metricLabel:Fe,secondary:T,emptyCopy:d.length>0?"No data for this filter":A,canFilter:me?(tt,Wt)=>_(me,Ke(tt),We?{dimension:We,value:Wt}:void 0):()=>!1,onFilter:me?(tt,Wt)=>D(me,Ke(tt),We?{dimension:We,value:Wt}:void 0):void 0})}})};Ge.useEffect(()=>{if(!w)return;let V,de=()=>{V===void 0&&(V=setInterval(()=>void x.refetchStatus(),Jd))},ge=()=>{V!==void 0&&(clearInterval(V),V=void 0)},le=()=>{typeof document<"u"&&document.hidden?ge():(x.refetchStatus(),de())};return(typeof document>"u"||!document.hidden)&&de(),document?.addEventListener("visibilitychange",le),()=>{ge(),document?.removeEventListener("visibilitychange",le)}},[w,x.refetchStatus]);let Nt=Ge.useRef(void 0);if(Ge.useEffect(()=>{if(!C){Nt.current=void 0;return}let V=Nt.current;Nt.current=w,V===!0&&!w&&x.refetch()},[C,w,x.refetch]),C&&!C.collecting){let V=i===!1,de=!!o&&String(o).slice(0,10)<Yd;return Te(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:va("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Te("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:V?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":de?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return G?Te(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:va("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Te("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."})]})}):L?Te(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:va("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),va("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",C?.timezone?` ${C.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Te("div",{className:"af-mt-4 af-flex af-justify-center",children:Te(fr,{currentVisitors:M.currentVisitors,asOf:M.asOf,isStale:M.isStale,isUnreachable:M.isUnreachable||M.error!==null,isInitialLoad:M.isInitialLoad})})]})}):Te(xt,{title:"Analytics",onBackToWebsite:t,className:n,children:va("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[va("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Te("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Zd.map(V=>Te("button",{type:"button","aria-pressed":V.value===f,onClick:()=>m(V.value),className:V.value===f?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:V.label},V.value))}),Te(fr,{currentVisitors:M.currentVisitors,asOf:M.asOf,isStale:M.isStale,isUnreachable:M.isUnreachable||M.error!==null,isInitialLoad:M.isInitialLoad,scopeIsSiteWide:d.length>0})]}),Te(Qi,{filters:d,onChange:b,suggestions:oe,expandValues:q,resetKey:y}),he?va("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Te("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:he}),Te("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,!he&&C?.timezone_defaulted?Te("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,he?null:va(to,{children:[Te(As,{sourced:x.summary.data,error:x.summary.error,isLoading:x.summary.isLoading,what:"The traffic summary",collecting:C?.collecting,onRetry:x.refetch,children:V=>va(to,{children:[Te(Xi,{summary:V,selected:U,onSelect:l}),V.previous_unavailable?va("p",{className:"af-text-xs af-text-muted-foreground",children:[V.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]})}),Te("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Te(As,{sourced:x.timeseries.data,error:x.timeseries.error,isLoading:x.timeseries.isLoading,what:"The visitors chart",collecting:C?.collecting,onRetry:x.refetch,children:V=>{let de=x.timeseries.data?.status==="ok"?x.timeseries.data.window:{from:"",to:""};return Te(eo,{rows:V,window:de,metric:U,timeZone:(x.timeseries.data?.status==="ok"?x.timeseries.data.timezone:void 0)??C?.timezone??"UTC"})}})}),va("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Te(Ds,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Te(As,{sourced:x.channels.data,error:x.channels.error,isLoading:x.channels.isLoading,what:"Channels",collecting:C?.collecting,onRetry:x.refetch,children:V=>Te(dr,{rows:V,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:d.length>0?"No data for this filter":"No data for this period",canFilter:de=>_("channel",de),onFilter:de=>D("channel",de)})})},{id:"sources",label:"Sources",render:Be("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:Be("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),Te(Ds,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:Be("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:Be("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:Be("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),Te(Ds,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:Be("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:Be("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:Be("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),Te(Ds,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:Be("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:Be("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:Be("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]})]})]})})}export{ya as AifeaturesApiError,io as AifeaturesProvider,Xd as AnalyticsView,ln as CustomerDetail,dn as CustomersList,Ks as FormSettings,qs as FormSubmissions,Lr as FormsDashboard,Us as FormsList,Zn as InvoiceDetail,Ts as InvoiceLabelBadge,ls as InvoicesList,Ui as InvoicesView,Ii as LeadsView,ys as MAX_ANALYTICS_FILTERS,hs as MAX_ANALYTICS_FILTER_VALUES,sn as OrderDetail,Xa as OrderStatusBadge,rs as OrdersList,vi as OrdersView,mi as PaymentsDashboard,pn as PaymentsSetup,Qs as ProductSettings,Ys as ProductsList,Ri as ProductsView,lr as REALTIME_FAILURES_BEFORE_ERROR,or as REALTIME_POLL_MS,Qn as RetainerStatusBadge,cs as RetainersPanel,zs as SubmissionDetail,Fi as SubscriptionsView,Zs as VariantsEditor,xt as ViewShell,Gs as WebhookDeliveries,Ws as WebhookSettings,da as chargedTotal,In as createApiClient,j as formatPrice,Ra as isZeroDecimalCurrency,ht as toMajorUnits,ua as toMinorUnits,ee as useAifeatures,ee as useAifeaturesContext,_n as useAnalytics,gn as useBusinessSummary,on as useCustomers,js as useEventDestinations,ss as useForms,is as useInvoices,Xs as useOrders,ds as usePaymentsStatus,wn as usePeople,Nn as usePerson,us as useProducts,Pn as useRealtimeVisitors,fs as useRetainers,Hs as useSubmissions,Sn as useSubscriptions};
2
+ import*as Ha from"react";function Bs(e,a){let s=new URLSearchParams({period:String(e)});return a&&a.length>0&&s.set("filters",JSON.stringify(a)),s.toString()}var ya=class extends Error{constructor(s,t,n){super(s);this.status=t;this.details=n;this.name="AifeaturesApiError"}};function En(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 In(e,a="https://aifeatures.dev"){async function s(t,n={}){let i=`${a}${t}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let f;try{f=await o.json()}catch{}throw new ya(En(f?.error,o.status),o.status,f)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(t){return s(`/api/v1/forms/${t}`)},async createForm(t){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(t)})},async updateForm(t,n){return s(`/api/v1/forms/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(t){await s(`/api/v1/forms/${t}`,{method:"DELETE"})},async getSubmissions(t,n={}){let i=new URLSearchParams;n.limit!==void 0&&i.set("limit",String(n.limit)),n.offset!==void 0&&i.set("offset",String(n.offset));let o=i.toString(),f=`/api/v1/forms/${t}/submissions${o?`?${o}`:""}`;return s(f)},async getSubmission(t){return s(`/api/v1/submissions/${t}`)},async deleteSubmission(t){await s(`/api/v1/submissions/${t}`,{method:"DELETE"})},async downloadAttachment(t,n){let i=typeof n=="string"?{name:n}:n,o=i.name,f=i.id??i.name,m=`${a}/api/v1/submissions/${t}/attachments/${encodeURIComponent(f)}`,b=await fetch(m,{headers:{Authorization:`Bearer ${e}`}});if(!b.ok){let p;try{p=await b.json()}catch{}throw new ya(En(p?.error,b.status),b.status,p)}let r=await b.blob(),g=URL.createObjectURL(r),y=document.createElement("a");y.href=g,y.download=o,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(g)},async getPaymentsStatus(){return s("/api/v1/payments/status")},async getProducts(t={}){let n=new URLSearchParams;t.include&&n.set("include",t.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(t){return s(`/api/v1/products/${t}`)},async createProduct(t){return s("/api/v1/products",{method:"POST",body:JSON.stringify(t)})},async updateProduct(t,n){return s(`/api/v1/products/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(t){await s(`/api/v1/products/${t}`,{method:"DELETE"})},async attachProductFile(t,n){let i=new FormData;i.append("file",n);let o=await fetch(`${a}/api/v1/products/${t}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let f;try{f=await o.json()}catch{}throw new ya(En(f?.error,o.status),o.status,f)}return o.json()},async attachProductFileFromUrl(t,n){return s(`/api/v1/products/${t}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(t,n){return s(`/api/v1/products/${t}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(t,n){return s(`/api/v1/options/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(t){await s(`/api/v1/options/${t}`,{method:"DELETE"})},async createVariant(t,n){return s(`/api/v1/products/${t}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(t,n){return s(`/api/v1/variants/${t}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(t){await s(`/api/v1/variants/${t}`,{method:"DELETE"})},async setVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(t,n){return s(`/api/v1/variants/${t}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(t={}){let n=new URLSearchParams;t.email?n.set("email",t.email):t.q&&n.set("q",t.q),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(t){return s(`/api/v1/customers/${t}`)},async getOrders(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.source&&n.set("source",t.source),t.excludeStatus?.length&&n.set("exclude_status",t.excludeStatus.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.unfulfilledOnly&&n.set("unfulfilled_only","true"),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(t){return s(`/api/v1/orders/${t}`)},async getInvoices(t={}){let n=new URLSearchParams;t.labels?.length&&n.set("label",t.labels.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.customerId&&n.set("customer_id",t.customerId),t.q&&n.set("q",t.q),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),t.includeAggregates&&n.set("include","aggregates"),t.retainerId&&n.set("retainer_id",t.retainerId),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(t){return s(`/api/v1/invoices/${t}`)},async getInvoicePreview(t){return s(`/api/v1/invoices/${t}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(t={}){let n=new URLSearchParams;t.statuses?.length&&n.set("status",t.statuses.join(",")),t.customerEmail&&n.set("customer_email",t.customerEmail),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(t){return s(`/api/v1/retainers/${t}`)},async resendOrderReceipt(t){await s(`/api/v1/orders/${t}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(t){return s(`/api/v1/orders/${t}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(t,n){return s(`/api/v1/orders/${t}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(t={}){let n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(t,n){return s(`/api/v1/analytics/summary?${Bs(t,n)}`)},async getAnalyticsTimeseries(t,n){return s(`/api/v1/analytics/timeseries?${Bs(t,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(t,n){return s(`/api/v1/analytics/channels?${Bs(t,n)}`)},async getAnalyticsBreakdown(t,n,i){let o=t.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${Bs(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 ws,jsxs as oo}from"react/jsx-runtime";var Nr=Ha.createContext(null);function ro(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 io({siteToken:e,apiUrl:a="https://aifeatures.dev",dark:s=!1,className:t,children:n}){let i=Ha.useMemo(()=>ro(e),[e]),o=Ha.useMemo(()=>In(e,a),[e,a]),f=Ha.useMemo(()=>({siteToken:e,apiUrl:a,api:o}),[e,a,o]);return i?ws("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:oo("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[ws("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),ws("p",{className:"af-text-sm af-text-destructive",children:i})]})}):ws(Nr.Provider,{value:f,children:ws("div",{className:`aifeatures-admin ${s?"dark":""} ${t||""}`,children:n})})}function ae(){let e=Ha.useContext(Nr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}import*as qa from"react";import{ArrowLeft as cl,Settings as dl,Inbox as ul}from"lucide-react";import*as Fs from"react";import*as sa from"@radix-ui/react-tabs";import{clsx as lo}from"clsx";import{extendTailwindMerge as co}from"tailwind-merge";var uo=co({prefix:"af-"});function $(...e){return uo(lo(e))}import{jsx as An}from"react/jsx-runtime";var Ms=sa.Root,Ns=Fs.forwardRef(({className:e,...a},s)=>An(sa.List,{ref:s,className:$("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}));Ns.displayName=sa.List.displayName;var ha=Fs.forwardRef(({className:e,...a},s)=>An(sa.Trigger,{ref:s,className:$("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}));ha.displayName=sa.Trigger.displayName;var xa=Fs.forwardRef(({className:e,...a},s)=>An(sa.Content,{ref:s,className:$("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}));xa.displayName=sa.Content.displayName;import*as Sr from"react";import{Slot as fo}from"@radix-ui/react-slot";import{cva as mo}from"class-variance-authority";import{jsx as go}from"react/jsx-runtime";var po=mo("af-inline-flex af-items-center af-justify-center af-gap-2 af-whitespace-nowrap af-rounded-md af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring disabled:af-pointer-events-none disabled:af-opacity-50 [&_svg]:af-pointer-events-none [&_svg]:af-size-4 [&_svg]:af-shrink-0",{variants:{variant:{default:"af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",destructive:"af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",outline:"af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",secondary:"af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",ghost:"hover:af-bg-accent hover:af-text-accent-foreground",link:"af-text-primary af-underline-offset-4 hover:af-underline"},size:{default:"af-h-9 af-px-4 af-py-2",sm:"af-h-8 af-rounded-md af-px-3 af-text-xs",lg:"af-h-10 af-rounded-md af-px-8",icon:"af-h-9 af-w-9"}},defaultVariants:{variant:"default",size:"default"}}),S=Sr.forwardRef(({className:e,variant:a,size:s,asChild:t=!1,...n},i)=>go(t?fo:"button",{className:$(po({variant:a,size:s,className:e})),ref:i,...n}));S.displayName="Button";import{Inbox as Rr,Settings as yo}from"lucide-react";import*as Oa from"react";import{jsx as La}from"react/jsx-runtime";var Le=Oa.forwardRef(({className:e,...a},s)=>La("div",{className:"af-relative af-w-full af-overflow-auto",children:La("table",{ref:s,className:$("af-w-full af-caption-bottom af-text-sm",e),...a})}));Le.displayName="Table";var Oe=Oa.forwardRef(({className:e,...a},s)=>La("thead",{ref:s,className:$("[&_tr]:af-border-b",e),...a}));Oe.displayName="TableHeader";var Be=Oa.forwardRef(({className:e,...a},s)=>La("tbody",{ref:s,className:$("[&_tr:last-child]:af-border-0",e),...a}));Be.displayName="TableBody";var vo=Oa.forwardRef(({className:e,...a},s)=>La("tfoot",{ref:s,className:$("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...a}));vo.displayName="TableFooter";var me=Oa.forwardRef(({className:e,...a},s)=>La("tr",{ref:s,className:$("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...a}));me.displayName="TableRow";var O=Oa.forwardRef(({className:e,...a},s)=>La("th",{ref:s,className:$("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}));O.displayName="TableHead";var B=Oa.forwardRef(({className:e,...a},s)=>La("td",{ref:s,className:$("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...a}));B.displayName="TableCell";var bo=Oa.forwardRef(({className:e,...a},s)=>La("caption",{ref:s,className:$("af-mt-4 af-text-sm af-text-muted-foreground",e),...a}));bo.displayName="TableCaption";import*as na from"react";function rs(){let{api:e}=ae(),[a,s]=na.useState([]),[t,n]=na.useState(!0),[i,o]=na.useState(null),f=na.useCallback(async()=>{try{n(!0),o(null);let g=await e.getForms();s(g)}catch(g){o(g instanceof Error?g:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);na.useEffect(()=>{f()},[f]);let m=na.useCallback(async g=>{let y=await e.createForm(g);return s(p=>[...p,y]),y},[e]),b=na.useCallback(async(g,y)=>{let p=await e.updateForm(g,y);return s(c=>c.map(d=>d.id===g?p:d)),p},[e]),r=na.useCallback(async g=>{await e.deleteForm(g),s(y=>y.filter(p=>p.id!==g))},[e]);return{forms:a,isLoading:t,error:i,refetch:f,createForm:m,updateForm:b,deleteForm:r}}import{jsx as ht,jsxs as Ba}from"react/jsx-runtime";function Us({onSelectForm:e,className:a}){let{forms:s,isLoading:t,error:n}=rs();return t?ht("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:ht("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?ht("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:Ba("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?Ba("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[ht(Rr,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Ba("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",ht("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):ht("div",{className:a,children:Ba(Le,{children:[ht(Oe,{children:Ba(me,{children:[ht(O,{children:"Name"}),ht(O,{children:"Endpoint"}),ht(O,{className:"af-text-right",children:"Actions"})]})}),ht(Be,{children:s.map(i=>Ba(me,{children:[ht(B,{className:"af-font-medium",children:i.name}),ht(B,{children:ht("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","")})}),ht(B,{className:"af-text-right",children:Ba("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[Ba(S,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[ht(Rr,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),Ba(S,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[ht(yo,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}import{AlertTriangle as No}from"lucide-react";import{cva as ho}from"class-variance-authority";import{jsx as wo}from"react/jsx-runtime";var xo=ho("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 wo("div",{className:$(xo({variant:a}),e),...s})}import{jsx as Za,jsxs as Vs}from"react/jsx-runtime";var So={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 $s(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 Dn(e=[]){return e.some(a=>!["sending","sent","delivered"].includes(a.state))}function Ro(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 Ss({deliveries:e,label:a="Email needs attention"}){return Dn(e)?Vs("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:[Za(No,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),a]}):null}function wa({deliveries:e,problemsOnly:a=!1,className:s=""}){let t=(e??[]).filter(n=>!a||Dn([n]));return t.length?Za("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:t.map(n=>{let i=$s(n),o=Ro(n);return Vs("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[Vs("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Za("span",{className:"af-font-medium",children:So[n.kind]??"Email notification"}),Za(Z,{variant:i.variant,children:i.label})]}),Vs("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&Dn([n])&&Za("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&&Za("p",{className:"af-mt-1",children:i.detail}),o&&Za("p",{className:"af-mt-1",children:o})]},n.id)})}):null}import*as Rs from"react";import{ChevronLeft as Mo,ChevronRight as Uo,Eye as Vo,Inbox as $o,Paperclip as Ho}from"lucide-react";import*as za from"react";import*as we from"@radix-ui/react-select";import{Check as _o,ChevronDown as _r,ChevronUp as Po}from"lucide-react";import{jsx as Rt,jsxs as Ln}from"react/jsx-runtime";var Kt=we.Root;var Jt=we.Value,$t=za.forwardRef(({className:e,children:a,...s},t)=>Ln(we.Trigger,{ref:t,className:$("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,Rt(we.Icon,{asChild:!0,children:Rt(_r,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));$t.displayName=we.Trigger.displayName;var Pr=za.forwardRef(({className:e,...a},s)=>Rt(we.ScrollUpButton,{ref:s,className:$("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Rt(Po,{className:"af-h-4 af-w-4"})}));Pr.displayName=we.ScrollUpButton.displayName;var Tr=za.forwardRef(({className:e,...a},s)=>Rt(we.ScrollDownButton,{ref:s,className:$("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...a,children:Rt(_r,{className:"af-h-4 af-w-4"})}));Tr.displayName=we.ScrollDownButton.displayName;var Ht=za.forwardRef(({className:e,children:a,position:s="popper",...t},n)=>Rt(we.Portal,{children:Ln(we.Content,{ref:n,className:$("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:[Rt(Pr,{}),Rt(we.Viewport,{className:$("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}),Rt(Tr,{})]})}));Ht.displayName=we.Content.displayName;var To=za.forwardRef(({className:e,...a},s)=>Rt(we.Label,{ref:s,className:$("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...a}));To.displayName=we.Label.displayName;var Ue=za.forwardRef(({className:e,children:a,...s},t)=>Ln(we.Item,{ref:t,className:$("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:[Rt("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:Rt(we.ItemIndicator,{children:Rt(_o,{className:"af-h-4 af-w-4"})})}),Rt(we.ItemText,{children:a})]}));Ue.displayName=we.Item.displayName;var Co=za.forwardRef(({className:e,...a},s)=>Rt(we.Separator,{ref:s,className:$("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...a}));Co.displayName=we.Separator.displayName;import*as Yt from"react";function Hs({formId:e,initialPageSize:a=25}){let{api:s}=ae(),[t,n]=Yt.useState([]),[i,o]=Yt.useState(0),[f,m]=Yt.useState(!0),[b,r]=Yt.useState(null),[g,y]=Yt.useState(0),[p,c]=Yt.useState(a),d=Yt.useCallback(async()=>{if(e)try{m(!0),r(null);let R={limit:p,offset:g*p},E=await s.getSubmissions(e,R);n(E.submissions),o(E.total)}catch(R){r(R instanceof Error?R:new Error("Failed to fetch submissions"))}finally{m(!1)}},[s,e,g,p]);Yt.useEffect(()=>{d()},[d]);let v=Yt.useCallback(async R=>{await s.deleteSubmission(R),n(E=>E.filter(M=>M.id!==R)),o(E=>E-1)},[s]),h=Math.ceil(i/p);return{submissions:t,total:i,isLoading:f,error:b,page:g,pageSize:p,hasNextPage:g<h-1,hasPreviousPage:g>0,setPage:y,setPageSize:R=>{c(R),y(0)},refetch:d,deleteSubmission:v}}import*as kr from"react";import{ArrowLeft as ko,Download as Eo,Globe as Io,Clock as Ao,FileText as Do,Loader2 as Lo,Monitor as Oo,Mail as Bo}from"lucide-react";import{jsx as Xe,jsxs as et}from"react/jsx-runtime";function Cr(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Fo(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}=ae(),[t,n]=kr.useState(null),i=m=>m.id??m.name,o=async m=>{n(i(m));try{await s.downloadAttachment(e.id,m)}catch(b){console.error("Download failed:",b)}finally{n(null)}},f=Object.entries(e.data).filter(([m])=>!m.startsWith("_"));return et("div",{children:[et("div",{className:"af-mb-6",children:[et(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[Xe(ko,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),Xe("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),et("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Cr(e.metadata.submitted_at)]})]}),et("div",{className:"af-space-y-6",children:[Xe(wa,{deliveries:e.email_deliveries}),et("div",{children:[Xe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),et("div",{className:"af-space-y-3",children:[f.map(([m,b])=>et("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[Xe("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:m.replace(/_/g," ")}),Xe("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof b=="string"&&b.includes(`
3
+ `)?Xe("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:b}):String(b)})]},m)),f.length===0&&Xe("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&et("div",{children:[Xe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),Xe("div",{className:"af-space-y-2",children:e.attachments.map((m,b)=>et("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[et("div",{className:"af-flex af-items-center af-gap-2",children:[Xe(Do,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Xe("span",{className:"af-text-sm",children:m.name}),et("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Fo(m.size),")"]})]}),et(S,{variant:"ghost",size:"sm",onClick:()=>o(m),disabled:t===i(m),children:[t===i(m)?Xe(Lo,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Xe(Eo,{className:"af-h-4 af-w-4 af-mr-1"}),t===i(m)?"Downloading...":"Download"]})]},b))})]}),et("div",{children:[Xe("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),et("div",{className:"af-space-y-2 af-text-sm",children:[et("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Xe(Ao,{className:"af-h-4 af-w-4"}),Xe("span",{children:Cr(e.metadata.submitted_at)})]}),e.metadata.ip_address&&et("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Xe(Io,{className:"af-h-4 af-w-4"}),et("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&et("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[Xe(Oo,{className:"af-h-4 af-w-4 af-mt-0.5"}),Xe("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&et("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[Xe(Bo,{className:"af-h-4 af-w-4"}),et("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}import{jsx as _e,jsxs as mt}from"react/jsx-runtime";function zo(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qo(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 jo(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:f,pageSize:m,hasNextPage:b,hasPreviousPage:r,setPage:g,setPageSize:y}=Hs({formId:e}),[p,c]=Rs.useState("list"),[d,v]=Rs.useState(null);Rs.useEffect(()=>{if(s&&t.length>0){let l=t.find(x=>x.id===s);l&&(v(l),c("detail"))}},[s,t]);let h=l=>{v(l),c("detail")},R=()=>{c("list"),v(null)};if(p==="detail"&&d)return _e("div",{className:a,children:_e(zs,{submission:d,onBack:R})});if(i)return _e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:_e("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return _e("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:mt("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(t.length===0&&f===0)return mt("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[_e($o,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),mt("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",_e("br",{}),"Submissions will appear here when visitors use your form."]})]});let E=f*m+1,M=Math.min((f+1)*m,n);return mt("div",{className:a,children:[mt(Le,{children:[_e(Oe,{children:mt(me,{children:[_e(O,{children:"Email"}),_e(O,{children:"Preview"}),_e(O,{children:"Date"}),_e(O,{className:"af-text-right",children:"Actions"})]})}),_e(Be,{children:t.map(l=>{let x=qo(l.data),C=jo(l.data);return mt(me,{children:[mt(B,{className:"af-font-medium",children:[mt("div",{className:"af-flex af-items-center af-gap-2",children:[x||_e("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),l.attachments.length>0&&mt("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${l.attachments.length} attachment(s)`,children:[_e(Ho,{className:"af-h-3 af-w-3"}),_e("span",{className:"af-text-xs",children:l.attachments.length})]})]}),_e(Ss,{deliveries:l.email_deliveries,label:"Notification email needs attention"})]}),_e(B,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:C||_e("span",{className:"af-italic",children:"No preview available"})}),_e(B,{className:"af-text-muted-foreground",children:zo(l.metadata.submitted_at)}),_e(B,{className:"af-text-right",children:_e(S,{variant:"ghost",size:"icon",onClick:()=>h(l),title:"View details",children:_e(Vo,{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 ",E,"-",M," of ",n]}),mt(Kt,{value:String(m),onValueChange:l=>y(Number(l)),children:[_e($t,{className:"af-w-[70px] af-h-8",children:_e(Jt,{})}),mt(Ht,{children:[_e(Ue,{value:"10",children:"10"}),_e(Ue,{value:"25",children:"25"}),_e(Ue,{value:"50",children:"50"}),_e(Ue,{value:"100",children:"100"})]})]}),_e("span",{children:"per page"})]}),mt("div",{className:"af-flex af-items-center af-gap-2",children:[mt(S,{variant:"outline",size:"sm",onClick:()=>g(f-1),disabled:!r,children:[_e(Mo,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),mt(S,{variant:"outline",size:"sm",onClick:()=>g(f+1),disabled:!b,children:["Next",_e(Uo,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as qt from"react";import{Plus as rl,X as il,Loader2 as ol,Check as ll}from"lucide-react";import*as Er from"react";import{jsx as Go}from"react/jsx-runtime";var pe=Er.forwardRef(({className:e,type:a,...s},t)=>Go("input",{type:a,className:$("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}));pe.displayName="Input";import*as Ir from"react";import{cva as Wo}from"class-variance-authority";import{jsx as Jo}from"react/jsx-runtime";var Ko=Wo("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ge=Ir.forwardRef(({className:e,...a},s)=>Jo("label",{ref:s,className:$(Ko(),e),...a}));ge.displayName="Label";import*as Qt from"react";import{Plus as Xo,Loader2 as Bn,Copy as el,Check as tl,Trash2 as al,RefreshCw as sl,AlertTriangle as nl}from"lucide-react";import*as _s from"react";import*as ct from"@radix-ui/react-dialog";import{X as Yo}from"lucide-react";import{jsx as Fa,jsxs as On}from"react/jsx-runtime";var Na=ct.Root;var Zo=ct.Portal;var Ar=_s.forwardRef(({className:e,...a},s)=>Fa(ct.Overlay,{ref:s,className:$("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...a}));Ar.displayName=ct.Overlay.displayName;var ra=_s.forwardRef(({className:e,children:a,...s},t)=>Fa(Zo,{children:On("div",{className:"aifeatures-admin",children:[Fa(Ar,{}),On(ct.Content,{ref:t,className:$("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,On(ct.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:[Fa(Yo,{className:"af-h-4 af-w-4"}),Fa("span",{className:"af-sr-only",children:"Close"})]})]})]})}));ra.displayName=ct.Content.displayName;var ia=({className:e,...a})=>Fa("div",{className:$("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...a});ia.displayName="DialogHeader";var oa=({className:e,...a})=>Fa("div",{className:$("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...a});oa.displayName="DialogFooter";var la=_s.forwardRef(({className:e,...a},s)=>Fa(ct.Title,{ref:s,className:$("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...a}));la.displayName=ct.Title.displayName;var ca=_s.forwardRef(({className:e,...a},s)=>Fa(ct.Description,{ref:s,className:$("af-text-sm af-text-muted-foreground",e),...a}));ca.displayName=ct.Description.displayName;import*as zt from"react";function js(){let{api:e}=ae(),[a,s]=zt.useState([]),[t,n]=zt.useState(!0),[i,o]=zt.useState(null),f=zt.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]);zt.useEffect(()=>{f()},[f]);let m=zt.useCallback(async p=>{let c=await e.createEventDestination(p);return s(d=>[c,...d]),c},[e]),b=zt.useCallback(async(p,c)=>{let d=await e.updateEventDestination(p,c);return s(v=>v.map(h=>h.id===p?d:h)),d},[e]),r=zt.useCallback(async p=>{await e.deleteEventDestination(p),s(c=>c.filter(d=>d.id!==p))},[e]),g=zt.useCallback(async p=>{let c=await e.rotateEventDestinationSecret(p);return s(d=>d.map(v=>v.id===p?c:v)),c},[e]),y=zt.useCallback(p=>e.getEventDestinationSecret(p),[e]);return{destinations:a,isLoading:t,error:i,refetch:f,createDestination:m,updateDestination:b,deleteDestination:r,rotateSecret:g,getSecret:y}}import*as Ma from"react";import{Loader2 as Dr,RotateCw as Qo}from"lucide-react";import{jsx as Zt,jsxs as Ps}from"react/jsx-runtime";function Gs({destinationId:e,limit:a=25,className:s}){let{api:t}=ae(),[n,i]=Ma.useState([]),[o,f]=Ma.useState(!0),[m,b]=Ma.useState(null),[r,g]=Ma.useState(null),y=Ma.useCallback(async()=>{try{f(!0),b(null),i(await t.getEventDeliveries(e,a))}catch(c){b(c instanceof Error?c.message:"Failed to load deliveries")}finally{f(!1)}},[t,e,a]);Ma.useEffect(()=>{y()},[y]);let p=async c=>{try{g(c.id),b(null);let d=await t.retryEventDelivery(e,c.id);i(v=>v.map(h=>h.id===c.id?d:h))}catch(d){b(d instanceof Error?d.message:"Retry failed")}finally{g(null)}};return o?Ps("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[Zt(Dr,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):m?Zt("div",{className:"af-text-sm af-text-destructive af-py-2",children:m}):n.length===0?Zt("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):Zt("div",{className:s,children:Zt("div",{className:"af-divide-y af-border af-rounded",children:n.map(c=>{let d=c.delivered_at!==null;return Ps("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[Ps("div",{className:"af-min-w-0",children:[Ps("div",{className:"af-flex af-items-center af-gap-2",children:[d?Zt(Z,{variant:"secondary",children:c.last_status??200}):Zt(Z,{variant:"destructive",children:c.last_status??"failed"}),Zt("span",{className:"af-text-sm af-truncate",children:c.type})]}),Ps("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[c.event_id," \xB7 ",c.created_at,c.attempts>0&&` \xB7 ${c.attempts} failed ${c.attempts===1?"attempt":"attempts"}`]}),!d&&c.last_error&&Zt("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),Zt(S,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===c.id,onClick:()=>p(c),children:r===c.id?Zt(Dr,{className:"af-h-4 af-w-4 af-animate-spin"}):Zt(Qo,{className:"af-h-4 af-w-4"})})]},c.id)})})})}import{jsx as Pe,jsxs as nt}from"react/jsx-runtime";function Ws({formId:e,topics:a,description:s,className:t}){let{destinations:n,isLoading:i,error:o,createDestination:f,updateDestination:m,deleteDestination:b,rotateSecret:r,getSecret:g}=js(),[y,p]=Qt.useState(""),[c,d]=Qt.useState(!1),[v,h]=Qt.useState(null),[R,E]=Qt.useState(null),[M,l]=Qt.useState(null),[x,C]=Qt.useState(!1),[j,L]=Qt.useState(null),[w,K]=Qt.useState(null),[u,z]=Qt.useState(null),le=Qt.useMemo(()=>n.filter(q=>q.form_id===e),[n,e]),ie=async()=>{let q=y.trim();if(q){if(!q.startsWith("https://")){h("Webhook URLs must start with https://");return}try{d(!0),h(null),await f({url:q,form_id:e,...a&&a.length>0?{topics:a}:{}}),p("")}catch(he){h(he instanceof Error?he.message:"Failed to add webhook")}finally{d(!1)}}},X=async q=>{try{K(q.id),h(null),await r(q.id),C(!1),l(await g(q.id))}catch(he){h(he instanceof Error?he.message:"Failed to rotate secret")}finally{K(null)}},be=async q=>{try{K(q.id),h(null),await m(q.id,{status:"active"})}catch(he){h(he instanceof Error?he.message:"Failed to re-enable")}finally{K(null)}},G=async()=>{if(j)try{K(j.id),await b(j.id),L(null)}catch(q){h(q instanceof Error?q.message:"Failed to delete")}finally{K(null)}},oe=async q=>{if(R===q.id){E(null),l(null);return}try{K(q.id),h(null),C(!1),E(q.id),l(await g(q.id))}catch(he){E(null),h(he instanceof Error?he.message:"Failed to read secret")}finally{K(null)}},ce=async()=>{if(M)try{await navigator.clipboard.writeText(M),C(!0)}catch{}};return nt("div",{className:t,children:[nt("div",{className:"af-space-y-1",children:[Pe(ge,{children:"Webhooks"}),Pe("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."})]}),nt("div",{className:"af-flex af-gap-2 af-mt-4",children:[Pe(pe,{value:y,placeholder:"https://hooks.zapier.com/...",onChange:q=>p(q.target.value),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),ie())},disabled:c}),nt(S,{onClick:ie,disabled:c||!y.trim(),children:[c?Pe(Bn,{className:"af-h-4 af-w-4 af-animate-spin"}):Pe(Xo,{className:"af-h-4 af-w-4"}),Pe("span",{className:"af-ml-1",children:"Add"})]})]}),(v||o)&&Pe("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:v||o?.message}),nt("div",{className:"af-mt-4 af-space-y-2",children:[i&&nt("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Pe(Bn,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&le.length===0&&Pe("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),le.map(q=>nt("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[nt("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[nt("div",{className:"af-min-w-0",children:[nt("div",{className:"af-flex af-items-center af-gap-2",children:[Pe("span",{className:"af-font-mono af-text-sm af-truncate",children:q.url}),q.status==="disabled"?Pe(Z,{variant:"destructive",children:"Disabled"}):Pe(Z,{variant:"secondary",children:"Active"})]}),Pe("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:q.topics.includes("*")?"All events":q.topics.join(", ")})]}),nt("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[Pe(S,{variant:"ghost",size:"sm",onClick:()=>z(u===q.id?null:q.id),children:u===q.id?"Hide log":"Deliveries"}),Pe(S,{variant:"ghost",size:"sm",onClick:()=>oe(q),disabled:w===q.id,children:R===q.id?"Hide secret":"Show secret"}),Pe(S,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:w===q.id,onClick:()=>L(q),children:Pe(al,{className:"af-h-4 af-w-4"})})]})]}),q.status==="disabled"&&nt("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[Pe(nl,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),nt("div",{className:"af-text-sm",children:[nt("p",{children:["We stopped sending after repeated failures."," ",q.disabled_reason]}),Pe(S,{variant:"outline",size:"sm",className:"af-mt-2",disabled:w===q.id,onClick:()=>be(q),children:"Re-enable"})]})]}),R===q.id&&M&&nt("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[Pe("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."}),nt("div",{className:"af-flex af-gap-2",children:[Pe(pe,{readOnly:!0,value:M,className:"af-font-mono"}),Pe(S,{variant:"outline",title:"Copy signing secret",onClick:ce,children:x?Pe(tl,{className:"af-h-4 af-w-4"}):Pe(el,{className:"af-h-4 af-w-4"})}),Pe(S,{variant:"outline",title:"Rotate signing secret",disabled:w===q.id,onClick:()=>X(q),children:w===q.id?Pe(Bn,{className:"af-h-4 af-w-4 af-animate-spin"}):Pe(sl,{className:"af-h-4 af-w-4"})})]})]}),u===q.id&&Pe(Gs,{destinationId:q.id})]},q.id))]}),Pe(Na,{open:!!j,onOpenChange:q=>{!q&&!w&&L(null)},children:nt(ra,{children:[nt(ia,{children:[Pe(la,{children:"Delete this webhook?"}),nt(ca,{children:["New submissions will stop being sent to ",j?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),nt(oa,{children:[Pe(S,{variant:"outline",onClick:()=>L(null),disabled:!!w,children:"Cancel"}),Pe(S,{variant:"destructive",onClick:G,disabled:!!w,children:w?"Deleting...":"Delete"})]})]})})]})}import{jsx as Ae,jsxs as da}from"react/jsx-runtime";function Ks({form:e,onSaved:a,className:s}){let{updateForm:t}=rs(),[n,i]=qt.useState(!1),[o,f]=qt.useState(null),[m,b]=qt.useState(null),[r,g]=qt.useState(e.name),[y,p]=qt.useState(e.redirect_url||""),[c,d]=qt.useState(e.email_recipients),[v,h]=qt.useState("");qt.useEffect(()=>{g(e.name),p(e.redirect_url||""),d(e.email_recipients),b(null)},[e]);let R=qt.useCallback(async C=>{try{i(!0),b(null);let j=await t(e.id,C);f(new Date),a?.(j)}catch(j){b(j instanceof Error?j.message:"Failed to save")}finally{i(!1)}},[e.id,t,a]);qt.useEffect(()=>{if(o){let C=setTimeout(()=>f(null),2e3);return()=>clearTimeout(C)}},[o]);let E=async()=>{let C=v.trim().toLowerCase();if(!C)return;if(!C.includes("@")){b("Please enter a valid email address");return}if(c.includes(C)){b("This email is already added");return}let j=[...c,C];d(j),h(""),b(null),await R({email_recipients:j})},M=async C=>{let j=c.filter(L=>L!==C);d(j),await R({email_recipients:j})},l=async()=>{r!==e.name&&await R({name:r})},x=async()=>{let C=y||null;C!==e.redirect_url&&await R({redirect_url:C})};return da("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&Ae("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?da("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:[Ae(ol,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),Ae("span",{className:"af-text-sm",children:"Saving..."})]}):da("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:[Ae(ll,{className:"af-h-4 af-w-4 af-text-green-600"}),Ae("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),da("div",{className:"af-space-y-2",children:[Ae(ge,{htmlFor:"form-name",children:"Form Name"}),Ae(pe,{id:"form-name",value:r,onChange:C=>g(C.target.value),onBlur:l,placeholder:"Contact Form"}),Ae("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),da("div",{className:"af-space-y-2",children:[Ae(ge,{children:"Email Recipients"}),Ae("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),da("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(C=>da(Z,{variant:"secondary",className:"af-gap-1",children:[C,Ae("button",{type:"button",onClick:()=>M(C),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:Ae(il,{className:"af-h-3 af-w-3"})})]},C)),c.length===0&&Ae("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),da("div",{className:"af-flex af-gap-2",children:[Ae(pe,{type:"email",value:v,onChange:C=>h(C.target.value),placeholder:"Add email address",onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),E())},disabled:n}),Ae(S,{type:"button",variant:"outline",onClick:E,disabled:!v.trim()||n,children:Ae(rl,{className:"af-h-4 af-w-4"})})]})]}),da("div",{className:"af-space-y-2",children:[Ae(ge,{htmlFor:"redirect-url",children:"Redirect URL"}),Ae(pe,{id:"redirect-url",value:y,onChange:C=>p(C.target.value),onBlur:x,placeholder:"/thank-you"}),Ae("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."})]}),da("div",{className:"af-space-y-2",children:[Ae(ge,{children:"Form Endpoint"}),Ae("div",{className:"af-flex af-items-center af-gap-2",children:Ae("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})}),Ae("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),da("div",{className:"af-space-y-2",children:[Ae(ge,{children:"Captcha Protection"}),Ae("div",{className:"af-flex af-items-center af-gap-2",children:Ae(Z,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),Ae("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),Ae(Ws,{formId:e.id}),m&&Ae("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 Pt,jsxs as Sa}from"react/jsx-runtime";function Lr({className:e,submissionId:a}){let{api:s}=ae(),[t,n]=qa.useState("list"),[i,o]=qa.useState(null),[f,m]=qa.useState("submissions"),[b,r]=qa.useState(a),[g,y]=qa.useState(!!a);qa.useEffect(()=>{if(!a)return;async function v(){try{let h=await s.getSubmission(a),R=await s.getForm(h.form_id);o(R),n("detail"),m("submissions"),r(a)}catch(h){console.error("Failed to load submission for deep link:",h)}finally{y(!1)}}v()},[a,s]);let p=(v,h)=>{o(v),n("detail"),m(h),r(void 0)},c=()=>{n("list"),o(null),r(void 0)},d=v=>{o(v)};return g?Pt("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:Pt("div",{className:"af-text-muted-foreground",children:"Loading..."})}):Sa("div",{className:e,children:[t==="list"&&Sa("div",{children:[Sa("div",{className:"af-mb-6",children:[Pt("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),Pt("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),Pt(Us,{onSelectForm:p})]}),t==="detail"&&i&&Sa("div",{children:[Sa("div",{className:"af-mb-6",children:[Sa(S,{variant:"ghost",size:"sm",onClick:c,className:"af-mb-2 af--ml-2",children:[Pt(cl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),Pt("h2",{className:"af-text-lg af-font-semibold",children:i.name}),Pt("p",{className:"af-text-sm af-text-muted-foreground",children:Pt("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),Sa(Ms,{value:f,onValueChange:v=>m(v),children:[Sa(Ns,{className:"af-mb-4",children:[Sa(ha,{value:"submissions",className:"af-gap-2",children:[Pt(ul,{className:"af-h-4 af-w-4"}),"Submissions"]}),Sa(ha,{value:"settings",className:"af-gap-2",children:[Pt(dl,{className:"af-h-4 af-w-4"}),"Settings"]})]}),Pt(xa,{value:"submissions",children:Pt(qs,{formId:i.id,defaultSubmissionId:b})}),Pt(xa,{value:"settings",children:Pt(Ks,{form:i,onSaved:d})})]})]})]})}import*as gs from"react";import{ArrowLeft as Lc,FileText as Oc,Package as Bc,Receipt as Fc,Settings as Mc,Users as Uc}from"lucide-react";import*as Js from"react";import{Package as ml,Pencil as pl,Plus as Or,Trash2 as gl}from"lucide-react";var fl=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Ra(e){return fl.has(e.toLowerCase())}function H(e,a,s){let t=Ra(a)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:a.toUpperCase()}).format(t)}catch{return`${t} ${a.toUpperCase()}`}}function ua(e){let a=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+a}function fa(e,a){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let t=Ra(a)?s:s*100;return Math.round(t)}function xt(e,a){return Ra(a)?e:e/100}import{jsx as Fe,jsxs as _t}from"react/jsx-runtime";function vl(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 Ys({productsState:e,onSelectProduct:a,onCreateProduct:s,className:t}){let{products:n,isLoading:i,error:o,deleteProduct:f}=e,[m,b]=Js.useState(null),[r,g]=Js.useState(!1),[y,p]=Js.useState(null),c=async()=>{if(m)try{g(!0),p(null),await f(m.id),b(null)}catch(d){p(d instanceof Error?d.message:"Failed to delete product")}finally{g(!1)}};return i?Fe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:Fe("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?Fe("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:_t("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?_t("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[Fe(ml,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),_t("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",Fe("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),_t(S,{variant:"outline",onClick:()=>s?.(),children:[Fe(Or,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):_t("div",{className:t,children:[Fe("div",{className:"af-flex af-justify-end af-mb-4",children:_t(S,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[Fe(Or,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),_t(Le,{children:[Fe(Oe,{children:_t(me,{children:[Fe(O,{children:"Name"}),Fe(O,{children:"Price"}),Fe(O,{children:"Fulfillment"}),Fe(O,{children:"Status"}),Fe(O,{className:"af-text-right",children:"Actions"})]})}),Fe(Be,{children:n.map(d=>_t(me,{children:[Fe(B,{className:"af-font-medium",children:d.name}),Fe(B,{children:vl(d)}),Fe(B,{className:"af-text-muted-foreground",children:bl(d)}),Fe(B,{children:Fe(Z,{variant:d.active?"success":"secondary",children:d.active?"Active":"Inactive"})}),Fe(B,{className:"af-text-right",children:_t("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[_t(S,{variant:"ghost",size:"sm",onClick:()=>a?.(d),children:[Fe(pl,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),_t(S,{variant:"ghost",size:"sm",onClick:()=>{p(null),b(d)},children:[Fe(gl,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},d.id))})]}),Fe(Na,{open:!!m,onOpenChange:d=>{!d&&!r&&b(null)},children:_t(ra,{children:[_t(ia,{children:[Fe(la,{children:"Delete product?"}),_t(ca,{children:['"',m?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),y&&Fe("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y}),_t(oa,{children:[Fe(S,{variant:"outline",onClick:()=>b(null),disabled:r,children:"Cancel"}),Fe(S,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}import*as ze from"react";import{FileText as hl,Link2 as xl,Loader2 as Mr,Plus as wl,Upload as Nl,X as Sl}from"lucide-react";import*as rt from"react";import{Loader2 as Br,Plus as Fn,Trash2 as Fr,X as yl}from"lucide-react";import{jsx as U,jsxs as de}from"react/jsx-runtime";function Mn(e){return e.option_values.length>0?e.option_values.map(a=>a.value).join(" / "):e.title||"Default"}function Zs({productId:e,currency:a,className:s}){let{api:t}=ae(),n=Ra(a)?"1":"0.01",[i,o]=rt.useState(null),[f,m]=rt.useState(!0),[b,r]=rt.useState(null),[g,y]=rt.useState(null),[p,c]=rt.useState(!1),d=rt.useRef(!0);rt.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);let v=rt.useCallback(async()=>{try{let _=await t.getProduct(e);if(!d.current)return;o(_)}catch(_){if(!d.current)return;r(_ instanceof Error?_.message:"Failed to load product")}finally{d.current&&m(!1)}},[t,e]);rt.useEffect(()=>{v()},[v]);let h=async _=>{y(null),c(!0);try{await _(),await v()}catch(A){d.current&&y(A instanceof Error?A.message:"Something went wrong")}finally{d.current&&c(!1)}},[R,E]=rt.useState(""),[M,l]=rt.useState(""),[x,C]=rt.useState({}),j=()=>h(async()=>{let _=R.trim(),A=M.split(",").map(fe=>fe.trim()).filter(Boolean);if(!_)throw new Error("Option name is required");if(A.length===0)throw new Error("Add at least one value");await t.createOption(e,{title:_,values:A}),d.current&&(E(""),l(""))}),L=_=>h(async()=>{let A=(x[_.id]??"").trim();if(!A)throw new Error("Enter a value");await t.updateOption(_.id,{add_values:[A]}),d.current&&C(fe=>({...fe,[_.id]:""}))}),w=(_,A)=>h(()=>t.updateOption(_.id,{remove_values:[A]})),K=_=>h(()=>t.deleteOption(_.id)),[u,z]=rt.useState(null),[le,ie]=rt.useState(null),[X,be]=rt.useState(!1),[G,oe]=rt.useState(null),ce=i?.options??[],q=i?.variants??[],he=()=>{ie(null),z({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ce.map(_=>[_.id,_.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},ut=_=>{ie(null);let A=_.inventory?.on_hand??0,fe=A<0?"":String(A);z({variant:_,title:_.title??"",sku:_.sku??"",unitAmount:_.unit_amount!=null?String(xt(_.unit_amount,a)):"",compareAt:_.compare_at_amount!=null?String(xt(_.compare_at_amount,a)):"",active:_.active,optionValues:{},tracked:_.inventory?.tracked??!1,onHand:fe,initialOnHand:fe,allowBackorder:_.inventory?.allow_backorder??!1})},bt=async()=>{if(!u)return;ie(null);let _=u.variant?.allow_custom_amount??!1,A=null,fe=null;if(!_){if(A=fa(u.unitAmount,a),A===null||A<=0){ie("Enter a valid price");return}if(u.compareAt.trim()&&(fe=fa(u.compareAt,a),fe===null||fe<=A)){ie("Compare-at price must be greater than the price");return}}let Ce=u.onHand.trim()!==u.initialOnHand.trim(),ke=parseInt(u.onHand,10);if(u.tracked&&Ce&&(!Number.isFinite(ke)||ke<0)){ie("On-hand quantity must be zero or more");return}try{if(be(!0),u.variant)await t.updateVariant(u.variant.id,{title:u.title.trim()||null,sku:u.sku.trim()||null,..._?{}:{unit_amount:A,compare_at_amount:fe},active:u.active}),await t.setVariantInventory(u.variant.id,{tracked:u.tracked,on_hand:u.tracked&&Ce?ke:void 0,allow_backorder:u.allowBackorder});else{let Ve={};for(let $e of ce){let St=u.optionValues[$e.id];if(!St){ie(`Choose a ${$e.title}`),be(!1);return}Ve[$e.title]=St}await t.createVariant(e,{title:u.title.trim()||null,sku:u.sku.trim()||null,unit_amount:A,compare_at_amount:fe,active:u.active,option_values:ce.length>0?Ve:void 0,inventory:u.tracked?{tracked:!0,on_hand:ke,allow_backorder:u.allowBackorder}:{tracked:!1,allow_backorder:u.allowBackorder}})}await v(),d.current&&z(null)}catch(Ve){if(d.current&&ie(Ve instanceof Error?Ve.message:"Failed to save variant"),u.variant)try{let $e=await t.getProduct(e);d.current&&o($e)}catch{}}finally{d.current&&be(!1)}},xe=()=>h(async()=>{G&&(await t.deleteVariant(G.id),d.current&&oe(null))}),ft=u?.variant?.allow_custom_amount??!1,Y=u?.variant!=null&&u.variant.option_values.length===0&&ce.length>0&&!u.variant.active,ee=u?.variant?.inventory!=null&&u.variant.inventory.on_hand<0?-u.variant.inventory.on_hand:null;function ve(_){let A=_.inventory;if(!A||!A.tracked)return U("span",{className:"af-text-muted-foreground",children:"Unlimited"});let fe=A.available??A.on_hand;return fe<0?de("span",{children:[-fe," backordered"]}):de("span",{children:[fe," in stock",A.allow_backorder&&U("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return f?U("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:U(Br,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):b?U("div",{className:s,children:U("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b})}):de("div",{className:`af-space-y-6 ${s||""}`,children:[de("div",{className:"af-space-y-3",children:[de("div",{children:[U(ge,{children:"Options"}),U("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."})]}),ce.length>0&&U("div",{className:"af-space-y-3",children:ce.map(_=>de("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[de("div",{className:"af-flex af-items-center af-justify-between",children:[U("span",{className:"af-text-sm af-font-medium",children:_.title}),U(S,{variant:"ghost",size:"sm",onClick:()=>K(_),disabled:p,children:U(Fr,{className:"af-h-4 af-w-4"})})]}),U("div",{className:"af-flex af-flex-wrap af-gap-2",children:_.values.map(A=>de(Z,{variant:"secondary",className:"af-gap-1",children:[A.value,U("button",{type:"button",onClick:()=>w(_,A.value),className:"af-ml-1 hover:af-text-destructive",disabled:p,title:"Remove value",children:U(yl,{className:"af-h-3 af-w-3"})})]},A.id))}),de("div",{className:"af-flex af-gap-2",children:[U(pe,{value:x[_.id]??"",onChange:A=>C(fe=>({...fe,[_.id]:A.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),L(_))},disabled:p}),U(S,{type:"button",variant:"outline",size:"sm",onClick:()=>L(_),disabled:p||!(x[_.id]??"").trim(),children:U(Fn,{className:"af-h-4 af-w-4"})})]})]},_.id))}),de("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[de("div",{className:"af-space-y-1",children:[U(ge,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),U(pe,{id:"new-option-title",value:R,onChange:_=>E(_.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:p})]}),de("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[U(ge,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),U(pe,{id:"new-option-values",value:M,onChange:_=>l(_.target.value),placeholder:"S, M, L",disabled:p})]}),de(S,{type:"button",variant:"outline",onClick:j,disabled:p||!R.trim()||!M.trim(),children:[U(Fn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),de("div",{className:"af-space-y-3",children:[de("div",{className:"af-flex af-items-center af-justify-between",children:[U(ge,{children:"Variants"}),de(S,{type:"button",variant:"outline",size:"sm",onClick:he,disabled:p||ce.length===0,children:[U(Fn,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ce.length===0&&U("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),q.length===0?U("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):de(Le,{children:[U(Oe,{children:de(me,{children:[U(O,{children:"Variant"}),U(O,{children:"SKU"}),U(O,{children:"Price"}),U(O,{children:"Stock"}),U(O,{children:"Status"}),U(O,{className:"af-text-right",children:"Actions"})]})}),U(Be,{children:q.map(_=>de(me,{children:[U(B,{className:"af-font-medium",children:Mn(_)}),U(B,{className:"af-text-muted-foreground",children:_.sku||"-"}),U(B,{children:_.unit_amount!=null?de("span",{children:[_.compare_at_amount!=null&&U("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:H(_.compare_at_amount,_.currency)}),H(_.unit_amount,_.currency)]}):_.allow_custom_amount?U("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),U(B,{children:ve(_)}),U(B,{children:U(Z,{variant:_.active?"success":"secondary",children:_.active?"Active":"Inactive"})}),U(B,{className:"af-text-right",children:de("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[U(S,{variant:"ghost",size:"sm",onClick:()=>ut(_),disabled:p,children:"Edit"}),U(S,{variant:"ghost",size:"icon",onClick:()=>oe(_),disabled:p,title:"Delete variant",children:U(Fr,{className:"af-h-4 af-w-4"})})]})})]},_.id))})]})]}),g&&U("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g}),U(Na,{open:u!==null,onOpenChange:_=>{!_&&!X&&z(null)},children:de(ra,{children:[de(ia,{children:[U(la,{children:u?.variant?"Edit variant":"Add variant"}),U(ca,{children:"Price, markdown, and stock live on the variant."})]}),u&&de("div",{className:"af-space-y-3",children:[u.variant?u.variant.option_values.length>0&&de("div",{className:"af-text-sm",children:[U("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Mn(u.variant)]}):ce.map(_=>de("div",{className:"af-space-y-1",children:[U(ge,{className:"af-text-xs af-text-muted-foreground",children:_.title}),de(Kt,{value:u.optionValues[_.id]??"",onValueChange:A=>z(fe=>fe&&{...fe,optionValues:{...fe.optionValues,[_.id]:A}}),children:[U($t,{children:U(Jt,{placeholder:`Choose ${_.title}`})}),U(Ht,{children:_.values.map(A=>U(Ue,{value:A.value,children:A.value},A.id))})]})]},_.id)),ft?de("div",{className:"af-space-y-1",children:[U(ge,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),U("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):de("div",{className:"af-flex af-gap-3",children:[de("div",{className:"af-space-y-1",children:[de(ge,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",a.toUpperCase(),")"]}),U(pe,{id:"variant-price",type:"number",min:"0",step:n,value:u.unitAmount,onChange:_=>z(A=>A&&{...A,unitAmount:_.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),de("div",{className:"af-space-y-1",children:[U(ge,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),U(pe,{id:"variant-compare",type:"number",min:"0",step:n,value:u.compareAt,onChange:_=>z(A=>A&&{...A,compareAt:_.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),de("div",{className:"af-space-y-1",children:[U(ge,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),U(pe,{id:"variant-sku",value:u.sku,onChange:_=>z(A=>A&&{...A,sku:_.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),de("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[U("input",{type:"checkbox",checked:u.tracked,onChange:_=>z(A=>A&&{...A,tracked:_.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),u.tracked&&de("div",{className:"af-space-y-1 af-pl-6",children:[de("div",{className:"af-flex af-items-end af-gap-3",children:[de("div",{className:"af-space-y-1",children:[U(ge,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),U(pe,{id:"variant-onhand",type:"number",min:"0",step:"1",value:u.onHand,onChange:_=>z(A=>A&&{...A,onHand:_.target.value}),placeholder:ee!=null?"0":void 0,className:"af-w-[100px]"})]}),de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[U("input",{type:"checkbox",checked:u.allowBackorder,onChange:_=>z(A=>A&&{...A,allowBackorder:_.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),ee!=null&&de("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",ee," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),de("div",{className:"af-space-y-1",children:[de("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[U("input",{type:"checkbox",checked:u.active,onChange:_=>z(A=>A&&{...A,active:_.target.checked}),className:"af-h-4 af-w-4",disabled:Y}),"Active (buyers can purchase this variant)"]}),Y&&U("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."})]}),le&&U("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:le})]}),de(oa,{children:[U(S,{variant:"outline",onClick:()=>z(null),disabled:X,children:"Cancel"}),de(S,{onClick:bt,disabled:X,children:[X?U(Br,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,u?.variant?"Save":"Add variant"]})]})]})}),U(Na,{open:G!==null,onOpenChange:_=>{!_&&!p&&oe(null)},children:de(ra,{children:[de(ia,{children:[U(la,{children:"Delete variant?"}),U(ca,{children:G&&`"${Mn(G)}" will no longer be purchasable. Past orders are unaffected.`})]}),de(oa,{children:[U(S,{variant:"outline",onClick:()=>oe(null),disabled:p,children:"Cancel"}),U(S,{variant:"destructive",onClick:xe,disabled:p,children:"Delete"})]})]})})]})}import{Fragment as _l,jsx as ue,jsxs as Se}from"react/jsx-runtime";function Rl(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 Qs({productsState:e,product:a,currency:s,onSaved:t,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:f,attachProductFileFromUrl:m}=e,b=!!a,r=a?.currency??s,g=Ra(r)?"1":"0.01",y=a!=null&&a.unit_amount===null&&!a.allow_custom_amount,[p,c]=ze.useState(!1),[d,v]=ze.useState(null),h=ze.useRef(!0);ze.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);let[R,E]=ze.useState(a?.name??""),[M,l]=ze.useState(a?.description??""),[x,C]=ze.useState(a?.allow_custom_amount?"custom":"fixed"),[j,L]=ze.useState(a?.unit_amount!=null?String(xt(a.unit_amount,r)):""),[w,K]=ze.useState(a?.min_amount!=null?String(xt(a.min_amount,r)):""),[u,z]=ze.useState(a?.max_amount!=null?String(xt(a.max_amount,r)):""),[le,ie]=ze.useState(String(a?.max_quantity??10)),X=ze.useRef({pricingMode:a?.allow_custom_amount?"custom":"fixed",unitAmount:a?.unit_amount!=null?String(xt(a.unit_amount,r)):"",minAmount:a?.min_amount!=null?String(xt(a.min_amount,r)):"",maxAmount:a?.max_amount!=null?String(xt(a.max_amount,r)):"",maxQuantity:String(a?.max_quantity??10)}).current,[be,G]=ze.useState(a?.collect_shipping_address??!1),[oe,ce]=ze.useState(a?.active??!0),[q,he]=ze.useState(a?.images??[]),[ut,bt]=ze.useState(""),[xe,ft]=ze.useState(a?.fulfillment??null),[Y,ee]=ze.useState(!1),[ve,_]=ze.useState(""),[A,fe]=ze.useState(null),Ce=ze.useRef(null),ke=p||Y,Ve=()=>{let te=ut.trim();if(te){if(q.includes(te)){v("This image URL is already added");return}he(De=>[...De,te]),bt(""),v(null)}},$e=te=>{he(De=>De.filter(He=>He!==te))},St=async()=>{if(v(null),!R.trim()){v("Product name is required");return}let te=null,De=null,He=null,aa=!b||x!==X.pricingMode||(x==="fixed"?j!==X.unitAmount:w!==X.minAmount||u!==X.maxAmount),It=!b||le!==X.maxQuantity,Da=y||x==="fixed";if(!(y||!aa))if(x==="fixed"){if(te=fa(j,r),te===null||te<=0){v("Enter a valid price");return}}else{if(De=fa(w,r),He=fa(u,r),De===null||He===null){v("Enter valid minimum and maximum amounts");return}if(He<De){v("Maximum amount must be at least the minimum amount");return}}let st=parseInt(le,10);if(Da&&It&&(!Number.isFinite(st)||st<1)){v("Max quantity must be at least 1");return}try{c(!0);let Ze;if(b&&a){let k={name:R.trim(),description:M.trim()||null,images:q,collect_shipping_address:be,active:oe};!y&&aa&&(k.allow_custom_amount=x==="custom",x==="fixed"?k.unit_amount=te:(k.min_amount=De,k.max_amount=He)),Da&&It&&(k.max_quantity=st),Ze=await o(a.id,k),X.pricingMode=Ze.allow_custom_amount?"custom":"fixed",X.unitAmount=Ze.unit_amount!=null?String(xt(Ze.unit_amount,r)):"",X.minAmount=Ze.min_amount!=null?String(xt(Ze.min_amount,r)):"",X.maxAmount=Ze.max_amount!=null?String(xt(Ze.max_amount,r)):"",X.maxQuantity=String(Ze.max_quantity)}else{let k={name:R.trim(),allow_custom_amount:x==="custom",collect_shipping_address:be,active:oe};M.trim()&&(k.description=M.trim()),q.length>0&&(k.images=q),x==="fixed"?(k.unit_amount=te,k.max_quantity=st):(k.min_amount=De,k.max_amount=He),Ze=await i(k)}if(!h.current)return;ft(Ze.fulfillment),t?.(Ze)}catch(Ze){if(!h.current)return;v(Ze instanceof Error?Ze.message:"Failed to save product")}finally{h.current&&c(!1)}},ta=async te=>{let De=te.target.files?.[0];if(!(!De||!a))try{ee(!0),fe(null);let He=await f(a.id,De);if(!h.current)return;ft(He.fulfillment),t?.(He)}catch(He){if(!h.current)return;fe(He instanceof Error?He.message:"Failed to upload file")}finally{h.current&&(ee(!1),Ce.current&&(Ce.current.value=""))}},yt=async()=>{let te=ve.trim();if(!(!te||!a))try{ee(!0),fe(null);let De=await m(a.id,te);if(!h.current)return;ft(De.fulfillment),_(""),t?.(De)}catch(De){if(!h.current)return;fe(De instanceof Error?De.message:"Failed to fetch file")}finally{h.current&&ee(!1)}};return Se("div",{className:`af-space-y-6 ${n||""}`,children:[Se("div",{className:"af-space-y-2",children:[ue(ge,{htmlFor:"product-name",children:"Name"}),ue(pe,{id:"product-name",value:R,onChange:te=>E(te.target.value),placeholder:"My product"})]}),Se("div",{className:"af-space-y-2",children:[ue(ge,{htmlFor:"product-description",children:"Description"}),ue("textarea",{id:"product-description",value:M,onChange:te=>l(te.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),Se("div",{className:"af-space-y-2",children:[ue(ge,{children:"Pricing"}),y?ue("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):Se(_l,{children:[Se(Kt,{value:x,onValueChange:te=>C(te),children:[ue($t,{className:"af-w-[260px]",children:ue(Jt,{})}),Se(Ht,{children:[ue(Ue,{value:"fixed",children:"Fixed price"}),ue(Ue,{value:"custom",children:"Buyer chooses the amount"})]})]}),x==="fixed"?ue("div",{className:"af-flex af-items-end af-gap-3",children:Se("div",{className:"af-space-y-1",children:[Se(ge,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),ue(pe,{id:"product-price",type:"number",min:"0",step:g,value:j,onChange:te=>L(te.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):Se("div",{className:"af-space-y-1",children:[Se("div",{className:"af-flex af-items-end af-gap-3",children:[Se("div",{className:"af-space-y-1",children:[Se(ge,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),ue(pe,{id:"product-min-amount",type:"number",min:"0",step:g,value:w,onChange:te=>K(te.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),Se("div",{className:"af-space-y-1",children:[Se(ge,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),ue(pe,{id:"product-max-amount",type:"number",min:"0",step:g,value:u,onChange:te=>z(te.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),ue("p",{className:"af-text-xs af-text-muted-foreground",children:"Buyers pick their own amount within these bounds (tip jar, pay-what-you-want). Quantity is always 1."})]}),Se("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",r.toUpperCase(),"), which follows the country of your payment account."]})]}),(y||x==="fixed")&&Se("div",{className:"af-space-y-1",children:[ue(ge,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),ue(pe,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:le,onChange:te=>ie(te.target.value),className:"af-w-[140px]"})]})]}),Se("div",{className:"af-space-y-2",children:[ue(ge,{children:"Images"}),ue("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),Se("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[q.map(te=>Se(Z,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[ue("span",{className:"af-truncate",children:te}),ue("button",{type:"button",onClick:()=>$e(te),className:"af-ml-1 hover:af-text-destructive",disabled:p,children:ue(Sl,{className:"af-h-3 af-w-3"})})]},te)),q.length===0&&ue("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),Se("div",{className:"af-flex af-gap-2",children:[ue(pe,{type:"url",value:ut,onChange:te=>bt(te.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),Ve())},disabled:p}),ue(S,{type:"button",variant:"outline",onClick:Ve,disabled:!ut.trim()||p,children:ue(wl,{className:"af-h-4 af-w-4"})})]})]}),Se("div",{className:"af-space-y-2",children:[ue(ge,{children:"Digital File"}),ue("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."}),b?Se("div",{className:"af-space-y-3",children:[xe?.type==="download"&&Se("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[ue(hl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),ue("span",{className:"af-text-sm",children:xe.filename}),xe.size!=null&&Se("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Rl(xe.size),")"]})]}),xe?.type==="redirect"&&xe.url&&Se("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[ue(xl,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),Se("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",xe.url]})]}),Se("div",{className:"af-flex af-items-center af-gap-2",children:[ue("input",{ref:Ce,type:"file",onChange:ta,className:"af-hidden",disabled:ke}),Se(S,{type:"button",variant:"outline",size:"sm",onClick:()=>Ce.current?.click(),disabled:ke,children:[Y?ue(Mr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):ue(Nl,{className:"af-h-4 af-w-4 af-mr-1"}),xe?.type==="download"?"Replace file":"Upload file"]}),ue("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),ue(pe,{type:"url",value:ve,onChange:te=>_(te.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Y}),ue(S,{type:"button",variant:"outline",size:"sm",onClick:yt,disabled:!ve.trim()||ke,children:"Fetch from URL"})]}),A&&ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:A})]}):ue("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),Se("div",{className:"af-space-y-2",children:[ue(ge,{children:"Settings"}),Se("div",{className:"af-space-y-2",children:[Se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ue("input",{type:"checkbox",checked:be,onChange:te=>G(te.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),Se("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[ue("input",{type:"checkbox",checked:oe,onChange:te=>ce(te.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),b&&a&&Se("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[ue(ge,{children:"Options & Variants"}),ue(Zs,{productId:a.id,currency:r})]}),d&&ue("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d}),ue("div",{className:"af-flex af-items-center af-gap-2",children:Se(S,{type:"button",onClick:St,disabled:ke,children:[p?ue(Mr,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,b?"Save changes":"Create product"]})})]})}import*as pt from"react";import{ChevronLeft as Jl,ChevronRight as Zr,Loader2 as Yl,Receipt as Zl,Search as Ql,SlidersHorizontal as Xl}from"lucide-react";import*as Qe from"react";var Pl=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Xs({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ae(),[t,n]=Qe.useState([]),[i,o]=Qe.useState(0),[f,m]=Qe.useState(!0),[b,r]=Qe.useState(null),[g,y]=Qe.useState(0),[p,c]=Qe.useState(e),[d,v]=Qe.useState(void 0),[h,R]=Qe.useState(""),[E,M]=Qe.useState(""),[l,x]=Qe.useState(""),[C,j]=Qe.useState(!1),[L,w]=Qe.useState(!1),[K,u]=Qe.useState(void 0),z=K?K.join(","):"",le=Qe.useMemo(()=>{if(!z)return;let G=new Set(z.split(","));return Pl.filter(oe=>!G.has(oe))},[z]),ie=Qe.useRef(0),X=Qe.useCallback(async()=>{let G=++ie.current;try{m(!0),r(null);let oe={limit:p,offset:g*p};d?oe.status=d:le?oe.excludeStatus=le:C||(oe.excludeStatus=["pending","expired"]),h.trim()&&(oe.customerEmail=h.trim()),E.trim()&&(oe.from=E.trim()),l.trim()&&(oe.to=l.trim()),L&&(oe.unfulfilledOnly=!0);let ce=await s.getOrders(oe);if(G!==ie.current)return;n(ce.orders),o(ce.total)}catch(oe){if(G!==ie.current)return;r(oe instanceof Error?oe:new Error("Failed to fetch orders"))}finally{G===ie.current&&m(!1)}},[s,g,p,d,le,C,L,h,E,l,a]);Qe.useEffect(()=>{X()},[X]);let be=Math.ceil(i/p);return{orders:t,total:i,isLoading:f,error:b,page:g,pageSize:p,hasNextPage:g<be-1,hasPreviousPage:g>0,setPage:y,setPageSize:G=>{c(G),y(0)},status:d,setStatus:G=>{v(G),y(0)},statusIn:K,setStatusIn:G=>{u(G&&G.length>0?G:void 0),y(0)},customerEmail:h,setCustomerEmail:G=>{R(G),y(0)},from:E,setFrom:G=>{M(G),y(0)},to:l,setTo:G=>{x(G),y(0)},showAbandoned:C,setShowAbandoned:G=>{j(G),y(0)},unfulfilledOnly:L,setUnfulfilledOnly:G=>{w(G),y(0)},clearFilters:()=>{v(void 0),u(void 0),j(!1),w(!1),R(""),M(""),x(""),y(0)},refetch:X}}import*as tt from"react";import{ArrowLeft as kl,Check as zr,ChevronLeft as El,ChevronRight as Il,ClipboardCopy as Al,Copy as Dl,Download as Ll,Loader2 as tn,Mail as qr,MoreHorizontal as Ol,Package as Bl,RotateCcw as Fl,Truck as Ml,Undo2 as jr}from"lucide-react";import*as Ur from"react";import*as _a from"@radix-ui/react-popover";import{jsx as Un}from"react/jsx-runtime";var Vr=_a.Root,$r=_a.Trigger;var Vn=Ur.forwardRef(({className:e,align:a="end",sideOffset:s=4,...t},n)=>Un(_a.Portal,{children:Un("div",{className:"aifeatures-admin",children:Un(_a.Content,{ref:n,align:a,sideOffset:s,className:$("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})})}));Vn.displayName=_a.Content.displayName;import{jsx as en}from"react/jsx-runtime";var Tl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Cl(e){return Tl[e]??e}function Hr(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 Qa({status:e,className:a}){return en(Z,{variant:Hr(e),className:a,children:Cl(e)})}function Xa({status:e}){return en(Qa,{status:e})}function is({order:e,className:a}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?en(Z,{variant:"outline",className:a,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?en(Z,{variant:"warning",className:a,children:"Needs shipping"}):null:null}function Ua(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}import{Fragment as Gl,jsx as T,jsxs as W}from"react/jsx-runtime";var Jr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",es="af-text-xs af-text-muted-foreground";function $n(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 Ul(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yr(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 an=24,Vl=["paid","partially_refunded"],$l=["paid","partially_refunded","disputed"],Hl=/^[A-Za-z0-9 _-]*$/,Gr=100;function qn(e,a,s,t,n){let i=Vl.includes(t);return a==="sent"?{label:"Sent",variant:"success",detail:null}:a==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:a==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${an} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${an} 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<an&&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<an&&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 Wr({title:e,recipient:a,status:s,attempts:t,side:n,orderStatus:i,action:o,delivery:f}){if(f)return W("div",{children:[T(wa,{deliveries:[f]}),o&&T("div",{className:"af-mt-2",children:o})]});let m=qn(n,s,t,i,a);return W("div",{children:[W("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[W("div",{className:"af-min-w-0",children:[T("div",{className:"af-text-sm",children:e}),a&&T("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:a})]}),T(Z,{variant:m.variant,className:"af-shrink-0",children:m.label})]}),m.detail&&T("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:m.detail}),o&&T("div",{className:"af-mt-2",children:o})]})}function Kr(e){let a=[];typeof e.name=="string"&&e.name&&a.push(e.name);let s=Ul(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}: ${Yr(n)}`)}function zl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function jn({value:e,label:a,children:s,className:t,size:n="icon"}){let[i,o]=tt.useState(!1);if(!zl())return null;let f=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},m=i?T(zr,{className:"af-h-3 af-w-3"}):T(Dl,{className:"af-h-3 af-w-3"});return n==="icon"?T(S,{variant:"ghost",size:"icon",className:$("af-h-6 af-w-6 af-shrink-0",t),onClick:f,title:a,"aria-label":a,children:m}):W(S,{variant:"outline",size:"sm",className:t,onClick:f,"aria-label":a,children:[i?T(zr,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):T(Al,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Hn({label:e,value:a}){return W("div",{children:[T("div",{className:es,children:e}),W("div",{className:"af-flex af-items-center af-gap-1",children:[T("code",{className:"af-text-xs af-font-mono af-break-all",children:a}),T(jn,{value:a,label:`Copy ${e}`})]})]})}function ql({src:e}){let[a,s]=tt.useState(!1);return!e||a?T("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:T(Bl,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):T("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 ja({title:e,action:a,children:s,className:t}){return W("section",{className:$("af-rounded-lg af-border af-p-4",t),children:[W("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[T("h4",{className:Jr,children:e}),a]}),T("div",{className:"af-mt-3",children:s})]})}function Ga({label:e,emphasis:a,divider:s,children:t}){return W("div",{className:$("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[T("span",{className:a?"af-text-base af-font-semibold":es,children:e}),T("span",{className:$("af-text-right af-tabular-nums",a?"af-text-base af-font-semibold":"af-text-sm"),children:t})]})}function zn({onSelect:e,disabled:a,icon:s,children:t}){return W(S,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:a,children:[T("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),t]})}function jl(e){let a=[];if(a.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&a.push({key:"paid",text:`Payment received \u2014 ${H(ua(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?$s(s):qn("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?$s(s):qn("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 sn({order:e,onBack:a,onRefund:s,onOrderUpdated:t,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:f=!1,hasNextOrder:m=!1}){let{api:b}=ae(),[r,g]=tt.useState(e),[y,p]=tt.useState(null),[c,d]=tt.useState(null),[v,h]=tt.useState(!1),[R,E]=tt.useState(!1),[M,l]=tt.useState(!1),[x,C]=tt.useState(!1),[j,L]=tt.useState(""),[w,K]=tt.useState(!1),[u,z]=tt.useState(null),[le,ie]=tt.useState(!1),[X,be]=tt.useState(""),[G,oe]=tt.useState([]),[ce,q]=tt.useState(!1),[he,ut]=tt.useState(!1),[bt,xe]=tt.useState(null);tt.useEffect(()=>{g(e)},[e]);let ft=D=>{let Ie=D.id===r.id&&D.email_deliveries===void 0?{...D,email_deliveries:r.email_deliveries}:D;g(Ie),t?.(Ie)},Y=Object.entries(r.metadata??{}),ee=ua(r)-r.amount_refunded,ve=(r.status==="paid"||r.status==="partially_refunded")&&ee>0,_=D=>(typeof D.unitAmount=="number"?D.unitAmount:0)*(typeof D.quantity=="number"&&D.quantity>0?D.quantity:1),A=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),fe=G.reduce((D,Ie)=>D+_(r.line_items[Ie]??{}),0)+(ce?A:0),Ce=r.tax_total??0,ke=r.automatic_tax&&r.tax_behavior==="exclusive"&&Ce>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,Ce-(r.tax_refunded??0)),Math.round(Ce*fe/(r.amount_total+(r.shipping_total??0)))):0,Ve=fe+ke,$e=G.length>0||ce,St=$e?Ve:fa(X,r.currency),ta=Ra(r.currency)?"1":"0.01",yt=async()=>{try{h(!0),p(null),d(null),await b.resendOrderReceipt(r.id);let D=await b.getOrder(r.id);ft(D),d("Receipt email queued.")}catch(D){p(D instanceof Error?D.message:"Failed to resend receipt")}finally{h(!1)}},te=async()=>{try{E(!0),p(null),d(null);let D=await b.resetOrderDownloads(r.id);ft(D),l(!1),d("Download count reset.")}catch(D){p(D instanceof Error?D.message:"Failed to reset downloads")}finally{E(!1)}},De=r.line_items.some(D=>D.collectShippingAddress===!0),He=typeof r.merchant_fulfilled_at=="string",aa=$l.includes(r.status),It=j.trim(),Da=Hl.test(It)&&It.length<=Gr,st=async D=>{try{K(!0),z(null),d(null);let Ie=await b.setOrderFulfillment(r.id,{fulfilled:D,...D&&It?{trackingNumber:It}:{}});ft(Ie),L(""),d(D?"Marked as shipped.":"Marked as not shipped.")}catch(Ie){Ie instanceof ya&&Ie.status===409?z(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):z(Ie instanceof Error?Ie.message:"Failed to update the order")}finally{K(!1)}},Ze=()=>{xe(null),be(String(xt(ee,r.currency))),oe([]),q(!1),ie(!0)},k=D=>oe(Ie=>Ie.includes(D)?Ie.filter(Dt=>Dt!==D):[...Ie,D]),Me=async(D,Ie)=>{if(s)try{ut(!0),xe(null),await s(r,D,Ie);let Dt=await b.getOrder(r.id);ft(Dt),ie(!1),d("Refund issued.")}catch(Dt){xe(Dt instanceof Error?Dt.message:"Refund failed")}finally{ut(!1)}},F=async()=>{if($e){if(Ve<=0){xe("The lines you picked were charged nothing");return}if(Ve>ee){xe(`That selection exceeds the refundable remainder (${H(ee,r.currency)})`);return}await Me(Ve,{...G.length>0?{line_items:[...G].sort((Ie,Dt)=>Ie-Dt)}:{},...ce?{shipping:!0}:{}});return}let D=fa(X,r.currency);if(D===null||D<=0){xe("Enter a valid refund amount");return}if(D>ee){xe(`Amount exceeds the refundable remainder (${H(ee,r.currency)})`);return}await Me(D,{amount:D})},At=()=>Me(ee,{full:!0}),gr=r.fulfillment_type==="download",vr=n&&De,ao=jl(r),so=r.shipping_address?Kr(r.shipping_address).join(`
4
+ `):"",br=r.shipping_total!=null,yr=!!r.automatic_tax&&r.tax_behavior==="exclusive"&&(r.tax_total??0)>0,no=!(r.automatic_tax&&r.tax_behavior==="exclusive")&&(r.tax_total??0)>0,hr=br||yr,xs=[];return xs.push(T(zn,{icon:v?T(tn,{className:"af-h-4 af-w-4 af-animate-spin"}):T(qr,{className:"af-h-4 af-w-4"}),disabled:v||r.fulfillment_status!=="fulfilled",onSelect:()=>{C(!1),yt()},children:"Resend receipt"},"resend")),gr&&xs.push(T(zn,{icon:T(Fl,{className:"af-h-4 af-w-4"}),disabled:R,onSelect:()=>{C(!1),l(!0)},children:"Reset download count"},"reset")),ve&&xs.push(W("div",{children:[T(zn,{icon:T(jr,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{C(!1),Ze()},children:"Refund\u2026"}),!s&&T("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),W("div",{children:[W("div",{className:"af-mb-6",children:[W(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[T(kl,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),W("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[W("div",{className:"af-min-w-0",children:[W("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[T("h3",{className:"af-text-xl af-font-semibold",children:Ua(r)}),T(Qa,{status:r.status}),n&&T(is,{order:r}),r.is_test&&T(Z,{variant:"outline",children:"Test"})]}),W("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",$n(r.created_at)]}),r.is_test&&T("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),W("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&W("div",{className:"af-flex af-items-center",children:[T(S,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!f,"aria-label":"Previous order",children:T(El,{className:"af-h-4 af-w-4"})}),T(S,{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:T(Il,{className:"af-h-4 af-w-4"})})]}),vr&&(He?W("div",{className:"af-flex af-items-center af-gap-1",children:[W("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${$n(r.merchant_fulfilled_at)}`:""]}),aa&&W(S,{variant:"ghost",size:"sm",onClick:()=>st(!1),disabled:w,children:[w?T(tn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):T(jr,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):aa?W("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[T(pe,{value:j,onChange:D=>L(D.target.value),placeholder:"Tracking number (optional)",maxLength:Gr,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:w}),W(S,{variant:"default",className:"af-shrink-0",onClick:()=>st(!0),disabled:w||!Da,children:[w?T(tn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):T(Ml,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),xs.length>0&&W(Vr,{open:x,onOpenChange:C,children:[T($r,{asChild:!0,children:T(S,{variant:"outline",size:"icon","aria-label":"More actions",children:T(Ol,{className:"af-h-4 af-w-4"})})}),T(Vn,{children:T("div",{className:"af-space-y-0.5",children:xs})})]})]})]}),vr&&!He&&!Da&&T("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."}),u&&T("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:u}),c&&T("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:c}),y&&T("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:y})]}),W("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[W("div",{className:"af-space-y-6",children:[r.line_items.length>0&&T(ja,{title:"Items",children:T("ul",{className:"af-space-y-3",children:r.line_items.map((D,Ie)=>{let Dt=typeof D.name=="string"&&D.name?D.name:"Item",xr=typeof D.quantity=="number"&&D.quantity>0?D.quantity:1,wr=typeof D.unitAmount=="number";return W("li",{className:"af-flex af-items-start af-gap-3",children:[T(ql,{src:typeof D.imageUrl=="string"&&D.imageUrl?D.imageUrl:void 0}),W("div",{className:"af-min-w-0 af-flex-1",children:[W("div",{className:"af-text-sm af-font-medium",children:[Dt,typeof D.variantTitle=="string"&&D.variantTitle&&W("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",D.variantTitle]})]}),W("div",{className:es,children:[xr," \xD7"," ",wr?H(D.unitAmount,r.currency):"\u2014"]}),D.refunded===!0&&T(Z,{variant:"secondary",className:"af-mt-1",children:D.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),T("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:wr?H(D.unitAmount*xr,r.currency):"\u2014"})]},Ie)})})}),Y.length>0&&T(ja,{title:"Order details",children:T("dl",{className:"af-space-y-2",children:Y.map(([D,Ie])=>W("div",{children:[T("dt",{className:$(es,"af-capitalize"),children:D.replace(/_/g," ")}),T("dd",{className:"af-text-sm af-break-words",children:Yr(Ie)})]},D))})}),T(ja,{title:"Totals",children:W("div",{className:"af-w-full",children:[hr&&T(Ga,{label:"Subtotal",children:H(r.amount_total,r.currency)}),br&&T(Ga,{label:"Shipping",children:r.shipping_total===0?"Free":H(r.shipping_total??0,r.currency)}),yr&&T(Ga,{label:"Tax",children:H(r.tax_total??0,r.currency)}),T(Ga,{label:"Total",emphasis:!0,divider:hr,children:H(ua(r),r.currency)}),no&&T(Ga,{label:"incl. tax",children:H(r.tax_total??0,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&W(Ga,{label:"Your price",children:[H(r.base_amount_total,r.base_currency),W("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&W(Gl,{children:[W(Ga,{label:"Refunded",children:["\u2212",H(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&W("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",H(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),T(Ga,{label:"Net",children:T("span",{className:"af-font-medium",children:H(Math.max(0,ua(r)-r.amount_refunded),r.currency)})})]})]})}),T(ja,{title:"Timeline",children:T("ol",{className:"af-space-y-3",children:ao.map(D=>W("li",{className:"af-flex af-gap-3",children:[T("span",{"aria-hidden":"true",className:$("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",D.tone==="destructive"?"af-bg-destructive":D.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),W("div",{className:"af-min-w-0",children:[T("div",{className:"af-text-sm af-break-words",children:D.text}),D.at&&T("div",{className:"af-text-xs af-text-muted-foreground",children:$n(D.at)})]})]},D.key))})})]}),W("div",{className:"af-space-y-6",children:[T(ja,{title:"Customer",children:W("div",{className:"af-space-y-2",children:[W("div",{children:[T("div",{className:es,children:"Email"}),W("div",{className:"af-flex af-items-center af-gap-1",children:[T("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||T("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&T(jn,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&W("div",{children:[T("div",{className:es,children:"Name"}),T("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&W("div",{children:[T("div",{className:es,children:"Customer record"}),W("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[T("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),T(Z,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&T(ja,{title:"Ship to",action:T(jn,{value:so,label:"Copy address",size:"sm",children:"Copy address"}),children:T("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Kr(r.shipping_address).map((D,Ie)=>T("div",{children:D},Ie))})}),W(ja,{title:"Emails",children:[T(wa,{deliveries:r.email_deliveries?.filter(D=>!["purchase_receipt","merchant_sale"].includes(D.kind)),problemsOnly:!0,className:"af-mb-4"}),W("div",{className:"af-space-y-4",children:[T(Wr,{side:"buyer",title:"Receipt to buyer",delivery:r.email_deliveries?.find(D=>D.kind==="purchase_receipt"),recipient:r.customer_email,status:r.buyer_email_status,attempts:r.buyer_email_attempts,orderStatus:r.status,action:W(S,{variant:"outline",size:"sm",onClick:yt,disabled:v||r.fulfillment_status!=="fulfilled",children:[v?T(tn,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):T(qr,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),T(Wr,{side:"merchant",title:"Sale alert to you",delivery:r.email_deliveries?.find(D=>D.kind==="merchant_sale"),recipient:null,status:r.merchant_email_status,attempts:r.merchant_email_attempts,orderStatus:r.status})]})]}),gr&&T(ja,{title:"Download",children:W("div",{className:"af-space-y-2",children:[W("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[T(Ll,{className:"af-h-4 af-w-4"}),W("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&T("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"})]})}),W("details",{className:"af-rounded-lg af-border af-p-4",children:[T("summary",{className:$(Jr,"af-cursor-pointer af-select-none"),children:"Technical details"}),W("div",{className:"af-mt-3 af-space-y-2",children:[T(Hn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&T(Hn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&T(Hn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),T(Na,{open:M,onOpenChange:D=>{!D&&!R&&l(!1)},children:W(ra,{children:[W(ia,{children:[T(la,{children:"Reset download count?"}),T(ca,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),W(oa,{children:[T(S,{variant:"outline",onClick:()=>l(!1),disabled:R,children:"Cancel"}),T(S,{onClick:te,disabled:R,children:R?"Resetting...":"Reset"})]})]})}),T(Na,{open:le,onOpenChange:D=>{!D&&!he&&ie(!1)},children:W(ra,{children:[W(ia,{children:[T(la,{children:"Refund order"}),W(ca,{children:["Refund up to ",H(ee,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),W("div",{className:"af-space-y-4",children:[(r.line_items.length>0||A>0)&&W("div",{className:"af-space-y-2",children:[T(ge,{children:"Items"}),W("div",{className:"af-space-y-2",children:[r.line_items.map((D,Ie)=>{let Dt=D.refunded===!0;return W("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[T("input",{type:"checkbox",checked:G.includes(Ie),onChange:()=>k(Ie),disabled:he||Dt,className:"af-h-4 af-w-4"}),W("span",{className:Dt?"af-text-muted-foreground af-line-through":void 0,children:[typeof D.name=="string"&&D.name?D.name:"Item",typeof D.variantTitle=="string"&&D.variantTitle?` \u2014 ${D.variantTitle}`:"",typeof D.quantity=="number"&&D.quantity>1?` \xD7 ${D.quantity}`:""]}),T("span",{className:"af-ml-auto af-text-muted-foreground",children:Dt?"Refunded":H(_(D),r.currency)})]},Ie)}),A>0&&W("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[T("input",{type:"checkbox",checked:ce,onChange:D=>q(D.target.checked),disabled:he,className:"af-h-4 af-w-4"}),T("span",{children:"Shipping"}),T("span",{className:"af-ml-auto af-text-muted-foreground",children:H(A,r.currency)})]})]})]}),W("div",{className:"af-space-y-2",children:[W(ge,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),T(pe,{id:"refund-amount",type:"number",min:"0",step:ta,value:$e?String(xt(Ve,r.currency)):X,onChange:D=>be(D.target.value),disabled:he||$e}),$e&&T("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),bt&&T("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:bt}),W(oa,{children:[T(S,{variant:"outline",onClick:()=>ie(!1),disabled:he,children:"Cancel"}),T(S,{variant:"outline",onClick:At,disabled:he,children:"Refund everything"}),T(S,{variant:"destructive",onClick:F,disabled:he,children:he?"Refunding...":St!==null&&St>0?`Refund ${H(St,r.currency)}`:"Refund"})]})]})})]})}import*as nn from"react";import{ArrowLeft as Wl,RefreshCw as Kl}from"lucide-react";import{jsx as Pa,jsxs as ts}from"react/jsx-runtime";function wt({title:e,onBackToWebsite:a,hideBackButton:s=!1,children:t,className:n}){let i=nn.useRef(null);return nn.useEffect(()=>{i.current?.focus()},[]),ts("div",{className:$("af-bg-background",n),children:[ts("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:[Pa("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),a&&!s&&ts(S,{type:"button",variant:"outline",size:"sm",onClick:a,children:[Pa(Wl,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),Pa("div",{className:"af-p-4",children:t})]})}function Q({className:e}){return Pa("div",{"aria-hidden":"true",className:$("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Ke({label:e,children:a,detail:s,valueClassName:t}){return ts("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[Pa("div",{className:"af-text-xs af-text-muted-foreground",children:e}),Pa("div",{className:$("af-mt-1 af-text-lg af-font-semibold",t),children:a}),s&&Pa("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function jt({message:e,onRetry:a}){return ts("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[Pa("span",{children:e}),ts(S,{type:"button",variant:"ghost",size:"sm",onClick:a,children:[Pa(Kl,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ta({icon:e,children:a}){return ts("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,Pa("p",{className:"af-text-muted-foreground af-text-center",children:a})]})}import{Fragment as tc,jsx as I,jsxs as ye}from"react/jsx-runtime";var ec={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Qr={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Xr(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 ei(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 rn(e){return e.customer?.name||e.customer_name||null}function os({onRefund:e,className:a,refreshKey:s,initialOrderId:t,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:f}=ae(),m=Xs({refreshKey:s}),{orders:b,total:r,isLoading:g,error:y,page:p,pageSize:c,hasNextPage:d,hasPreviousPage:v,setPage:h,setPageSize:R,customerEmail:E,setCustomerEmail:M,setStatusIn:l,from:x,setFrom:C,to:j,setTo:L,showAbandoned:w,setShowAbandoned:K,setUnfulfilledOnly:u,refetch:z}=m,[le,ie]=pt.useState("list"),[X,be]=pt.useState(null),[G,oe]=pt.useState(""),[ce,q]=pt.useState(""),[he,ut]=pt.useState(n?"needs_shipping":"all"),[bt,xe]=pt.useState(!1),[ft,Y]=pt.useState(!!t),[ee,ve]=pt.useState(null);pt.useEffect(()=>{if(!t)return;let F=!1;return Y(!0),ve(null),f.getOrder(t).then(At=>{F||(be(At),ie("detail"))}).catch(()=>{F||ve("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{F||Y(!1)}),()=>{F=!0}},[f,t]);let _=pt.useCallback(F=>{ut(F);let At=Qr[F];l(At.statusIn),u(At.unfulfilledOnly)},[l,u]);pt.useEffect(()=>{n&&u(!0)},[]);let A=pt.useRef(!n);pt.useEffect(()=>{A.current||g||(A.current=!0,b.length===0&&_("all"))},[g,b.length,_]);let fe=le==="detail"&&!!X;pt.useEffect(()=>{o?.(fe)},[fe,o]);let Ce=(x?1:0)+(j?1:0)+(w?1:0),ke=Ce>0||!!E||!!ce,Ve=!!x&&!!j&&x>j,$e=F=>{be(F),ie("detail")},St=()=>{ie("list"),be(null),z()},ta=F=>{let At=F.trim();if(!At){q(""),E&&M("");return}if(At.startsWith("#")||/^\d+$/.test(At)){q(At),E&&M("");return}q(""),M(At)},yt=()=>{oe(""),q(""),M(""),C(""),L(""),K(!1),xe(!1)},te=ce.replace(/^#/,"").toLowerCase(),De=te?b.filter(F=>String(F.order_number??"")===te||F.id.toLowerCase().startsWith(te)):b,He=X?b.findIndex(F=>F.id===X.id):-1,aa=He>0,It=He>=0&&He<b.length-1;if(ft)return I("div",{className:a,children:I("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:I(Yl,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(le==="detail"&&X)return I("div",{className:a,children:I(sn,{order:X,onBack:St,onRefund:e,onOrderUpdated:F=>be(F),allowFulfillment:n,onPrevOrder:aa?()=>be(b[He-1]):void 0,onNextOrder:It?()=>be(b[He+1]):void 0,hasPrevOrder:aa,hasNextOrder:It},X.id)});let st=ye("div",{className:"af-mb-4 af-space-y-3",children:[ee&&I("p",{className:"af-text-xs af-text-muted-foreground",children:ee}),ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[I("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(F=>I("button",{type:"button","aria-pressed":he===F,onClick:()=>_(F),className:$("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",he===F?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:ec[F]},F))}),ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[I(Ql,{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"}),I(pe,{type:"text",value:G,onChange:F=>oe(F.target.value),onBlur:()=>ta(G),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),ta(G))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),ye(S,{type:"button",variant:Ce>0?"secondary":"ghost",size:"sm",onClick:()=>xe(F=>!F),"aria-expanded":bt,children:[I(Xl,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ce>0&&I(Z,{variant:"secondary",className:"af-ml-2",children:Ce})]}),ke&&I(S,{type:"button",variant:"ghost",size:"sm",onClick:yt,children:"Clear filters"})]}),(bt||!!x||!!j)&&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:[I(ge,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),I(pe,{id:"orders-from",type:"date",value:x,max:j||void 0,onChange:F=>C(F.target.value),className:"af-w-[170px]"}),I(ge,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),I(pe,{id:"orders-to",type:"date",value:j,min:x||void 0,onChange:F=>L(F.target.value),className:"af-w-[170px]"}),!Qr[he].statusIn&&I(S,{type:"button",variant:w?"secondary":"ghost",size:"sm",onClick:()=>K(!w),"aria-pressed":w,children:w?"Hide abandoned":"Show abandoned"})]}),Ve&&I("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(g)return ye("div",{className:a,children:[st,I("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(F=>ye("div",{className:"af-rounded-md af-border af-p-3",children:[ye("div",{className:"af-flex af-items-center af-justify-between",children:[I(Q,{className:"af-h-4 af-w-16"}),I(Q,{className:"af-h-4 af-w-14"})]}),I(Q,{className:"af-mt-2 af-h-3 af-w-40"}),I(Q,{className:"af-mt-2 af-h-3 af-w-24"})]},F))}),I("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Le,{children:[I(Oe,{children:ye(me,{children:[I(O,{children:"Order"}),I(O,{children:"Date"}),I(O,{children:"Customer"}),I(O,{children:"Items"}),I(O,{className:"af-text-right",children:"Total"}),I(O,{children:"Status"}),I(O,{className:"af-w-8"})]})}),I(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(F=>ye(me,{children:[I(B,{children:I(Q,{className:"af-h-4 af-w-14"})}),I(B,{children:I(Q,{className:"af-h-4 af-w-24"})}),I(B,{children:I(Q,{className:"af-h-4 af-w-40"})}),I(B,{children:I(Q,{className:"af-h-4 af-w-32"})}),I(B,{children:I(Q,{className:"af-ml-auto af-h-4 af-w-16"})}),I(B,{children:I(Q,{className:"af-h-5 af-w-16"})}),I(B,{})]},F))})]})}),I("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(y)return ye("div",{className:a,children:[st,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[I("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),I(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>z(),children:"Try again"})]})]});let Ze=he!=="all";if(De.length===0&&p===0)return ye("div",{className:a,children:[(ke||Ze)&&st,ye("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[I(Zl,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),I("p",{className:"af-text-muted-foreground af-text-center",children:ke||Ze?"No orders match these filters.":i??ye(tc,{children:["No orders yet.",I("br",{}),"Orders will appear here when someone buys from your website."]})}),!ke&&!Ze&&I(S,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>K(!0),children:"Show abandoned checkouts"})]})]});let k=p*c+1,Me=Math.min((p+1)*c,r);return ye("div",{className:a,children:[st,I("div",{className:"af-space-y-3 lg:af-hidden",children:De.map(F=>ye("button",{type:"button",onClick:()=>$e(F),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:[I("span",{className:"af-font-medium",children:Ua(F)}),I("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:H(ua(F),F.currency)})]}),ye("div",{className:"af-mt-1 af-min-w-0",children:[ye("div",{className:"af-truncate af-text-sm",children:[F.customer_email||I("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),rn(F)&&ye("span",{className:"af-text-muted-foreground",children:[" \xB7 ",rn(F)]})]}),I("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ei(F)}),F.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(F.amount_refunded,F.currency)," refunded"]})]}),ye("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[I(Qa,{status:F.status}),I(Ss,{deliveries:F.email_deliveries}),F.is_test&&I(Z,{variant:"outline",children:"Test"}),n&&I(is,{order:F}),I("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Xr(F.created_at)})]})]},F.id))}),I("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:ye(Le,{children:[I(Oe,{children:ye(me,{children:[I(O,{children:"Order"}),I(O,{children:"Date"}),I(O,{children:"Customer"}),I(O,{children:"Items"}),I(O,{className:"af-text-right",children:"Total"}),I(O,{children:"Status"}),I(O,{className:"af-w-8"})]})}),I(Be,{children:De.map(F=>ye(me,{onClick:()=>$e(F),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[ye(B,{className:"af-whitespace-nowrap af-font-medium",children:[I("button",{type:"button",onClick:At=>{At.stopPropagation(),$e(F)},"aria-label":`Open order ${Ua(F)}`,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:Ua(F)}),F.is_test&&I(Z,{variant:"outline",className:"af-ml-2",children:"Test"})]}),I(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Xr(F.created_at)}),ye(B,{className:"af-max-w-[220px]",children:[I("div",{className:"af-truncate",children:F.customer_email||I("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),rn(F)&&I("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:rn(F)})]}),I(B,{className:"af-max-w-[220px]",children:I("div",{className:"af-truncate af-text-muted-foreground",children:ei(F)})}),ye(B,{className:"af-whitespace-nowrap af-text-right",children:[I("div",{className:"af-font-medium af-tabular-nums",children:H(ua(F),F.currency)}),F.amount_refunded>0&&ye("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(F.amount_refunded,F.currency)," ","refunded"]})]}),I(B,{children:ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[I(Qa,{status:F.status}),I(Ss,{deliveries:F.email_deliveries}),n&&I(is,{order:F})]})}),I(B,{className:"af-w-8 af-text-right",children:I(Zr,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},F.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:[I("span",{children:te?`${De.length} matching this page`:`Showing ${k}-${Me} of ${r}`}),ye(Kt,{value:String(c),onValueChange:F=>R(Number(F)),children:[I($t,{className:"af-w-[70px] af-h-8",children:I(Jt,{})}),ye(Ht,{children:[I(Ue,{value:"10",children:"10"}),I(Ue,{value:"25",children:"25"}),I(Ue,{value:"50",children:"50"}),I(Ue,{value:"100",children:"100"})]})]}),I("span",{children:"per page"})]}),ye("div",{className:"af-flex af-items-center af-gap-2",children:[ye(S,{variant:"outline",size:"sm",onClick:()=>h(p-1),disabled:!v,children:[I(Jl,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),ye(S,{variant:"outline",size:"sm",onClick:()=>h(p+1),disabled:!d,children:["Next",I(Zr,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as cn from"react";import{ChevronLeft as rc,ChevronRight as ic,Eye as oc,Search as lc,Users as cc}from"lucide-react";import*as Lt from"react";function on({initialPageSize:e=25}={}){let{api:a}=ae(),[s,t]=Lt.useState([]),[n,i]=Lt.useState(0),[o,f]=Lt.useState(!0),[m,b]=Lt.useState(null),[r,g]=Lt.useState(0),[y,p]=Lt.useState(e),[c,d]=Lt.useState(""),v=Lt.useRef(0),h=Lt.useCallback(async()=>{let E=++v.current;try{f(!0),b(null);let M={limit:y,offset:r*y};c.trim()&&(M.email=c.trim());let l=await a.getCustomers(M);if(E!==v.current)return;t(l.customers),i(l.total)}catch(M){if(E!==v.current)return;b(M instanceof Error?M:new Error("Failed to fetch customers"))}finally{E===v.current&&f(!1)}},[a,r,y,c]);Lt.useEffect(()=>{h()},[h]);let R=Math.ceil(n/y);return{customers:s,total:n,isLoading:o,error:m,page:r,pageSize:y,hasNextPage:r<R-1,hasPreviousPage:r>0,setPage:g,setPageSize:E=>{p(E),g(0)},email:c,setEmail:E=>{d(E),g(0)},refetch:h}}import*as as from"react";import{ArrowLeft as ac,Loader2 as sc}from"lucide-react";import{jsx as Ee,jsxs as Nt}from"react/jsx-runtime";function ti(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 ln({customer:e,onBack:a,className:s}){let{api:t}=ae(),[n,i]=as.useState(null),[o,f]=as.useState([]),[m,b]=as.useState(!0),[r,g]=as.useState(null);as.useEffect(()=>{let c=!1;return b(!0),g(null),Promise.all([t.getCustomer(e.id),t.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([d,v])=>{c||(i(d),f(v.orders))}).catch(d=>{c||g(d instanceof Error?d.message:"Failed to load customer")}).finally(()=>{c||b(!1)}),()=>{c=!0}},[t,e.id,e.email]);let y=n?.addresses??[],p=n?.order_count??o.length;return Nt("div",{className:s,children:[Nt("div",{className:"af-mb-6",children:[Nt(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[Ee(ac,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),Ee("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),Nt("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",ti(e.created_at)]})]}),m?Ee("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Ee(sc,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?Ee("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):Nt("div",{className:"af-space-y-6",children:[Ee(wa,{deliveries:n?.email_deliveries}),Nt("div",{children:[Ee("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),Nt("div",{className:"af-space-y-1 af-text-sm",children:[Nt("div",{className:"af-flex af-gap-2",children:[Ee("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),Ee("span",{children:e.email})]}),e.name&&Nt("div",{className:"af-flex af-gap-2",children:[Ee("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),Ee("span",{children:e.name})]}),e.phone&&Nt("div",{className:"af-flex af-gap-2",children:[Ee("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),Ee("span",{children:e.phone})]}),Nt("div",{className:"af-flex af-gap-2",children:[Ee("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),Ee("span",{children:p})]})]})]}),y.length>0&&Nt("div",{children:[Ee("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),Ee("div",{className:"af-flex af-flex-wrap af-gap-3",children:y.map(c=>Nt("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&Ee(Z,{variant:"secondary",className:"af-mb-1",children:"Default"}),nc(c).map((d,v)=>Ee("div",{children:d},v))]},c.id))})]}),Nt("div",{children:[Ee("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?Ee("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):Nt(Le,{children:[Ee(Oe,{children:Nt(me,{children:[Ee(O,{children:"Date"}),Ee(O,{children:"Amount"}),Ee(O,{children:"Status"})]})}),Ee(Be,{children:o.map(c=>Nt(me,{children:[Ee(B,{className:"af-text-muted-foreground",children:ti(c.created_at)}),Ee(B,{children:H(ua(c),c.currency)}),Ee(B,{children:Ee(Xa,{status:c.status})})]},c.id))})]})]})]})]})}import{Fragment as uc,jsx as Re,jsxs as it}from"react/jsx-runtime";function dc(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function dn({className:e}){let{customers:a,total:s,isLoading:t,error:n,page:i,pageSize:o,hasNextPage:f,hasPreviousPage:m,setPage:b,setPageSize:r,email:g,setEmail:y,refetch:p}=on(),[c,d]=cn.useState("list"),[v,h]=cn.useState(null),[R,E]=cn.useState(""),M=L=>{h(L),d("detail")},l=()=>{d("list"),h(null),p()};if(c==="detail"&&v)return Re("div",{className:e,children:Re(ln,{customer:v,onBack:l})});let x=it("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[Re(pe,{type:"email",value:R,onChange:L=>E(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),y(R.trim()))}}),it(S,{type:"button",variant:"outline",size:"sm",onClick:()=>y(R.trim()),children:[Re(lc,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),g&&Re(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>{E(""),y("")},children:"Clear"})]});if(t)return it("div",{className:e,children:[x,Re("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:Re("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return it("div",{className:e,children:[x,Re("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:it("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(a.length===0&&i===0)return it("div",{className:e,children:[g&&x,it("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[Re(cc,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),Re("p",{className:"af-text-muted-foreground af-text-center",children:g?"No customers match that email.":it(uc,{children:["No customers yet.",Re("br",{}),"Customers appear here after their first purchase."]})})]})]});let C=i*o+1,j=Math.min((i+1)*o,s);return it("div",{className:e,children:[x,it(Le,{children:[Re(Oe,{children:it(me,{children:[Re(O,{children:"Email"}),Re(O,{children:"Name"}),Re(O,{children:"Customer since"}),Re(O,{className:"af-text-right",children:"Actions"})]})}),Re(Be,{children:a.map(L=>it(me,{children:[Re(B,{className:"af-font-medium",children:L.email}),Re(B,{children:L.name||Re("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),Re(B,{className:"af-text-muted-foreground",children:dc(L.created_at)}),Re(B,{className:"af-text-right",children:Re(S,{variant:"ghost",size:"icon",onClick:()=>M(L),title:"View customer",children:Re(oc,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),it("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[it("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[it("span",{children:["Showing ",C,"-",j," of ",s]}),it(Kt,{value:String(o),onValueChange:L=>r(Number(L)),children:[Re($t,{className:"af-w-[70px] af-h-8",children:Re(Jt,{})}),it(Ht,{children:[Re(Ue,{value:"10",children:"10"}),Re(Ue,{value:"25",children:"25"}),Re(Ue,{value:"50",children:"50"}),Re(Ue,{value:"100",children:"100"})]})]}),Re("span",{children:"per page"})]}),it("div",{className:"af-flex af-items-center af-gap-2",children:[it(S,{variant:"outline",size:"sm",onClick:()=>b(i-1),disabled:!m,children:[Re(rc,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),it(S,{variant:"outline",size:"sm",onClick:()=>b(i+1),disabled:!f,children:["Next",Re(ic,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}import*as Ne from"react";import{ArrowLeft as fc,ChevronLeft as mc,ChevronRight as ai,Copy as pc,Download as gc,ExternalLink as vc,FileText as ri,Loader2 as bc,Search as yc}from"lucide-react";import*as ot from"react";function ls({initialPageSize:e=25,refreshKey:a,includeAggregates:s=!1}={}){let{api:t}=ae(),[n,i]=ot.useState([]),[o,f]=ot.useState(0),[m,b]=ot.useState(null),[r,g]=ot.useState(!0),[y,p]=ot.useState(null),[c,d]=ot.useState(0),[v,h]=ot.useState(e),[R,E]=ot.useState(void 0),[M,l]=ot.useState(""),[x,C]=ot.useState(""),[j,L]=ot.useState(""),[w,K]=ot.useState(""),[u,z]=ot.useState(""),le=R?R.join(","):"",ie=ot.useRef(0),X=ot.useCallback(async()=>{let G=++ie.current;g(!0),p(null);try{let oe={labels:le?le.split(","):void 0,customerEmail:M||void 0,q:x||void 0,from:j||void 0,to:w||void 0,retainerId:u||void 0,includeAggregates:s,limit:v,offset:c*v},ce=await t.getInvoices(oe);if(G!==ie.current)return;if(c>0&&c*v>=ce.total){d(Math.max(0,Math.ceil(ce.total/v)-1));return}i(ce.invoices),f(ce.total),s&&b(ce.aggregates??null)}catch(oe){if(G!==ie.current)return;p(oe instanceof Error?oe:new Error("Failed to fetch invoices"))}finally{G===ie.current&&g(!1)}},[t,le,M,x,j,w,u,c,v,s]);ot.useEffect(()=>{X()},[X,a]);let be=G=>oe=>{d(0),G(oe)};return{invoices:n,total:o,aggregates:m,isLoading:r,error:y,page:c,pageSize:v,hasNextPage:(c+1)*v<o,hasPreviousPage:c>0,setPage:d,setPageSize:be(h),labels:R,setLabels:be(E),customerEmail:M,setCustomerEmail:be(l),q:x,setQ:be(C),from:j,setFrom:be(L),to:w,setTo:be(K),retainerId:u,setRetainerId:be(z),clearFilters:()=>{d(0),E(void 0),l(""),C(""),L(""),K(""),z("")},refetch:X}}import{Fragment as _c,jsx as P,jsxs as V}from"react/jsx-runtime";var hc={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 Yn(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:hc[e.label]??e.label}function xc(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 Jn={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},wc={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ts({invoice:e,className:a}){return V("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[P(Z,{variant:xc(e.label),className:a,children:Yn(e)}),e.collection_method==="charge_automatically"&&P(Z,{variant:"secondary",children:"Managed in Stripe"})]})}function fn({delivery:e,className:a}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return P(Z,{variant:s,className:a,children:Jn[e.state]??e.state})}function cs(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ea(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 si={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Gn={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 Nc(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 Wn=100,Kn=5e3;async function Sc(e,a){let s=[],t=0;for(let n=0;n<Kn;n+=Wn){let i=await e.getInvoices({...a,limit:Wn,offset:n});if(t=i.total,s.push(...i.invoices),i.invoices.length<Wn||s.length>=t)break}return{invoices:s.slice(0,Kn),total:t,truncated:t>s.length||t>Kn}}function ii(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,cs(t),Yn(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(Nc).join(",")).join(`
5
+ `)}function Rc(e){if(typeof document>"u")return;let a=new Blob([ii(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 ds({className:e,refreshKey:a,initialInvoiceId:s,onDetailOpenChange:t,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:f=null,onClearRetainerFilter:m}){let{api:b}=ae(),{invoices:r,total:g,isLoading:y,error:p,page:c,pageSize:d,hasNextPage:v,hasPreviousPage:h,setPage:R,labels:E,setLabels:M,customerEmail:l,setCustomerEmail:x,q:C,setQ:j,from:L,setFrom:w,to:K,setTo:u,retainerId:z,setRetainerId:le,refetch:ie}=ls({refreshKey:a}),[X,be]=Ne.useState("open"),[G,oe]=Ne.useState(""),[ce,q]=Ne.useState(null),he=Ne.useRef(0),ut=Ne.useCallback(k=>{he.current++,xe(!1),q(k)},[]),[bt,xe]=Ne.useState(!1),[ft,Y]=Ne.useState(0),[ee,ve]=Ne.useState(null),[_,A]=Ne.useState(!1),[fe,Ce]=Ne.useState(0);Ne.useEffect(()=>{q(k=>{if(!k)return k;let Me=r.find(F=>F.id===k.id);return Me&&Me!==k?Me:k})},[r]);let[ke,Ve]=Ne.useState(!1),[$e,St]=Ne.useState(null),ta=async()=>{if(!ke){Ve(!0),St(null);try{let{invoices:k,total:Me,truncated:F}=await Sc(b,{labels:E,customerEmail:l,q:C,from:L,to:K,retainerId:z});Rc(k),St(F?`Exported the first ${k.length.toLocaleString()} of ${Me.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{St("Couldn't export \u2014 try again.")}finally{Ve(!1)}}},yt=!l&&!C&&!L&&!K&&!z,[te,De]=Ne.useState(null);Ne.useEffect(()=>{if(y||g>0||!yt||X!=="open")return;let k=!1;return b.getInvoices({limit:1}).then(Me=>{k||De(Me.total>0)}).catch(()=>{k||De(!0)}),()=>{k=!0}},[b,y,g,yt,X,a]),Ne.useEffect(()=>{M(Gn.open)},[]),Ne.useEffect(()=>{let k=f?.id??"";k!==z&&(le(k),k&&(be("all"),M(Gn.all),x(""),j(""),oe(""),w(""),u("")))},[f?.id]),Ne.useEffect(()=>{let k=!1;return A(!1),b.getInvoiceSettings().then(Me=>{k||ve({payments_active:Me.payments_active,blocked:Me.blocked})}).catch(()=>{k||A(!0)}),()=>{k=!0}},[b,a,fe]),Ne.useEffect(()=>{if(!s)return;let k=!1,Me=he.current;return xe(!1),b.getInvoice(s).then(F=>{!k&&Me===he.current&&q(F)}).catch(()=>{!k&&Me===he.current&&xe(!0)}),()=>{k=!0}},[b,s,ft]),Ne.useEffect(()=>{t?.(ce!==null)},[ce,t]);let He=k=>{be(k),M(Gn[k])},aa=k=>{let Me=k.trim();if(!Me){C&&j(""),l&&x("");return}if(Me.includes("@")){C&&j(""),x(Me);return}l&&x(""),j(Me.replace(/^#/,""))},It=r,Da=bt&&V("div",{role:"alert",className:"af-mb-3 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't open the requested invoice. ",P(S,{type:"button",variant:"link",size:"sm",onClick:()=>Y(k=>k+1),children:"Retry opening invoice"})]});if(ce)return V("div",{className:e,children:[Da,P(Zn,{invoice:ce,refreshKey:a,onBack:()=>{ut(null),ie()}},ce.id)]});let st=V("div",{className:"af-mb-4 af-space-y-3",children:[_&&V("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",P(S,{type:"button",variant:"link",size:"sm",onClick:()=>Ce(k=>k+1),children:"Retry setup check"})]}),Da,ee?.blocked&&V("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",ee.blocked.reason?`: ${ee.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),f&&V("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[V(Z,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",f.label]}),m&&P(S,{type:"button",variant:"link",size:"sm",onClick:m,children:"Clear schedule filter"})]}),V("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[P("div",{role:"group","aria-label":"Invoice views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Object.keys(si).map(k=>P("button",{type:"button","aria-pressed":X===k,onClick:()=>He(k),className:$("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",X===k?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:si[k]},k))}),V("div",{className:"af-relative af-w-full af-max-w-xs",children:[P(yc,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),P(pe,{type:"text",value:G,onChange:k=>oe(k.target.value),onBlur:()=>aa(G),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),aa(G))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),V("div",{className:"af-flex af-items-center af-gap-2",children:[P(ge,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),P(pe,{id:"invoices-from",type:"date",value:L,max:K||void 0,onChange:k=>w(k.target.value),className:"af-invoice-date af-w-[150px]"})]}),V("div",{className:"af-flex af-items-center af-gap-2",children:[P(ge,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),P(pe,{id:"invoices-to",type:"date",value:K,min:L||void 0,onChange:k=>u(k.target.value),className:"af-invoice-date af-w-[150px]"})]}),V(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ta(),disabled:ke||y||!!p||g===0,"aria-busy":ke,children:[P(gc,{className:"af-h-4 af-w-4 af-mr-1"}),ke?"Exporting\u2026":"Export CSV (all matching)"]})]}),$e&&P("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:$e})]});return y?V("div",{className:e,children:[st,P("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(k=>V("div",{className:"af-rounded-md af-border af-p-3",children:[V("div",{className:"af-flex af-items-center af-justify-between",children:[P(Q,{className:"af-h-4 af-w-20"}),P(Q,{className:"af-h-4 af-w-16"})]}),P(Q,{className:"af-mt-2 af-h-3 af-w-40"})]},k))})]}):p?V("div",{className:e,children:[st,V("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",P(S,{type:"button",variant:"link",size:"sm",onClick:()=>void ie(),children:"Retry"})]})]}):g===0&&yt&&te===!1&&X==="open"?ee?.blocked?V("div",{className:e,children:[st,P(un,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?V("div",{className:e,children:[st,P(un,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):ee&&!ee.payments_active?V("div",{className:e,children:[st,P(un,{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})]}):V("div",{className:e,children:[st,P(un,{heading:"No invoices yet",body:!ee||_?"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."})]}):V("div",{className:e,children:[st,It.length===0?P("div",{className:"af-rounded-md af-border af-px-3 af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:"No invoices match."}):V(_c,{children:[P("div",{className:"af-space-y-3 lg:af-hidden",children:It.map(k=>V("button",{type:"button",onClick:()=>ut(k),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[V("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[P("span",{className:"af-font-medium",children:cs(k)}),P(Ts,{invoice:k})]}),P("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:k.customer_name??k.customer_email??"\u2014"}),k.delivery&&P("div",{className:"af-mt-1",children:P(fn,{delivery:k.delivery})}),V("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[P("span",{children:k.collection_method==="charge_automatically"?"Automatic collection":k.due_at?`Due ${ea(k.due_at)}`:"Due on receipt"}),P("span",{className:"af-font-medium af-tabular-nums",children:H(k.amount_due??k.amount_total,k.currency)})]})]},k.id))}),P("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:V(Le,{children:[P(Oe,{children:V(me,{children:[P(O,{children:"Invoice"}),P(O,{children:"Created"}),P(O,{children:"Customer"}),P(O,{children:"Due"}),P(O,{className:"af-text-right",children:"Amount"}),P(O,{children:"Status"}),P(O,{children:"Delivery"}),P(O,{className:"af-w-8"})]})}),P(Be,{children:It.map(k=>V(me,{className:"af-cursor-pointer",onClick:()=>ut(k),children:[P(B,{className:"af-font-medium",children:P("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:Me=>{Me.stopPropagation(),ut(k)},"aria-label":`Open invoice ${cs(k)}`,children:cs(k)})}),P(B,{children:ea(k.created_at)}),V(B,{children:[P("div",{children:k.customer_name??"\u2014"}),P("div",{className:"af-text-xs af-text-muted-foreground",children:k.customer_email})]}),P(B,{children:k.collection_method==="charge_automatically"?"Automatic":k.due_at?ea(k.due_at):"On receipt"}),P(B,{className:"af-text-right af-tabular-nums",children:H(k.amount_due??k.amount_total,k.currency)}),P(B,{children:P(Ts,{invoice:k})}),P(B,{children:P(fn,{delivery:k.delivery})}),P(B,{children:P(ai,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},k.id))})]})}),V("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[V("span",{children:[g," invoice",g===1?"":"s"]}),V("div",{className:"af-flex af-items-center af-gap-1",children:[P(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(c-1),disabled:!h,"aria-label":"Previous page",children:P(mc,{className:"af-h-4 af-w-4"})}),V("span",{className:"af-tabular-nums",children:[c*d+1,"\u2013",Math.min((c+1)*d,g)]}),P(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(c+1),disabled:!v,"aria-label":"Next page",children:P(ai,{className:"af-h-4 af-w-4"})})]})]})]})]})}function un({heading:e,body:a,action:s}){return V("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[P(ri,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),P("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),P("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:a}),s&&P(S,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var Va="af-text-xs af-text-muted-foreground";function ni(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Zn({invoice:e,onBack:a,refreshKey:s,className:t}){let{api:n}=ae(),i=Ne.useRef(null);Ne.useEffect(()=>{i.current?.focus()},[e.id]);let[o,f]=Ne.useState(!1),[m,b]=Ne.useState(null),[r,g]=Ne.useState(!1),[y,p]=Ne.useState(!1),c=Ne.useRef(0),[d,v]=Ne.useState(null),[h,R]=Ne.useState(!1),[E,M]=Ne.useState(0);Ne.useEffect(()=>{let u=!1;return R(!1),n.getInvoice(e.id).then(z=>{u||v({source:e,value:z})}).catch(()=>{u||R(!0)}),()=>{u=!0}},[n,e,s,E]);let l=d?.source===e?d.value:e,x=l.collection_method==="charge_automatically";Ne.useEffect(()=>(c.current++,b(null),g(!1),p(!1),f(!1),()=>{c.current++}),[n,l,s]);let C=u=>u==null?"\u2014":H(u,l.currency),j=async()=>{if(!(!l.pay_url||!ni()))try{await navigator.clipboard.writeText(l.pay_url),f(!0),setTimeout(()=>f(!1),1500)}catch{}},L=async()=>{if(m){b(null);return}let u=++c.current;p(!1),g(!0);try{let z=await n.getInvoicePreview(l.id);u===c.current&&b(z)}catch{u===c.current&&p(!0)}finally{u===c.current&&g(!1)}},w=l.bill_to,K=w?[w.company,w.name,w.address?.line1,w.address?.line2,[w.address?.city,w.address?.state,w.address?.postal_code].filter(Boolean).join(", "),w.address?.country,w.tax_id?`${w.tax_id.value}`:null,w.po_number?`PO ${w.po_number}`:null,w.service_period?`Service period: ${w.service_period}`:null].filter(u=>!!u&&u.length>0):[];return V("div",{className:t,children:[V("div",{className:"af-mb-4",children:[V(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[P(fc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),V("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[V("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",cs(l)]}),P(Ts,{invoice:l}),P(fn,{delivery:l.delivery})]}),V("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[l.customer_name??l.customer_email,l.customer_name&&l.customer_email?` \xB7 ${l.customer_email}`:""]})]}),h&&V("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't refresh this invoice. These details may be out of date. ",P(S,{type:"button",variant:"link",size:"sm",onClick:()=>M(u=>u+1),children:"Retry details"})]}),l.label==="failed"&&P("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),l.label==="creating"&&P("p",{role:"status",className:"af-mb-4 af-text-sm af-text-muted-foreground",children:"This invoice is still being created. Its final details will appear when it is ready."}),V("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[V("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[V("section",{className:"af-rounded-md af-border af-p-4",children:[V(Le,{children:[P(Oe,{children:V(me,{children:[P(O,{children:"Description"}),P(O,{className:"af-text-right",children:"Qty"}),P(O,{className:"af-text-right",children:"Amount"})]})}),P(Be,{children:l.line_items.map((u,z)=>V(me,{children:[P(B,{style:{overflowWrap:"anywhere"},children:u.description}),P(B,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:u.quantity}),P(B,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:C(u.amount)})]},z))})]}),V("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[P(Wa,{label:"Subtotal",value:C(l.amount_subtotal)}),(l.discount_total??0)>0&&P(Wa,{label:"Discount",value:`-${C(l.discount_total)}`}),l.tax_total>0&&P(Wa,{label:l.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:C(l.tax_total)}),P(Wa,{label:"Total",value:C(l.amount_total),strong:!0}),l.credit_applied>0&&P(Wa,{label:"Credit applied",value:`-${C(l.credit_applied)}`}),l.amount_due!==null&&l.amount_due!==l.amount_total&&P(Wa,{label:"Amount due",value:C(l.amount_due),strong:!0}),l.amount_paid!==null&&l.amount_paid>0&&P(Wa,{label:"Amount paid",value:C(l.amount_paid)}),l.amount_refunded>0&&P(Wa,{label:"Refunded",value:C(l.amount_refunded)})]}),l.credit_notes?.length>0&&V("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[P("div",{className:Va,children:"Credit notes"}),l.credit_notes.map(u=>V("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[V("span",{className:"af-text-muted-foreground",children:[ea(u.created_at)," \xB7 ",u.origin==="dashboard"?"issued in Stripe":"refund",u.stripe_credit_note_id?"":" \xB7 being created"]}),V("span",{className:"af-tabular-nums",children:["-",H(u.amount,u.currency)]})]},u.id))]})]}),(l.note||l.footer)&&V("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[l.note&&V("div",{children:[P("div",{className:Va,children:"Note"}),P("div",{className:"af-whitespace-pre-wrap af-break-words",children:l.note})]}),l.footer&&V("div",{children:[P("div",{className:Va,children:"Footer"}),P("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:l.footer})]})]}),m&&!x&&V("section",{className:"af-rounded-md af-border af-p-4",children:[V("div",{className:$(Va,"af-break-words"),children:["Email preview \u2014 ",m.subject]}),P("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),P("iframe",{title:"Invoice email preview",srcDoc:m.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),V("div",{className:"af-min-w-0 af-space-y-4",children:[V("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[P(Xt,{label:"Created",value:ea(l.created_at)}),P(Xt,{label:"Due",value:l.collection_method==="charge_automatically"?"Managed in Stripe":l.due_at?ea(l.due_at):"On receipt"}),l.paid_at&&P(Xt,{label:"Paid",value:ea(l.paid_at)}),l.payment_method&&P(Xt,{label:"Paid by",value:l.paid_out_of_band?`${l.payment_method} (recorded outside Stripe)`:l.payment_method}),l.payment_state!=="none"&&P(Xt,{label:"Payment",value:l.payment_state==="processing"?"Processing":l.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),l.delivery&&P(Xt,{label:"Delivery",value:`${Jn[l.delivery.state]} \xB7 ${l.delivery.recipient}`}),l.marked_uncollectible_at&&P(Xt,{label:"Written off",value:ea(l.marked_uncollectible_at)}),l.correction_reason&&P(Xt,{label:"Correction",value:l.correction_reason}),l.replaced_by_order_id&&P(Xt,{label:"Replaced by",value:l.replaced_by_order_id}),l.collection_method==="charge_automatically"?P(Xt,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):l.retainer_id&&P(Xt,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),l.replaces_order_id&&P(Xt,{label:"Replaces",value:l.replaces_order_id})]}),V("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[P("div",{className:Va,children:"Reminders"}),x?P("div",{children:"View automatic payment reminders in Stripe."}):l.reminders.disabled?P("div",{children:"Off for this invoice."}):l.reminders.paused_until?V("div",{children:["Paused until ",ea(l.reminders.paused_until),"."]}):l.reminders.next_at?V("div",{children:["Next on ",ea(l.reminders.next_at),"."]}):l.reminders.final_sent_at?V("div",{children:["Final reminder sent ",ea(l.reminders.final_sent_at),"."]}):P("div",{children:"None scheduled."}),!x&&V("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",l.reminders.schedule.length===0?"none":l.reminders.schedule.map(u=>u<0?`${-u}d before`:u===0?"due day":`${u}d after`).join(", ")]})]}),l.communications&&l.communications.length>0&&V("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[P("div",{className:Va,children:"Email delivery history"}),l.communications.map(u=>V("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[V("span",{className:"af-min-w-0 af-break-words",children:[wc[u.kind]??u.kind,u.kind==="reminder"&&u.slot!==null?` #${u.slot}`:"",V("span",{className:"af-text-muted-foreground",children:[" \xB7 ",u.recipient]})]}),V("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Jn[u.state]??u.state," \xB7 ",ea(u.state_at??u.created_at)]})]},u.id))]}),K.length>0&&V("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[P("div",{className:Va,children:"Bill to"}),K.map((u,z)=>P("div",{className:"af-break-words",children:u},z))]}),V("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[l.pay_url&&V(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void j(),disabled:!ni(),children:[P(pc,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":x?"Copy invoice link":"Copy pay link"]}),l.pdf_url&&P(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:V("a",{href:l.pdf_url,target:"_blank",rel:"noreferrer",children:[P(vc,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!x&&V(S,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void L(),disabled:r,children:[r?P(bc,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):P(ri,{className:"af-h-4 af-w-4 af-mr-1"}),m?"Hide email preview":y?"Retry email preview":"Show email preview"]}),y&&!x&&P("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),l.pay_url&&P("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:l.pay_url}),P("p",{className:"af-text-xs af-text-muted-foreground",children:x?"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 Xt({label:e,value:a}){return V("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[P("span",{className:$(Va,"af-shrink-0"),children:e}),P("span",{className:"af-min-w-0 af-break-words af-text-right",children:a})]})}function Wa({label:e,value:a,strong:s}){return V("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[P("dt",{className:$(Va,s&&"af-font-medium af-text-foreground"),children:e}),P("dd",{className:$("af-tabular-nums",s&&"af-font-semibold"),children:a})]})}import{Repeat as Pc}from"lucide-react";import{jsx as lt,jsxs as ma}from"react/jsx-runtime";var Tc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},oi={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Cc(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 li(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(a=>oi[a]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(a=>oi[a]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Tc[e.status]}function ci(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 ${mn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${mn(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 ${mn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${mn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function mn(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 Qn({retainer:e,className:a}){return lt(Z,{variant:Cc(e.status),className:$("af-max-w-full af-whitespace-normal af-break-words",a),children:li(e)})}function us({retainers:e,isLoading:a,error:s,onRetry:t,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:f=0,isLoadingMore:m=!1,onLoadMore:b,includeEnded:r=!1,onIncludeEndedChange:g,className:y}){let p=!!g;if(!a&&!s&&e.length===0&&!(p&&(r||f>0)))return null;let c=o!==void 0?Math.max(0,o-e.length):0;return ma("section",{className:$("af-mb-6",y),"aria-label":"Recurring invoices",children:[ma("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[lt(Pc,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),lt("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),lt("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&&lt(S,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>g?.(!r),children:r?"Hide ended recurring invoices":f>0&&e.length===0?`Show ended recurring invoices (${f})`:"Show ended recurring invoices"})]}),s?ma("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",lt(S,{type:"button",variant:"link",size:"sm",onClick:t,children:"Retry"})]}):a?lt("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(d=>ma("div",{className:"af-rounded-md af-border af-p-3",children:[lt(Q,{className:"af-h-4 af-w-48"}),lt(Q,{className:"af-mt-2 af-h-3 af-w-32"})]},d))}):e.length===0?lt("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."}):lt("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(d=>{let v=i===d.id;return ma("li",{className:$("af-rounded-md af-border af-p-3",v&&"af-border-primary af-bg-muted/40"),children:[ma("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[ma("div",{className:"af-min-w-0",children:[lt("div",{className:"af-truncate af-font-medium",children:d.customer_name??d.customer_email??"\u2014"}),lt("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:d.description})]}),lt(Qn,{retainer:d})]}),d.collection_method==="charge_automatically"?ma("div",{className:"af-mt-2 af-space-y-1",children:[lt(Z,{variant:"secondary",children:"Managed in Stripe"}),lt("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."})]}):lt("div",{className:"af-mt-2 af-text-sm",children:ci(d)}),ma("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:[ma("span",{children:[kc(d)," \xB7 ",d.cycles.count===0?"no invoices yet":`${d.cycles.paid} paid${d.cycles.open>0?`, ${d.cycles.open} open`:""}`]}),d.cycles.count>0&&lt(S,{type:"button",variant:v?"secondary":"ghost",size:"sm",onClick:()=>n(d),"aria-pressed":v,children:v?"Showing invoices":"View invoices"})]}),d.status==="failed"&&d.operation?.last_error&&ma("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",d.operation.last_error,". Ask in the chat to try again."]})]},d.id)})}),!a&&!s&&c>0&&b&&lt("div",{className:"af-mt-2",children:lt(S,{type:"button",variant:"outline",size:"sm",onClick:b,disabled:m,children:m?"Loading\u2026":`Load more (${c} more)`})})]})}import*as ui from"react";import{AlertTriangle as di,CheckCircle2 as Ec,CreditCard as Xn,Loader2 as Ic,RefreshCw as Ac}from"lucide-react";import*as Ca from"react";function fs(){let{api:e}=ae(),[a,s]=Ca.useState(null),[t,n]=Ca.useState(!0),[i,o]=Ca.useState(null),f=Ca.useRef(0),m=Ca.useCallback(async()=>{let b=++f.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(b!==f.current)return;s(r)}catch(r){if(b!==f.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{b===f.current&&n(!1)}},[e]);return Ca.useEffect(()=>{m()},[m]),{status:a,isLoading:t,error:i,refetch:m}}import{jsx as Je,jsxs as gt}from"react/jsx-runtime";function pn({onConnectStripe:e,onUpgradePlan:a,className:s}){let{status:t,isLoading:n,error:i,refetch:o}=fs(),[f,m]=ui.useState(!1),b=async()=>{m(!0);try{await o()}finally{m(!1)}};return n&&!t?Je("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:Je("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!t?Je("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:gt("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):t.status==="active"?Je("div",{className:s,children:gt("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:[Je(Ec,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),gt("div",{children:[Je("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),gt("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."]})]})]})}):gt("div",{className:`af-space-y-4 ${s||""}`,children:[t.reason==="needs_stripe"&&gt("div",{className:"af-space-y-3",children:[gt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Je(Xn,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),gt("div",{children:[Je("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),Je("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?gt(S,{onClick:e,children:[Je(Xn,{className:"af-h-4 af-w-4 af-mr-1"}),t.stripe_account_connected?"Finish setting up":"Set up payments"]}):Je("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"&&gt("div",{className:"af-space-y-3",children:[gt("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[Je(di,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),gt("div",{children:[Je("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),Je("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?Je(S,{onClick:a,children:"Upgrade plan"}):Je("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),t.reason==="account_disabled"&&gt("div",{className:"af-space-y-3",children:[gt("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:[Je(di,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),gt("div",{children:[Je("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),t.stripe_account_connected?Je("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."}):Je("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."})]})]}),gt("div",{className:"af-flex af-gap-2",children:[e&&t.stripe_account_connected&&gt(S,{onClick:e,children:[Je(Xn,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),gt(S,{variant:"outline",onClick:b,disabled:f,children:[f?Je(Ic,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):Je(Ac,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}import*as Tt from"react";function er(e,a,s){return e.map(t=>t.id===a?{...t,...s}:t)}function ms({includeStats:e=!1,refreshKey:a}={}){let{api:s}=ae(),[t,n]=Tt.useState([]),[i,o]=Tt.useState(!0),[f,m]=Tt.useState(null),b=Tt.useRef(0),r=Tt.useCallback(async()=>{let v=++b.current;try{o(!0),m(null);let h=await s.getProducts(e?{include:"stats"}:{});if(v!==b.current)return;n(h)}catch(h){if(v!==b.current)return;m(h instanceof Error?h:new Error("Failed to fetch products"))}finally{v===b.current&&o(!1)}},[s,e,a]);Tt.useEffect(()=>{r()},[r]);let g=Tt.useCallback(async v=>{let h=await s.createProduct(v);return n(R=>[h,...R]),h},[s]),y=Tt.useCallback(async(v,h)=>{let R=await s.updateProduct(v,h);return n(E=>er(E,v,R)),R},[s]),p=Tt.useCallback(async v=>{await s.deleteProduct(v),n(h=>h.filter(R=>R.id!==v))},[s]),c=Tt.useCallback(async(v,h)=>{let R=await s.attachProductFile(v,h);return n(E=>er(E,v,R)),R},[s]),d=Tt.useCallback(async(v,h)=>{let R=await s.attachProductFileFromUrl(v,h);return n(E=>er(E,v,R)),R},[s]);return{products:t,isLoading:i,error:f,refetch:r,createProduct:g,updateProduct:y,deleteProduct:p,attachProductFile:c,attachProductFileFromUrl:d}}import*as Ct from"react";var fi=["creating","active","paused","canceling"],Dc=["canceled","failed"];function ps({refreshKey:e,includeEnded:a=!1,limit:s=50}={}){let{api:t}=ae(),[n,i]=Ct.useState([]),[o,f]=Ct.useState(0),[m,b]=Ct.useState(0),[r,g]=Ct.useState(!0),[y,p]=Ct.useState(!1),[c,d]=Ct.useState(null),[v,h]=Ct.useState(a),R=Ct.useRef(0),E=Ct.useCallback(async()=>{let l=++R.current;g(!0),p(!1),d(null);try{let x=await t.getRetainers({statuses:v?void 0:fi,limit:s,offset:0});if(l!==R.current)return;if(i(x.retainers),f(x.total),!v&&x.total===0){let C=await t.getRetainers({statuses:Dc,limit:1,offset:0});if(l!==R.current)return;b(C.total)}else b(0)}catch(x){if(l!==R.current)return;d(x instanceof Error?x:new Error("Failed to fetch retainers"))}finally{l===R.current&&g(!1)}},[t,v,s]);Ct.useEffect(()=>{E()},[E,e]);let M=Ct.useCallback(async()=>{if(r||y||n.length>=o)return;let l=R.current;p(!0);try{let x=await t.getRetainers({statuses:v?void 0:fi,limit:s,offset:n.length});if(l!==R.current)return;i(C=>{let j=new Set(C.map(L=>L.id));return[...C,...x.retainers.filter(L=>!j.has(L.id))]}),f(x.total)}catch(x){if(l!==R.current)return;d(x instanceof Error?x:new Error("Failed to fetch retainers"))}finally{l===R.current&&p(!1)}},[t,v,s,r,y,n.length,o]);return{retainers:n,total:o,endedTotal:m,hasMore:n.length<o,isLoading:r,isLoadingMore:y,error:c,includeEnded:v,setIncludeEnded:h,loadMore:M,refetch:E}}import{Fragment as $c,jsx as qe,jsxs as Ot}from"react/jsx-runtime";function mi({className:e,defaultTab:a="products",onConnectStripe:s,onRefund:t,onUpgradePlan:n}){let[i,o]=gs.useState(a),[f,m]=gs.useState("list"),[b,r]=gs.useState(null),g=ms(),{status:y,error:p}=fs(),c=y?.currency,d=E=>{r(E),m("edit")},v=()=>{r(null),m("create")},h=()=>{m("list"),r(null)},R=E=>{r(E),m("edit")};return Ot("div",{className:e,children:[Ot("div",{className:"af-mb-6",children:[qe("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),qe("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),Ot(Ms,{value:i,onValueChange:E=>o(E),children:[Ot(Ns,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[Ot(ha,{value:"products",className:"af-gap-2",children:[qe(Bc,{className:"af-h-4 af-w-4"}),"Products"]}),Ot(ha,{value:"orders",className:"af-gap-2",children:[qe(Fc,{className:"af-h-4 af-w-4"}),"Orders"]}),Ot(ha,{value:"invoices",className:"af-gap-2",children:[qe(Oc,{className:"af-h-4 af-w-4"}),"Invoices"]}),Ot(ha,{value:"customers",className:"af-gap-2",children:[qe(Uc,{className:"af-h-4 af-w-4"}),"Customers"]}),Ot(ha,{value:"setup",className:"af-gap-2",children:[qe(Mc,{className:"af-h-4 af-w-4"}),"Setup"]})]}),qe(xa,{value:"products",children:f==="list"?qe(Ys,{productsState:g,onSelectProduct:d,onCreateProduct:v}):Ot("div",{children:[Ot("div",{className:"af-mb-6",children:[Ot(S,{variant:"ghost",size:"sm",onClick:h,className:"af-mb-2 af--ml-2",children:[qe(Lc,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),qe("h3",{className:"af-text-lg af-font-semibold",children:f==="create"?"New Product":b?.name})]}),f==="create"&&!c?qe("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:p?Ot("div",{className:"af-text-destructive",children:["Error: ",p.message]}):qe("div",{className:"af-text-muted-foreground",children:"Loading..."})}):qe(Qs,{productsState:g,product:f==="edit"?b:null,currency:c??"usd",onSaved:R},f==="edit"?b?.id??"edit":"new")]})}),qe(xa,{value:"orders",children:qe(os,{onRefund:t})}),qe(xa,{value:"invoices",children:qe(Vc,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:y?.reason==="needs_paid_plan"})}),qe(xa,{value:"customers",children:qe(dn,{})}),qe(xa,{value:"setup",children:qe(pn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Vc({onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s}){let t=ps(),[n,i]=gs.useState(null),[o,f]=gs.useState(!1);return Ot($c,{children:[!o&&qe(us,{retainers:t.retainers,isLoading:t.isLoading,error:t.error,onRetry:()=>void t.refetch(),activeRetainerId:n?.id??null,onShowCycles:m=>i(b=>b?.id===m.id?null:m),total:t.total,endedTotal:t.endedTotal,isLoadingMore:t.isLoadingMore,onLoadMore:()=>void t.loadMore(),includeEnded:t.includeEnded,onIncludeEndedChange:t.setIncludeEnded}),qe(ds,{onDetailOpenChange:f,onConnectStripe:e,onUpgradePlan:a,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}import*as gi from"react";import*as ka from"react";function gn({refreshKey:e}={}){let{api:a}=ae(),[s,t]=ka.useState(null),[n,i]=ka.useState(!0),[o,f]=ka.useState(null),m=ka.useRef(0),b=ka.useCallback(async()=>{let r=++m.current;try{i(!0),f(null);let g=await a.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==m.current)return;t(g)}catch(g){if(r!==m.current)return;f(g instanceof Error?g:new Error("Failed to fetch summary"))}finally{r===m.current&&i(!1)}},[a,e]);return ka.useEffect(()=>{b()},[b]),{summary:s,isLoading:n,error:o,refetch:b}}import{Fragment as tr,jsx as vt,jsxs as ar}from"react/jsx-runtime";function pi(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 vi({refreshKey:e,initialOrderId:a,isOwner:s=!1,onRefund:t,onBackToWebsite:n,className:i}){let{summary:o,isLoading:f,error:m,refetch:b}=gn({refreshKey:e}),[r,g]=gi.useState(!1),y=vt("div",{className:"af-mb-6",children:m&&!o?vt(jt,{message:"Couldn't load your revenue summary.",onRetry:()=>b()}):vt("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:f||!o?ar(tr,{children:[vt(Ke,{label:"This week",children:vt(Q,{className:"af-h-6 af-w-24"})}),vt(Ke,{label:"Today",children:vt(Q,{className:"af-h-6 af-w-24"})}),vt(Ke,{label:"Needs attention",children:vt(Q,{className:"af-h-6 af-w-10"})})]}):vt(tr,{children:(()=>{let p=pi(o.revenue.d7,o.currency),c=pi(o.revenue.today,o.currency);return ar(tr,{children:[vt(Ke,{label:"This week",detail:p.extra.length>0?vt("div",{children:p.extra.map(d=>vt("div",{children:d},d))}):void 0,children:p.headline}),vt(Ke,{label:"Today",detail:c.extra.length>0?vt("div",{children:c.extra.map(d=>vt("div",{children:d},d))}):void 0,children:c.headline}),vt(Ke,{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 ar(wt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[y,vt(os,{refreshKey:e,initialOrderId:a,onDetailOpenChange:g,showFulfillment:!0,onRefund:s?t:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}import*as $a from"react";import{ImageOff as Gc,Package as Wc,Search as Kc}from"lucide-react";import*as Ea from"react";import{ArrowLeft as qc,ImageOff as jc}from"lucide-react";import{jsx as pa,jsxs as Cs}from"react/jsx-runtime";var bi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ka="af-text-xs af-text-muted-foreground",vn="af-text-sm af-font-medium af-tabular-nums",Hc=3;function zc(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,b=e.max_amount??a?.max_amount??null;return m!==null&&b!==null?{text:`Buyer chooses (${H(m,s)} \u2013 ${H(b,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)}`,f=a?.compare_at_amount??null;return{text:o,compareAt:f!==null&&f>i?H(f,s):null}}function bn({product:e,className:a}){let s=zc(e);return Cs("div",{className:a,children:[pa("span",{className:vn,children:s.text}),s.compareAt&&pa("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function yn({product:e}){let a=e.inventory;return a?a.tracked?a.out_of_stock?pa(Z,{variant:"destructive",children:"Out of stock"}):a.low_stock?Cs(Z,{variant:"warning",children:["Low stock \xB7 ",a.available]}):a.allow_backorder?pa(Z,{variant:"secondary",children:"Backorder"}):a.available===null?null:Cs(Z,{variant:"secondary",children:["In stock \xB7 ",a.available]}):null:e.stats?.low_stock?pa(Z,{variant:"warning",children:"Low stock"}):null}function hn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function xn(e){return e.map(a=>H(a.amount,a.currency)).join(" + ")}function yi(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 hi({variant:e}){let a=e.inventory;if(!a||!a.tracked)return pa("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=a.available??0;return a.allow_backorder?Cs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[pa("span",{className:"af-tabular-nums",children:Math.max(0,s)}),pa(Z,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?pa(Z,{variant:"destructive",children:"Out of stock"}):Cs("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[pa("span",{className:"af-tabular-nums",children:s}),s<=Hc&&pa(Z,{variant:"warning",children:"Low"})]})}import{jsx as ne,jsxs as je}from"react/jsx-runtime";function ks({title:e,children:a,className:s}){return je("section",{className:$("af-rounded-lg af-border af-p-4",s),children:[ne("h4",{className:bi,children:e}),ne("div",{className:"af-mt-3",children:a})]})}function xi({src:e,className:a}){let[s,t]=Ea.useState(!1);return Ea.useEffect(()=>t(!1),[e]),!e||s?ne("div",{"aria-hidden":"true",className:$("af-flex af-items-center af-justify-center af-bg-muted",a),children:ne(jc,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):ne("img",{src:e,alt:"",loading:"lazy",onError:()=>t(!0),className:$("af-object-cover",a)})}function wi({product:e,showStats:a=!1,onBack:s}){let{api:t}=ae(),[n,i]=Ea.useState(null),[o,f]=Ea.useState(!0),[m,b]=Ea.useState(null),[r,g]=Ea.useState(0),[y,p]=Ea.useState(0);Ea.useEffect(()=>{let l=!1;return f(!0),b(null),t.getProduct(e.id).then(x=>{l||i(x)}).catch(x=>{l||b(x instanceof Error?x:new Error("Failed to load product"))}).finally(()=>{l||f(!1)}),()=>{l=!0}},[t,e.id,r]);let c=n?{...e,...n}:e,d=c.images.length>0?c.images:e.images,v=d[y]??d[0],h=hn(c),R=a?c.stats:void 0,E=n?.variants??[],M=E.length>1;return je("div",{children:[je("div",{className:"af-mb-6",children:[je(S,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[ne(qc,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),je("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[ne("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),ne(Z,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),ne(yn,{product:c})]}),ne(bn,{product:c,className:"af-mt-1"}),!c.active&&ne("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),je("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[je("div",{className:"af-space-y-2",children:[ne(xi,{src:v,className:"af-h-48 af-w-full af-rounded-md af-border"}),d.length>1&&ne("div",{className:"af-flex af-flex-wrap af-gap-2",children:d.map((l,x)=>ne("button",{type:"button",onClick:()=>p(x),"aria-label":`Show photo ${x+1} of ${d.length}`,"aria-pressed":x===y,className:$("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",x===y?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:ne(xi,{src:l,className:"af-h-12 af-w-12 af-rounded-md"})},`${l}-${x}`))})]}),je("div",{className:"af-space-y-6",children:[c.description&&ne(ks,{title:"Description",children:ne("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?je(ks,{title:"Variants",children:[ne("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(l=>je("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[ne(Q,{className:"af-h-4 af-w-28"}),ne(Q,{className:"af-h-4 af-w-20"}),ne(Q,{className:"af-h-4 af-w-16"})]},l))}),ne("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):m?ne(jt,{message:"Couldn't load this product's variants.",onRetry:()=>g(l=>l+1)}):M?ne(ks,{title:`Variants \xB7 ${E.length}`,children:ne("div",{className:"af-overflow-x-auto",children:je(Le,{children:[ne(Oe,{children:je(me,{children:[ne(O,{children:"Variant"}),ne(O,{children:"SKU"}),ne(O,{className:"af-text-right",children:"Price"}),ne(O,{children:"Stock"})]})}),ne(Be,{children:E.map(l=>je(me,{children:[je(B,{className:"af-font-medium",children:[l.title||l.option_values.map(x=>x.value).join(" / ")||"\u2014",!l.active&&ne(Z,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),ne(B,{className:"af-text-muted-foreground",children:l.sku?ne("code",{className:"af-font-mono af-text-xs af-break-all",children:l.sku}):"\u2014"}),je(B,{className:"af-whitespace-nowrap af-text-right",children:[ne("div",{className:vn,children:yi(l)}),l.compare_at_amount!==null&&l.unit_amount!==null&&l.compare_at_amount>l.unit_amount&&ne("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:H(l.compare_at_amount,l.currency)})]}),ne(B,{className:"af-text-sm",children:ne(hi,{variant:l})})]},l.id))})]})})}):null,ne(ks,{title:"Details",children:je("dl",{className:"af-space-y-2",children:[je("div",{children:[ne("dt",{className:Ka,children:"Delivery"}),ne("dd",{className:"af-text-sm",children:h==="Digital download"?c.fulfillment.filename??"Digital download":h??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&je("div",{children:[ne("dt",{className:Ka,children:"Sends buyers to"}),ne("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),je("div",{children:[ne("dt",{className:Ka,children:"Shipping address"}),ne("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),je("div",{children:[ne("dt",{className:Ka,children:"Most one buyer can order"}),ne("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),R&&ne(ks,{title:"Last 30 days",children:je("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[je("div",{children:[ne("dt",{className:Ka,children:"Units sold"}),ne("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.units_sold})]}),je("div",{children:[ne("dt",{className:Ka,children:"Orders"}),ne("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.orders})]}),je("div",{children:[ne("dt",{className:Ka,children:"Gross"}),ne("dd",{className:vn,children:R.gross.length>0?xn(R.gross):"\u2014"})]})]})}),ne("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 vs,jsx as re,jsxs as Ye}from"react/jsx-runtime";var Jc={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Yc=["all","active","draft","low_stock","out_of_stock"];function Ni(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(a).getTime();return Number.isNaN(s)?0:s}function Si(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function Zc(e){return e.inventory?.out_of_stock??!1}function Qc(e,a){switch(a){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Si(e);case"out_of_stock":return Zc(e);default:return!0}}function Xc({product:e,showStats:a,onOpen:s}){let t=e.images[0],n=a?e.stats:void 0,i=hn(e),o=e.variant_count??0;return Ye("button",{type:"button",onClick:s,"aria-label":`Open ${e.name}`,className:"af-block af-w-full af-overflow-hidden af-rounded-md af-border af-text-left af-transition-colors hover:af-bg-muted/50 focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[t?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(Gc,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),Ye("div",{className:"af-space-y-2 af-p-3",children:[Ye("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ye("div",{className:"af-min-w-0",children:[re("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),re(bn,{product:e,className:"af-mt-0.5"})]}),!e.active&&re(Z,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),Ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[re(yn,{product:e}),o>1&&Ye(Z,{variant:"outline",children:[o," variants"]}),i&&re(Z,{variant:"outline",children:i})]}),n&&Ye("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${xn(n.gross)}`:""," ",re("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function ed(){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=>Ye("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"}),Ye("div",{className:"af-space-y-2 af-p-3",children:[re(Q,{className:"af-w-32"}),re(Q,{className:"af-w-16"}),re(Q,{className:"af-h-5 af-w-24"})]})]},e))})}function Ri({refreshKey:e,showStats:a=!1,onBackToWebsite:s,className:t}){let{products:n,isLoading:i,error:o,refetch:f}=ms({includeStats:a,refreshKey:e}),[m,b]=$a.useState(null),[r,g]=$a.useState("all"),[y,p]=$a.useState(""),[c,d]=$a.useState("newest"),v=$a.useMemo(()=>{if(!a)return null;let w=null;for(let K of n)!K.stats||K.stats.units_sold===0||(!w||K.stats.units_sold>(w.stats?.units_sold??0))&&(w=K);return w},[n,a]),h=$a.useMemo(()=>n.filter(Si).length,[n]),R=y.trim().toLowerCase(),E=$a.useMemo(()=>{let K=[...n.filter(u=>Qc(u,r)&&(!R||u.name.toLowerCase().includes(R)))];return c==="name"?K.sort((u,z)=>u.name.localeCompare(z.name)):c==="best_selling"?K.sort((u,z)=>(z.stats?.units_sold??0)-(u.stats?.units_sold??0)):K.sort((u,z)=>Ni(z.created_at)-Ni(u.created_at)),K},[n,r,R,c]),M=r!=="all"||!!R,l=()=>{g("all"),p("")},x=i||o!==null&&n.length===0,C=re("div",{className:"af-mb-6",children:re("div",{className:$("af-grid af-grid-cols-1 af-gap-3",a?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:x?Ye(vs,{children:[re(Ke,{label:"Products",children:re(Q,{className:"af-h-6 af-w-10"})}),a?Ye(vs,{children:[re(Ke,{label:"Best seller",children:re(Q,{className:"af-h-6 af-w-28"})}),re(Ke,{label:"Low stock",children:re(Q,{className:"af-h-6 af-w-10"})})]}):re(Ke,{label:"Active",children:re(Q,{className:"af-h-6 af-w-10"})})]}):Ye(vs,{children:[re(Ke,{label:"Products",children:n.length}),a?Ye(vs,{children:[re(Ke,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:v?`${v.stats?.units_sold??0} sold, last 30 days`:void 0,children:v?re("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:v.name}):re("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),re(Ke,{label:"Low stock",children:h})]}):re(Ke,{label:"Active",children:n.filter(w=>w.active).length})]})})}),j=Ye("div",{className:"af-mb-4 af-space-y-3",children:[Ye("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[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:Yc.map(w=>re("button",{type:"button","aria-pressed":r===w,onClick:()=>g(w),className:$("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",r===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Jc[w]},w))}),Ye("div",{className:"af-relative af-w-full af-max-w-xs",children:[re(Kc,{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(pe,{type:"text",value:y,onChange:w=>p(w.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),Ye(Kt,{value:c,onValueChange:w=>d(w),children:[re($t,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:re(Jt,{})}),Ye(Ht,{children:[re(Ue,{value:"newest",children:"Newest"}),re(Ue,{value:"name",children:"Name A\u2013Z"}),a&&re(Ue,{value:"best_selling",children:"Best selling"})]})]}),M&&re(S,{type:"button",variant:"ghost",size:"sm",onClick:l,children:"Clear filters"})]}),i&&n.length===0?re(Q,{className:"af-h-4 af-w-28"}):re("p",{className:"af-text-sm af-text-muted-foreground",children:M?`${E.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${h>0?` \xB7 ${h} low stock`:""}`})]}),L;return m?L=re(wi,{product:m,showStats:a,onBack:()=>{b(null),f()}},m.id):i&&n.length===0?L=Ye(vs,{children:[j,re(ed,{}),re("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?L=re("div",{className:"af-flex af-justify-center af-py-8",children:re(jt,{message:"Couldn't load your products.",onRetry:()=>f()})}):n.length===0?L=Ye(Ta,{icon:re(Wc,{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."]}):L=Ye(vs,{children:[j,o&&re("div",{className:"af-mb-4",children:re(jt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>f()})}),E.length===0?Ye(Ta,{children:["No products match these filters.",re("br",{}),re(S,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:l,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:E.map(w=>re(Xc,{product:w,showStats:a,onOpen:()=>b(w)},w.id))})]}),Ye(wt,{title:"Products",onBackToWebsite:s,hideBackButton:!!m,className:t,children:[!m&&C,L]})}import*as ga from"react";import{ArrowLeft as ki,Check as td,ChevronLeft as _i,ChevronRight as Pi,ClipboardCopy as ad,Mail as nr,Search as sd,Users as nd}from"lucide-react";import*as Gt from"react";function wn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ae(),[t,n]=Gt.useState([]),[i,o]=Gt.useState(!0),[f,m]=Gt.useState(null),[b,r]=Gt.useState(0),[g]=Gt.useState(e),[y,p]=Gt.useState(""),c=Gt.useRef(0),d=Gt.useCallback(async()=>{let v=++c.current;try{o(!0),m(null);let h={limit:g,offset:b*g};y.trim()&&(h.q=y.trim());let R=await s.getPeople(h);if(v!==c.current)return;n(R.people)}catch(h){if(v!==c.current)return;m(h instanceof Error?h:new Error("Failed to fetch people"))}finally{v===c.current&&o(!1)}},[s,b,g,y,a]);return Gt.useEffect(()=>{d()},[d]),{people:t,isLoading:i,error:f,page:b,pageSize:g,hasNextPage:t.length===g,hasPreviousPage:b>0,setPage:r,q:y,setQ:v=>{p(v),r(0)},refetch:d}}import*as Ia from"react";function Nn(e,{refreshKey:a}={}){let{api:s}=ae(),[t,n]=Ia.useState(null),[i,o]=Ia.useState(e!==null),[f,m]=Ia.useState(null),b=Ia.useRef(0),r=Ia.useCallback(async()=>{if(e===null){n(null),o(!1),m(null);return}let g=++b.current;try{o(!0),m(null);let y=await s.getPerson(e);if(g!==b.current)return;n(y)}catch(y){if(g!==b.current)return;m(y instanceof Error?y:new Error("Failed to fetch person"))}finally{g===b.current&&o(!1)}},[s,e,a]);return Ia.useEffect(()=>{r()},[r]),{person:t,isLoading:i,error:f,refetch:r}}import{jsx as N,jsxs as se}from"react/jsx-runtime";var sr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",rd="af-text-xs af-text-muted-foreground";function bs(e){let a=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function rr(e,a){let s=a?`Re: ${a}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function id(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function od({value:e,label:a}){let[s,t]=ga.useState(!1);return id()?se(S,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),t(!0),setTimeout(()=>t(!1),1500)}catch{}},"aria-label":a,className:"af-shrink-0",children:[s?N(td,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):N(ad,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function Ti(e){return se("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&se(Z,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&N(Z,{variant:"secondary",children:"Contact form"})]})}function Ci(e){return e.name?e.name:e.email?e.email:N("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var ld=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,cd=40;function dd(e){let a=Object.entries(e).filter(([n])=>!n.startsWith("_")),t=a.find(([n,i])=>ld.test(n)&&typeof i=="string"&&i.trim())??a.filter(([,n])=>typeof n=="string"&&n.trim().length>=cd).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 ud(e){return e.replace(/_/g," ")}function fd(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function md({data:e}){let{message:a,rest:s}=dd(e);return a===null&&s.length===0?N("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):se("div",{className:"af-space-y-3",children:[a!==null&&N("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:a}),s.length>0&&N("dl",{className:"af-space-y-1",children:s.map(([t,n])=>se("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[N("dt",{className:$(rd,"af-w-28 af-shrink-0 af-capitalize"),children:ud(t)}),N("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:fd(n)})]},t))})]})}function Ei({formName:e,createdAt:a,data:s}){return se("div",{className:"af-rounded-md af-border af-p-3",children:[se("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[N(Z,{variant:"outline",children:"Form submission (unverified)"}),e&&N("span",{className:"af-text-xs af-text-muted-foreground",children:e}),N("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:bs(a)})]}),N(md,{data:s})]})}function pd(e){return e.charged_total??e.amount_total}function gd({email:e,refreshKey:a,onBack:s}){let{person:t,isLoading:n,error:i,refetch:o}=Nn(e,{refreshKey:a}),f=rr(e,t?.submissions[0]?.form_name);return se("div",{children:[se("div",{className:"af-mb-6",children:[se(S,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[N(ki,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),se("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[se("div",{className:"af-min-w-0",children:[n?N(Q,{className:"af-h-7 af-w-48"}):N("h3",{className:"af-text-xl af-font-semibold af-break-all",children:t?.name||e}),se("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[N("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),N(od,{value:e,label:"Copy email address"})]})]}),N(S,{asChild:!0,children:se("a",{href:f,children:[N(nr,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?se("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(m=>se("div",{className:"af-rounded-md af-border af-p-3",children:[N(Q,{className:"af-w-40"}),N(Q,{className:"af-mt-2 af-w-64"})]},m)),N("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!t?N("div",{className:"af-flex af-justify-center af-py-8",children:N(jt,{message:"Couldn't load this person.",onRetry:()=>o()})}):se("div",{className:"af-space-y-6",children:[t.customer&&se("div",{children:[N("h4",{className:$(sr,"af-mb-3"),children:"Customer"}),se("dl",{className:"af-space-y-1 af-text-sm",children:[t.customer.name&&se("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),N("dd",{children:t.customer.name})]}),t.customer.phone&&se("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),N("dd",{children:t.customer.phone})]}),se("div",{className:"af-flex af-gap-2",children:[N("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),N("dd",{children:bs(t.customer.created_at)})]})]})]}),t.orders.length>0&&se("div",{children:[N("h4",{className:$(sr,"af-mb-3"),children:"Purchases"}),N("div",{className:"af-overflow-x-auto",children:se(Le,{children:[N(Oe,{children:se(me,{children:[N(O,{children:"Order"}),N(O,{children:"Date"}),N(O,{className:"af-text-right",children:"Total"}),N(O,{children:"Status"})]})}),N(Be,{children:t.orders.map(m=>se(me,{children:[N(B,{className:"af-whitespace-nowrap af-font-medium",children:Ua(m)}),N(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:bs(m.created_at)}),N(B,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:H(pd(m),m.currency)}),N(B,{children:N(Xa,{status:m.status})})]},m.id))})]})}),N("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:"Ask the AI to open one of these orders for the full details."})]}),t.submissions.length>0&&se("div",{children:[N("h4",{className:$(sr,"af-mb-3"),children:"Messages"}),N("div",{className:"af-space-y-3",children:t.submissions.map(m=>N(Ei,{formName:m.form_name,createdAt:m.created_at,data:m.data},m.id))})]})]})]})}function vd({submissionId:e,onBack:a}){let{api:s}=ae(),[t,n]=ga.useState(null),[i,o]=ga.useState(!0),[f,m]=ga.useState(null),[b,r]=ga.useState(0);return ga.useEffect(()=>{let g=!1;return o(!0),m(null),s.getSubmission(e).then(y=>{g||n(y)}).catch(y=>{g||m(y instanceof Error?y:new Error("Failed to load submission"))}).finally(()=>{g||o(!1)}),()=>{g=!0}},[s,e,b]),se("div",{children:[se("div",{className:"af-mb-6",children:[se(S,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[N(ki,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),N("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?N(Q,{className:"af-mt-1 af-h-4 af-w-32"}):t&&N("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:bs(t.metadata.submitted_at)})]}),i?se("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[N(Q,{className:"af-w-40"}),N(Q,{className:"af-mt-2 af-w-64"}),N(Q,{className:"af-mt-2 af-w-52"}),N("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):f||!t?N("div",{className:"af-flex af-justify-center af-py-8",children:N(jt,{message:"Couldn't load this submission.",onRetry:()=>r(g=>g+1)})}):se("div",{className:"af-space-y-3",children:[N(Ei,{formName:null,createdAt:t.metadata.submitted_at,data:t.data}),N("p",{className:"af-text-xs af-text-muted-foreground",children:"No email address came with this submission, so there is nobody to reply to."})]})]})}var bd={all:"All",customers:"Customers",leads:"Leads"},yd=["all","customers","leads"];function hd(e,a){return a==="customers"?e.sources.includes("customer"):a==="leads"?e.sources.includes("lead"):!0}function Ii({refreshKey:e,onBackToWebsite:a,className:s}){let{people:t,isLoading:n,error:i,page:o,pageSize:f,hasNextPage:m,hasPreviousPage:b,setPage:r,q:g,setQ:y,refetch:p}=wn({refreshKey:e}),[c,d]=ga.useState({kind:"list"}),[v,h]=ga.useState(""),[R,E]=ga.useState("all"),M=L=>{L.email?d({kind:"person",email:L.email}):L.submission_id&&d({kind:"submission",submissionId:L.submission_id})},l=()=>{d({kind:"list"}),p()},x=L=>{let w=L.trim();w!==g&&y(w)},C=t.filter(L=>hd(L,R)),j;if(c.kind==="person")j=N(gd,{email:c.email,refreshKey:e,onBack:l});else if(c.kind==="submission")j=N(vd,{submissionId:c.submissionId,onBack:l});else{let L=se("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[N("div",{role:"group","aria-label":"People views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:yd.map(w=>N("button",{type:"button","aria-pressed":R===w,onClick:()=>E(w),className:$("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:bd[w]},w))}),se("div",{className:"af-relative af-w-full af-max-w-xs",children:[N(sd,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),N(pe,{type:"text",value:v,onChange:w=>h(w.target.value),onBlur:()=>x(v),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),x(v))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),g&&N(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>{h(""),y("")},children:"Clear search"})]});if(n)j=se("div",{children:[L,N("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(w=>se("div",{className:"af-rounded-md af-border af-p-3",children:[se("div",{className:"af-flex af-items-center af-justify-between",children:[N(Q,{className:"af-h-4 af-w-32"}),N(Q,{className:"af-h-4 af-w-16"})]}),N(Q,{className:"af-mt-2 af-h-5 af-w-28"}),N(Q,{className:"af-mt-2 af-h-3 af-w-56"})]},w))}),N("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:se(Le,{children:[N(Oe,{children:se(me,{children:[N(O,{children:"Person"}),N(O,{children:"Came from"}),N(O,{children:"Latest message"}),N(O,{children:"Last activity"}),N(O,{className:"af-w-8"}),N(O,{className:"af-w-8"})]})}),N(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(w=>se(me,{children:[N(B,{children:N(Q,{className:"af-h-4 af-w-40"})}),N(B,{children:N(Q,{className:"af-h-5 af-w-24"})}),N(B,{children:N(Q,{className:"af-h-4 af-w-56"})}),N(B,{children:N(Q,{className:"af-h-4 af-w-24"})}),N(B,{}),N(B,{})]},w))})]})}),N("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)j=se("div",{children:[L,N("div",{className:"af-flex af-justify-center af-py-8",children:N(jt,{message:"Couldn't load your leads.",onRetry:()=>p()})})]});else if(C.length===0&&o===0){let w=!!g||R!=="all";j=se("div",{children:[w&&L,w?N(Ta,{children:g?"Nobody matches that search.":R==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):N(Ta,{icon:N(nd,{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)j=se("div",{children:[L,N(Ta,{children:"No more results."}),N("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:se(S,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[N(_i,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let w=o*f+1,K=o*f+t.length;j=se("div",{children:[L,N("div",{className:"af-space-y-3 lg:af-hidden",children:C.map((u,z)=>se("div",{onClick:()=>M(u),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[se("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[se("div",{className:"af-min-w-0",children:[N("button",{type:"button",onClick:le=>{le.stopPropagation(),M(u)},"aria-label":`Open ${u.name||u.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:Ci(u)}),u.name&&u.email&&N("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:u.email})]}),se("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[N("span",{className:"af-text-xs af-text-muted-foreground",children:bs(u.last_activity_at)}),u.email&&N(S,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:N("a",{href:rr(u.email),onClick:le=>le.stopPropagation(),"aria-label":`Email ${u.email}`,children:N(nr,{className:"af-h-4 af-w-4"})})})]})]}),N("div",{className:"af-mt-2",children:Ti(u)}),u.latest_message_excerpt&&N("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:u.latest_message_excerpt})]},u.email??u.submission_id??z))}),N("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:se(Le,{children:[N(Oe,{children:se(me,{children:[N(O,{children:"Person"}),N(O,{children:"Came from"}),N(O,{children:"Latest message"}),N(O,{children:"Last activity"}),N(O,{className:"af-w-8",children:N("span",{className:"af-sr-only",children:"Reply"})}),N(O,{className:"af-w-8"})]})}),N(Be,{children:C.map((u,z)=>se(me,{onClick:()=>M(u),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[se(B,{className:"af-max-w-[260px] af-font-medium",children:[N("button",{type:"button",onClick:le=>{le.stopPropagation(),M(u)},"aria-label":`Open ${u.name||u.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:Ci(u)}),u.name&&u.email&&N("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:u.email})]}),N(B,{children:Ti(u)}),N(B,{className:"af-max-w-[320px]",children:u.latest_message_excerpt?N("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:u.latest_message_excerpt}):N("span",{className:"af-text-muted-foreground",children:"\u2014"})}),N(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:bs(u.last_activity_at)}),N(B,{className:"af-w-8",children:u.email&&N(S,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:N("a",{href:rr(u.email),onClick:le=>le.stopPropagation(),"aria-label":`Email ${u.email}`,children:N(nr,{className:"af-h-4 af-w-4"})})})}),N(B,{className:"af-w-8 af-text-right",children:N(Pi,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},u.email??u.submission_id??z))})]})}),se("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[N("span",{className:"af-text-sm af-text-muted-foreground",children:R==="all"?`Showing ${w}-${K}`:`${C.length} of ${t.length} on this page`}),se("div",{className:"af-flex af-items-center af-gap-2",children:[se(S,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!b,children:[N(_i,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),se(S,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!m,children:["Next",N(Pi,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return N(wt,{title:"Leads",onBackToWebsite:a,hideBackButton:c.kind!=="list",className:s,children:j})}import{ChevronLeft as Ai,ChevronRight as xd,Repeat as wd}from"lucide-react";import*as Bt from"react";function Sn({initialPageSize:e=25,refreshKey:a}={}){let{api:s}=ae(),[t,n]=Bt.useState([]),[i,o]=Bt.useState(0),[f,m]=Bt.useState(!0),[b,r]=Bt.useState(null),[g,y]=Bt.useState(0),[p,c]=Bt.useState(e),[d,v]=Bt.useState(void 0),h=Bt.useRef(0),R=Bt.useCallback(async()=>{let M=++h.current;try{m(!0),r(null);let l={limit:p,offset:g*p};d&&(l.status=d);let x=await s.getSubscriptions(l);if(M!==h.current)return;n(x.subscriptions),o(x.total)}catch(l){if(M!==h.current)return;r(l instanceof Error?l:new Error("Failed to fetch subscriptions"))}finally{M===h.current&&m(!1)}},[s,g,p,d,a]);Bt.useEffect(()=>{R()},[R]);let E=Math.ceil(i/p);return{subscriptions:t,total:i,isLoading:f,error:b,page:g,pageSize:p,hasNextPage:g<E-1,hasPreviousPage:g>0,setPage:y,setPageSize:M=>{c(M),y(0)},status:d,setStatus:M=>{v(M),y(0)},refetch:R}}import{jsx as J,jsxs as Ge}from"react/jsx-runtime";function Di(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 Li({sub:e}){return e.status==="canceled"?J(Z,{variant:"outline",children:"Canceled"}):e.status==="past_due"?J(Z,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?J(Z,{variant:"warning",children:"Scheduled to cancel"}):J(Z,{variant:"success",children:"Active"}):J(Z,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Nd(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 Oi({sub:e}){let a=e.current_amount!==e.plan_amount;return Ge("div",{children:[J("div",{className:"af-font-medium af-tabular-nums",children:Nd(e,e.current_amount)}),a&&Ge("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",H(e.plan_amount,e.currency)]})]})}function Bi(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Di(e.current_period_end)}`:"Ends at period end":e.current_period_end?Di(e.current_period_end):"\u2014"}function Fi({refreshKey:e,onBackToWebsite:a,className:s}){let{subscriptions:t,total:n,isLoading:i,error:o,page:f,pageSize:m,hasNextPage:b,hasPreviousPage:r,setPage:g,refetch:y}=Sn({refreshKey:e}),p;if(i)p=Ge("div",{children:[J("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(c=>Ge("div",{className:"af-rounded-md af-border af-p-3",children:[Ge("div",{className:"af-flex af-items-center af-justify-between",children:[J(Q,{className:"af-h-4 af-w-40"}),J(Q,{className:"af-h-4 af-w-20"})]}),J(Q,{className:"af-mt-2 af-h-3 af-w-32"}),J(Q,{className:"af-mt-2 af-h-5 af-w-24"})]},c))}),J("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ge(Le,{children:[J(Oe,{children:Ge(me,{children:[J(O,{children:"Subscriber"}),J(O,{children:"Plan"}),J(O,{className:"af-text-right",children:"Amount"}),J(O,{children:"Renews"}),J(O,{children:"Status"})]})}),J(Be,{"aria-hidden":"true",children:[0,1,2,3,4].map(c=>Ge(me,{children:[J(B,{children:J(Q,{className:"af-h-4 af-w-44"})}),J(B,{children:J(Q,{className:"af-h-4 af-w-32"})}),J(B,{className:"af-text-right",children:J(Q,{className:"af-ml-auto af-h-4 af-w-24"})}),J(B,{children:J(Q,{className:"af-h-4 af-w-24"})}),J(B,{children:J(Q,{className:"af-h-5 af-w-20"})})]},c))})]})}),J("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=J("div",{className:"af-flex af-justify-center af-py-8",children:J(jt,{message:"Couldn't load your subscriptions.",onRetry:()=>y()})});else if(t.length===0&&f===0)p=J(Ta,{icon:J(wd,{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=Ge("div",{children:[J(Ta,{children:"No more results."}),J("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:Ge(S,{variant:"outline",size:"sm",onClick:()=>g(f-1),children:[J(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=f*m+1,d=f*m+t.length;p=Ge("div",{children:[J("div",{className:"af-space-y-3 lg:af-hidden",children:t.map(v=>Ge("div",{className:"af-rounded-md af-border af-p-3",children:[Ge("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[Ge("div",{className:"af-min-w-0",children:[J("div",{className:"af-truncate af-text-sm af-font-medium",children:v.customer_email||J("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),J("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:v.plan_title||"Untitled plan"})]}),J("div",{className:"af-shrink-0 af-text-right",children:J(Oi,{sub:v})})]}),Ge("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[J(Li,{sub:v}),v.is_test&&J(Z,{variant:"outline",children:"Test"}),J("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Bi(v)})]}),J(wa,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},v.id))}),J("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:Ge(Le,{children:[J(Oe,{children:Ge(me,{children:[J(O,{children:"Subscriber"}),J(O,{children:"Plan"}),J(O,{className:"af-text-right",children:"Amount"}),J(O,{children:"Renews"}),J(O,{children:"Status"})]})}),J(Be,{children:t.map(v=>Ge(me,{children:[J(B,{className:"af-max-w-[240px]",children:J("div",{className:"af-truncate af-font-medium",children:v.customer_email||J("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),J(B,{className:"af-max-w-[220px]",children:J("div",{className:"af-truncate",children:v.plan_title||J("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),J(B,{className:"af-whitespace-nowrap af-text-right",children:J(Oi,{sub:v})}),J(B,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bi(v)}),Ge(B,{children:[Ge("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[J(Li,{sub:v}),v.is_test&&J(Z,{variant:"outline",children:"Test"})]}),J(wa,{deliveries:v.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},v.id))})]})}),Ge("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[J("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${c}-${d} of ${n}`}),Ge("div",{className:"af-flex af-items-center af-gap-2",children:[Ge(S,{variant:"outline",size:"sm",onClick:()=>g(f-1),disabled:!r,children:[J(Ai,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),Ge(S,{variant:"outline",size:"sm",onClick:()=>g(f+1),disabled:!b,children:["Next",J(xd,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return J(wt,{title:"Subscriptions",onBackToWebsite:a,className:s,children:p})}import*as ir from"react";import{Fragment as Mi,jsx as Wt,jsxs as Rn}from"react/jsx-runtime";function Ui({refreshKey:e,initialInvoiceId:a,onBackToWebsite:s,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:f,isLoading:m,error:b,refetch:r}=ls({refreshKey:e,initialPageSize:1,includeAggregates:!0}),g=ps({refreshKey:e}),[y,p]=ir.useState(!1),[c,d]=ir.useState(null),v=Wt("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:b||!m&&!f?Rn("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. ",Wt(S,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):m||!f?Rn(Mi,{children:[Wt(Ke,{label:"Outstanding",children:Wt(Q,{className:"af-h-6 af-w-24"})}),Wt(Ke,{label:"Overdue",children:Wt(Q,{className:"af-h-6 af-w-24"})}),Wt(Ke,{label:"Paid this month",children:Wt(Q,{className:"af-h-6 af-w-24"})})]}):Rn(Mi,{children:[Wt(Ke,{label:"Outstanding",detail:`${f.outstanding.count} open`,children:H(f.outstanding.amount,f.currency)}),Wt(Ke,{label:"Overdue",detail:f.overdue.count===0?"Nothing overdue":`${f.overdue.count} overdue`,valueClassName:f.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:H(f.overdue.amount,f.currency)}),Wt(Ke,{label:"Paid this month",detail:`${f.paid_this_month.count} paid`,children:H(f.paid_this_month.amount,f.currency)})]})});return Rn(wt,{title:"Invoices",onBackToWebsite:s,hideBackButton:y,className:o,children:[v,!y&&Wt(us,{retainers:g.retainers,isLoading:g.isLoading,error:g.error,onRetry:()=>void g.refetch(),activeRetainerId:c?.id??null,onShowCycles:h=>d(R=>R?.id===h.id?null:h),total:g.total,endedTotal:g.endedTotal,isLoadingMore:g.isLoadingMore,onLoadMore:()=>void g.loadMore(),includeEnded:g.includeEnded,onIncludeEndedChange:g.setIncludeEnded}),Wt(ds,{refreshKey:e,initialInvoiceId:a,onDetailOpenChange:p,onConnectStripe:t,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:c?{id:c.id,label:`${c.customer_name??c.customer_email??"Recurring invoices"} \u2014 ${c.description}`}:null,onClearRetainerFilter:()=>d(null)})]})}import*as Mt from"react";var Sd=2e3,Ft=()=>({data:null,error:null,isLoading:!0});function _n(e,{refreshKey:a,breakdowns:s=[],filters:t=[]}={}){let{api:n}=ae(),[i,o]=Mt.useState(Ft),[f,m]=Mt.useState(Ft),[b,r]=Mt.useState(Ft),[g,y]=Mt.useState(Ft),p=L=>Object.fromEntries(L.map(w=>[w,Ft()])),[c,d]=Mt.useState(()=>p(s)),v=Mt.useRef(0),h=s.join(","),R=JSON.stringify(t),E=`${e}:${h}:${R}`,[M,l]=Mt.useState({api:n,fetchIdentity:E});(M.api!==n||M.fetchIdentity!==E)&&(l({api:n,fetchIdentity:E}),v.current+=1,o(Ft),m(Ft),r(Ft),y(Ft),d(p(h?h.split(","):[])));let x=Mt.useCallback(async()=>{let L=++v.current,w=h?h.split(","):[];o(Ft),m(Ft),r(Ft),y(Ft),d(Object.fromEntries(w.map(G=>[G,Ft()])));let K=(G,oe)=>oe.then(ce=>{L===v.current&&G({data:ce,error:null,isLoading:!1})},ce=>{L===v.current&&G({data:null,error:ce instanceof Error?ce:new Error("Failed to fetch report"),isLoading:!1})}),u=n.getAnalyticsStatus(),z=K(o,u),le=Symbol("status-timeout"),ie,X=await Promise.race([u.then(G=>G,()=>null),new Promise(G=>{ie=setTimeout(()=>G(le),Sd)})]);if(clearTimeout(ie),L!==v.current)return;if(X===le&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),X!==null&&X!==le&&(X.collecting!==!0||X.first_seen===null&&!X.first_seen_unavailable||X.first_seen!==null&&X.first_seen_in_reports===!1)){let G={data:null,error:null,isLoading:!1};m(G),r(G),y(G),d(Object.fromEntries(w.map(oe=>[oe,{...G}]))),await z;return}await Promise.all([X===le?Promise.resolve():z,K(m,n.getAnalyticsSummary(e,t)),K(r,n.getAnalyticsTimeseries(e,t)),K(y,n.getAnalyticsChannels(e,t)),...w.map(G=>n.getAnalyticsBreakdown(G,e,t).then(oe=>{L===v.current&&d(ce=>({...ce,[G]:{data:oe,error:null,isLoading:!1}}))},oe=>{L===v.current&&d(ce=>({...ce,[G]:{data:null,error:oe instanceof Error?oe:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,h,R]),C=Mt.useCallback(async()=>{let L=v.current;try{let w=await n.getAnalyticsStatus();if(L!==v.current)return;o({data:w,error:null,isLoading:!1})}catch(w){if(L!==v.current)return;o(K=>({data:K.data,error:w instanceof Error?w:new Error("Failed to fetch status"),isLoading:!1}))}},[n]);Mt.useEffect(()=>{x()},[x,a]);let j=i.isLoading||f.isLoading||b.isLoading||g.isLoading||Object.values(c).some(L=>L.isLoading);return{status:i,summary:f,timeseries:b,channels:g,breakdowns:c,isLoading:j,refetch:x,refetchStatus:C}}import*as dt from"react";var or=3e4,lr=3;function Pn(e={}){let a="collecting"in e,{collecting:s,statusFailed:t=!1,identity:n}=e,{api:i}=ae(),[o,f]=dt.useState(null),[m,b]=dt.useState(null),[r,g]=dt.useState(!1),[y,p]=dt.useState(null),[c,d]=dt.useState(!1),[v,h]=dt.useState(!0),[R,E]=dt.useState(0),M=dt.useRef(0),l=dt.useRef(0),x=dt.useRef(void 0);s!==void 0&&(x.current=s);let C=a?x.current===!0||x.current===void 0&&t:!0,[j,L]=dt.useState({api:i,identity:n}),w=n!==void 0&&n!==j.identity;(j.api!==i||w)&&(x.current=void 0,L({api:i,identity:n}),l.current+=1,M.current=0,f(null),b(null),g(!1),p(null),d(!1),h(!0),E(0));let K=dt.useRef(()=>{}),u=dt.useRef(null),z=dt.useCallback(async()=>{if(u.current!==null&&u.current===l.current)return;let le=++l.current;u.current=le;try{let ie=await i.getAnalyticsRealtime();if(le!==l.current)return;if(ie.status==="unreachable"){d(!0),g(!0),h(!1),E(X=>X+1);return}M.current=0,d(!1),f(ie.data.current_visitors),b(ie.as_of),g(!1),p(null),h(!1),E(X=>X+1)}catch(ie){if(le!==l.current)return;M.current+=1,h(!1),E(X=>X+1),g(!0),M.current>=lr&&p(ie instanceof Error?ie:new Error("Realtime unavailable"))}finally{u.current===le&&(u.current=null)}},[i]);return K.current=()=>void z(),dt.useEffect(()=>{let le,ie=()=>{le===void 0&&(le=setInterval(()=>K.current(),or))},X=()=>{le!==void 0&&(clearInterval(le),le=void 0)},be=()=>{typeof document<"u"&&document.hidden?X():(K.current(),ie())};return C?((typeof document>"u"||!document.hidden)&&(K.current(),ie()),document?.addEventListener("visibilitychange",be),()=>{X(),document?.removeEventListener("visibilitychange",be),l.current+=1}):()=>{document?.removeEventListener("visibilitychange",be)}},[j.api,j.identity,C]),{currentVisitors:o,asOf:m,isStale:r,error:y,isUnreachable:c,isInitialLoad:v,polls:R}}import*as We from"react";import*as ns from"react";var Rd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function va(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?va(o*t):`${o}${n}`}return String(e)}function Tn(e){return`${(e*100).toFixed(1)}%`}function Es(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 $i(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`:Es(a)}function Hi(e){let a=e*100;return Number.isInteger(a)?`${a}%`:`${a.toFixed(1)}%`}function zi(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 Is(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function qi(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 cr(e){let a=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${Rd[a-1]} ${s}`}function Vi(e,a){return new Intl.DateTimeFormat("en-CA",{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function _d(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function ji(e,a,s="UTC"){let t=new Map(a.map(o=>[o.date,o])),n=[],i=Vi(e.to,s);for(let o=Vi(e.from,s);o<i;o=_d(o))n.push(t.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Gi(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 Td,jsx as Ja,jsxs as Pd}from"react/jsx-runtime";function Wi({what:e="This report",onRetry:a,collecting:s}){return Pd("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:[Ja("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),Ja("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?Ja("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 Ki({what:e="No data"}){return Ja("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 As({sourced:e,error:a,isLoading:s,what:t,onRetry:n,collecting:i,children:o}){return s?Ja("div",{role:"status","aria-label":`Loading ${t}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):a?Ja(Wi,{what:t,onRetry:n,collecting:i}):!e||e.status==="unreachable"?Ja(Wi,{what:t,onRetry:n,collecting:i}):Ja(Td,{children:o(e.data)})}import{Fragment as Cd,jsx as Ut,jsxs as ss}from"react/jsx-runtime";function dr({rows:e,dimension:a,metric:s,metricLabel:t,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:f,maxRows:m=9}){let[b,r]=ns.useState(!1);if(e.length===0)return Ut(Ki,{what:i});let g=e.reduce((c,d)=>Math.max(c,Number(d[s]??0)),0)||1,y=Math.max(0,e.length-m),p=b?e:e.slice(0,m);return ss(Cd,{children:[ss("table",{className:"af-w-full af-text-sm",children:[Ut("thead",{children:ss("tr",{className:"af-text-xs af-text-muted-foreground",children:[Ut("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:a==="pathname"?"Page":"Name"}),Ut("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:t})]})}),Ut("tbody",{children:p.map((c,d)=>{let v=Number(c[s]??0),h=c[a]??null,R=Is(h),E=n?c[n]:null,M=h!==null&&(f?f(h,E):!0);return ss("tr",{className:"af-border-t af-border-border",children:[ss("td",{className:"af-relative af-py-1.5 af-pr-2",children:[Ut("span",{"aria-hidden":"true",className:"af-absolute af-inset-y-0.5 af-left-0 af-rounded-sm af-bg-muted",style:{width:`${Math.max(2,v/g*100)}%`}}),h!==null&&o&&M?Ut("button",{type:"button",onClick:()=>o(h,E),title:`Filter by ${R}`,"aria-label":`Filter by ${R}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:R}):Ut("span",{className:"af-relative af-break-words af-text-foreground",children:R}),E?Ut("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:E}):null]}),Ut("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:va(v)})]},`${R}-${E??""}-${d}`)})})]}),y>0?Ut("button",{type:"button",onClick:()=>r(c=>!c),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:b?"Show fewer":`Show all ${e.length}`}):null]})}function Ds({title:e,tabs:a,defaultTabId:s,headerRight:t}){let[n,i]=ns.useState(s),o=a.find(p=>p.id===n)??a[0],f=ns.useId(),m=p=>`${f}-tab-${p}`,b=p=>`${f}-panel-${p}`,r=ns.useRef(null),g=(p,c)=>{p.preventDefault();let d=(c+a.length)%a.length;i(a[d].id),r.current?.querySelectorAll('[role="tab"]')?.[d]?.focus()};return ss("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[ss("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:[Ut("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:p=>{let c=a.findIndex(d=>d.id===n);p.key==="ArrowRight"&&g(p,c+1),p.key==="ArrowLeft"&&g(p,c-1),p.key==="Home"&&g(p,0),p.key==="End"&&g(p,a.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:a.map(p=>Ut("button",{id:m(p.id),role:"tab",type:"button","aria-selected":p.id===n,"aria-controls":b(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?Ut("div",{id:b(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 Vt from"react";import*as Ya from"@radix-ui/react-popover";var ys=3,hs=100;import{jsx as at,jsxs as Aa}from"react/jsx-runtime";var Ls={channel:"Channel",source:"Source",campaign:"Campaign",utm_source:"UTM source",utm_medium:"UTM medium",utm_content:"UTM content",utm_term:"UTM term",page:"Page",entry_page:"Entry page",exit_page:"Exit page",country:"Country",region:"Region",city:"City",browser:"Browser",os:"Operating system",device:"Device"},kd=Object.keys(Ls);function Ji(e){let a=Ls[e.dimension],s=e.operator==="is_not"?"is not":"is",t=e.values.map(n=>Is(n)).join(" or ");return`${a} ${s} ${t}`}function ur(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 Ed(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 Yi(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 Id(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Zi(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=Ed(e.byDimension,s);for(let[i,o]of Object.entries(t)){let f=e.foldsByLabel.get(i)??new Set;for(let m of o)f.add(m);e.foldsByLabel.set(i,f)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Qi(e){let{filters:a,onChange:s}=e,t=a.length>=3;return Vt.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]),Aa("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[a.map((n,i)=>Aa("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:[at("span",{className:"af-text-foreground",children:Ji(n)}),at("button",{type:"button","aria-label":`Remove filter ${Ji(n)}`,onClick:()=>s(a.filter((o,f)=>f!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),at(Ad,{...e,disabled:t}),a.length>0?at("button",{type:"button",onClick:()=>s([]),className:"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"Clear all"}):null]})}function Ad({filters:e,onChange:a,suggestions:s,resetKey:t,disabled:n,expandValues:i}){let[o,f]=Vt.useState(!1),m=Vt.useRef(null),[b,r]=Vt.useState(null);Vt.useEffect(()=>{r(m.current?.closest(".aifeatures-admin")??null)},[]);let[g,y]=Vt.useState(null),[p,c]=Vt.useState("is"),[d,v]=Vt.useState(""),[h,R]=Vt.useState([]);Vt.useEffect(()=>{o||(y(null),c("is"),v(""),R([]))},[o]);let E=Vt.useRef(t);E.current!==t&&(E.current=t,o&&f(!1),g!==null&&y(null),h.length>0&&R([]),d!==""&&v(""),p!=="is"&&c("is"));let M=w=>{let K=Id(w);y(K.dimension),R(K.picked),v(K.search),c(K.operator)},x=(g?s[g]??[]:[]).filter(w=>w.toLowerCase().includes(d.trim().toLowerCase())),C=g===null||h.length===0?null:ur(e,{dimension:g,operator:p,values:i?i(g,h):h}),j=C!==null&&C!==e,L=()=>{let w=C;!w||w===e||(a(w),f(!1))};return Aa(Ya.Root,{open:o,onOpenChange:f,children:[at(Ya.Trigger,{asChild:!0,children:at("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"})}),at(Ya.Portal,{container:b,children:at(Ya.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:g===null?Aa("div",{children:[at("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),at("div",{className:"af-max-h-96 af-overflow-y-auto",children:kd.filter(w=>s[w]!==void 0).map(w=>{let K=s[w]?.length??0,u=!e.some(z=>z.dimension===w)&&e.length>=3;return Aa("button",{type:"button",onClick:()=>M(w),disabled:K===0||u,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:[at("span",{children:Ls[w]}),at("span",{className:"af-text-muted-foreground",children:K===0?"no data":u?"no room":K})]},w)})})]}):Aa("div",{children:[Aa("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[at("button",{type:"button",onClick:()=>M(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),at("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Ls[g]}),Aa("select",{"aria-label":"Operator",value:p,onChange:w=>c(w.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:[at("option",{value:"is",children:"is"}),at("option",{value:"is_not",children:"is not"})]})]}),at("input",{type:"text",value:d,onChange:w=>v(w.target.value),placeholder:"Search\u2026","aria-label":`Search ${Ls[g]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),at("div",{className:"af-max-h-48 af-overflow-y-auto",children:x.length===0?Aa("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",d,"\u201D."]}):x.map(w=>Aa("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:[at("input",{type:"checkbox",checked:h.includes(w),disabled:!h.includes(w)&&h.length>=100,onChange:K=>R(u=>K.target.checked?[...u,w]:u.filter(z=>z!==w))}),at("span",{className:"af-break-all",children:Is(w)})]},w))}),at("button",{type:"button",onClick:L,disabled:!j,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:h.length<=1?"Apply filter":h.length>=100?`Apply filter (${h.length} values \u2014 the maximum)`:`Apply filter (${h.length} values)`})]})})})]})}import{Fragment as Od,jsx as kt,jsxs as Cn}from"react/jsx-runtime";var Dd=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:va,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:va,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:va,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:Tn,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Es,chart:"visit_duration_seconds"}];function Ld({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 kt("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 Xi({summary:e,selected:a,onSelect:s}){return kt("div",{className:"af-@container",children:kt("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Dd.map(t=>{let n=t.chart===a,i=s!==void 0,o=Cn(Od,{children:[kt("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:t.label}),Cn("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[kt("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:t.format(t.get(e.current))}),e.previous?kt(Ld,{current:t.get(e.current),previous:t.get(e.previous),downIsGood:t.downIsGood}):null]})]});return i?kt("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):kt("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},t.key)})})})}function fr({currentVisitors:e,asOf:a,isStale:s,isUnreachable:t,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!t)return Cn("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:[kt("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),kt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(t||e===null)return kt("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=a?qi(a):"freshness unknown",f=i?" across the whole site, not the current filter,":"",m=s?`${e} current visitors${f} ${o} (not updating)`:`${e} current visitors${f} ${o}`;return Cn("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:[kt("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"}),kt("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),kt("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),kt("span",{className:"af-sr-only",children:m})]})}import{Area as Bd,AreaChart as Fd,CartesianGrid as Md,ResponsiveContainer as Ud,Tooltip as Vd,XAxis as $d,YAxis as Hd}from"recharts";import{jsx as Et,jsxs as Os}from"react/jsx-runtime";var kn={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},pr={visitors:va,visits:va,pageviews:va,views_per_visit:e=>e.toFixed(2),bounce_rate:Tn,visit_duration_seconds:Es},zd=new Set(["visitors","visits","pageviews"]),qd={...pr,bounce_rate:Hi,visit_duration_seconds:$i},mr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],jd=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Gd=[.01,.02,.05,.1,.2,.25,.5,1],Wd=[.25,.5,1,2,5,10,25,50],Kd={visitors:mr,visits:mr,pageviews:mr,views_per_visit:Wd,bounce_rate:Gd,visit_duration_seconds:jd};function Jd({active:e,payload:a,label:s,metric:t}){if(!e||!a||a.length===0)return null;let n=a[0].payload;return Os("div",{className:"af-rounded-lg af-border af-border-border af-bg-popover af-px-3 af-py-2 af-text-popover-foreground af-shadow-md",children:[Et("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:kn[t]}),Os("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[Et("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),Et("span",{className:"af-text-muted-foreground",children:Gi(String(s))}),Et("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:pr[t](Number(n[t]??0))})]})]})}function eo({rows:e,window:a,metric:s,timeZone:t="UTC",height:n=260}){let i=ji(a,e,t),o=pr[s],f=qd[s],m=zi(i.reduce((r,g)=>Math.max(r,Number(g[s]??0)),0),Kd[s]),b=`${kn[s]} by day: ${i.map(r=>`${cr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return Os("figure",{"aria-label":`${kn[s]} over time`,className:"af-m-0",children:[Et(Ud,{width:"100%",height:n,children:Os(Fd,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[Et("defs",{children:Os("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[Et("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),Et("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),Et(Md,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),Et($d,{dataKey:"date",tickFormatter:cr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),Et(Hd,{allowDecimals:!zd.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...m?{ticks:m,domain:[0,m[m.length-1]]}:{},tickFormatter:r=>f(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),Et(Vd,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:Et(Jd,{metric:s})}),Et(Bd,{type:"monotone",dataKey:s,name:kn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),Et("figcaption",{className:"af-sr-only",children:b})]})}import{Fragment as to,jsx as Te,jsxs as ba}from"react/jsx-runtime";var Yd=3e4,Zd="2026-08-13",Qd=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Xd=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function eu({filters:e,onFiltersChange:a,refreshKey:s,onBackToWebsite:t,className:n,published:i,lastPublishedAt:o}){let[f,m]=We.useState(30),b=e!==void 0&&a!==void 0,[r,g]=We.useState(e??[]),{api:y}=ae(),[p,c]=We.useState(y);p!==y&&(c(y),!b&&r.length>0&&g([]));let d=b?e:r,v=We.useCallback(Y=>{a&&a(Y),b||g(Y)},[a,b]),h=We.useCallback((Y,ee,ve)=>{let _=Array.isArray(ee)?ee:[ee];if(_.length===0)return null;let A=ur(d,{dimension:Y,operator:"is",values:_});if(ve&&(!ve.value||(A=Yi(A,{dimension:ve.dimension,operator:"is",values:[ve.value]}),!A.find(ke=>ke.dimension===ve.dimension&&ke.operator!=="is_not")?.values.includes(ve.value))))return null;let fe=A.find(Ce=>Ce.dimension===Y&&Ce.operator!=="is_not");return _.every(Ce=>fe?.values.includes(Ce))?JSON.stringify(A)===JSON.stringify(d)?null:A:null},[d]),R=We.useCallback((Y,ee,ve)=>h(Y,ee,ve)!==null,[h]),E=We.useCallback((Y,ee,ve)=>{let _=h(Y,ee,ve);_&&v(_)},[h,v]),[M,l]=We.useState("visitors"),x=_n(f,{refreshKey:s,breakdowns:Xd,filters:d}),C=x.status.data,j=i===!1,L=C!=null&&(!C.collecting||j&&C.first_seen===null&&!C.first_seen_unavailable),w=!L&&C?.collecting===!0&&C.first_seen===null&&!C.first_seen_unavailable,K=C?.collecting===!0&&C.first_seen!==null&&C.first_seen_in_reports===!1,u=w||K,z=Pn({collecting:w||L?!1:C?.collecting,statusFailed:x.status.error!=null,identity:C?.analytics_id}),le=We.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),ie=We.useMemo(()=>{let Y=x.breakdowns.sources?.data,ee={};if(!Y||Y.status!=="ok")return ee;for(let ve of Y.data){let _=ve.source,A=ve.sources;typeof _=="string"&&Array.isArray(A)&&A.length>0&&(ee[_]=A)}return ee},[x.breakdowns.sources?.data]),X=We.useMemo(()=>{let Y=(_,A)=>{let fe=x.breakdowns[_]?.data;return!fe||fe.status!=="ok"?[]:[...new Set(fe.data.map(Ce=>Ce[A]).filter(Ce=>typeof Ce=="string"&&Ce!==""))]};return{channel:x.channels.data?.status==="ok"?[...new Set(x.channels.data.data.map(_=>_.channel))]:[],source:Y("sources","source"),campaign:Y("utm/campaign","campaign"),page:Y("pages","pathname"),entry_page:Y("entry-pages","pathname"),exit_page:Y("exit-pages","pathname"),country:Y("countries","country"),browser:Y("browsers","browser"),os:Y("operating-systems","os"),device:Y("devices","device")}},[x.breakdowns,x.channels.data]),[be,G]=We.useState({}),oe=JSON.stringify(X),[ce,q]=We.useState(new Map),he=JSON.stringify(ie);We.useEffect(()=>{let{suggestions:Y,folds:ee}=Zi(le.current,{api:y,period:f},JSON.parse(oe),JSON.parse(he));G(Y),q(ee)},[oe,he,y,f]);let ut=We.useCallback((Y,ee)=>Y!=="source"?ee:[...new Set(ee.flatMap(ve=>{let _=[...ce.get(ve)??[],...ie[ve]??[]];return _.length>0?_:[ve]}))],[ce,ie]),bt=We.useMemo(()=>{let Y=[x.summary,x.timeseries,x.channels,...Object.values(x.breakdowns)];for(let ee of Y){let ve=ee?.error;if(ve instanceof ya&&ve.details?.code==="filter_unsupported")return ve.message}return null},[x.summary,x.timeseries,x.channels,x.breakdowns]),xe=(Y,ee,ve,_,A,fe,Ce,ke,Ve)=>()=>{let $e=x.breakdowns[Y];return Te(As,{sourced:$e?.data??null,error:$e?.error,isLoading:$e?.isLoading,what:ee,collecting:C?.collecting,onRetry:x.refetch,children:St=>{let ta=yt=>ke?ut(ke,[yt]):yt;return Te(dr,{rows:St,dimension:ve,metric:_,metricLabel:A,secondary:fe,emptyCopy:d.length>0?"No data for this filter":Ce,canFilter:ke?(yt,te)=>R(ke,ta(yt),Ve?{dimension:Ve,value:te}:void 0):()=>!1,onFilter:ke?(yt,te)=>E(ke,ta(yt),Ve?{dimension:Ve,value:te}:void 0):void 0})}})};We.useEffect(()=>{if(!u)return;let Y,ee=()=>{Y===void 0&&(Y=setInterval(()=>void x.refetchStatus(),Yd))},ve=()=>{Y!==void 0&&(clearInterval(Y),Y=void 0)},_=()=>{typeof document<"u"&&document.hidden?ve():(x.refetchStatus(),ee())};return(typeof document>"u"||!document.hidden)&&ee(),document?.addEventListener("visibilitychange",_),()=>{ve(),document?.removeEventListener("visibilitychange",_)}},[u,x.refetchStatus]);let ft=We.useRef(void 0);if(We.useEffect(()=>{if(!C){ft.current=void 0;return}let Y=ft.current;ft.current=u,Y===!0&&!u&&x.refetch()},[C,u,x.refetch]),L){let Y=!!o&&String(o).slice(0,10)<Zd;return Te(wt,{title:"Analytics",onBackToWebsite:t,className:n,children:ba("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),Te("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:j?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":Y?"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 w?Te(wt,{title:"Analytics",onBackToWebsite:t,className:n,children:ba("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),Te("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."})]})}):K?Te(wt,{title:"Analytics",onBackToWebsite:t,className:n,children:ba("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),ba("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:["Analytics is working and your first visit is in. Reports cover whole days, so today\u2019s traffic appears here after midnight",C?.timezone?` ${C.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),Te("div",{className:"af-mt-4 af-flex af-justify-center",children:Te(fr,{currentVisitors:z.currentVisitors,asOf:z.asOf,isStale:z.isStale,isUnreachable:z.isUnreachable||z.error!==null,isInitialLoad:z.isInitialLoad})})]})}):Te(wt,{title:"Analytics",onBackToWebsite:t,className:n,children:ba("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[ba("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[Te("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Qd.map(Y=>Te("button",{type:"button","aria-pressed":Y.value===f,onClick:()=>m(Y.value),className:Y.value===f?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:Y.label},Y.value))}),Te(fr,{currentVisitors:z.currentVisitors,asOf:z.asOf,isStale:z.isStale,isUnreachable:z.isUnreachable||z.error!==null,isInitialLoad:z.isInitialLoad,scopeIsSiteWide:d.length>0})]}),Te(Qi,{filters:d,onChange:v,suggestions:be,expandValues:ut,resetKey:y}),bt?ba("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[Te("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),Te("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:bt}),Te("button",{type:"button",onClick:()=>v([]),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,!bt&&C?.timezone_defaulted?Te("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,bt?null:ba(to,{children:[Te(As,{sourced:x.summary.data,error:x.summary.error,isLoading:x.summary.isLoading,what:"The traffic summary",collecting:C?.collecting,onRetry:x.refetch,children:Y=>ba(to,{children:[Te(Xi,{summary:Y,selected:M,onSelect:l}),Y.previous_unavailable?ba("p",{className:"af-text-xs af-text-muted-foreground",children:[Y.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]})}),Te("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:Te(As,{sourced:x.timeseries.data,error:x.timeseries.error,isLoading:x.timeseries.isLoading,what:"The visitors chart",collecting:C?.collecting,onRetry:x.refetch,children:Y=>{let ee=x.timeseries.data?.status==="ok"?x.timeseries.data.window:{from:"",to:""};return Te(eo,{rows:Y,window:ee,metric:M,timeZone:(x.timeseries.data?.status==="ok"?x.timeseries.data.timezone:void 0)??C?.timezone??"UTC"})}})}),ba("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[Te(Ds,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>Te(As,{sourced:x.channels.data,error:x.channels.error,isLoading:x.channels.isLoading,what:"Channels",collecting:C?.collecting,onRetry:x.refetch,children:Y=>Te(dr,{rows:Y,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:d.length>0?"No data for this filter":"No data for this period",canFilter:ee=>R("channel",ee),onFilter:ee=>E("channel",ee)})})},{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")}]}),Te(Ds,{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")}]}),Te(Ds,{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")}]}),Te(Ds,{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{ya as AifeaturesApiError,io as AifeaturesProvider,eu as AnalyticsView,ln as CustomerDetail,dn as CustomersList,Ks as FormSettings,qs as FormSubmissions,Lr as FormsDashboard,Us as FormsList,Zn as InvoiceDetail,Ts as InvoiceLabelBadge,ds as InvoicesList,Ui as InvoicesView,Ii as LeadsView,ys as MAX_ANALYTICS_FILTERS,hs as MAX_ANALYTICS_FILTER_VALUES,sn as OrderDetail,Xa as OrderStatusBadge,os as OrdersList,vi as OrdersView,mi as PaymentsDashboard,pn as PaymentsSetup,Qs as ProductSettings,Ys as ProductsList,Ri as ProductsView,lr as REALTIME_FAILURES_BEFORE_ERROR,or as REALTIME_POLL_MS,Qn as RetainerStatusBadge,us as RetainersPanel,zs as SubmissionDetail,Fi as SubscriptionsView,Zs as VariantsEditor,wt as ViewShell,Gs as WebhookDeliveries,Ws as WebhookSettings,ua as chargedTotal,In as createApiClient,H as formatPrice,Ra as isZeroDecimalCurrency,xt as toMajorUnits,fa as toMinorUnits,ae as useAifeatures,ae as useAifeaturesContext,_n as useAnalytics,gn as useBusinessSummary,on as useCustomers,js as useEventDestinations,rs as useForms,ls as useInvoices,Xs as useOrders,fs as usePaymentsStatus,wn as usePeople,Nn as usePerson,ms as useProducts,Pn as useRealtimeVisitors,ps as useRetainers,Hs as useSubmissions,Sn as useSubscriptions};