@aifeatures/admin-react 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +84 -3
- package/dist/index.d.ts +84 -3
- package/dist/index.js +4 -4
- package/package.json +14 -13
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var Yi=Object.create;var sn=Object.defineProperty;var Zi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty;var to=(e,t)=>{for(var s in t)sn(e,s,{get:t[s],enumerable:!0})},wr=(e,t,s,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Qi(t))!eo.call(e,n)&&n!==s&&sn(e,n,{get:()=>t[n],enumerable:!(a=Zi(t,n))||a.enumerable});return e};var ue=(e,t,s)=>(s=e!=null?Yi(Xi(e)):{},wr(t||!e||!e.__esModule?sn(s,"default",{value:e,enumerable:!0}):s,e)),ao=e=>wr(sn({},"__esModule",{value:!0}),e);var $l={};to($l,{AifeaturesApiError:()=>Dt,AifeaturesProvider:()=>Sr,AnalyticsView:()=>qi,CustomerDetail:()=>Hs,CustomersList:()=>zs,FormSettings:()=>As,FormSubmissions:()=>Cs,FormsDashboard:()=>Mn,FormsList:()=>Ns,InvoiceDetail:()=>Nn,InvoiceLabelBadge:()=>gs,InvoicesList:()=>ns,InvoicesView:()=>ir,LeadsView:()=>sr,MAX_ANALYTICS_FILTERS:()=>us,MAX_ANALYTICS_FILTER_VALUES:()=>ds,OrderDetail:()=>$s,OrderStatusBadge:()=>Ga,OrdersList:()=>ts,OrdersView:()=>Xn,PaymentsDashboard:()=>Qn,PaymentsSetup:()=>qs,ProductSettings:()=>Fs,ProductsList:()=>Os,ProductsView:()=>er,PromosPanel:()=>Qa,REALTIME_FAILURES_BEFORE_ERROR:()=>Dn,REALTIME_POLL_MS:()=>In,RetainerStatusBadge:()=>_n,RetainersPanel:()=>rs,SubmissionDetail:()=>Rs,SubscriptionsView:()=>nr,VariantsEditor:()=>Bs,ViewShell:()=>xt,WebhookDeliveries:()=>Is,WebhookSettings:()=>Ds,chargedTotal:()=>Ra,createApiClient:()=>rn,formatPrice:()=>q,isZeroDecimalCurrency:()=>Gt,toMajorUnits:()=>rt,toMinorUnits:()=>Tt,useAifeatures:()=>ie,useAifeaturesContext:()=>ie,useAnalytics:()=>Ys,useBusinessSummary:()=>js,useCustomers:()=>Vs,useEventDestinations:()=>ks,useForms:()=>Ya,useInvoices:()=>ss,useOrders:()=>Ms,usePaymentsStatus:()=>Fa,usePeople:()=>Ws,usePerson:()=>Ks,useProducts:()=>is,useRealtimeVisitors:()=>Zs,useRetainers:()=>os,useSubmissions:()=>_s,useSubscriptions:()=>Js});module.exports=ao($l);var Ha=ue(require("react"),1);function nn(e,t){let s=new URLSearchParams({period:String(e)});return t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var Dt=class extends Error{constructor(s,a,n){super(s);this.status=a;this.details=n;this.name="AifeaturesApiError"}};function Bn(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function rn(e,t="https://aifeatures.dev"){async function s(a,n={}){let i=`${t}${a}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let v;try{v=await o.json()}catch{}throw new Dt(Bn(v?.error,o.status),o.status,v)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,n){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(a){await s(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,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(),v=`/api/v1/forms/${a}/submissions${o?`?${o}`:""}`;return s(v)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,n){let i=typeof n=="string"?{name:n}:n,o=i.name,v=i.id??i.name,g=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(v)}`,y=await fetch(g,{headers:{Authorization:`Bearer ${e}`}});if(!y.ok){let b;try{b=await y.json()}catch{}throw new Dt(Bn(b?.error,y.status),y.status,b)}let r=await y.blob(),h=URL.createObjectURL(r),w=document.createElement("a");w.href=h,w.download=o,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(h)},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(a){let n=new URLSearchParams({limit:"10"});return a&&n.set("cursor",a),s(`/api/v1/promos?${n}`)},getPromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,n){return s(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(n)})},async getProducts(a={}){let n=new URLSearchParams;a.include&&n.set("include",a.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,n){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,n){let i=new FormData;i.append("file",n);let o=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let v;try{v=await o.json()}catch{}throw new Dt(Bn(v?.error,o.status),o.status,v)}return o.json()},async attachProductFileFromUrl(a,n){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(a,n){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(a,n){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,n){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(a,n){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,n){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(a,n){return s(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(a={}){let n=new URLSearchParams;a.email?n.set("email",a.email):a.q&&n.set("q",a.q),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async getOrders(a={}){let n=new URLSearchParams;a.status&&n.set("status",a.status),a.source&&n.set("source",a.source),a.excludeStatus?.length&&n.set("exclude_status",a.excludeStatus.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.from&&n.set("from",a.from),a.to&&n.set("to",a.to),a.unfulfilledOnly&&n.set("unfulfilled_only","true"),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(a){return s(`/api/v1/orders/${a}`)},async getInvoices(a={}){let n=new URLSearchParams;a.labels?.length&&n.set("label",a.labels.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.customerId&&n.set("customer_id",a.customerId),a.q&&n.set("q",a.q),a.from&&n.set("from",a.from),a.to&&n.set("to",a.to),a.includeAggregates&&n.set("include","aggregates"),a.retainerId&&n.set("retainer_id",a.retainerId),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(a){return s(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return s(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(a={}){let n=new URLSearchParams;a.statuses?.length&&n.set("status",a.statuses.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(a){return s(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,n){return s(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(a={}){let n=new URLSearchParams;a.status&&n.set("status",a.status),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(a,n){return s(`/api/v1/analytics/summary?${nn(a,n)}`)},async getAnalyticsTimeseries(a,n){return s(`/api/v1/analytics/timeseries?${nn(a,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,n){return s(`/api/v1/analytics/channels?${nn(a,n)}`)},async getAnalyticsBreakdown(a,n,i){let o=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${nn(n,i)}`)},async getBusinessSummary(a){let n=new URLSearchParams;return n.set("tz_offset_minutes",String(a.tzOffsetMinutes)),s(`/api/v1/summary?${n.toString()}`)},async getPeople(a={}){let n=new URLSearchParams;a.since&&n.set("since",a.since),a.q&&n.set("q",a.q),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,n){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${i}`)).deliveries},async retryEventDelivery(a,n){return s(`/api/v1/event-destinations/${a}/deliveries/${n}/retry`,{method:"POST"})}}}var Va=require("react/jsx-runtime"),Nr=Ha.createContext(null);function so(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 Sr({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:a,children:n}){let i=Ha.useMemo(()=>so(e),[e]),o=Ha.useMemo(()=>rn(e,t),[e,t]),v=Ha.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return i?(0,Va.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:(0,Va.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Va.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Va.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,Va.jsx)(Nr.Provider,{value:v,children:(0,Va.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:n})})}function ie(){let e=Ha.useContext(Nr);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ja=ue(require("react"),1),fs=require("lucide-react");var on=ue(require("react"),1),la=ue(require("@radix-ui/react-tabs"),1);var _r=require("clsx"),Rr=require("tailwind-merge"),no=(0,Rr.extendTailwindMerge)({prefix:"af-"});function Y(...e){return no((0,_r.clsx)(e))}var cn=require("react/jsx-runtime"),ln=la.Root,xs=on.forwardRef(({className:e,...t},s)=>(0,cn.jsx)(la.List,{ref:s,className:Y("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));xs.displayName=la.List.displayName;var ca=on.forwardRef(({className:e,...t},s)=>(0,cn.jsx)(la.Trigger,{ref:s,className:Y("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));ca.displayName=la.Trigger.displayName;var ua=on.forwardRef(({className:e,...t},s)=>(0,cn.jsx)(la.Content,{ref:s,className:Y("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));ua.displayName=la.Content.displayName;var Pr=ue(require("react"),1),Cr=require("@radix-ui/react-slot"),Tr=require("class-variance-authority");var kr=require("react/jsx-runtime"),ro=(0,Tr.cva)("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"}}),_=Pr.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,...n},i)=>(0,kr.jsx)(a?Cr.Slot:"button",{className:Y(ro({variant:t,size:s,className:e})),ref:i,...n}));_.displayName="Button";var ws=require("lucide-react");var Oa=ue(require("react"),1);var xa=require("react/jsx-runtime"),Me=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,xa.jsx)("table",{ref:s,className:Y("af-w-full af-caption-bottom af-text-sm",e),...t})}));Me.displayName="Table";var Ue=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("thead",{ref:s,className:Y("[&_tr]:af-border-b",e),...t}));Ue.displayName="TableHeader";var $e=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("tbody",{ref:s,className:Y("[&_tr:last-child]:af-border-0",e),...t}));$e.displayName="TableBody";var io=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("tfoot",{ref:s,className:Y("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));io.displayName="TableFooter";var he=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("tr",{ref:s,className:Y("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));he.displayName="TableRow";var U=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("th",{ref:s,className:Y("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));U.displayName="TableHead";var $=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("td",{ref:s,className:Y("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));$.displayName="TableCell";var oo=Oa.forwardRef(({className:e,...t},s)=>(0,xa.jsx)("caption",{ref:s,className:Y("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));oo.displayName="TableCaption";var da=ue(require("react"),1);function Ya(){let{api:e}=ie(),[t,s]=da.useState([]),[a,n]=da.useState(!0),[i,o]=da.useState(null),v=da.useCallback(async()=>{try{n(!0),o(null);let h=await e.getForms();s(h)}catch(h){o(h instanceof Error?h:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);da.useEffect(()=>{v()},[v]);let g=da.useCallback(async h=>{let w=await e.createForm(h);return s(b=>[...b,w]),w},[e]),y=da.useCallback(async(h,w)=>{let b=await e.updateForm(h,w);return s(u=>u.map(l=>l.id===h?b:l)),b},[e]),r=da.useCallback(async h=>{await e.deleteForm(h),s(w=>w.filter(b=>b.id!==h))},[e]);return{forms:t,isLoading:a,error:i,refetch:v,createForm:g,updateForm:y,deleteForm:r}}var Ve=require("react/jsx-runtime");function Ns({onSelectForm:e,className:t}){let{forms:s,isLoading:a,error:n}=Ya();return a?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Ve.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,Ve.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Ve.jsx)(ws.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Ve.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Ve.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Ve.jsx)("div",{className:t,children:(0,Ve.jsxs)(Me,{children:[(0,Ve.jsx)(Ue,{children:(0,Ve.jsxs)(he,{children:[(0,Ve.jsx)(U,{children:"Name"}),(0,Ve.jsx)(U,{children:"Endpoint"}),(0,Ve.jsx)(U,{className:"af-text-right",children:"Actions"})]})}),(0,Ve.jsx)($e,{children:s.map(i=>(0,Ve.jsxs)(he,{children:[(0,Ve.jsx)($,{className:"af-font-medium",children:i.name}),(0,Ve.jsx)($,{children:(0,Ve.jsx)("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","")})}),(0,Ve.jsx)($,{className:"af-text-right",children:(0,Ve.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Ve.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,Ve.jsx)(ws.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Ve.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,Ve.jsx)(ws.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var Dr=require("lucide-react");var Er=require("class-variance-authority");var Ir=require("react/jsx-runtime"),lo=(0,Er.cva)("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 Q({className:e,variant:t,...s}){return(0,Ir.jsx)("div",{className:Y(lo({variant:t}),e),...s})}var Vt=require("react/jsx-runtime"),co={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function un(e){switch(e.state){case"sending":return{label:"Sending",variant:"secondary",detail:null};case"sent":return{label:"Sent",variant:"secondary",detail:"Accepted for sending. Delivery has not been confirmed yet."};case"delivered":return{label:"Delivered",variant:"success",detail:"Accepted by the recipient\u2019s email server. This does not confirm it was read."};case"delivery_delayed":return{label:"Delayed",variant:"warning",detail:"Delivery is delayed. The email provider is still trying."};case"bounced":return{label:"Bounced",variant:"destructive",detail:"A receiving email server rejected this message."};case"complained":return{label:"Marked as spam",variant:"destructive",detail:"A recipient marked this email as spam. Do not resend it to that recipient."};case"suppressed":return{label:"Delivery blocked",variant:"destructive",detail:"The email provider blocked delivery to a recipient after a previous delivery problem or spam complaint."};case"failed":return{label:"Send failed",variant:"destructive",detail:"The email provider reported a sending failure."};case"unknown":return{label:"Delivery unconfirmed",variant:"warning",detail:"We could not confirm whether the email was sent. Check with the recipient before sending it again."}}}function Fn(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function uo(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function Ss({deliveries:e,label:t="Email needs attention"}){return Fn(e)?(0,Vt.jsxs)("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:[(0,Vt.jsx)(Dr.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function wa({deliveries:e,problemsOnly:t=!1,className:s=""}){let a=(e??[]).filter(n=>!t||Fn([n]));return a.length?(0,Vt.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:a.map(n=>{let i=un(n),o=uo(n);return(0,Vt.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Vt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Vt.jsx)("span",{className:"af-font-medium",children:co[n.kind]??"Email notification"}),(0,Vt.jsx)(Q,{variant:i.variant,children:i.label})]}),(0,Vt.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&Fn([n])&&(0,Vt.jsx)("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&&(0,Vt.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,Vt.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var Ps=ue(require("react"),1),Na=require("lucide-react");var za=ue(require("react"),1),Te=ue(require("@radix-ui/react-select"),1),Za=require("lucide-react");var nt=require("react/jsx-runtime"),ea=Te.Root;var ta=Te.Value,Ht=za.forwardRef(({className:e,children:t,...s},a)=>(0,nt.jsxs)(Te.Trigger,{ref:a,className:Y("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:[t,(0,nt.jsx)(Te.Icon,{asChild:!0,children:(0,nt.jsx)(Za.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Ht.displayName=Te.Trigger.displayName;var Ar=za.forwardRef(({className:e,...t},s)=>(0,nt.jsx)(Te.ScrollUpButton,{ref:s,className:Y("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,nt.jsx)(Za.ChevronUp,{className:"af-h-4 af-w-4"})}));Ar.displayName=Te.ScrollUpButton.displayName;var Lr=za.forwardRef(({className:e,...t},s)=>(0,nt.jsx)(Te.ScrollDownButton,{ref:s,className:Y("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,nt.jsx)(Za.ChevronDown,{className:"af-h-4 af-w-4"})}));Lr.displayName=Te.ScrollDownButton.displayName;var zt=za.forwardRef(({className:e,children:t,position:s="popper",...a},n)=>(0,nt.jsx)(Te.Portal,{children:(0,nt.jsxs)(Te.Content,{ref:n,className:Y("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,...a,children:[(0,nt.jsx)(Ar,{}),(0,nt.jsx)(Te.Viewport,{className:Y("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,nt.jsx)(Lr,{})]})}));zt.displayName=Te.Content.displayName;var fo=za.forwardRef(({className:e,...t},s)=>(0,nt.jsx)(Te.Label,{ref:s,className:Y("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));fo.displayName=Te.Label.displayName;var qe=za.forwardRef(({className:e,children:t,...s},a)=>(0,nt.jsxs)(Te.Item,{ref:a,className:Y("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:[(0,nt.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,nt.jsx)(Te.ItemIndicator,{children:(0,nt.jsx)(Za.Check,{className:"af-h-4 af-w-4"})})}),(0,nt.jsx)(Te.ItemText,{children:t})]}));qe.displayName=Te.Item.displayName;var mo=za.forwardRef(({className:e,...t},s)=>(0,nt.jsx)(Te.Separator,{ref:s,className:Y("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));mo.displayName=Te.Separator.displayName;var aa=ue(require("react"),1);function _s({formId:e,initialPageSize:t=25}){let{api:s}=ie(),[a,n]=aa.useState([]),[i,o]=aa.useState(0),[v,g]=aa.useState(!0),[y,r]=aa.useState(null),[h,w]=aa.useState(0),[b,u]=aa.useState(t),l=aa.useCallback(async()=>{if(e)try{g(!0),r(null);let P={limit:b,offset:h*b},L=await s.getSubmissions(e,P);n(L.submissions),o(L.total)}catch(P){r(P instanceof Error?P:new Error("Failed to fetch submissions"))}finally{g(!1)}},[s,e,h,b]);aa.useEffect(()=>{l()},[l]);let x=aa.useCallback(async P=>{await s.deleteSubmission(P),n(L=>L.filter(M=>M.id!==P)),o(L=>L-1)},[s]),S=Math.ceil(i/b);return{submissions:a,total:i,isLoading:v,error:y,page:h,pageSize:b,hasNextPage:h<S-1,hasPreviousPage:h>0,setPage:w,setPageSize:P=>{u(P),w(0)},refetch:l,deleteSubmission:x}}var Br=ue(require("react"),1),Rt=require("lucide-react");var xe=require("react/jsx-runtime");function Or(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function po(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function Rs({submission:e,onBack:t}){let{api:s}=ie(),[a,n]=Br.useState(null),i=g=>g.id??g.name,o=async g=>{n(i(g));try{await s.downloadAttachment(e.id,g)}catch(y){console.error("Download failed:",y)}finally{n(null)}},v=Object.entries(e.data).filter(([g])=>!g.startsWith("_"));return(0,xe.jsxs)("div",{children:[(0,xe.jsxs)("div",{className:"af-mb-6",children:[(0,xe.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,xe.jsx)(Rt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,xe.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,xe.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Or(e.metadata.submitted_at)]})]}),(0,xe.jsxs)("div",{className:"af-space-y-6",children:[(0,xe.jsx)(wa,{deliveries:e.email_deliveries}),(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,xe.jsxs)("div",{className:"af-space-y-3",children:[v.map(([g,y])=>(0,xe.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,xe.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:g.replace(/_/g," ")}),(0,xe.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof y=="string"&&y.includes(`
|
|
3
|
-
`)?(0,xe.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:y}):String(y)})]},g)),v.length===0&&(0,xe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,xe.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((g,y)=>(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,xe.jsx)(Rt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,xe.jsx)("span",{className:"af-text-sm",children:g.name}),(0,xe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",po(g.size),")"]})]}),(0,xe.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>o(g),disabled:a===i(g),children:[a===i(g)?(0,xe.jsx)(Rt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,xe.jsx)(Rt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===i(g)?"Downloading...":"Download"]})]},y))})]}),(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,xe.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Rt.Clock,{className:"af-h-4 af-w-4"}),(0,xe.jsx)("span",{children:Or(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Rt.Globe,{className:"af-h-4 af-w-4"}),(0,xe.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,xe.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Rt.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,xe.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Rt.Mail,{className:"af-h-4 af-w-4"}),(0,xe.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var me=require("react/jsx-runtime");function go(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function vo(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}function bo(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")&&!n.toLowerCase().includes("email"));if(t.length===0)return"";let[,s]=t[0],a=String(s);return a.length>50?a.slice(0,50)+"...":a}function Cs({formId:e,className:t,defaultSubmissionId:s}){let{submissions:a,total:n,isLoading:i,error:o,page:v,pageSize:g,hasNextPage:y,hasPreviousPage:r,setPage:h,setPageSize:w}=_s({formId:e}),[b,u]=Ps.useState("list"),[l,x]=Ps.useState(null);Ps.useEffect(()=>{if(s&&a.length>0){let c=a.find(N=>N.id===s);c&&(x(c),u("detail"))}},[s,a]);let S=c=>{x(c),u("detail")},P=()=>{u("list"),x(null)};if(b==="detail"&&l)return(0,me.jsx)("div",{className:t,children:(0,me.jsx)(Rs,{submission:l,onBack:P})});if(i)return(0,me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return(0,me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(a.length===0&&v===0)return(0,me.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,me.jsx)(Na.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,me.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,me.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let L=v*g+1,M=Math.min((v+1)*g,n);return(0,me.jsxs)("div",{className:t,children:[(0,me.jsxs)(Me,{children:[(0,me.jsx)(Ue,{children:(0,me.jsxs)(he,{children:[(0,me.jsx)(U,{children:"Email"}),(0,me.jsx)(U,{children:"Preview"}),(0,me.jsx)(U,{children:"Date"}),(0,me.jsx)(U,{className:"af-text-right",children:"Actions"})]})}),(0,me.jsx)($e,{children:a.map(c=>{let N=vo(c.data),E=bo(c.data);return(0,me.jsxs)(he,{children:[(0,me.jsxs)($,{className:"af-font-medium",children:[(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[N||(0,me.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&(0,me.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[(0,me.jsx)(Na.Paperclip,{className:"af-h-3 af-w-3"}),(0,me.jsx)("span",{className:"af-text-xs",children:c.attachments.length})]})]}),(0,me.jsx)(Ss,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),(0,me.jsx)($,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:E||(0,me.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,me.jsx)($,{className:"af-text-muted-foreground",children:go(c.metadata.submitted_at)}),(0,me.jsx)($,{className:"af-text-right",children:(0,me.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>S(c),title:"View details",children:(0,me.jsx)(Na.Eye,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),(0,me.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,me.jsxs)("span",{children:["Showing ",L,"-",M," of ",n]}),(0,me.jsxs)(ea,{value:String(g),onValueChange:c=>w(Number(c)),children:[(0,me.jsx)(Ht,{className:"af-w-[70px] af-h-8",children:(0,me.jsx)(ta,{})}),(0,me.jsxs)(zt,{children:[(0,me.jsx)(qe,{value:"10",children:"10"}),(0,me.jsx)(qe,{value:"25",children:"25"}),(0,me.jsx)(qe,{value:"50",children:"50"}),(0,me.jsx)(qe,{value:"100",children:"100"})]})]}),(0,me.jsx)("span",{children:"per page"})]}),(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,me.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v-1),disabled:!r,children:[(0,me.jsx)(Na.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,me.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v+1),disabled:!y,children:["Next",(0,me.jsx)(Na.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var jt=ue(require("react"),1),qa=require("lucide-react");var Fr=ue(require("react"),1);var Mr=require("react/jsx-runtime"),we=Fr.forwardRef(({className:e,type:t,...s},a)=>(0,Mr.jsx)("input",{type:t,className:Y("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:a,...s}));we.displayName="Input";var Ur=ue(require("react"),1),$r=require("class-variance-authority");var Vr=require("react/jsx-runtime"),yo=(0,$r.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),_e=Ur.forwardRef(({className:e,...t},s)=>(0,Vr.jsx)("label",{ref:s,className:Y(yo(),e),...t}));_e.displayName="Label";var sa=ue(require("react"),1),Pt=require("lucide-react");var Ts=ue(require("react"),1),ft=ue(require("@radix-ui/react-dialog"),1),Hr=require("lucide-react");var At=require("react/jsx-runtime"),Sa=ft.Root;var ho=ft.Portal;var zr=Ts.forwardRef(({className:e,...t},s)=>(0,At.jsx)(ft.Overlay,{ref:s,className:Y("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));zr.displayName=ft.Overlay.displayName;var fa=Ts.forwardRef(({className:e,children:t,...s},a)=>(0,At.jsx)(ho,{children:(0,At.jsxs)("div",{className:"aifeatures-admin",children:[(0,At.jsx)(zr,{}),(0,At.jsxs)(ft.Content,{ref:a,className:Y("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:[t,(0,At.jsxs)(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:[(0,At.jsx)(Hr.X,{className:"af-h-4 af-w-4"}),(0,At.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));fa.displayName=ft.Content.displayName;var ma=({className:e,...t})=>(0,At.jsx)("div",{className:Y("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});ma.displayName="DialogHeader";var pa=({className:e,...t})=>(0,At.jsx)("div",{className:Y("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});pa.displayName="DialogFooter";var ga=Ts.forwardRef(({className:e,...t},s)=>(0,At.jsx)(ft.Title,{ref:s,className:Y("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));ga.displayName=ft.Title.displayName;var va=Ts.forwardRef(({className:e,...t},s)=>(0,At.jsx)(ft.Description,{ref:s,className:Y("af-text-sm af-text-muted-foreground",e),...t}));va.displayName=ft.Description.displayName;var qt=ue(require("react"),1);function ks(){let{api:e}=ie(),[t,s]=qt.useState([]),[a,n]=qt.useState(!0),[i,o]=qt.useState(null),v=qt.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(b){o(b instanceof Error?b:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);qt.useEffect(()=>{v()},[v]);let g=qt.useCallback(async b=>{let u=await e.createEventDestination(b);return s(l=>[u,...l]),u},[e]),y=qt.useCallback(async(b,u)=>{let l=await e.updateEventDestination(b,u);return s(x=>x.map(S=>S.id===b?l:S)),l},[e]),r=qt.useCallback(async b=>{await e.deleteEventDestination(b),s(u=>u.filter(l=>l.id!==b))},[e]),h=qt.useCallback(async b=>{let u=await e.rotateEventDestinationSecret(b);return s(l=>l.map(x=>x.id===b?u:x)),u},[e]),w=qt.useCallback(b=>e.getEventDestinationSecret(b),[e]);return{destinations:t,isLoading:a,error:i,refetch:v,createDestination:g,updateDestination:y,deleteDestination:r,rotateSecret:h,getSecret:w}}var Ba=ue(require("react"),1),Es=require("lucide-react");var mt=require("react/jsx-runtime");function Is({destinationId:e,limit:t=25,className:s}){let{api:a}=ie(),[n,i]=Ba.useState([]),[o,v]=Ba.useState(!0),[g,y]=Ba.useState(null),[r,h]=Ba.useState(null),w=Ba.useCallback(async()=>{try{v(!0),y(null),i(await a.getEventDeliveries(e,t))}catch(u){y(u instanceof Error?u.message:"Failed to load deliveries")}finally{v(!1)}},[a,e,t]);Ba.useEffect(()=>{w()},[w]);let b=async u=>{try{h(u.id),y(null);let l=await a.retryEventDelivery(e,u.id);i(x=>x.map(S=>S.id===u.id?l:S))}catch(l){y(l instanceof Error?l.message:"Retry failed")}finally{h(null)}};return o?(0,mt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,mt.jsx)(Es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):g?(0,mt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:g}):n.length===0?(0,mt.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,mt.jsx)("div",{className:s,children:(0,mt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let l=u.delivered_at!==null;return(0,mt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,mt.jsxs)("div",{className:"af-min-w-0",children:[(0,mt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[l?(0,mt.jsx)(Q,{variant:"secondary",children:u.last_status??200}):(0,mt.jsx)(Q,{variant:"destructive",children:u.last_status??"failed"}),(0,mt.jsx)("span",{className:"af-text-sm af-truncate",children:u.type})]}),(0,mt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!l&&u.last_error&&(0,mt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),(0,mt.jsx)(_,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>b(u),children:r===u.id?(0,mt.jsx)(Es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,mt.jsx)(Es.RotateCw,{className:"af-h-4 af-w-4"})})]},u.id)})})})}var de=require("react/jsx-runtime");function Ds({formId:e,topics:t,description:s,className:a}){let{destinations:n,isLoading:i,error:o,createDestination:v,updateDestination:g,deleteDestination:y,rotateSecret:r,getSecret:h}=ks(),[w,b]=sa.useState(""),[u,l]=sa.useState(!1),[x,S]=sa.useState(null),[P,L]=sa.useState(null),[M,c]=sa.useState(null),[N,E]=sa.useState(!1),[G,D]=sa.useState(null),[C,V]=sa.useState(null),[m,z]=sa.useState(null),se=sa.useMemo(()=>n.filter(J=>J.form_id===e),[n,e]),X=async()=>{let J=w.trim();if(J){if(!J.startsWith("https://")){S("Webhook URLs must start with https://");return}try{l(!0),S(null),await v({url:J,form_id:e,...t&&t.length>0?{topics:t}:{}}),b("")}catch(Pe){S(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{l(!1)}}},ee=async J=>{try{V(J.id),S(null),await r(J.id),E(!1),c(await h(J.id))}catch(Pe){S(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{V(null)}},fe=async J=>{try{V(J.id),S(null),await g(J.id,{status:"active"})}catch(Pe){S(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{V(null)}},K=async()=>{if(G)try{V(G.id),await y(G.id),D(null)}catch(J){S(J instanceof Error?J.message:"Failed to delete")}finally{V(null)}},ae=async J=>{if(P===J.id){L(null),c(null);return}try{V(J.id),S(null),E(!1),L(J.id),c(await h(J.id))}catch(Pe){L(null),S(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{V(null)}},ce=async()=>{if(M)try{await navigator.clipboard.writeText(M),E(!0)}catch{}};return(0,de.jsxs)("div",{className:a,children:[(0,de.jsxs)("div",{className:"af-space-y-1",children:[(0,de.jsx)(_e,{children:"Webhooks"}),(0,de.jsx)("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."})]}),(0,de.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,de.jsx)(we,{value:w,placeholder:"https://hooks.zapier.com/...",onChange:J=>b(J.target.value),onKeyDown:J=>{J.key==="Enter"&&(J.preventDefault(),X())},disabled:u}),(0,de.jsxs)(_,{onClick:X,disabled:u||!w.trim(),children:[u?(0,de.jsx)(Pt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,de.jsx)(Pt.Plus,{className:"af-h-4 af-w-4"}),(0,de.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(x||o)&&(0,de.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:x||o?.message}),(0,de.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[i&&(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,de.jsx)(Pt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&se.length===0&&(0,de.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),se.map(J=>(0,de.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,de.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,de.jsxs)("div",{className:"af-min-w-0",children:[(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,de.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:J.url}),J.status==="disabled"?(0,de.jsx)(Q,{variant:"destructive",children:"Disabled"}):(0,de.jsx)(Q,{variant:"secondary",children:"Active"})]}),(0,de.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:J.topics.includes("*")?"All events":J.topics.join(", ")})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,de.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>z(m===J.id?null:J.id),children:m===J.id?"Hide log":"Deliveries"}),(0,de.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>ae(J),disabled:C===J.id,children:P===J.id?"Hide secret":"Show secret"}),(0,de.jsx)(_,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:C===J.id,onClick:()=>D(J),children:(0,de.jsx)(Pt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),J.status==="disabled"&&(0,de.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,de.jsx)(Pt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,de.jsxs)("div",{className:"af-text-sm",children:[(0,de.jsxs)("p",{children:["We stopped sending after repeated failures."," ",J.disabled_reason]}),(0,de.jsx)(_,{variant:"outline",size:"sm",className:"af-mt-2",disabled:C===J.id,onClick:()=>fe(J),children:"Re-enable"})]})]}),P===J.id&&M&&(0,de.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,de.jsx)("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."}),(0,de.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,de.jsx)(we,{readOnly:!0,value:M,className:"af-font-mono"}),(0,de.jsx)(_,{variant:"outline",title:"Copy signing secret",onClick:ce,children:N?(0,de.jsx)(Pt.Check,{className:"af-h-4 af-w-4"}):(0,de.jsx)(Pt.Copy,{className:"af-h-4 af-w-4"})}),(0,de.jsx)(_,{variant:"outline",title:"Rotate signing secret",disabled:C===J.id,onClick:()=>ee(J),children:C===J.id?(0,de.jsx)(Pt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,de.jsx)(Pt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),m===J.id&&(0,de.jsx)(Is,{destinationId:J.id})]},J.id))]}),(0,de.jsx)(Sa,{open:!!G,onOpenChange:J=>{!J&&!C&&D(null)},children:(0,de.jsxs)(fa,{children:[(0,de.jsxs)(ma,{children:[(0,de.jsx)(ga,{children:"Delete this webhook?"}),(0,de.jsxs)(va,{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."]})]}),(0,de.jsxs)(pa,{children:[(0,de.jsx)(_,{variant:"outline",onClick:()=>D(null),disabled:!!C,children:"Cancel"}),(0,de.jsx)(_,{variant:"destructive",onClick:K,disabled:!!C,children:C?"Deleting...":"Delete"})]})]})})]})}var Se=require("react/jsx-runtime");function As({form:e,onSaved:t,className:s}){let{updateForm:a}=Ya(),[n,i]=jt.useState(!1),[o,v]=jt.useState(null),[g,y]=jt.useState(null),[r,h]=jt.useState(e.name),[w,b]=jt.useState(e.redirect_url||""),[u,l]=jt.useState(e.email_recipients),[x,S]=jt.useState("");jt.useEffect(()=>{h(e.name),b(e.redirect_url||""),l(e.email_recipients),y(null)},[e]);let P=jt.useCallback(async E=>{try{i(!0),y(null);let G=await a(e.id,E);v(new Date),t?.(G)}catch(G){y(G instanceof Error?G.message:"Failed to save")}finally{i(!1)}},[e.id,a,t]);jt.useEffect(()=>{if(o){let E=setTimeout(()=>v(null),2e3);return()=>clearTimeout(E)}},[o]);let L=async()=>{let E=x.trim().toLowerCase();if(!E)return;if(!E.includes("@")){y("Please enter a valid email address");return}if(u.includes(E)){y("This email is already added");return}let G=[...u,E];l(G),S(""),y(null),await P({email_recipients:G})},M=async E=>{let G=u.filter(D=>D!==E);l(G),await P({email_recipients:G})},c=async()=>{r!==e.name&&await P({name:r})},N=async()=>{let E=w||null;E!==e.redirect_url&&await P({redirect_url:E})};return(0,Se.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,Se.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,Se.jsxs)("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:[(0,Se.jsx)(qa.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Se.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Se.jsxs)("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:[(0,Se.jsx)(qa.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Se.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{htmlFor:"form-name",children:"Form Name"}),(0,Se.jsx)(we,{id:"form-name",value:r,onChange:E=>h(E.target.value),onBlur:c,placeholder:"Contact Form"}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{children:"Email Recipients"}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(E=>(0,Se.jsxs)(Q,{variant:"secondary",className:"af-gap-1",children:[E,(0,Se.jsx)("button",{type:"button",onClick:()=>M(E),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,Se.jsx)(qa.X,{className:"af-h-3 af-w-3"})})]},E)),u.length===0&&(0,Se.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Se.jsx)(we,{type:"email",value:x,onChange:E=>S(E.target.value),placeholder:"Add email address",onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),L())},disabled:n}),(0,Se.jsx)(_,{type:"button",variant:"outline",onClick:L,disabled:!x.trim()||n,children:(0,Se.jsx)(qa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Se.jsx)(we,{id:"redirect-url",value:w,onChange:E=>b(E.target.value),onBlur:N,placeholder:"/thank-you"}),(0,Se.jsx)("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."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{children:"Form Endpoint"}),(0,Se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Se.jsx)("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})}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(_e,{children:"Captcha Protection"}),(0,Se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Se.jsx)(Q,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Se.jsx)(Ds,{formId:e.id}),g&&(0,Se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g})]})}var He=require("react/jsx-runtime");function Mn({className:e,submissionId:t}){let{api:s}=ie(),[a,n]=ja.useState("list"),[i,o]=ja.useState(null),[v,g]=ja.useState("submissions"),[y,r]=ja.useState(t),[h,w]=ja.useState(!!t);ja.useEffect(()=>{if(!t)return;async function x(){try{let S=await s.getSubmission(t),P=await s.getForm(S.form_id);o(P),n("detail"),g("submissions"),r(t)}catch(S){console.error("Failed to load submission for deep link:",S)}finally{w(!1)}}x()},[t,s]);let b=(x,S)=>{o(x),n("detail"),g(S),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},l=x=>{o(x)};return h?(0,He.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,He.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,He.jsxs)("div",{className:e,children:[a==="list"&&(0,He.jsxs)("div",{children:[(0,He.jsxs)("div",{className:"af-mb-6",children:[(0,He.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,He.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,He.jsx)(Ns,{onSelectForm:b})]}),a==="detail"&&i&&(0,He.jsxs)("div",{children:[(0,He.jsxs)("div",{className:"af-mb-6",children:[(0,He.jsxs)(_,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[(0,He.jsx)(fs.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),(0,He.jsx)("h2",{className:"af-text-lg af-font-semibold",children:i.name}),(0,He.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:(0,He.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),(0,He.jsxs)(ln,{value:v,onValueChange:x=>g(x),children:[(0,He.jsxs)(xs,{className:"af-mb-4",children:[(0,He.jsxs)(ca,{value:"submissions",className:"af-gap-2",children:[(0,He.jsx)(fs.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,He.jsxs)(ca,{value:"settings",className:"af-gap-2",children:[(0,He.jsx)(fs.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,He.jsx)(ua,{value:"submissions",children:(0,He.jsx)(Cs,{formId:i.id,defaultSubmissionId:y})}),(0,He.jsx)(ua,{value:"settings",children:(0,He.jsx)(As,{form:i,onSaved:l})})]})]})]})}var Fe=ue(require("react"),1);var _a=ue(require("react"),1);function Fa(){let{api:e}=ie(),[t,s]=_a.useState(null),[a,n]=_a.useState(!0),[i,o]=_a.useState(null),v=_a.useRef(0),g=_a.useCallback(async()=>{let y=++v.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(y!==v.current)return;s(r)}catch(r){if(y!==v.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{y===v.current&&n(!1)}},[e]);return _a.useEffect(()=>{g()},[g]),{status:t,isLoading:a,error:i,refetch:g}}var xo=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Gt(e){return xo.has(e.toLowerCase())}function q(e,t,s){let a=Gt(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(a)}catch{return`${a} ${t.toUpperCase()}`}}function Ra(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function Tt(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let a=Gt(t)?s:s*100;return Math.round(a)}function rt(e,t){return Gt(t)?e:e/100}function dn(e){return e.amount_paid??Math.max(0,Ra(e)-(e.credit_applied??0))}var ne=require("react/jsx-runtime");function Ls(e){return e instanceof Dt&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function qr(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${q(e.amount_off,e.currency)} off`:"Discount unavailable"}function Qa(){let{api:e,siteToken:t}=ie();return(0,ne.jsx)(wo,{api:e},t)}function wo({api:e}){let{status:t,error:s}=Fa(),[a,n]=Fe.useState([]),[i,o]=Fe.useState(null),[v,g]=Fe.useState(null),[y,r]=Fe.useState(!1),[h,w]=Fe.useState(!1),[b,u]=Fe.useState(""),[l,x]=Fe.useState(null),[S,P]=Fe.useState(null),[L,M]=Fe.useState(!1),c=Fe.useRef(0),N=Fe.useCallback(async D=>{let C=++c.current;r(!0),u("");try{let V=await e.getPromos(D);if(C!==c.current)return;n(m=>D?[...m,...V.promos.filter(z=>!m.some(se=>se.id===z.id))]:V.promos),o(V.next_cursor),g(V.checkout_enabled)}catch(V){C===c.current&&u(Ls(V))}finally{C===c.current&&r(!1)}},[e]);Fe.useEffect(()=>(N(),()=>{c.current++}),[N]);async function E(D){let C=++c.current;r(!0),u(""),M(!1);try{let V=await e.getPromo(D);C===c.current&&x(V)}catch(V){C===c.current&&u(Ls(V))}finally{C===c.current&&r(!1)}}async function G(){if(l){w(!0),r(!0),u("");try{let D=await e.disablePromo(l.id);if(x(D),!["inactive","expired","exhausted"].includes(D.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");M(!1),await N()}catch(D){u(Ls(D))}finally{w(!1),r(!1)}}}return S?(0,ne.jsx)(No,{currency:t?.currency??void 0,replaces:S.replaces,onCancel:()=>P(null),onSave:async D=>{let C=S.replaces?await e.replacePromo(S.replaces.id,D):await e.createPromo(D),V=await e.getPromo(C.id);if(V.status==="pending"||V.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");x(V),P(null),await N()}}):(0,ne.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ne.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ne.jsx)(_,{disabled:y||!t?.currency,onClick:()=>{u(""),P({})},children:"Create promo code"})]}),(0,ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),v===!1&&(0,ne.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,ne.jsx)("p",{className:"af-text-sm",children:s?Ls(s):"Connect Stripe and set the payment currency before creating codes."}),b&&(0,ne.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[b," ",(0,ne.jsx)(_,{variant:"outline",disabled:y,onClick:()=>l?void E(l.id):void N(),children:"Refresh"})]}),l?(0,ne.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ne.jsx)(_,{variant:"ghost",disabled:h,onClick:()=>{x(null),M(!1),N()},children:"Back to codes"}),(0,ne.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),(0,ne.jsxs)("p",{children:[qr(l)," \xB7 ",l.status]}),(0,ne.jsxs)("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),(0,ne.jsxs)("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${q(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ne.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",l.duration==="repeating"?`${l.duration_in_months} months`:l.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,ne.jsx)("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ne.jsx)(_,{variant:"outline",disabled:y,onClick:()=>void E(l.id),children:"Refresh details"}),(0,ne.jsx)(_,{variant:"outline",disabled:y||l.status==="pending"||l.status==="unavailable"||!t?.currency,onClick:()=>P({replaces:l}),children:"Replace with new code"}),(0,ne.jsx)(_,{variant:"outline",disabled:y||!["active","pending","unavailable"].includes(l.status),onClick:()=>M(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),L&&(0,ne.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ne.jsxs)("p",{className:"af-text-sm",children:[l.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${l.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,ne.jsx)(_,{disabled:y,onClick:()=>void G(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ne.jsx)(_,{variant:"ghost",disabled:y,onClick:()=>M(!1),children:"Cancel"})]})]}):(0,ne.jsxs)(ne.Fragment,{children:[a.map(D=>(0,ne.jsxs)("button",{type:"button",disabled:y,onClick:()=>void E(D.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ne.jsx)("span",{className:"af-font-semibold af-break-all",children:D.code}),(0,ne.jsx)("span",{className:"af-text-sm",children:D.status})]}),(0,ne.jsxs)("div",{className:"af-text-sm",children:[qr(D)," \xB7"," ",D.times_redeemed==null?"Usage unavailable":`${D.times_redeemed} redemptions`]})]},D.id)),!y&&!b&&a.length===0&&(0,ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),y&&(0,ne.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),i&&(0,ne.jsx)(_,{variant:"outline",disabled:y,onClick:()=>void N(i),children:"Load more"})]})]})}function No({currency:e,replaces:t,onCancel:s,onSave:a}){let[n,i]=Fe.useState(""),[o,v]=Fe.useState(t?.name??""),[g,y]=Fe.useState(t?.amount_off!=null?"fixed":"percent"),[r,h]=Fe.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(rt(t.amount_off,e)):"")),[w,b]=Fe.useState(t?.minimum_amount!=null&&e?String(rt(t.minimum_amount,e)):""),[u,l]=Fe.useState(()=>{if(!t?.expires_at)return"";let fe=new Date(t.expires_at);return Number.isFinite(fe.getTime())?new Date(fe.getTime()-fe.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[x,S]=Fe.useState(t?.max_redemptions?.toString()??""),[P,L]=Fe.useState(t?.duration??"once"),[M,c]=Fe.useState(t?.duration_in_months?.toString()??"3"),[N,E]=Fe.useState(null),[G,D]=Fe.useState(!1),[C,V]=Fe.useState(""),m=Fe.useRef(!1),z=e&&Gt(e)?"1":"0.01";async function se(fe){if(fe.preventDefault(),m.current)return;V("");let K=N;if(!K){if(!e){V("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){V("Choose a different code for the replacement.");return}let ae=Tt(r,e),ce=w?Tt(w,e):null;if(g==="fixed"&&(!ae||ae>999999999999)||w&&(!ce||ce>999999999999)){V("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){V("Choose a future expiry.");return}K={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:P,...g==="percent"?{percent_off:Number(r)}:{amount_off:ae,currency:e},...w?{minimum_amount:ce,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...x?{max_redemptions:Number(x)}:{},...P==="repeating"?{duration_in_months:Number(M)}:{}},E(K)}m.current=!0,D(!0);try{await a(K)}catch(ae){V(Ls(ae)),ae instanceof Dt&&ae.status>=400&&ae.status<500&&ae.details?.retryable!==!0&&E(null)}finally{m.current=!1,D(!1)}}let X=(fe,K,ae,ce={})=>(0,ne.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[fe,(0,ne.jsx)(we,{"aria-label":fe,value:K,onChange:J=>ae(J.target.value),...ce})]}),ee="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ne.jsxs)("form",{onSubmit:se,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ne.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ne.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,ne.jsxs)("fieldset",{disabled:G||!!N,className:"af-grid af-gap-4",children:[X("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),X("Name",o,v,{required:!0,maxLength:40}),(0,ne.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ne.jsxs)("select",{"aria-label":"Discount type",className:ee,value:g,onChange:fe=>y(fe.target.value),children:[(0,ne.jsx)("option",{value:"percent",children:"Percentage"}),(0,ne.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),X("Discount",r,h,{type:"number",required:!0,min:g==="percent"?"0.01":z,max:g==="percent"?"100":void 0,step:g==="percent"?"0.01":z}),X("Minimum order amount",w,b,{type:"number",min:z,step:z,placeholder:e?.toUpperCase()}),(0,ne.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),X("Expires at (local time)",u,l,{type:"datetime-local",step:1}),X("Maximum redemptions",x,S,{type:"number",min:1,max:1e6,step:1}),(0,ne.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ne.jsxs)("select",{"aria-label":"Subscription duration",className:ee,value:P,onChange:fe=>L(fe.target.value),children:[(0,ne.jsx)("option",{value:"once",children:"First invoice only"}),(0,ne.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ne.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),P==="repeating"&&X("Months",M,c,{type:"number",required:!0,min:1,max:36,step:1})]}),C&&(0,ne.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:C}),N&&!G&&(0,ne.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ne.jsx)("span",{className:"af-break-all",children:N.request_id})]}),(0,ne.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ne.jsx)(_,{type:"submit",disabled:G,children:G?"Saving\u2026":N?"Retry same request":t?"Create replacement":"Create code"}),(0,ne.jsx)(_,{type:"button",variant:"ghost",disabled:G||!!N,onClick:s,children:"Cancel"})]})]})}var vs=ue(require("react"),1),oa=require("lucide-react");var fn=ue(require("react"),1),Ma=require("lucide-react");var be=require("react/jsx-runtime");function So(e){if(e.allow_custom_amount){let t=e.min_amount!==null?q(e.min_amount,e.currency):"?",s=e.max_amount!==null?q(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":q(e.unit_amount,e.currency)}function _o(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Os({productsState:e,onSelectProduct:t,onCreateProduct:s,className:a}){let{products:n,isLoading:i,error:o,deleteProduct:v}=e,[g,y]=fn.useState(null),[r,h]=fn.useState(!1),[w,b]=fn.useState(null),u=async()=>{if(g)try{h(!0),b(null),await v(g.id),y(null)}catch(l){b(l instanceof Error?l.message:"Failed to delete product")}finally{h(!1)}};return i?(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?(0,be.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,be.jsx)(Ma.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,be.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,be.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,be.jsxs)(_,{variant:"outline",onClick:()=>s?.(),children:[(0,be.jsx)(Ma.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,be.jsxs)("div",{className:a,children:[(0,be.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,be.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,be.jsx)(Ma.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,be.jsxs)(Me,{children:[(0,be.jsx)(Ue,{children:(0,be.jsxs)(he,{children:[(0,be.jsx)(U,{children:"Name"}),(0,be.jsx)(U,{children:"Price"}),(0,be.jsx)(U,{children:"Fulfillment"}),(0,be.jsx)(U,{children:"Status"}),(0,be.jsx)(U,{className:"af-text-right",children:"Actions"})]})}),(0,be.jsx)($e,{children:n.map(l=>(0,be.jsxs)(he,{children:[(0,be.jsx)($,{className:"af-font-medium",children:l.name}),(0,be.jsx)($,{children:So(l)}),(0,be.jsx)($,{className:"af-text-muted-foreground",children:_o(l)}),(0,be.jsx)($,{children:(0,be.jsx)(Q,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),(0,be.jsx)($,{className:"af-text-right",children:(0,be.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>t?.(l),children:[(0,be.jsx)(Ma.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>{b(null),y(l)},children:[(0,be.jsx)(Ma.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),(0,be.jsx)(Sa,{open:!!g,onOpenChange:l=>{!l&&!r&&y(null)},children:(0,be.jsxs)(fa,{children:[(0,be.jsxs)(ma,{children:[(0,be.jsx)(ga,{children:"Delete product?"}),(0,be.jsxs)(va,{children:['"',g?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),w&&(0,be.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:w}),(0,be.jsxs)(pa,{children:[(0,be.jsx)(_,{variant:"outline",onClick:()=>y(null),disabled:r,children:"Cancel"}),(0,be.jsx)(_,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var We=ue(require("react"),1),Wt=require("lucide-react");var ct=ue(require("react"),1),na=require("lucide-react");var k=require("react/jsx-runtime");function Un(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Bs({productId:e,currency:t,className:s}){let{api:a}=ie(),n=Gt(t)?"1":"0.01",[i,o]=ct.useState(null),[v,g]=ct.useState(!0),[y,r]=ct.useState(null),[h,w]=ct.useState(null),[b,u]=ct.useState(!1),l=ct.useRef(!0);ct.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let x=ct.useCallback(async()=>{try{let T=await a.getProduct(e);if(!l.current)return;o(T)}catch(T){if(!l.current)return;r(T instanceof Error?T.message:"Failed to load product")}finally{l.current&&g(!1)}},[a,e]);ct.useEffect(()=>{x()},[x]);let S=async T=>{w(null),u(!0);try{await T(),await x()}catch(O){l.current&&w(O instanceof Error?O.message:"Something went wrong")}finally{l.current&&u(!1)}},[P,L]=ct.useState(""),[M,c]=ct.useState(""),[N,E]=ct.useState({}),G=()=>S(async()=>{let T=P.trim(),O=M.split(",").map(ve=>ve.trim()).filter(Boolean);if(!T)throw new Error("Option name is required");if(O.length===0)throw new Error("Add at least one value");await a.createOption(e,{title:T,values:O}),l.current&&(L(""),c(""))}),D=T=>S(async()=>{let O=(N[T.id]??"").trim();if(!O)throw new Error("Enter a value");await a.updateOption(T.id,{add_values:[O]}),l.current&&E(ve=>({...ve,[T.id]:""}))}),C=(T,O)=>S(()=>a.updateOption(T.id,{remove_values:[O]})),V=T=>S(()=>a.deleteOption(T.id)),[m,z]=ct.useState(null),[se,X]=ct.useState(null),[ee,fe]=ct.useState(!1),[K,ae]=ct.useState(null),ce=i?.options??[],J=i?.variants??[],Pe=()=>{X(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})},vt=T=>{X(null);let O=T.inventory?.on_hand??0,ve=O<0?"":String(O);z({variant:T,title:T.title??"",sku:T.sku??"",unitAmount:T.unit_amount!=null?String(rt(T.unit_amount,t)):"",compareAt:T.compare_at_amount!=null?String(rt(T.compare_at_amount,t)):"",active:T.active,optionValues:{},tracked:T.inventory?.tracked??!1,onHand:ve,initialOnHand:ve,allowBackorder:T.inventory?.allow_backorder??!1})},St=async()=>{if(!m)return;X(null);let T=m.variant?.allow_custom_amount??!1,O=null,ve=null;if(!T){if(O=Tt(m.unitAmount,t),O===null||O<=0){X("Enter a valid price");return}if(m.compareAt.trim()&&(ve=Tt(m.compareAt,t),ve===null||ve<=O)){X("Compare-at price must be greater than the price");return}}let Le=m.onHand.trim()!==m.initialOnHand.trim(),Ie=parseInt(m.onHand,10);if(m.tracked&&Le&&(!Number.isFinite(Ie)||Ie<0)){X("On-hand quantity must be zero or more");return}try{if(fe(!0),m.variant)await a.updateVariant(m.variant.id,{title:m.title.trim()||null,sku:m.sku.trim()||null,...T?{}:{unit_amount:O,compare_at_amount:ve},active:m.active}),await a.setVariantInventory(m.variant.id,{tracked:m.tracked,on_hand:m.tracked&&Le?Ie:void 0,allow_backorder:m.allowBackorder});else{let lt={};for(let st of ce){let yt=m.optionValues[st.id];if(!yt){X(`Choose a ${st.title}`),fe(!1);return}lt[st.title]=yt}await a.createVariant(e,{title:m.title.trim()||null,sku:m.sku.trim()||null,unit_amount:O,compare_at_amount:ve,active:m.active,option_values:ce.length>0?lt:void 0,inventory:m.tracked?{tracked:!0,on_hand:Ie,allow_backorder:m.allowBackorder}:{tracked:!1,allow_backorder:m.allowBackorder}})}await x(),l.current&&z(null)}catch(lt){if(l.current&&X(lt instanceof Error?lt.message:"Failed to save variant"),m.variant)try{let st=await a.getProduct(e);l.current&&o(st)}catch{}}finally{l.current&&fe(!1)}},Ce=()=>S(async()=>{K&&(await a.deleteVariant(K.id),l.current&&ae(null))}),bt=m?.variant?.allow_custom_amount??!1,Z=m?.variant!=null&&m.variant.option_values.length===0&&ce.length>0&&!m.variant.active,re=m?.variant?.inventory!=null&&m.variant.inventory.on_hand<0?-m.variant.inventory.on_hand:null;function Re(T){let O=T.inventory;if(!O||!O.tracked)return(0,k.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ve=O.available??O.on_hand;return ve<0?(0,k.jsxs)("span",{children:[-ve," backordered"]}):(0,k.jsxs)("span",{children:[ve," in stock",O.allow_backorder&&(0,k.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return v?(0,k.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,k.jsx)(na.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):y?(0,k.jsx)("div",{className:s,children:(0,k.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y})}):(0,k.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,k.jsxs)("div",{className:"af-space-y-3",children:[(0,k.jsxs)("div",{children:[(0,k.jsx)(_e,{children:"Options"}),(0,k.jsx)("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&&(0,k.jsx)("div",{className:"af-space-y-3",children:ce.map(T=>(0,k.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,k.jsx)("span",{className:"af-text-sm af-font-medium",children:T.title}),(0,k.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>V(T),disabled:b,children:(0,k.jsx)(na.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,k.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:T.values.map(O=>(0,k.jsxs)(Q,{variant:"secondary",className:"af-gap-1",children:[O.value,(0,k.jsx)("button",{type:"button",onClick:()=>C(T,O.value),className:"af-ml-1 hover:af-text-destructive",disabled:b,title:"Remove value",children:(0,k.jsx)(na.X,{className:"af-h-3 af-w-3"})})]},O.id))}),(0,k.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,k.jsx)(we,{value:N[T.id]??"",onChange:O=>E(ve=>({...ve,[T.id]:O.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),D(T))},disabled:b}),(0,k.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>D(T),disabled:b||!(N[T.id]??"").trim(),children:(0,k.jsx)(na.Plus,{className:"af-h-4 af-w-4"})})]})]},T.id))}),(0,k.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(_e,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,k.jsx)(we,{id:"new-option-title",value:P,onChange:T=>L(T.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:b})]}),(0,k.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,k.jsx)(_e,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,k.jsx)(we,{id:"new-option-values",value:M,onChange:T=>c(T.target.value),placeholder:"S, M, L",disabled:b})]}),(0,k.jsxs)(_,{type:"button",variant:"outline",onClick:G,disabled:b||!P.trim()||!M.trim(),children:[(0,k.jsx)(na.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,k.jsxs)("div",{className:"af-space-y-3",children:[(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,k.jsx)(_e,{children:"Variants"}),(0,k.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:b||ce.length===0,children:[(0,k.jsx)(na.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ce.length===0&&(0,k.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),J.length===0?(0,k.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,k.jsxs)(Me,{children:[(0,k.jsx)(Ue,{children:(0,k.jsxs)(he,{children:[(0,k.jsx)(U,{children:"Variant"}),(0,k.jsx)(U,{children:"SKU"}),(0,k.jsx)(U,{children:"Price"}),(0,k.jsx)(U,{children:"Stock"}),(0,k.jsx)(U,{children:"Status"}),(0,k.jsx)(U,{className:"af-text-right",children:"Actions"})]})}),(0,k.jsx)($e,{children:J.map(T=>(0,k.jsxs)(he,{children:[(0,k.jsx)($,{className:"af-font-medium",children:Un(T)}),(0,k.jsx)($,{className:"af-text-muted-foreground",children:T.sku||"-"}),(0,k.jsx)($,{children:T.unit_amount!=null?(0,k.jsxs)("span",{children:[T.compare_at_amount!=null&&(0,k.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:q(T.compare_at_amount,T.currency)}),q(T.unit_amount,T.currency)]}):T.allow_custom_amount?(0,k.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,k.jsx)($,{children:Re(T)}),(0,k.jsx)($,{children:(0,k.jsx)(Q,{variant:T.active?"success":"secondary",children:T.active?"Active":"Inactive"})}),(0,k.jsx)($,{className:"af-text-right",children:(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,k.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>vt(T),disabled:b,children:"Edit"}),(0,k.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>ae(T),disabled:b,title:"Delete variant",children:(0,k.jsx)(na.Trash2,{className:"af-h-4 af-w-4"})})]})})]},T.id))})]})]}),h&&(0,k.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:h}),(0,k.jsx)(Sa,{open:m!==null,onOpenChange:T=>{!T&&!ee&&z(null)},children:(0,k.jsxs)(fa,{children:[(0,k.jsxs)(ma,{children:[(0,k.jsx)(ga,{children:m?.variant?"Edit variant":"Add variant"}),(0,k.jsx)(va,{children:"Price, markdown, and stock live on the variant."})]}),m&&(0,k.jsxs)("div",{className:"af-space-y-3",children:[m.variant?m.variant.option_values.length>0&&(0,k.jsxs)("div",{className:"af-text-sm",children:[(0,k.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Un(m.variant)]}):ce.map(T=>(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(_e,{className:"af-text-xs af-text-muted-foreground",children:T.title}),(0,k.jsxs)(ea,{value:m.optionValues[T.id]??"",onValueChange:O=>z(ve=>ve&&{...ve,optionValues:{...ve.optionValues,[T.id]:O}}),children:[(0,k.jsx)(Ht,{children:(0,k.jsx)(ta,{placeholder:`Choose ${T.title}`})}),(0,k.jsx)(zt,{children:T.values.map(O=>(0,k.jsx)(qe,{value:O.value,children:O.value},O.id))})]})]},T.id)),bt?(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(_e,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,k.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,k.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsxs)(_e,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,k.jsx)(we,{id:"variant-price",type:"number",min:"0",step:n,value:m.unitAmount,onChange:T=>z(O=>O&&{...O,unitAmount:T.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(_e,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,k.jsx)(we,{id:"variant-compare",type:"number",min:"0",step:n,value:m.compareAt,onChange:T=>z(O=>O&&{...O,compareAt:T.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(_e,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,k.jsx)(we,{id:"variant-sku",value:m.sku,onChange:T=>z(O=>O&&{...O,sku:T.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,k.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,k.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,k.jsx)("input",{type:"checkbox",checked:m.tracked,onChange:T=>z(O=>O&&{...O,tracked:T.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),m.tracked&&(0,k.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,k.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(_e,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,k.jsx)(we,{id:"variant-onhand",type:"number",min:"0",step:"1",value:m.onHand,onChange:T=>z(O=>O&&{...O,onHand:T.target.value}),placeholder:re!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,k.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,k.jsx)("input",{type:"checkbox",checked:m.allowBackorder,onChange:T=>z(O=>O&&{...O,allowBackorder:T.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),re!=null&&(0,k.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",re," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,k.jsx)("input",{type:"checkbox",checked:m.active,onChange:T=>z(O=>O&&{...O,active:T.target.checked}),className:"af-h-4 af-w-4",disabled:Z}),"Active (buyers can purchase this variant)"]}),Z&&(0,k.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-pl-6",children:"This is the original pre-options variant \u2014 it has no option values, so buyers can't select it. It stays inactive while the product has options; delete all options to use it again."})]}),se&&(0,k.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:se})]}),(0,k.jsxs)(pa,{children:[(0,k.jsx)(_,{variant:"outline",onClick:()=>z(null),disabled:ee,children:"Cancel"}),(0,k.jsxs)(_,{onClick:St,disabled:ee,children:[ee?(0,k.jsx)(na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,m?.variant?"Save":"Add variant"]})]})]})}),(0,k.jsx)(Sa,{open:K!==null,onOpenChange:T=>{!T&&!b&&ae(null)},children:(0,k.jsxs)(fa,{children:[(0,k.jsxs)(ma,{children:[(0,k.jsx)(ga,{children:"Delete variant?"}),(0,k.jsx)(va,{children:K&&`"${Un(K)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,k.jsxs)(pa,{children:[(0,k.jsx)(_,{variant:"outline",onClick:()=>ae(null),disabled:b,children:"Cancel"}),(0,k.jsx)(_,{variant:"destructive",onClick:Ce,disabled:b,children:"Delete"})]})]})})]})}var j=require("react/jsx-runtime");function Ro(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function Fs({productsState:e,product:t,currency:s,onSaved:a,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:v,attachProductFileFromUrl:g}=e,y=!!t,r=t?.currency??s,h=Gt(r)?"1":"0.01",w=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[b,u]=We.useState(!1),[l,x]=We.useState(null),S=We.useRef(!0);We.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]);let[P,L]=We.useState(t?.name??""),[M,c]=We.useState(t?.description??""),[N,E]=We.useState(t?.allow_custom_amount?"custom":"fixed"),[G,D]=We.useState(t?.unit_amount!=null?String(rt(t.unit_amount,r)):""),[C,V]=We.useState(t?.min_amount!=null?String(rt(t.min_amount,r)):""),[m,z]=We.useState(t?.max_amount!=null?String(rt(t.max_amount,r)):""),[se,X]=We.useState(String(t?.max_quantity??10)),ee=We.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(rt(t.unit_amount,r)):"",minAmount:t?.min_amount!=null?String(rt(t.min_amount,r)):"",maxAmount:t?.max_amount!=null?String(rt(t.max_amount,r)):"",maxQuantity:String(t?.max_quantity??10)}).current,[fe,K]=We.useState(t?.collect_shipping_address??!1),[ae,ce]=We.useState(t?.active??!0),[J,Pe]=We.useState(t?.images??[]),[vt,St]=We.useState(""),[Ce,bt]=We.useState(t?.fulfillment??null),[Z,re]=We.useState(!1),[Re,T]=We.useState(""),[O,ve]=We.useState(null),Le=We.useRef(null),Ie=b||Z,lt=()=>{let oe=vt.trim();if(oe){if(J.includes(oe)){x("This image URL is already added");return}Pe(Be=>[...Be,oe]),St(""),x(null)}},st=oe=>{Pe(Be=>Be.filter(Je=>Je!==oe))},yt=async()=>{if(x(null),!P.trim()){x("Product name is required");return}let oe=null,Be=null,Je=null,ha=!y||N!==ee.pricingMode||(N==="fixed"?G!==ee.unitAmount:C!==ee.minAmount||m!==ee.maxAmount),Xt=!y||se!==ee.maxQuantity,La=w||N==="fixed";if(!(w||!ha))if(N==="fixed"){if(oe=Tt(G,r),oe===null||oe<=0){x("Enter a valid price");return}}else{if(Be=Tt(C,r),Je=Tt(m,r),Be===null||Je===null){x("Enter valid minimum and maximum amounts");return}if(Je<Be){x("Maximum amount must be at least the minimum amount");return}}let Xe=parseInt(se,10);if(La&&Xt&&(!Number.isFinite(Xe)||Xe<1)){x("Max quantity must be at least 1");return}try{u(!0);let Ye;if(y&&t){let A={name:P.trim(),description:M.trim()||null,images:J,collect_shipping_address:fe,active:ae};!w&&ha&&(A.allow_custom_amount=N==="custom",N==="fixed"?A.unit_amount=oe:(A.min_amount=Be,A.max_amount=Je)),La&&Xt&&(A.max_quantity=Xe),Ye=await o(t.id,A),ee.pricingMode=Ye.allow_custom_amount?"custom":"fixed",ee.unitAmount=Ye.unit_amount!=null?String(rt(Ye.unit_amount,r)):"",ee.minAmount=Ye.min_amount!=null?String(rt(Ye.min_amount,r)):"",ee.maxAmount=Ye.max_amount!=null?String(rt(Ye.max_amount,r)):"",ee.maxQuantity=String(Ye.max_quantity)}else{let A={name:P.trim(),allow_custom_amount:N==="custom",collect_shipping_address:fe,active:ae};M.trim()&&(A.description=M.trim()),J.length>0&&(A.images=J),N==="fixed"?(A.unit_amount=oe,A.max_quantity=Xe):(A.min_amount=Be,A.max_amount=Je),Ye=await i(A)}if(!S.current)return;bt(Ye.fulfillment),a?.(Ye)}catch(Ye){if(!S.current)return;x(Ye instanceof Error?Ye.message:"Failed to save product")}finally{S.current&&u(!1)}},Ct=async oe=>{let Be=oe.target.files?.[0];if(!(!Be||!t))try{re(!0),ve(null);let Je=await v(t.id,Be);if(!S.current)return;bt(Je.fulfillment),a?.(Je)}catch(Je){if(!S.current)return;ve(Je instanceof Error?Je.message:"Failed to upload file")}finally{S.current&&(re(!1),Le.current&&(Le.current.value=""))}},ht=async()=>{let oe=Re.trim();if(!(!oe||!t))try{re(!0),ve(null);let Be=await g(t.id,oe);if(!S.current)return;bt(Be.fulfillment),T(""),a?.(Be)}catch(Be){if(!S.current)return;ve(Be instanceof Error?Be.message:"Failed to fetch file")}finally{S.current&&re(!1)}};return(0,j.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(_e,{htmlFor:"product-name",children:"Name"}),(0,j.jsx)(we,{id:"product-name",value:P,onChange:oe=>L(oe.target.value),placeholder:"My product"})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(_e,{htmlFor:"product-description",children:"Description"}),(0,j.jsx)("textarea",{id:"product-description",value:M,onChange:oe=>c(oe.target.value),rows:3,placeholder:"Shown on the Stripe checkout page.",className:"af-flex af-w-full af-rounded-md af-border af-border-input af-bg-transparent af-px-3 af-py-2 af-text-sm af-shadow-sm placeholder:af-text-muted-foreground focus-visible:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring"})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(_e,{children:"Pricing"}),w?(0,j.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(ea,{value:N,onValueChange:oe=>E(oe),children:[(0,j.jsx)(Ht,{className:"af-w-[260px]",children:(0,j.jsx)(ta,{})}),(0,j.jsxs)(zt,{children:[(0,j.jsx)(qe,{value:"fixed",children:"Fixed price"}),(0,j.jsx)(qe,{value:"custom",children:"Buyer chooses the amount"})]})]}),N==="fixed"?(0,j.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsxs)(_e,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,j.jsx)(we,{id:"product-price",type:"number",min:"0",step:h,value:G,onChange:oe=>D(oe.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsxs)(_e,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,j.jsx)(we,{id:"product-min-amount",type:"number",min:"0",step:h,value:C,onChange:oe=>V(oe.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsxs)(_e,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,j.jsx)(we,{id:"product-max-amount",type:"number",min:"0",step:h,value:m,onChange:oe=>z(oe.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,j.jsx)("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."})]}),(0,j.jsxs)("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."]})]}),(w||N==="fixed")&&(0,j.jsxs)("div",{className:"af-space-y-1",children:[(0,j.jsx)(_e,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,j.jsx)(we,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:se,onChange:oe=>X(oe.target.value),className:"af-w-[140px]"})]})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(_e,{children:"Images"}),(0,j.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,j.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[J.map(oe=>(0,j.jsxs)(Q,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,j.jsx)("span",{className:"af-truncate",children:oe}),(0,j.jsx)("button",{type:"button",onClick:()=>st(oe),className:"af-ml-1 hover:af-text-destructive",disabled:b,children:(0,j.jsx)(Wt.X,{className:"af-h-3 af-w-3"})})]},oe)),J.length===0&&(0,j.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,j.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,j.jsx)(we,{type:"url",value:vt,onChange:oe=>St(oe.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:oe=>{oe.key==="Enter"&&(oe.preventDefault(),lt())},disabled:b}),(0,j.jsx)(_,{type:"button",variant:"outline",onClick:lt,disabled:!vt.trim()||b,children:(0,j.jsx)(Wt.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(_e,{children:"Digital File"}),(0,j.jsx)("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."}),y?(0,j.jsxs)("div",{className:"af-space-y-3",children:[Ce?.type==="download"&&(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,j.jsx)(Wt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,j.jsx)("span",{className:"af-text-sm",children:Ce.filename}),Ce.size!=null&&(0,j.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Ro(Ce.size),")"]})]}),Ce?.type==="redirect"&&Ce.url&&(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,j.jsx)(Wt.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,j.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ce.url]})]}),(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsx)("input",{ref:Le,type:"file",onChange:Ct,className:"af-hidden",disabled:Ie}),(0,j.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>Le.current?.click(),disabled:Ie,children:[Z?(0,j.jsx)(Wt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,j.jsx)(Wt.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ce?.type==="download"?"Replace file":"Upload file"]}),(0,j.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,j.jsx)(we,{type:"url",value:Re,onChange:oe=>T(oe.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Z}),(0,j.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:ht,disabled:!Re.trim()||Ie,children:"Fetch from URL"})]}),O&&(0,j.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:O})]}):(0,j.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsx)(_e,{children:"Settings"}),(0,j.jsxs)("div",{className:"af-space-y-2",children:[(0,j.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,j.jsx)("input",{type:"checkbox",checked:fe,onChange:oe=>K(oe.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,j.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,j.jsx)("input",{type:"checkbox",checked:ae,onChange:oe=>ce(oe.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),y&&t&&(0,j.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,j.jsx)(_e,{children:"Options & Variants"}),(0,j.jsx)(Bs,{productId:t.id,currency:r})]}),l&&(0,j.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),(0,j.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,j.jsxs)(_,{type:"button",onClick:yt,disabled:Ie,children:[b?(0,j.jsx)(Wt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?"Save changes":"Create product"]})})]})}var wt=ue(require("react"),1),Jt=require("lucide-react");var et=ue(require("react"),1);var Po=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ms({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ie(),[a,n]=et.useState([]),[i,o]=et.useState(0),[v,g]=et.useState(!0),[y,r]=et.useState(null),[h,w]=et.useState(0),[b,u]=et.useState(e),[l,x]=et.useState(void 0),[S,P]=et.useState(""),[L,M]=et.useState(""),[c,N]=et.useState(""),[E,G]=et.useState(!1),[D,C]=et.useState(!1),[V,m]=et.useState(void 0),z=V?V.join(","):"",se=et.useMemo(()=>{if(!z)return;let K=new Set(z.split(","));return Po.filter(ae=>!K.has(ae))},[z]),X=et.useRef(0),ee=et.useCallback(async()=>{let K=++X.current;try{g(!0),r(null);let ae={limit:b,offset:h*b};l?ae.status=l:se?ae.excludeStatus=se:E||(ae.excludeStatus=["pending","expired"]),S.trim()&&(ae.customerEmail=S.trim()),L.trim()&&(ae.from=L.trim()),c.trim()&&(ae.to=c.trim()),D&&(ae.unfulfilledOnly=!0);let ce=await s.getOrders(ae);if(K!==X.current)return;n(ce.orders),o(ce.total)}catch(ae){if(K!==X.current)return;r(ae instanceof Error?ae:new Error("Failed to fetch orders"))}finally{K===X.current&&g(!1)}},[s,h,b,l,se,E,D,S,L,c,t]);et.useEffect(()=>{ee()},[ee]);let fe=Math.ceil(i/b);return{orders:a,total:i,isLoading:v,error:y,page:h,pageSize:b,hasNextPage:h<fe-1,hasPreviousPage:h>0,setPage:w,setPageSize:K=>{u(K),w(0)},status:l,setStatus:K=>{x(K),w(0)},statusIn:V,setStatusIn:K=>{m(K&&K.length>0?K:void 0),w(0)},customerEmail:S,setCustomerEmail:K=>{P(K),w(0)},from:L,setFrom:K=>{M(K),w(0)},to:c,setTo:K=>{N(K),w(0)},showAbandoned:E,setShowAbandoned:K=>{G(K),w(0)},unfulfilledOnly:D,setUnfulfilledOnly:K=>{C(K),w(0)},clearFilters:()=>{x(void 0),m(void 0),G(!1),C(!1),P(""),M(""),N(""),w(0)},refetch:ee}}var it=ue(require("react"),1),Ee=require("lucide-react");var jr=ue(require("react"),1),Pa=ue(require("@radix-ui/react-popover"),1);var mn=require("react/jsx-runtime"),Gr=Pa.Root,Wr=Pa.Trigger;var $n=jr.forwardRef(({className:e,align:t="end",sideOffset:s=4,...a},n)=>(0,mn.jsx)(Pa.Portal,{children:(0,mn.jsx)("div",{className:"aifeatures-admin",children:(0,mn.jsx)(Pa.Content,{ref:n,align:t,sideOffset:s,className:Y("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),...a})})}));$n.displayName=Pa.Content.displayName;var Us=require("react/jsx-runtime"),Co={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function To(e){return Co[e]??e}function Kr(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 Xa({status:e,className:t}){return(0,Us.jsx)(Q,{variant:Kr(e),className:t,children:To(e)})}function Ga({status:e}){return(0,Us.jsx)(Xa,{status:e})}function ms({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Us.jsx)(Q,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Us.jsx)(Q,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Ua(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var d=require("react/jsx-runtime"),Qr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",es="af-text-xs af-text-muted-foreground";function Vn(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xr(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var pn=24,Eo=["paid","partially_refunded"],Io=["paid","partially_refunded","disputed"],Do=/^[A-Za-z0-9 _-]*$/,Jr=100;function qn(e,t,s,a,n){let i=Eo.includes(a);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${pn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${pn} tries used). Nothing is being retried while the order is ${a.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<pn&&e==="merchant"?{label:"No recipient set",variant:"destructive",detail:"Nobody was told about this sale: this site has no notification email address set. Add one in your site settings and future sales will notify you."}:s<pn&&e==="buyer"&&!n?{label:"No buyer email",variant:"destructive",detail:"This order has no buyer email address, so no receipt could be sent. Send the buyer their details another way."}:{label:"Not delivered",variant:"destructive",detail:`We stopped after ${s} attempt${s===1?"":"s"}. This will not be retried automatically \u2014 it needs you to act.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${a==="refunded"?"because the order was refunded":a==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Yr({title:e,recipient:t,status:s,attempts:a,side:n,orderStatus:i,action:o,delivery:v}){if(v)return(0,d.jsxs)("div",{children:[(0,d.jsx)(wa,{deliveries:[v]}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]});let g=qn(n,s,a,i,t);return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,d.jsx)(Q,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]})}function Zr(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=ko(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&t.push(i)}let a=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");a&&t.push(a),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([a,n])=>`${a}: ${Xr(n)}`)}function Ao(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function jn({value:e,label:t,children:s,className:a,size:n="icon"}){let[i,o]=it.useState(!1);if(!Ao())return null;let v=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},g=i?(0,d.jsx)(Ee.Check,{className:"af-h-3 af-w-3"}):(0,d.jsx)(Ee.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,d.jsx)(_,{variant:"ghost",size:"icon",className:Y("af-h-6 af-w-6 af-shrink-0",a),onClick:v,title:t,"aria-label":t,children:g}):(0,d.jsxs)(_,{variant:"outline",size:"sm",className:a,onClick:v,"aria-label":t,children:[i?(0,d.jsx)(Ee.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,d.jsx)(Ee.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function Hn({label:e,value:t}){return(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:es,children:e}),(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,d.jsx)(jn,{value:t,label:`Copy ${e}`})]})]})}function Lo({src:e}){let[t,s]=it.useState(!1);return!e||t?(0,d.jsx)("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:(0,d.jsx)(Ee.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,d.jsx)("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 Ca({title:e,action:t,children:s,className:a}){return(0,d.jsxs)("section",{className:Y("af-rounded-lg af-border af-p-4",a),children:[(0,d.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,d.jsx)("h4",{className:Qr,children:e}),t]}),(0,d.jsx)("div",{className:"af-mt-3",children:s})]})}function Lt({label:e,emphasis:t,divider:s,children:a}){return(0,d.jsxs)("div",{className:Y("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,d.jsx)("span",{className:t?"af-text-base af-font-semibold":es,children:e}),(0,d.jsx)("span",{className:Y("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function zn({onSelect:e,disabled:t,icon:s,children:a}){return(0,d.jsxs)(_,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,d.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),a]})}function Oo(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${q(dn(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),a=s?un(s):qn("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),a=s?un(s):qn("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${q(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function $s({order:e,onBack:t,onRefund:s,onOrderUpdated:a,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:v=!1,hasNextOrder:g=!1}){let{api:y}=ie(),[r,h]=it.useState(e),[w,b]=it.useState(null),[u,l]=it.useState(null),[x,S]=it.useState(!1),[P,L]=it.useState(!1),[M,c]=it.useState(!1),[N,E]=it.useState(!1),[G,D]=it.useState(""),[C,V]=it.useState(!1),[m,z]=it.useState(null),[se,X]=it.useState(!1),[ee,fe]=it.useState(""),[K,ae]=it.useState([]),[ce,J]=it.useState(!1),[Pe,vt]=it.useState(!1),[St,Ce]=it.useState(null);it.useEffect(()=>{h(e)},[e]);let bt=I=>{let Oe=I.id===r.id&&I.email_deliveries===void 0?{...I,email_deliveries:r.email_deliveries}:I;h(Oe),a?.(Oe)},Z=Object.entries(r.metadata??{}),re=Math.max(0,dn(r)-r.amount_refunded),Re=(r.status==="paid"||r.status==="partially_refunded")&&re>0,T=r.exclusive_tax_total!=null,O=I=>typeof I.amountNet=="number"?I.amountNet+(I.exclusiveTax??0):(typeof I.unitAmount=="number"?I.unitAmount:0)*(typeof I.quantity=="number"&&I.quantity>0?I.quantity:1),ve=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),Le=K.reduce((I,Oe)=>I+O(r.line_items[Oe]??{}),0)+(ce?ve:0),Ie=r.tax_total??0,lt=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((I,Oe)=>I+(Oe.exclusiveTax??0),0)),st=T?ce&&ve>0?lt:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&Ie>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,Ie-(r.tax_refunded??0)),Math.round(Ie*Le/(r.amount_total+(r.shipping_total??0)))):0,yt=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(Le+st,re):Le+st,Ct=K.length>0||ce,ht=Ct?yt:Tt(ee,r.currency),oe=Gt(r.currency)?"1":"0.01",Be=async()=>{try{S(!0),b(null),l(null),await y.resendOrderReceipt(r.id);let I=await y.getOrder(r.id);bt(I),l("Receipt email queued.")}catch(I){b(I instanceof Error?I.message:"Failed to resend receipt")}finally{S(!1)}},Je=async()=>{try{L(!0),b(null),l(null);let I=await y.resetOrderDownloads(r.id);bt(I),c(!1),l("Download count reset.")}catch(I){b(I instanceof Error?I.message:"Failed to reset downloads")}finally{L(!1)}},ha=r.line_items.some(I=>I.collectShippingAddress===!0&&!I.refunded&&!I.unavailableReason),Xt=typeof r.merchant_fulfilled_at=="string",La=Io.includes(r.status)||r.status==="refunded"&&r.line_items.some(I=>I.collectShippingAddress===!0&&I.amountNet===0&&!I.refunded&&!I.unavailableReason),Xe=G.trim(),Ye=Do.test(Xe)&&Xe.length<=Jr,A=async I=>{try{V(!0),z(null),l(null);let Oe=await y.setOrderFulfillment(r.id,{fulfilled:I,...I&&Xe?{trackingNumber:Xe}:{}});bt(Oe),D(""),l(I?"Marked as shipped.":"Marked as not shipped.")}catch(Oe){Oe instanceof Dt&&Oe.status===409?z(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):z(Oe instanceof Error?Oe.message:"Failed to update the order")}finally{V(!1)}},Ge=()=>{Ce(null),fe(String(rt(re,r.currency))),ae([]),J(!1),X(!0)},H=I=>ae(Oe=>Oe.includes(I)?Oe.filter(It=>It!==I):[...Oe,I]),_t=async(I,Oe)=>{if(s)try{vt(!0),Ce(null),await s(r,I,Oe);let It=await y.getOrder(r.id);bt(It),X(!1),l("Refund issued.")}catch(It){Ce(It instanceof Error?It.message:"Refund failed")}finally{vt(!1)}},ji=async()=>{if(Ct){if(yt<=0){Ce("The lines you picked were charged nothing");return}if(yt>re){Ce(`That selection exceeds the refundable remainder (${q(re,r.currency)})`);return}await _t(yt,{...K.length>0?{line_items:[...K].sort((Oe,It)=>Oe-It)}:{},...ce?{shipping:!0}:{}});return}let I=Tt(ee,r.currency);if(I===null||I<=0){Ce("Enter a valid refund amount");return}if(I>re){Ce(`Amount exceeds the refundable remainder (${q(re,r.currency)})`);return}await _t(I,{amount:I})},Gi=()=>_t(re,{full:!0}),mr=!r.subscription_history_only&&r.fulfillment_type==="download",pr=!r.subscription_history_only&&n&&ha,Wi=Oo(r),Ki=r.shipping_address?Zr(r.shipping_address).join(`
|
|
4
|
-
`):"",gr=r.shipping_total!=null,On=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),vr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-On):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,br=On>0,Ji=vr>0,yr=r.amount_subtotal!=null||gr||br||(r.discount_total??0)>0,hs=[];return r.subscription_history_only||hs.push((0,d.jsx)(zn,{icon:x?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,d.jsx)(Ee.Mail,{className:"af-h-4 af-w-4"}),disabled:x||r.fulfillment_status!=="fulfilled",onSelect:()=>{E(!1),Be()},children:"Resend receipt"},"resend")),mr&&hs.push((0,d.jsx)(zn,{icon:(0,d.jsx)(Ee.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:P,onSelect:()=>{E(!1),c(!0)},children:"Reset download count"},"reset")),Re&&hs.push((0,d.jsxs)("div",{children:[(0,d.jsx)(zn,{icon:(0,d.jsx)(Ee.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{E(!1),Ge()},children:"Refund\u2026"}),!s&&(0,d.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"af-mb-6",children:[(0,d.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,d.jsx)(Ee.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,d.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Ua(r)}),(0,d.jsx)(Xa,{status:r.status}),n&&!r.subscription_history_only&&(0,d.jsx)(ms,{order:r}),r.is_test&&(0,d.jsx)(Q,{variant:"outline",children:"Test"})]}),(0,d.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",Vn(r.created_at)]}),r.is_test&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&(0,d.jsxs)("div",{className:"af-flex af-items-center",children:[(0,d.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!v,"aria-label":"Previous order",children:(0,d.jsx)(Ee.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,d.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!g,"aria-label":"Next order",children:(0,d.jsx)(Ee.ChevronRight,{className:"af-h-4 af-w-4"})})]}),pr&&(Xt?(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${Vn(r.merchant_fulfilled_at)}`:""]}),La&&(0,d.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>A(!1),disabled:C,children:[C?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ee.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):La?(0,d.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,d.jsx)(we,{value:G,onChange:I=>D(I.target.value),placeholder:"Tracking number (optional)",maxLength:Jr,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:C}),(0,d.jsxs)(_,{variant:"default",className:"af-shrink-0",onClick:()=>A(!0),disabled:C||!Ye,children:[C?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ee.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),hs.length>0&&(0,d.jsxs)(Gr,{open:N,onOpenChange:E,children:[(0,d.jsx)(Wr,{asChild:!0,children:(0,d.jsx)(_,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,d.jsx)(Ee.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,d.jsx)($n,{children:(0,d.jsx)("div",{className:"af-space-y-0.5",children:hs})})]})]})]}),pr&&!Xt&&!Ye&&(0,d.jsx)("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."}),m&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:m}),u&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:u}),w&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:w})]}),(0,d.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,d.jsxs)("div",{className:"af-space-y-6",children:[r.line_items.length>0&&(0,d.jsx)(Ca,{title:"Items",children:(0,d.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((I,Oe)=>{let It=typeof I.name=="string"&&I.name?I.name:"Item",hr=typeof I.quantity=="number"&&I.quantity>0?I.quantity:1,xr=typeof I.unitAmount=="number";return(0,d.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,d.jsx)(Lo,{src:typeof I.imageUrl=="string"&&I.imageUrl?I.imageUrl:void 0}),(0,d.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,d.jsxs)("div",{className:"af-text-sm af-font-medium",children:[It,typeof I.variantTitle=="string"&&I.variantTitle&&(0,d.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",I.variantTitle]})]}),(0,d.jsxs)("div",{className:es,children:[hr," \xD7"," ",xr?q(I.unitAmount,r.currency):"\u2014"]}),I.unavailableReason==="oversold"&&!I.refunded&&(0,d.jsx)(Q,{variant:"secondary",className:"af-mt-1",children:I.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),I.refunded===!0&&(0,d.jsx)(Q,{variant:"secondary",className:"af-mt-1",children:I.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,d.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof I.amountNet=="number"||xr?q(I.amountNet??I.unitAmount*hr,r.currency):"\u2014"})]},Oe)})})}),Z.length>0&&(0,d.jsx)(Ca,{title:"Order details",children:(0,d.jsx)("dl",{className:"af-space-y-2",children:Z.map(([I,Oe])=>(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{className:Y(es,"af-capitalize"),children:I.replace(/_/g," ")}),(0,d.jsx)("dd",{className:"af-text-sm af-break-words",children:Xr(Oe)})]},I))})}),(0,d.jsx)(Ca,{title:"Totals",children:(0,d.jsxs)("div",{className:"af-w-full",children:[yr&&(0,d.jsx)(Lt,{label:"Subtotal",children:q(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&(0,d.jsxs)(Lt,{label:"Discount",children:["\u2212",q(r.discount_total,r.currency)]}),gr&&(0,d.jsx)(Lt,{label:"Shipping",children:r.shipping_total===0?"Free":q(r.shipping_total??0,r.currency)}),br&&(0,d.jsx)(Lt,{label:"Tax",children:q(On,r.currency)}),(0,d.jsx)(Lt,{label:"Total",emphasis:!0,divider:yr,children:q(Ra(r),r.currency)}),(r.credit_applied??0)>0&&(0,d.jsxs)(Lt,{label:"Credit applied",children:["\u2212",q(r.credit_applied,r.currency)]}),r.amount_paid!=null&&(0,d.jsx)(Lt,{label:"Amount paid",children:q(r.amount_paid,r.currency)}),Ji&&(0,d.jsx)(Lt,{label:"incl. tax",children:q(vr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,d.jsxs)(Lt,{label:"Your price",children:[q(r.base_amount_total,r.base_currency),(0,d.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(Lt,{label:"Refunded",children:["\u2212",q(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&(0,d.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",q(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,d.jsx)(Lt,{label:"Net",children:(0,d.jsx)("span",{className:"af-font-medium",children:q(Math.max(0,dn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&(0,d.jsxs)(Ca,{title:"Platform fee",children:[r.application_fee_original!=null&&(0,d.jsx)(Lt,{label:"Collected",children:q(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&(0,d.jsx)(Lt,{label:"Returned",children:q(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&(0,d.jsx)(Lt,{label:"Retained",children:q(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&(0,d.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:r.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,d.jsx)(Ca,{title:"Timeline",children:(0,d.jsx)("ol",{className:"af-space-y-3",children:Wi.map(I=>(0,d.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,d.jsx)("span",{"aria-hidden":"true",className:Y("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")}),(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsx)("div",{className:"af-text-sm af-break-words",children:I.text}),I.at&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:Vn(I.at)})]})]},I.key))})})]}),(0,d.jsxs)("div",{className:"af-space-y-6",children:[(0,d.jsx)(Ca,{title:"Customer",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:es,children:"Email"}),(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||(0,d.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&(0,d.jsx)(jn,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:es,children:"Name"}),(0,d.jsx)("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:es,children:"Customer record"}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,d.jsx)("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),(0,d.jsx)(Q,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,d.jsx)(Ca,{title:"Ship to",action:(0,d.jsx)(jn,{value:Ki,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,d.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Zr(r.shipping_address).map((I,Oe)=>(0,d.jsx)("div",{children:I},Oe))})}),r.subscription_history_only?(0,d.jsx)(Ca,{title:"Subscription history",children:(0,d.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,d.jsxs)(Ca,{title:"Emails",children:[(0,d.jsx)(wa,{deliveries:r.email_deliveries?.filter(I=>!["purchase_receipt","merchant_sale"].includes(I.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(0,d.jsx)(Yr,{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:(0,d.jsxs)(_,{variant:"outline",size:"sm",onClick:Be,disabled:x||r.fulfillment_status!=="fulfilled",children:[x?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ee.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,d.jsx)(Yr,{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})]})]}),mr&&(0,d.jsx)(Ca,{title:"Download",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,d.jsx)(Ee.Download,{className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&(0,d.jsx)("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"})]})}),(0,d.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,d.jsx)("summary",{className:Y(Qr,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,d.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,d.jsx)(Hn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,d.jsx)(Hn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,d.jsx)(Hn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,d.jsx)(Sa,{open:M,onOpenChange:I=>{!I&&!P&&c(!1)},children:(0,d.jsxs)(fa,{children:[(0,d.jsxs)(ma,{children:[(0,d.jsx)(ga,{children:"Reset download count?"}),(0,d.jsx)(va,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,d.jsxs)(pa,{children:[(0,d.jsx)(_,{variant:"outline",onClick:()=>c(!1),disabled:P,children:"Cancel"}),(0,d.jsx)(_,{onClick:Je,disabled:P,children:P?"Resetting...":"Reset"})]})]})}),(0,d.jsx)(Sa,{open:se,onOpenChange:I=>{!I&&!Pe&&X(!1)},children:(0,d.jsxs)(fa,{children:[(0,d.jsxs)(ma,{children:[(0,d.jsx)(ga,{children:"Refund order"}),(0,d.jsxs)(va,{children:["Refund up to ",q(re,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(r.line_items.length>0||ve>0)&&(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsx)(_e,{children:"Items"}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((I,Oe)=>{let It=I.refunded===!0;return(0,d.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,d.jsx)("input",{type:"checkbox",checked:K.includes(Oe),onChange:()=>H(Oe),disabled:Pe||It||!!I.unavailableReason||O(I)<=0,className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{className:It?"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}`:""]}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:It?"Refunded":q(O(I),r.currency)})]},Oe)}),ve>0&&(0,d.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,d.jsx)("input",{type:"checkbox",checked:ce,onChange:I=>J(I.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,d.jsx)("span",{children:"Shipping"}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:q(ve,r.currency)})]})]})]}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)(_e,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,d.jsx)(we,{id:"refund-amount",type:"number",min:"0",step:oe,value:Ct?String(rt(yt,r.currency)):ee,onChange:I=>fe(I.target.value),disabled:Pe||Ct}),Ct&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),St&&(0,d.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:St}),(0,d.jsxs)(pa,{children:[(0,d.jsx)(_,{variant:"outline",onClick:()=>X(!1),disabled:Pe,children:"Cancel"}),(0,d.jsx)(_,{variant:"outline",onClick:Gi,disabled:Pe,children:"Refund everything"}),(0,d.jsx)(_,{variant:"destructive",onClick:ji,disabled:Pe,children:Pe?"Refunding...":ht!==null&&ht>0?`Refund ${q(ht,r.currency)}`:"Refund"})]})]})})]})}var gn=ue(require("react"),1),vn=require("lucide-react");var pt=require("react/jsx-runtime");function xt({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:a,className:n}){let i=gn.useRef(null);return gn.useEffect(()=>{i.current?.focus()},[]),(0,pt.jsxs)("div",{className:Y("af-bg-background",n),children:[(0,pt.jsxs)("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:[(0,pt.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&(0,pt.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:t,children:[(0,pt.jsx)(vn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,pt.jsx)("div",{className:"af-p-4",children:a})]})}function te({className:e}){return(0,pt.jsx)("div",{"aria-hidden":"true",className:Y("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Ze({label:e,children:t,detail:s,valueClassName:a}){return(0,pt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,pt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,pt.jsx)("div",{className:Y("af-mt-1 af-text-lg af-font-semibold",a),children:t}),s&&(0,pt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function Kt({message:e,onRetry:t}){return(0,pt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,pt.jsx)("span",{children:e}),(0,pt.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,pt.jsx)(vn.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ta({icon:e,children:t}){return(0,pt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,pt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}var R=require("react/jsx-runtime"),Bo={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},ei={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function ti(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ai(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let a=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${a} \xD7${n}`:a;return t.length>1?`${i} +${t.length-1} more`:i}function bn(e){return e.customer?.name||e.customer_name||null}function ts({onRefund:e,className:t,refreshKey:s,initialOrderId:a,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:v}=ie(),g=Ms({refreshKey:s}),{orders:y,total:r,isLoading:h,error:w,page:b,pageSize:u,hasNextPage:l,hasPreviousPage:x,setPage:S,setPageSize:P,customerEmail:L,setCustomerEmail:M,setStatusIn:c,from:N,setFrom:E,to:G,setTo:D,showAbandoned:C,setShowAbandoned:V,setUnfulfilledOnly:m,refetch:z}=g,[se,X]=wt.useState("list"),[ee,fe]=wt.useState(null),[K,ae]=wt.useState(""),[ce,J]=wt.useState(""),[Pe,vt]=wt.useState(n?"needs_shipping":"all"),[St,Ce]=wt.useState(!1),[bt,Z]=wt.useState(!!a),[re,Re]=wt.useState(null);wt.useEffect(()=>{if(!a)return;let H=!1;return Z(!0),Re(null),v.getOrder(a).then(_t=>{H||(fe(_t),X("detail"))}).catch(()=>{H||Re("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{H||Z(!1)}),()=>{H=!0}},[v,a]);let T=wt.useCallback(H=>{vt(H);let _t=ei[H];c(_t.statusIn),m(_t.unfulfilledOnly)},[c,m]);wt.useEffect(()=>{n&&m(!0)},[]);let O=wt.useRef(!n);wt.useEffect(()=>{O.current||h||(O.current=!0,y.length===0&&T("all"))},[h,y.length,T]);let ve=se==="detail"&&!!ee;wt.useEffect(()=>{o?.(ve)},[ve,o]);let Le=(N?1:0)+(G?1:0)+(C?1:0),Ie=Le>0||!!L||!!ce,lt=!!N&&!!G&&N>G,st=H=>{fe(H),X("detail")},yt=()=>{X("list"),fe(null),z()},Ct=H=>{let _t=H.trim();if(!_t){J(""),L&&M("");return}if(_t.startsWith("#")||/^\d+$/.test(_t)){J(_t),L&&M("");return}J(""),M(_t)},ht=()=>{ae(""),J(""),M(""),E(""),D(""),V(!1),Ce(!1)},oe=ce.replace(/^#/,"").toLowerCase(),Be=oe?y.filter(H=>String(H.order_number??"")===oe||H.id.toLowerCase().startsWith(oe)):y,Je=ee?y.findIndex(H=>H.id===ee.id):-1,ha=Je>0,Xt=Je>=0&&Je<y.length-1;if(bt)return(0,R.jsx)("div",{className:t,children:(0,R.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,R.jsx)(Jt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(se==="detail"&&ee)return(0,R.jsx)("div",{className:t,children:(0,R.jsx)($s,{order:ee,onBack:yt,onRefund:e,onOrderUpdated:H=>fe(H),allowFulfillment:n,onPrevOrder:ha?()=>fe(y[Je-1]):void 0,onNextOrder:Xt?()=>fe(y[Je+1]):void 0,hasPrevOrder:ha,hasNextOrder:Xt},ee.id)});let Xe=(0,R.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[re&&(0,R.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:re}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("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(H=>(0,R.jsx)("button",{type:"button","aria-pressed":Pe===H,onClick:()=>T(H),className:Y("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Pe===H?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Bo[H]},H))}),(0,R.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,R.jsx)(Jt.Search,{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"}),(0,R.jsx)(we,{type:"text",value:K,onChange:H=>ae(H.target.value),onBlur:()=>Ct(K),onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),Ct(K))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,R.jsxs)(_,{type:"button",variant:Le>0?"secondary":"ghost",size:"sm",onClick:()=>Ce(H=>!H),"aria-expanded":St,children:[(0,R.jsx)(Jt.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Le>0&&(0,R.jsx)(Q,{variant:"secondary",className:"af-ml-2",children:Le})]}),Ie&&(0,R.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:ht,children:"Clear filters"})]}),(St||!!N||!!G)&&(0,R.jsxs)("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:[(0,R.jsx)(_e,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,R.jsx)(we,{id:"orders-from",type:"date",value:N,max:G||void 0,onChange:H=>E(H.target.value),className:"af-w-[170px]"}),(0,R.jsx)(_e,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,R.jsx)(we,{id:"orders-to",type:"date",value:G,min:N||void 0,onChange:H=>D(H.target.value),className:"af-w-[170px]"}),!ei[Pe].statusIn&&(0,R.jsx)(_,{type:"button",variant:C?"secondary":"ghost",size:"sm",onClick:()=>V(!C),"aria-pressed":C,children:C?"Hide abandoned":"Show abandoned"})]}),lt&&(0,R.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(h)return(0,R.jsxs)("div",{className:t,children:[Xe,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(H=>(0,R.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,R.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,R.jsx)(te,{className:"af-h-4 af-w-16"}),(0,R.jsx)(te,{className:"af-h-4 af-w-14"})]}),(0,R.jsx)(te,{className:"af-mt-2 af-h-3 af-w-40"}),(0,R.jsx)(te,{className:"af-mt-2 af-h-3 af-w-24"})]},H))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(Me,{children:[(0,R.jsx)(Ue,{children:(0,R.jsxs)(he,{children:[(0,R.jsx)(U,{children:"Order"}),(0,R.jsx)(U,{children:"Date"}),(0,R.jsx)(U,{children:"Customer"}),(0,R.jsx)(U,{children:"Items"}),(0,R.jsx)(U,{className:"af-text-right",children:"Total"}),(0,R.jsx)(U,{children:"Status"}),(0,R.jsx)(U,{className:"af-w-8"})]})}),(0,R.jsx)($e,{"aria-hidden":"true",children:[0,1,2,3,4].map(H=>(0,R.jsxs)(he,{children:[(0,R.jsx)($,{children:(0,R.jsx)(te,{className:"af-h-4 af-w-14"})}),(0,R.jsx)($,{children:(0,R.jsx)(te,{className:"af-h-4 af-w-24"})}),(0,R.jsx)($,{children:(0,R.jsx)(te,{className:"af-h-4 af-w-40"})}),(0,R.jsx)($,{children:(0,R.jsx)(te,{className:"af-h-4 af-w-32"})}),(0,R.jsx)($,{children:(0,R.jsx)(te,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,R.jsx)($,{children:(0,R.jsx)(te,{className:"af-h-5 af-w-16"})}),(0,R.jsx)($,{})]},H))})]})}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(w)return(0,R.jsxs)("div",{className:t,children:[Xe,(0,R.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,R.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,R.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>z(),children:"Try again"})]})]});let Ye=Pe!=="all";if(Be.length===0&&b===0)return(0,R.jsxs)("div",{className:t,children:[(Ie||Ye)&&Xe,(0,R.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,R.jsx)(Jt.Receipt,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,R.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:Ie||Ye?"No orders match these filters.":i??(0,R.jsxs)(R.Fragment,{children:["No orders yet.",(0,R.jsx)("br",{}),"Orders will appear here when someone buys from your website."]})}),!Ie&&!Ye&&(0,R.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>V(!0),children:"Show abandoned checkouts"})]})]});let A=b*u+1,Ge=Math.min((b+1)*u,r);return(0,R.jsxs)("div",{className:t,children:[Xe,(0,R.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Be.map(H=>(0,R.jsxs)("button",{type:"button",onClick:()=>st(H),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,R.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,R.jsx)("span",{className:"af-font-medium",children:Ua(H)}),(0,R.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:q(Ra(H),H.currency)})]}),(0,R.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,R.jsxs)("div",{className:"af-truncate af-text-sm",children:[H.customer_email||(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),bn(H)&&(0,R.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",bn(H)]})]}),(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ai(H)}),H.amount_refunded>0&&(0,R.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",q(H.amount_refunded,H.currency)," refunded"]})]}),(0,R.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,R.jsx)(Xa,{status:H.status}),(0,R.jsx)(Ss,{deliveries:H.email_deliveries}),H.is_test&&(0,R.jsx)(Q,{variant:"outline",children:"Test"}),n&&(0,R.jsx)(ms,{order:H}),(0,R.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ti(H.created_at)})]})]},H.id))}),(0,R.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,R.jsxs)(Me,{children:[(0,R.jsx)(Ue,{children:(0,R.jsxs)(he,{children:[(0,R.jsx)(U,{children:"Order"}),(0,R.jsx)(U,{children:"Date"}),(0,R.jsx)(U,{children:"Customer"}),(0,R.jsx)(U,{children:"Items"}),(0,R.jsx)(U,{className:"af-text-right",children:"Total"}),(0,R.jsx)(U,{children:"Status"}),(0,R.jsx)(U,{className:"af-w-8"})]})}),(0,R.jsx)($e,{children:Be.map(H=>(0,R.jsxs)(he,{onClick:()=>st(H),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,R.jsxs)($,{className:"af-whitespace-nowrap af-font-medium",children:[(0,R.jsx)("button",{type:"button",onClick:_t=>{_t.stopPropagation(),st(H)},"aria-label":`Open order ${Ua(H)}`,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(H)}),H.is_test&&(0,R.jsx)(Q,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,R.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ti(H.created_at)}),(0,R.jsxs)($,{className:"af-max-w-[220px]",children:[(0,R.jsx)("div",{className:"af-truncate",children:H.customer_email||(0,R.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),bn(H)&&(0,R.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:bn(H)})]}),(0,R.jsx)($,{className:"af-max-w-[220px]",children:(0,R.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:ai(H)})}),(0,R.jsxs)($,{className:"af-whitespace-nowrap af-text-right",children:[(0,R.jsx)("div",{className:"af-font-medium af-tabular-nums",children:q(Ra(H),H.currency)}),H.amount_refunded>0&&(0,R.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",q(H.amount_refunded,H.currency)," ","refunded"]})]}),(0,R.jsx)($,{children:(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,R.jsx)(Xa,{status:H.status}),(0,R.jsx)(Ss,{deliveries:H.email_deliveries}),n&&(0,R.jsx)(ms,{order:H})]})}),(0,R.jsx)($,{className:"af-w-8 af-text-right",children:(0,R.jsx)(Jt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},H.id))})]})}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,R.jsx)("span",{children:oe?`${Be.length} matching this page`:`Showing ${A}-${Ge} of ${r}`}),(0,R.jsxs)(ea,{value:String(u),onValueChange:H=>P(Number(H)),children:[(0,R.jsx)(Ht,{className:"af-w-[70px] af-h-8",children:(0,R.jsx)(ta,{})}),(0,R.jsxs)(zt,{children:[(0,R.jsx)(qe,{value:"10",children:"10"}),(0,R.jsx)(qe,{value:"25",children:"25"}),(0,R.jsx)(qe,{value:"50",children:"50"}),(0,R.jsx)(qe,{value:"100",children:"100"})]})]}),(0,R.jsx)("span",{children:"per page"})]}),(0,R.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,R.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>S(b-1),disabled:!x,children:[(0,R.jsx)(Jt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,R.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>S(b+1),disabled:!l,children:["Next",(0,R.jsx)(Jt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var hn=ue(require("react"),1),ka=require("lucide-react");var Ot=ue(require("react"),1);function Vs({initialPageSize:e=25}={}){let{api:t}=ie(),[s,a]=Ot.useState([]),[n,i]=Ot.useState(0),[o,v]=Ot.useState(!0),[g,y]=Ot.useState(null),[r,h]=Ot.useState(0),[w,b]=Ot.useState(e),[u,l]=Ot.useState(""),x=Ot.useRef(0),S=Ot.useCallback(async()=>{let L=++x.current;try{v(!0),y(null);let M={limit:w,offset:r*w};u.trim()&&(M.email=u.trim());let c=await t.getCustomers(M);if(L!==x.current)return;a(c.customers),i(c.total)}catch(M){if(L!==x.current)return;y(M instanceof Error?M:new Error("Failed to fetch customers"))}finally{L===x.current&&v(!1)}},[t,r,w,u]);Ot.useEffect(()=>{S()},[S]);let P=Math.ceil(n/w);return{customers:s,total:n,isLoading:o,error:g,page:r,pageSize:w,hasNextPage:r<P-1,hasPreviousPage:r>0,setPage:h,setPageSize:L=>{b(L),h(0)},email:u,setEmail:L=>{l(L),h(0)},refetch:S}}var as=ue(require("react"),1),yn=require("lucide-react");var pe=require("react/jsx-runtime");function si(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Fo(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function Hs({customer:e,onBack:t,className:s}){let{api:a}=ie(),[n,i]=as.useState(null),[o,v]=as.useState([]),[g,y]=as.useState(!0),[r,h]=as.useState(null);as.useEffect(()=>{let u=!1;return y(!0),h(null),Promise.all([a.getCustomer(e.id),a.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,x])=>{u||(i(l),v(x.orders))}).catch(l=>{u||h(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{u||y(!1)}),()=>{u=!0}},[a,e.id,e.email]);let w=n?.addresses??[],b=n?.order_count??o.length;return(0,pe.jsxs)("div",{className:s,children:[(0,pe.jsxs)("div",{className:"af-mb-6",children:[(0,pe.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,pe.jsx)(yn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,pe.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,pe.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",si(e.created_at)]})]}),g?(0,pe.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,pe.jsx)(yn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,pe.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,pe.jsxs)("div",{className:"af-space-y-6",children:[(0,pe.jsx)(wa,{deliveries:n?.email_deliveries}),(0,pe.jsxs)("div",{children:[(0,pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,pe.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,pe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,pe.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,pe.jsx)("span",{children:e.email})]}),e.name&&(0,pe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,pe.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,pe.jsx)("span",{children:e.name})]}),e.phone&&(0,pe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,pe.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,pe.jsx)("span",{children:e.phone})]}),(0,pe.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,pe.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,pe.jsx)("span",{children:b})]})]})]}),w.length>0&&(0,pe.jsxs)("div",{children:[(0,pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,pe.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:w.map(u=>(0,pe.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&(0,pe.jsx)(Q,{variant:"secondary",className:"af-mb-1",children:"Default"}),Fo(u).map((l,x)=>(0,pe.jsx)("div",{children:l},x))]},u.id))})]}),(0,pe.jsxs)("div",{children:[(0,pe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,pe.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,pe.jsxs)(Me,{children:[(0,pe.jsx)(Ue,{children:(0,pe.jsxs)(he,{children:[(0,pe.jsx)(U,{children:"Date"}),(0,pe.jsx)(U,{children:"Amount"}),(0,pe.jsx)(U,{children:"Status"})]})}),(0,pe.jsx)($e,{children:o.map(u=>(0,pe.jsxs)(he,{children:[(0,pe.jsx)($,{className:"af-text-muted-foreground",children:si(u.created_at)}),(0,pe.jsx)($,{children:q(Ra(u),u.currency)}),(0,pe.jsx)($,{children:(0,pe.jsx)(Ga,{status:u.status})})]},u.id))})]})]})]})]})}var le=require("react/jsx-runtime");function Mo(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function zs({className:e}){let{customers:t,total:s,isLoading:a,error:n,page:i,pageSize:o,hasNextPage:v,hasPreviousPage:g,setPage:y,setPageSize:r,email:h,setEmail:w,refetch:b}=Vs(),[u,l]=hn.useState("list"),[x,S]=hn.useState(null),[P,L]=hn.useState(""),M=D=>{S(D),l("detail")},c=()=>{l("list"),S(null),b()};if(u==="detail"&&x)return(0,le.jsx)("div",{className:e,children:(0,le.jsx)(Hs,{customer:x,onBack:c})});let N=(0,le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,le.jsx)(we,{type:"email",value:P,onChange:D=>L(D.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),w(P.trim()))}}),(0,le.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>w(P.trim()),children:[(0,le.jsx)(ka.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),h&&(0,le.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{L(""),w("")},children:"Clear"})]});if(a)return(0,le.jsxs)("div",{className:e,children:[N,(0,le.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,le.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,le.jsxs)("div",{className:e,children:[N,(0,le.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,le.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&i===0)return(0,le.jsxs)("div",{className:e,children:[h&&N,(0,le.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,le.jsx)(ka.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,le.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:h?"No customers match that email.":(0,le.jsxs)(le.Fragment,{children:["No customers yet.",(0,le.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let E=i*o+1,G=Math.min((i+1)*o,s);return(0,le.jsxs)("div",{className:e,children:[N,(0,le.jsxs)(Me,{children:[(0,le.jsx)(Ue,{children:(0,le.jsxs)(he,{children:[(0,le.jsx)(U,{children:"Email"}),(0,le.jsx)(U,{children:"Name"}),(0,le.jsx)(U,{children:"Customer since"}),(0,le.jsx)(U,{className:"af-text-right",children:"Actions"})]})}),(0,le.jsx)($e,{children:t.map(D=>(0,le.jsxs)(he,{children:[(0,le.jsx)($,{className:"af-font-medium",children:D.email}),(0,le.jsx)($,{children:D.name||(0,le.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,le.jsx)($,{className:"af-text-muted-foreground",children:Mo(D.created_at)}),(0,le.jsx)($,{className:"af-text-right",children:(0,le.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>M(D),title:"View customer",children:(0,le.jsx)(ka.Eye,{className:"af-h-4 af-w-4"})})})]},D.id))})]}),(0,le.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,le.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,le.jsxs)("span",{children:["Showing ",E,"-",G," of ",s]}),(0,le.jsxs)(ea,{value:String(o),onValueChange:D=>r(Number(D)),children:[(0,le.jsx)(Ht,{className:"af-w-[70px] af-h-8",children:(0,le.jsx)(ta,{})}),(0,le.jsxs)(zt,{children:[(0,le.jsx)(qe,{value:"10",children:"10"}),(0,le.jsx)(qe,{value:"25",children:"25"}),(0,le.jsx)(qe,{value:"50",children:"50"}),(0,le.jsx)(qe,{value:"100",children:"100"})]})]}),(0,le.jsx)("span",{children:"per page"})]}),(0,le.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,le.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(i-1),disabled:!g,children:[(0,le.jsx)(ka.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,le.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(i+1),disabled:!v,children:["Next",(0,le.jsx)(ka.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ke=ue(require("react"),1),dt=require("lucide-react");var ut=ue(require("react"),1);function ss({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:a}=ie(),[n,i]=ut.useState([]),[o,v]=ut.useState(0),[g,y]=ut.useState(null),[r,h]=ut.useState(!0),[w,b]=ut.useState(null),[u,l]=ut.useState(0),[x,S]=ut.useState(e),[P,L]=ut.useState(void 0),[M,c]=ut.useState(""),[N,E]=ut.useState(""),[G,D]=ut.useState(""),[C,V]=ut.useState(""),[m,z]=ut.useState(""),se=P?P.join(","):"",X=ut.useRef(0),ee=ut.useCallback(async()=>{let K=++X.current;h(!0),b(null);try{let ae={labels:se?se.split(","):void 0,customerEmail:M||void 0,q:N||void 0,from:G||void 0,to:C||void 0,retainerId:m||void 0,includeAggregates:s,limit:x,offset:u*x},ce=await a.getInvoices(ae);if(K!==X.current)return;if(u>0&&u*x>=ce.total){l(Math.max(0,Math.ceil(ce.total/x)-1));return}i(ce.invoices),v(ce.total),s&&y(ce.aggregates??null)}catch(ae){if(K!==X.current)return;b(ae instanceof Error?ae:new Error("Failed to fetch invoices"))}finally{K===X.current&&h(!1)}},[a,se,M,N,G,C,m,u,x,s]);ut.useEffect(()=>{ee()},[ee,t]);let fe=K=>ae=>{l(0),K(ae)};return{invoices:n,total:o,aggregates:g,isLoading:r,error:w,page:u,pageSize:x,hasNextPage:(u+1)*x<o,hasPreviousPage:u>0,setPage:l,setPageSize:fe(S),labels:P,setLabels:fe(L),customerEmail:M,setCustomerEmail:fe(c),q:N,setQ:fe(E),from:G,setFrom:fe(D),to:C,setTo:fe(V),retainerId:m,setRetainerId:fe(z),clearFilters:()=>{l(0),L(void 0),c(""),E(""),D(""),V(""),z("")},refetch:ee}}var f=require("react/jsx-runtime"),Uo={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`:Uo[e.label]??e.label}function $o(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"},Vo={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function gs({invoice:e,className:t}){return(0,f.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,f.jsx)(Q,{variant:$o(e.label),className:t,children:Yn(e)}),e.collection_method==="charge_automatically"&&(0,f.jsx)(Q,{variant:"secondary",children:"Managed in Stripe"})]})}function wn({delivery:e,className:t}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,f.jsx)(Q,{variant:s,className:t,children:Jn[e.state]??e.state})}function ps(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ia(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var ni={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 Ho(e){let t=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),a=s?`'${t}`:t;return s||/[",;\r\n]/.test(a)?`"${a.replace(/"/g,'""')}"`:a}var Wn=100,Kn=5e3;async function zo(e,t){let s=[],a=0;for(let n=0;n<Kn;n+=Wn){let i=await e.getInvoices({...t,limit:Wn,offset:n});if(a=i.total,s.push(...i.invoices),i.invoices.length<Wn||s.length>=a)break}return{invoices:s.slice(0,Kn),total:a,truncated:a>s.length||a>Kn}}function ii(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(a=>[a.id,ps(a),Yn(a),a.customer_name??"",a.customer_email??"",a.created_at,a.due_at??"",a.paid_at??"",a.currency.toUpperCase(),q(a.amount_subtotal,a.currency),q(a.tax_total,a.currency),q(a.amount_total,a.currency),a.amount_due===null?"":q(a.amount_due,a.currency),a.amount_paid===null?"":q(a.amount_paid,a.currency),q(a.amount_refunded,a.currency),a.payment_method??"",a.pay_url??"",a.retainer_id??"",a.replaces_order_id??"",a.replaced_by_order_id??"",a.tax_behavior??"",a.discount_total===void 0?"":q(a.discount_total,a.currency),a.collection_method??""]);return[t,...s].map(a=>a.map(Ho).join(",")).join(`
|
|
5
|
-
`)}function qo(e){if(typeof document>"u")return;let t=new Blob([ii(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(t),a=document.createElement("a");a.href=s,a.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function ns({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:a,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:v=null,onClearRetainerFilter:g}){let{api:y}=ie(),{invoices:r,total:h,isLoading:w,error:b,page:u,pageSize:l,hasNextPage:x,hasPreviousPage:S,setPage:P,labels:L,setLabels:M,customerEmail:c,setCustomerEmail:N,q:E,setQ:G,from:D,setFrom:C,to:V,setTo:m,retainerId:z,setRetainerId:se,refetch:X}=ss({refreshKey:t}),[ee,fe]=ke.useState("open"),[K,ae]=ke.useState(""),[ce,J]=ke.useState(null),Pe=ke.useRef(0),vt=ke.useCallback(A=>{Pe.current++,Ce(!1),J(A)},[]),[St,Ce]=ke.useState(!1),[bt,Z]=ke.useState(0),[re,Re]=ke.useState(null),[T,O]=ke.useState(!1),[ve,Le]=ke.useState(0);ke.useEffect(()=>{J(A=>{if(!A)return A;let Ge=r.find(H=>H.id===A.id);return Ge&&Ge!==A?Ge:A})},[r]);let[Ie,lt]=ke.useState(!1),[st,yt]=ke.useState(null),Ct=async()=>{if(!Ie){lt(!0),yt(null);try{let{invoices:A,total:Ge,truncated:H}=await zo(y,{labels:L,customerEmail:c,q:E,from:D,to:V,retainerId:z});qo(A),yt(H?`Exported the first ${A.length.toLocaleString()} of ${Ge.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{yt("Couldn't export \u2014 try again.")}finally{lt(!1)}}},ht=!c&&!E&&!D&&!V&&!z,[oe,Be]=ke.useState(null);ke.useEffect(()=>{if(w||h>0||!ht||ee!=="open")return;let A=!1;return y.getInvoices({limit:1}).then(Ge=>{A||Be(Ge.total>0)}).catch(()=>{A||Be(!0)}),()=>{A=!0}},[y,w,h,ht,ee,t]),ke.useEffect(()=>{M(Gn.open)},[]),ke.useEffect(()=>{let A=v?.id??"";A!==z&&(se(A),A&&(fe("all"),M(Gn.all),N(""),G(""),ae(""),C(""),m("")))},[v?.id]),ke.useEffect(()=>{let A=!1;return O(!1),y.getInvoiceSettings().then(Ge=>{A||Re({payments_active:Ge.payments_active,blocked:Ge.blocked})}).catch(()=>{A||O(!0)}),()=>{A=!0}},[y,t,ve]),ke.useEffect(()=>{if(!s)return;let A=!1,Ge=Pe.current;return Ce(!1),y.getInvoice(s).then(H=>{!A&&Ge===Pe.current&&J(H)}).catch(()=>{!A&&Ge===Pe.current&&Ce(!0)}),()=>{A=!0}},[y,s,bt]),ke.useEffect(()=>{a?.(ce!==null)},[ce,a]);let Je=A=>{fe(A),M(Gn[A])},ha=A=>{let Ge=A.trim();if(!Ge){E&&G(""),c&&N("");return}if(Ge.includes("@")){E&&G(""),N(Ge);return}c&&N(""),G(Ge.replace(/^#/,""))},Xt=r,La=St&&(0,f.jsxs)("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. ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>Z(A=>A+1),children:"Retry opening invoice"})]});if(ce)return(0,f.jsxs)("div",{className:e,children:[La,(0,f.jsx)(Nn,{invoice:ce,refreshKey:t,onBack:()=>{vt(null),X()}},ce.id)]});let Xe=(0,f.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[T&&(0,f.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>Le(A=>A+1),children:"Retry setup check"})]}),La,re?.blocked&&(0,f.jsxs)("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",re.blocked.reason?`: ${re.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),v&&(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,f.jsxs)(Q,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",v.label]}),g&&(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:g,children:"Clear schedule filter"})]}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsx)("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(ni).map(A=>(0,f.jsx)("button",{type:"button","aria-pressed":ee===A,onClick:()=>Je(A),className:Y("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",ee===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:ni[A]},A))}),(0,f.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,f.jsx)(dt.Search,{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"}),(0,f.jsx)(we,{type:"text",value:K,onChange:A=>ae(A.target.value),onBlur:()=>ha(K),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),ha(K))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,f.jsx)(_e,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,f.jsx)(we,{id:"invoices-from",type:"date",value:D,max:V||void 0,onChange:A=>C(A.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,f.jsx)(_e,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,f.jsx)(we,{id:"invoices-to",type:"date",value:V,min:D||void 0,onChange:A=>m(A.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,f.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Ct(),disabled:Ie||w||!!b||h===0,"aria-busy":Ie,children:[(0,f.jsx)(dt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),Ie?"Exporting\u2026":"Export CSV (all matching)"]})]}),st&&(0,f.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:st})]});return w?(0,f.jsxs)("div",{className:e,children:[Xe,(0,f.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(A=>(0,f.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,f.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,f.jsx)(te,{className:"af-h-4 af-w-20"}),(0,f.jsx)(te,{className:"af-h-4 af-w-16"})]}),(0,f.jsx)(te,{className:"af-mt-2 af-h-3 af-w-40"})]},A))})]}):b?(0,f.jsxs)("div",{className:e,children:[Xe,(0,f.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void X(),children:"Retry"})]})]}):h===0&&ht&&oe===!1&&ee==="open"?re?.blocked?(0,f.jsxs)("div",{className:e,children:[Xe,(0,f.jsx)(xn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,f.jsxs)("div",{className:e,children:[Xe,(0,f.jsx)(xn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):re&&!re.payments_active?(0,f.jsxs)("div",{className:e,children:[Xe,(0,f.jsx)(xn,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:n?{label:"Payment setup",onClick:n}:void 0})]}):(0,f.jsxs)("div",{className:e,children:[Xe,(0,f.jsx)(xn,{heading:"No invoices yet",body:!re||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."})]}):(0,f.jsxs)("div",{className:e,children:[Xe,Xt.length===0?(0,f.jsx)("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."}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Xt.map(A=>(0,f.jsxs)("button",{type:"button",onClick:()=>vt(A),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,f.jsx)("span",{className:"af-font-medium",children:ps(A)}),(0,f.jsx)(gs,{invoice:A})]}),(0,f.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:A.customer_name??A.customer_email??"\u2014"}),A.delivery&&(0,f.jsx)("div",{className:"af-mt-1",children:(0,f.jsx)(wn,{delivery:A.delivery})}),(0,f.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,f.jsx)("span",{children:A.collection_method==="charge_automatically"?"Automatic collection":A.due_at?`Due ${ia(A.due_at)}`:"Due on receipt"}),(0,f.jsx)("span",{className:"af-font-medium af-tabular-nums",children:q(A.amount_due??A.amount_total,A.currency)})]})]},A.id))}),(0,f.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,f.jsxs)(Me,{children:[(0,f.jsx)(Ue,{children:(0,f.jsxs)(he,{children:[(0,f.jsx)(U,{children:"Invoice"}),(0,f.jsx)(U,{children:"Created"}),(0,f.jsx)(U,{children:"Customer"}),(0,f.jsx)(U,{children:"Due"}),(0,f.jsx)(U,{className:"af-text-right",children:"Amount"}),(0,f.jsx)(U,{children:"Status"}),(0,f.jsx)(U,{children:"Delivery"}),(0,f.jsx)(U,{className:"af-w-8"})]})}),(0,f.jsx)($e,{children:Xt.map(A=>(0,f.jsxs)(he,{className:"af-cursor-pointer",onClick:()=>vt(A),children:[(0,f.jsx)($,{className:"af-font-medium",children:(0,f.jsx)("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:Ge=>{Ge.stopPropagation(),vt(A)},"aria-label":`Open invoice ${ps(A)}`,children:ps(A)})}),(0,f.jsx)($,{children:ia(A.created_at)}),(0,f.jsxs)($,{children:[(0,f.jsx)("div",{children:A.customer_name??"\u2014"}),(0,f.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:A.customer_email})]}),(0,f.jsx)($,{children:A.collection_method==="charge_automatically"?"Automatic":A.due_at?ia(A.due_at):"On receipt"}),(0,f.jsx)($,{className:"af-text-right af-tabular-nums",children:q(A.amount_due??A.amount_total,A.currency)}),(0,f.jsx)($,{children:(0,f.jsx)(gs,{invoice:A})}),(0,f.jsx)($,{children:(0,f.jsx)(wn,{delivery:A.delivery})}),(0,f.jsx)($,{children:(0,f.jsx)(dt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},A.id))})]})}),(0,f.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,f.jsxs)("span",{children:[h," invoice",h===1?"":"s"]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,f.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>P(u-1),disabled:!S,"aria-label":"Previous page",children:(0,f.jsx)(dt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,f.jsxs)("span",{className:"af-tabular-nums",children:[u*l+1,"\u2013",Math.min((u+1)*l,h)]}),(0,f.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>P(u+1),disabled:!x,"aria-label":"Next page",children:(0,f.jsx)(dt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function xn({heading:e,body:t,action:s}){return(0,f.jsxs)("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[(0,f.jsx)(dt.FileText,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),(0,f.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),(0,f.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:t}),s&&(0,f.jsx)(_,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var $a="af-text-xs af-text-muted-foreground";function ri(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Nn({invoice:e,onBack:t,refreshKey:s,className:a}){let{api:n}=ie(),i=ke.useRef(null);ke.useEffect(()=>{i.current?.focus()},[e.id]);let[o,v]=ke.useState(!1),[g,y]=ke.useState(null),[r,h]=ke.useState(!1),[w,b]=ke.useState(!1),u=ke.useRef(0),[l,x]=ke.useState(null),[S,P]=ke.useState(!1),[L,M]=ke.useState(0);ke.useEffect(()=>{let m=!1;return P(!1),n.getInvoice(e.id).then(z=>{m||x({source:e,value:z})}).catch(()=>{m||P(!0)}),()=>{m=!0}},[n,e,s,L]);let c=l?.source===e?l.value:e,N=c.collection_method==="charge_automatically";ke.useEffect(()=>(u.current++,y(null),h(!1),b(!1),v(!1),()=>{u.current++}),[n,c,s]);let E=m=>m==null?"\u2014":q(m,c.currency),G=async()=>{if(!(!c.pay_url||!ri()))try{await navigator.clipboard.writeText(c.pay_url),v(!0),setTimeout(()=>v(!1),1500)}catch{}},D=async()=>{if(g){y(null);return}let m=++u.current;b(!1),h(!0);try{let z=await n.getInvoicePreview(c.id);m===u.current&&y(z)}catch{m===u.current&&b(!0)}finally{m===u.current&&h(!1)}},C=c.bill_to,V=C?[C.company,C.name,C.address?.line1,C.address?.line2,[C.address?.city,C.address?.state,C.address?.postal_code].filter(Boolean).join(", "),C.address?.country,C.tax_id?`${C.tax_id.value}`:null,C.po_number?`PO ${C.po_number}`:null,C.service_period?`Service period: ${C.service_period}`:null].filter(m=>!!m&&m.length>0):[];return(0,f.jsxs)("div",{className:a,children:[(0,f.jsxs)("div",{className:"af-mb-4",children:[(0,f.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,f.jsx)(dt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",ps(c)]}),(0,f.jsx)(gs,{invoice:c}),(0,f.jsx)(wn,{delivery:c.delivery})]}),(0,f.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),S&&(0,f.jsxs)("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. ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>M(m=>m+1),children:"Retry details"})]}),c.label==="failed"&&(0,f.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),c.label==="creating"&&(0,f.jsx)("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."}),(0,f.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,f.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,f.jsxs)(Me,{children:[(0,f.jsx)(Ue,{children:(0,f.jsxs)(he,{children:[(0,f.jsx)(U,{children:"Description"}),(0,f.jsx)(U,{className:"af-text-right",children:"Qty"}),(0,f.jsx)(U,{className:"af-text-right",children:"Amount"})]})}),(0,f.jsx)($e,{children:c.line_items.map((m,z)=>(0,f.jsxs)(he,{children:[(0,f.jsx)($,{style:{overflowWrap:"anywhere"},children:m.description}),(0,f.jsx)($,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:m.quantity}),(0,f.jsx)($,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:E(m.amount)})]},z))})]}),(0,f.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,f.jsx)(Wa,{label:"Subtotal",value:E(c.amount_subtotal)}),(c.discount_total??0)>0&&(0,f.jsx)(Wa,{label:"Discount",value:`-${E(c.discount_total)}`}),c.tax_total>0&&(0,f.jsx)(Wa,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:E(c.tax_total)}),(0,f.jsx)(Wa,{label:"Total",value:E(c.amount_total),strong:!0}),c.credit_applied>0&&(0,f.jsx)(Wa,{label:"Credit applied",value:`-${E(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&(0,f.jsx)(Wa,{label:"Amount due",value:E(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&(0,f.jsx)(Wa,{label:"Amount paid",value:E(c.amount_paid)}),c.amount_refunded>0&&(0,f.jsx)(Wa,{label:"Refunded",value:E(c.amount_refunded)})]}),c.credit_notes?.length>0&&(0,f.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,f.jsx)("div",{className:$a,children:"Credit notes"}),c.credit_notes.map(m=>(0,f.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,f.jsxs)("span",{className:"af-text-muted-foreground",children:[ia(m.created_at)," \xB7 ",m.origin==="dashboard"?"issued in Stripe":"refund",m.stripe_credit_note_id?"":" \xB7 being created"]}),(0,f.jsxs)("span",{className:"af-tabular-nums",children:["-",q(m.amount,m.currency)]})]},m.id))]})]}),(c.note||c.footer)&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:$a,children:"Note"}),(0,f.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:$a,children:"Footer"}),(0,f.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),g&&!N&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,f.jsxs)("div",{className:Y($a,"af-break-words"),children:["Email preview \u2014 ",g.subject]}),(0,f.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,f.jsx)("iframe",{title:"Invoice email preview",srcDoc:g.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,f.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,f.jsx)(ra,{label:"Created",value:ia(c.created_at)}),(0,f.jsx)(ra,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?ia(c.due_at):"On receipt"}),c.paid_at&&(0,f.jsx)(ra,{label:"Paid",value:ia(c.paid_at)}),c.payment_method&&(0,f.jsx)(ra,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&(0,f.jsx)(ra,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&(0,f.jsx)(ra,{label:"Delivery",value:`${Jn[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&(0,f.jsx)(ra,{label:"Written off",value:ia(c.marked_uncollectible_at)}),c.correction_reason&&(0,f.jsx)(ra,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&(0,f.jsx)(ra,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?(0,f.jsx)(ra,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&(0,f.jsx)(ra,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&(0,f.jsx)(ra,{label:"Replaces",value:c.replaces_order_id})]}),(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,f.jsx)("div",{className:$a,children:"Reminders"}),N?(0,f.jsx)("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?(0,f.jsx)("div",{children:"Off for this invoice."}):c.reminders.paused_until?(0,f.jsxs)("div",{children:["Paused until ",ia(c.reminders.paused_until),"."]}):c.reminders.next_at?(0,f.jsxs)("div",{children:["Next on ",ia(c.reminders.next_at),"."]}):c.reminders.final_sent_at?(0,f.jsxs)("div",{children:["Final reminder sent ",ia(c.reminders.final_sent_at),"."]}):(0,f.jsx)("div",{children:"None scheduled."}),!N&&(0,f.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(m=>m<0?`${-m}d before`:m===0?"due day":`${m}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,f.jsx)("div",{className:$a,children:"Email delivery history"}),c.communications.map(m=>(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,f.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[Vo[m.kind]??m.kind,m.kind==="reminder"&&m.slot!==null?` #${m.slot}`:"",(0,f.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",m.recipient]})]}),(0,f.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Jn[m.state]??m.state," \xB7 ",ia(m.state_at??m.created_at)]})]},m.id))]}),V.length>0&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,f.jsx)("div",{className:$a,children:"Bill to"}),V.map((m,z)=>(0,f.jsx)("div",{className:"af-break-words",children:m},z))]}),(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&(0,f.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void G(),disabled:!ri(),children:[(0,f.jsx)(dt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":N?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&(0,f.jsx)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,f.jsxs)("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,f.jsx)(dt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!N&&(0,f.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void D(),disabled:r,children:[r?(0,f.jsx)(dt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,f.jsx)(dt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),g?"Hide email preview":w?"Retry email preview":"Show email preview"]}),w&&!N&&(0,f.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&(0,f.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),(0,f.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:N?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function ra({label:e,value:t}){return(0,f.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,f.jsx)("span",{className:Y($a,"af-shrink-0"),children:e}),(0,f.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Wa({label:e,value:t,strong:s}){return(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,f.jsx)("dt",{className:Y($a,s&&"af-font-medium af-text-foreground"),children:e}),(0,f.jsx)("dd",{className:Y("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}var li=require("lucide-react");var De=require("react/jsx-runtime"),jo={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 Go(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 ci(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>oi[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>oi[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":jo[e.status]}function ui(e){let t=e.interval==="year"?"every year":"every month";return`${q(e.amount,e.currency)} ${t}`}function Wo(e){return e.status==="canceled"?`Ended ${Sn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Sn(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 ${Sn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Sn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Sn(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(t);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function _n({retainer:e,className:t}){return(0,De.jsx)(Q,{variant:Go(e.status),className:Y("af-max-w-full af-whitespace-normal af-break-words",t),children:ci(e)})}function rs({retainers:e,isLoading:t,error:s,onRetry:a,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:v=0,isLoadingMore:g=!1,onLoadMore:y,includeEnded:r=!1,onIncludeEndedChange:h,className:w}){let b=!!h;if(!t&&!s&&e.length===0&&!(b&&(r||v>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return(0,De.jsxs)("section",{className:Y("af-mb-6",w),"aria-label":"Recurring invoices",children:[(0,De.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,De.jsx)(li.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,De.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,De.jsx)("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."}),b&&(0,De.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>h?.(!r),children:r?"Hide ended recurring invoices":v>0&&e.length===0?`Show ended recurring invoices (${v})`:"Show ended recurring invoices"})]}),s?(0,De.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,De.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:a,children:"Retry"})]}):t?(0,De.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>(0,De.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,De.jsx)(te,{className:"af-h-4 af-w-48"}),(0,De.jsx)(te,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?(0,De.jsx)("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."}):(0,De.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let x=i===l.id;return(0,De.jsxs)("li",{className:Y("af-rounded-md af-border af-p-3",x&&"af-border-primary af-bg-muted/40"),children:[(0,De.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,De.jsxs)("div",{className:"af-min-w-0",children:[(0,De.jsx)("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),(0,De.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),(0,De.jsx)(_n,{retainer:l})]}),l.collection_method==="charge_automatically"?(0,De.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,De.jsx)(Q,{variant:"secondary",children:"Managed in Stripe"}),(0,De.jsx)("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."})]}):(0,De.jsx)("div",{className:"af-mt-2 af-text-sm",children:ui(l)}),(0,De.jsxs)("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:[(0,De.jsxs)("span",{children:[Wo(l)," \xB7 ",l.cycles.count===0?"no invoices yet":`${l.cycles.paid} paid${l.cycles.open>0?`, ${l.cycles.open} open`:""}`]}),l.cycles.count>0&&(0,De.jsx)(_,{type:"button",variant:x?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":x,children:x?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&(0,De.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!t&&!s&&u>0&&y&&(0,De.jsx)("div",{className:"af-mt-2",children:(0,De.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:y,disabled:g,children:g?"Loading\u2026":`Load more (${u} more)`})})]})}var di=ue(require("react"),1),Yt=require("lucide-react");var Ne=require("react/jsx-runtime");function qs({onConnectStripe:e,onUpgradePlan:t,className:s}){let{status:a,isLoading:n,error:i,refetch:o}=Fa(),[v,g]=di.useState(!1),y=async()=>{g(!0);try{await o()}finally{g(!1)}};return n&&!a?(0,Ne.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ne.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!a?(0,Ne.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ne.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):a.status==="active"?(0,Ne.jsx)("div",{className:s,children:(0,Ne.jsxs)("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:[(0,Ne.jsx)(Yt.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Ne.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",a.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Ne.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ne.jsx)(Yt.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Ne.jsx)("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?(0,Ne.jsxs)(_,{onClick:e,children:[(0,Ne.jsx)(Yt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),a.reason==="needs_paid_plan"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ne.jsx)(Yt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?(0,Ne.jsx)(_,{onClick:t,children:"Upgrade plan"}):(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("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:[(0,Ne.jsx)(Yt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,Ne.jsx)("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."}):(0,Ne.jsx)("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."})]})]}),(0,Ne.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,Ne.jsxs)(_,{onClick:e,children:[(0,Ne.jsx)(Yt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Ne.jsxs)(_,{variant:"outline",onClick:y,disabled:v,children:[v?(0,Ne.jsx)(Yt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Ne.jsx)(Yt.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var kt=ue(require("react"),1);function Zn(e,t,s){return e.map(a=>a.id===t?{...a,...s}:a)}function is({includeStats:e=!1,refreshKey:t}={}){let{api:s}=ie(),[a,n]=kt.useState([]),[i,o]=kt.useState(!0),[v,g]=kt.useState(null),y=kt.useRef(0),r=kt.useCallback(async()=>{let x=++y.current;try{o(!0),g(null);let S=await s.getProducts(e?{include:"stats"}:{});if(x!==y.current)return;n(S)}catch(S){if(x!==y.current)return;g(S instanceof Error?S:new Error("Failed to fetch products"))}finally{x===y.current&&o(!1)}},[s,e,t]);kt.useEffect(()=>{r()},[r]);let h=kt.useCallback(async x=>{let S=await s.createProduct(x);return n(P=>[S,...P]),S},[s]),w=kt.useCallback(async(x,S)=>{let P=await s.updateProduct(x,S);return n(L=>Zn(L,x,P)),P},[s]),b=kt.useCallback(async x=>{await s.deleteProduct(x),n(S=>S.filter(P=>P.id!==x))},[s]),u=kt.useCallback(async(x,S)=>{let P=await s.attachProductFile(x,S);return n(L=>Zn(L,x,P)),P},[s]),l=kt.useCallback(async(x,S)=>{let P=await s.attachProductFileFromUrl(x,S);return n(L=>Zn(L,x,P)),P},[s]);return{products:a,isLoading:i,error:v,refetch:r,createProduct:h,updateProduct:w,deleteProduct:b,attachProductFile:u,attachProductFileFromUrl:l}}var Et=ue(require("react"),1);var fi=["creating","active","paused","canceling"],Ko=["canceled","failed"];function os({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:a}=ie(),[n,i]=Et.useState([]),[o,v]=Et.useState(0),[g,y]=Et.useState(0),[r,h]=Et.useState(!0),[w,b]=Et.useState(!1),[u,l]=Et.useState(null),[x,S]=Et.useState(t),P=Et.useRef(0),L=Et.useCallback(async()=>{let c=++P.current;h(!0),b(!1),l(null);try{let N=await a.getRetainers({statuses:x?void 0:fi,limit:s,offset:0});if(c!==P.current)return;if(i(N.retainers),v(N.total),!x&&N.total===0){let E=await a.getRetainers({statuses:Ko,limit:1,offset:0});if(c!==P.current)return;y(E.total)}else y(0)}catch(N){if(c!==P.current)return;l(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{c===P.current&&h(!1)}},[a,x,s]);Et.useEffect(()=>{L()},[L,e]);let M=Et.useCallback(async()=>{if(r||w||n.length>=o)return;let c=P.current;b(!0);try{let N=await a.getRetainers({statuses:x?void 0:fi,limit:s,offset:n.length});if(c!==P.current)return;i(E=>{let G=new Set(E.map(D=>D.id));return[...E,...N.retainers.filter(D=>!G.has(D.id))]}),v(N.total)}catch(N){if(c!==P.current)return;l(N instanceof Error?N:new Error("Failed to fetch retainers"))}finally{c===P.current&&b(!1)}},[a,x,s,r,w,n.length,o]);return{retainers:n,total:o,endedTotal:g,hasMore:n.length<o,isLoading:r,isLoadingMore:w,error:u,includeEnded:x,setIncludeEnded:S,loadMore:M,refetch:L}}var ye=require("react/jsx-runtime");function Qn({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:a,onUpgradePlan:n}){let[i,o]=vs.useState(t),[v,g]=vs.useState("list"),[y,r]=vs.useState(null),h=is(),{status:w,error:b}=Fa(),u=w?.currency,l=L=>{r(L),g("edit")},x=()=>{r(null),g("create")},S=()=>{g("list"),r(null)},P=L=>{r(L),g("edit")};return(0,ye.jsxs)("div",{className:e,children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,ye.jsxs)(ln,{value:i,onValueChange:L=>o(L),children:[(0,ye.jsxs)(xs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,ye.jsxs)(ca,{value:"products",className:"af-gap-2",children:[(0,ye.jsx)(oa.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,ye.jsxs)(ca,{value:"orders",className:"af-gap-2",children:[(0,ye.jsx)(oa.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,ye.jsxs)(ca,{value:"invoices",className:"af-gap-2",children:[(0,ye.jsx)(oa.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,ye.jsxs)(ca,{value:"customers",className:"af-gap-2",children:[(0,ye.jsx)(oa.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,ye.jsx)(ca,{value:"promos",children:"Promo codes"}),(0,ye.jsxs)(ca,{value:"setup",className:"af-gap-2",children:[(0,ye.jsx)(oa.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,ye.jsx)(ua,{value:"products",children:v==="list"?(0,ye.jsx)(Os,{productsState:h,onSelectProduct:l,onCreateProduct:x}):(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsxs)(_,{variant:"ghost",size:"sm",onClick:S,className:"af-mb-2 af--ml-2",children:[(0,ye.jsx)(oa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:v==="create"?"New Product":y?.name})]}),v==="create"&&!u?(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:b?(0,ye.jsxs)("div",{className:"af-text-destructive",children:["Error: ",b.message]}):(0,ye.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,ye.jsx)(Fs,{productsState:h,product:v==="edit"?y:null,currency:u??"usd",onSaved:P},v==="edit"?y?.id??"edit":"new")]})}),(0,ye.jsx)(ua,{value:"orders",children:(0,ye.jsx)(ts,{onRefund:a})}),(0,ye.jsx)(ua,{value:"invoices",children:(0,ye.jsx)(Jo,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:w?.reason==="needs_paid_plan"})}),(0,ye.jsx)(ua,{value:"customers",children:(0,ye.jsx)(zs,{})}),(0,ye.jsx)(ua,{value:"promos",children:(0,ye.jsx)(Qa,{})}),(0,ye.jsx)(ua,{value:"setup",children:(0,ye.jsx)(qs,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Jo({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let a=os(),[n,i]=vs.useState(null),[o,v]=vs.useState(!1);return(0,ye.jsxs)(ye.Fragment,{children:[!o&&(0,ye.jsx)(rs,{retainers:a.retainers,isLoading:a.isLoading,error:a.error,onRetry:()=>void a.refetch(),activeRetainerId:n?.id??null,onShowCycles:g=>i(y=>y?.id===g.id?null:g),total:a.total,endedTotal:a.endedTotal,isLoadingMore:a.isLoadingMore,onLoadMore:()=>void a.loadMore(),includeEnded:a.includeEnded,onIncludeEndedChange:a.setIncludeEnded}),(0,ye.jsx)(ns,{onDetailOpenChange:v,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}var pi=ue(require("react"),1);var Ea=ue(require("react"),1);function js({refreshKey:e}={}){let{api:t}=ie(),[s,a]=Ea.useState(null),[n,i]=Ea.useState(!0),[o,v]=Ea.useState(null),g=Ea.useRef(0),y=Ea.useCallback(async()=>{let r=++g.current;try{i(!0),v(null);let h=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==g.current)return;a(h)}catch(h){if(r!==g.current)return;v(h instanceof Error?h:new Error("Failed to fetch summary"))}finally{r===g.current&&i(!1)}},[t,e]);return Ea.useEffect(()=>{y()},[y]),{summary:s,isLoading:n,error:o,refetch:y}}var ze=require("react/jsx-runtime");function mi(e,t){if(e.settled.complete)return{headline:q(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:q(s.gross,s.currency),extra:e.totals.slice(1).map(a=>`+ ${q(a.gross,a.currency)} in ${a.currency.toUpperCase()}`)}:{headline:q(0,t),extra:[]}}function Xn({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:a,onBackToWebsite:n,className:i}){let{summary:o,isLoading:v,error:g,refetch:y}=js({refreshKey:e}),[r,h]=pi.useState(!1),w=(0,ze.jsx)("div",{className:"af-mb-6",children:g&&!o?(0,ze.jsx)(Kt,{message:"Couldn't load your revenue summary.",onRetry:()=>y()}):(0,ze.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:v||!o?(0,ze.jsxs)(ze.Fragment,{children:[(0,ze.jsx)(Ze,{label:"This week",children:(0,ze.jsx)(te,{className:"af-h-6 af-w-24"})}),(0,ze.jsx)(Ze,{label:"Today",children:(0,ze.jsx)(te,{className:"af-h-6 af-w-24"})}),(0,ze.jsx)(Ze,{label:"Needs attention",children:(0,ze.jsx)(te,{className:"af-h-6 af-w-10"})})]}):(0,ze.jsx)(ze.Fragment,{children:(()=>{let b=mi(o.revenue.d7,o.currency),u=mi(o.revenue.today,o.currency);return(0,ze.jsxs)(ze.Fragment,{children:[(0,ze.jsx)(Ze,{label:"This week",detail:b.extra.length>0?(0,ze.jsx)("div",{children:b.extra.map(l=>(0,ze.jsx)("div",{children:l},l))}):void 0,children:b.headline}),(0,ze.jsx)(Ze,{label:"Today",detail:u.extra.length>0?(0,ze.jsx)("div",{children:u.extra.map(l=>(0,ze.jsx)("div",{children:l},l))}):void 0,children:u.headline}),(0,ze.jsx)(Ze,{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(0,ze.jsxs)(xt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[w,(0,ze.jsx)(ts,{refreshKey:e,initialOrderId:t,onDetailOpenChange:h,showFulfillment:!0,onRefund:s?a:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Da=ue(require("react"),1),bs=require("lucide-react");var Ia=ue(require("react"),1),En=require("lucide-react");var Nt=require("react/jsx-runtime"),gi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ka="af-text-xs af-text-muted-foreground",Rn="af-text-sm af-font-medium af-tabular-nums",Yo=3;function Zo(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let g=e.min_amount??t?.min_amount??null,y=e.max_amount??t?.max_amount??null;return g!==null&&y!==null?{text:`Buyer chooses (${q(g,s)} \u2013 ${q(y,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,i=t?.max_amount??e.unit_amount;if(n===null||i===null)return{text:"Varies by variant",compareAt:null};let o=n===i?q(n,s):`${q(n,s)} \u2013 ${q(i,s)}`,v=t?.compare_at_amount??null;return{text:o,compareAt:v!==null&&v>i?q(v,s):null}}function Pn({product:e,className:t}){let s=Zo(e);return(0,Nt.jsxs)("div",{className:t,children:[(0,Nt.jsx)("span",{className:Rn,children:s.text}),s.compareAt&&(0,Nt.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Cn({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,Nt.jsx)(Q,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,Nt.jsxs)(Q,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,Nt.jsx)(Q,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,Nt.jsxs)(Q,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,Nt.jsx)(Q,{variant:"warning",children:"Low stock"}):null}function Tn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function kn(e){return e.map(t=>q(t.amount,t.currency)).join(" + ")}function vi(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${q(e.min_amount,e.currency)} \u2013 ${q(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":q(e.unit_amount,e.currency)}function bi({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,Nt.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?(0,Nt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Nt.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,Nt.jsx)(Q,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,Nt.jsx)(Q,{variant:"destructive",children:"Out of stock"}):(0,Nt.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Nt.jsx)("span",{className:"af-tabular-nums",children:s}),s<=Yo&&(0,Nt.jsx)(Q,{variant:"warning",children:"Low"})]})}var W=require("react/jsx-runtime");function Gs({title:e,children:t,className:s}){return(0,W.jsxs)("section",{className:Y("af-rounded-lg af-border af-p-4",s),children:[(0,W.jsx)("h4",{className:gi,children:e}),(0,W.jsx)("div",{className:"af-mt-3",children:t})]})}function yi({src:e,className:t}){let[s,a]=Ia.useState(!1);return Ia.useEffect(()=>a(!1),[e]),!e||s?(0,W.jsx)("div",{"aria-hidden":"true",className:Y("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,W.jsx)(En.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,W.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>a(!0),className:Y("af-object-cover",t)})}function hi({product:e,showStats:t=!1,onBack:s}){let{api:a}=ie(),[n,i]=Ia.useState(null),[o,v]=Ia.useState(!0),[g,y]=Ia.useState(null),[r,h]=Ia.useState(0),[w,b]=Ia.useState(0);Ia.useEffect(()=>{let c=!1;return v(!0),y(null),a.getProduct(e.id).then(N=>{c||i(N)}).catch(N=>{c||y(N instanceof Error?N:new Error("Failed to load product"))}).finally(()=>{c||v(!1)}),()=>{c=!0}},[a,e.id,r]);let u=n?{...e,...n}:e,l=u.images.length>0?u.images:e.images,x=l[w]??l[0],S=Tn(u),P=t?u.stats:void 0,L=n?.variants??[],M=L.length>1;return(0,W.jsxs)("div",{children:[(0,W.jsxs)("div",{className:"af-mb-6",children:[(0,W.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,W.jsx)(En.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,W.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,W.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),(0,W.jsx)(Q,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),(0,W.jsx)(Cn,{product:u})]}),(0,W.jsx)(Pn,{product:u,className:"af-mt-1"}),!u.active&&(0,W.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,W.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,W.jsxs)("div",{className:"af-space-y-2",children:[(0,W.jsx)(yi,{src:x,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&(0,W.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((c,N)=>(0,W.jsx)("button",{type:"button",onClick:()=>b(N),"aria-label":`Show photo ${N+1} of ${l.length}`,"aria-pressed":N===w,className:Y("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===w?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,W.jsx)(yi,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${N}`))})]}),(0,W.jsxs)("div",{className:"af-space-y-6",children:[u.description&&(0,W.jsx)(Gs,{title:"Description",children:(0,W.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?(0,W.jsxs)(Gs,{title:"Variants",children:[(0,W.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>(0,W.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,W.jsx)(te,{className:"af-h-4 af-w-28"}),(0,W.jsx)(te,{className:"af-h-4 af-w-20"}),(0,W.jsx)(te,{className:"af-h-4 af-w-16"})]},c))}),(0,W.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):g?(0,W.jsx)(Kt,{message:"Couldn't load this product's variants.",onRetry:()=>h(c=>c+1)}):M?(0,W.jsx)(Gs,{title:`Variants \xB7 ${L.length}`,children:(0,W.jsx)("div",{className:"af-overflow-x-auto",children:(0,W.jsxs)(Me,{children:[(0,W.jsx)(Ue,{children:(0,W.jsxs)(he,{children:[(0,W.jsx)(U,{children:"Variant"}),(0,W.jsx)(U,{children:"SKU"}),(0,W.jsx)(U,{className:"af-text-right",children:"Price"}),(0,W.jsx)(U,{children:"Stock"})]})}),(0,W.jsx)($e,{children:L.map(c=>(0,W.jsxs)(he,{children:[(0,W.jsxs)($,{className:"af-font-medium",children:[c.title||c.option_values.map(N=>N.value).join(" / ")||"\u2014",!c.active&&(0,W.jsx)(Q,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,W.jsx)($,{className:"af-text-muted-foreground",children:c.sku?(0,W.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),(0,W.jsxs)($,{className:"af-whitespace-nowrap af-text-right",children:[(0,W.jsx)("div",{className:Rn,children:vi(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&(0,W.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:q(c.compare_at_amount,c.currency)})]}),(0,W.jsx)($,{className:"af-text-sm",children:(0,W.jsx)(bi,{variant:c})})]},c.id))})]})})}):null,(0,W.jsx)(Gs,{title:"Details",children:(0,W.jsxs)("dl",{className:"af-space-y-2",children:[(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Delivery"}),(0,W.jsx)("dd",{className:"af-text-sm",children:S==="Digital download"?u.fulfillment.filename??"Digital download":S??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Sends buyers to"}),(0,W.jsx)("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Shipping address"}),(0,W.jsx)("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Most one buyer can order"}),(0,W.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),P&&(0,W.jsx)(Gs,{title:"Last 30 days",children:(0,W.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Units sold"}),(0,W.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:P.units_sold})]}),(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Orders"}),(0,W.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:P.orders})]}),(0,W.jsxs)("div",{children:[(0,W.jsx)("dt",{className:Ka,children:"Gross"}),(0,W.jsx)("dd",{className:Rn,children:P.gross.length>0?kn(P.gross):"\u2014"})]})]})}),(0,W.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var F=require("react/jsx-runtime"),Qo={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Xo=["all","active","draft","low_stock","out_of_stock"];function xi(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function wi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function el(e){return e.inventory?.out_of_stock??!1}function tl(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return wi(e);case"out_of_stock":return el(e);default:return!0}}function al({product:e,showStats:t,onOpen:s}){let a=e.images[0],n=t?e.stats:void 0,i=Tn(e),o=e.variant_count??0;return(0,F.jsxs)("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:[a?(0,F.jsx)("img",{src:a,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,F.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,F.jsx)(bs.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,F.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,F.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,F.jsxs)("div",{className:"af-min-w-0",children:[(0,F.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,F.jsx)(Pn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,F.jsx)(Q,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,F.jsx)(Cn,{product:e}),o>1&&(0,F.jsxs)(Q,{variant:"outline",children:[o," variants"]}),i&&(0,F.jsx)(Q,{variant:"outline",children:i})]}),n&&(0,F.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${kn(n.gross)}`:""," ",(0,F.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function sl(){return(0,F.jsx)("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=>(0,F.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,F.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,F.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,F.jsx)(te,{className:"af-w-32"}),(0,F.jsx)(te,{className:"af-w-16"}),(0,F.jsx)(te,{className:"af-h-5 af-w-24"})]})]},e))})}function er({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:a}){let{products:n,isLoading:i,error:o,refetch:v}=is({includeStats:t,refreshKey:e}),[g,y]=Da.useState(!1),[r,h]=Da.useState(null),[w,b]=Da.useState("all"),[u,l]=Da.useState(""),[x,S]=Da.useState("newest"),P=Da.useMemo(()=>{if(!t)return null;let m=null;for(let z of n)!z.stats||z.stats.units_sold===0||(!m||z.stats.units_sold>(m.stats?.units_sold??0))&&(m=z);return m},[n,t]),L=Da.useMemo(()=>n.filter(wi).length,[n]),M=u.trim().toLowerCase(),c=Da.useMemo(()=>{let z=[...n.filter(se=>tl(se,w)&&(!M||se.name.toLowerCase().includes(M)))];return x==="name"?z.sort((se,X)=>se.name.localeCompare(X.name)):x==="best_selling"?z.sort((se,X)=>(X.stats?.units_sold??0)-(se.stats?.units_sold??0)):z.sort((se,X)=>xi(X.created_at)-xi(se.created_at)),z},[n,w,M,x]),N=w!=="all"||!!M,E=()=>{b("all"),l("")},G=i||o!==null&&n.length===0,D=(0,F.jsx)("div",{className:"af-mb-6",children:(0,F.jsx)("div",{className:Y("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:G?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Ze,{label:"Products",children:(0,F.jsx)(te,{className:"af-h-6 af-w-10"})}),t?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Ze,{label:"Best seller",children:(0,F.jsx)(te,{className:"af-h-6 af-w-28"})}),(0,F.jsx)(Ze,{label:"Low stock",children:(0,F.jsx)(te,{className:"af-h-6 af-w-10"})})]}):(0,F.jsx)(Ze,{label:"Active",children:(0,F.jsx)(te,{className:"af-h-6 af-w-10"})})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Ze,{label:"Products",children:n.length}),t?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Ze,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:P?`${P.stats?.units_sold??0} sold, last 30 days`:void 0,children:P?(0,F.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:P.name}):(0,F.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,F.jsx)(Ze,{label:"Low stock",children:L})]}):(0,F.jsx)(Ze,{label:"Active",children:n.filter(m=>m.active).length})]})})}),C=(0,F.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,F.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,F.jsx)("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:Xo.map(m=>(0,F.jsx)("button",{type:"button","aria-pressed":w===m,onClick:()=>b(m),className:Y("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===m?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Qo[m]},m))}),(0,F.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,F.jsx)(bs.Search,{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"}),(0,F.jsx)(we,{type:"text",value:u,onChange:m=>l(m.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,F.jsxs)(ea,{value:x,onValueChange:m=>S(m),children:[(0,F.jsx)(Ht,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,F.jsx)(ta,{})}),(0,F.jsxs)(zt,{children:[(0,F.jsx)(qe,{value:"newest",children:"Newest"}),(0,F.jsx)(qe,{value:"name",children:"Name A\u2013Z"}),t&&(0,F.jsx)(qe,{value:"best_selling",children:"Best selling"})]})]}),N&&(0,F.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:E,children:"Clear filters"})]}),i&&n.length===0?(0,F.jsx)(te,{className:"af-h-4 af-w-28"}):(0,F.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:N?`${c.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${L>0?` \xB7 ${L} low stock`:""}`})]}),V;return r?V=(0,F.jsx)(hi,{product:r,showStats:t,onBack:()=>{h(null),v()}},r.id):i&&n.length===0?V=(0,F.jsxs)(F.Fragment,{children:[C,(0,F.jsx)(sl,{}),(0,F.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?V=(0,F.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,F.jsx)(Kt,{message:"Couldn't load your products.",onRetry:()=>v()})}):n.length===0?V=(0,F.jsxs)(Ta,{icon:(0,F.jsx)(bs.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,F.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):V=(0,F.jsxs)(F.Fragment,{children:[C,o&&(0,F.jsx)("div",{className:"af-mb-4",children:(0,F.jsx)(Kt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>v()})}),c.length===0?(0,F.jsxs)(Ta,{children:["No products match these filters.",(0,F.jsx)("br",{}),(0,F.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:E,children:"Show all products"})]}):(0,F.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:c.map(m=>(0,F.jsx)(al,{product:m,showStats:t,onOpen:()=>h(m)},m.id))})]}),(0,F.jsx)(xt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:a,children:g?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(_,{variant:"ghost",onClick:()=>y(!1),children:"Back to products"}),(0,F.jsx)(Qa,{})]}):(0,F.jsxs)(F.Fragment,{children:[!r&&(0,F.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,F.jsx)(_,{variant:"outline",onClick:()=>y(!0),children:"Promo codes"})}),!r&&D,V]})})}var ba=ue(require("react"),1),ot=require("lucide-react");var Zt=ue(require("react"),1);function Ws({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ie(),[a,n]=Zt.useState([]),[i,o]=Zt.useState(!0),[v,g]=Zt.useState(null),[y,r]=Zt.useState(0),[h]=Zt.useState(e),[w,b]=Zt.useState(""),u=Zt.useRef(0),l=Zt.useCallback(async()=>{let x=++u.current;try{o(!0),g(null);let S={limit:h,offset:y*h};w.trim()&&(S.q=w.trim());let P=await s.getPeople(S);if(x!==u.current)return;n(P.people)}catch(S){if(x!==u.current)return;g(S instanceof Error?S:new Error("Failed to fetch people"))}finally{x===u.current&&o(!1)}},[s,y,h,w,t]);return Zt.useEffect(()=>{l()},[l]),{people:a,isLoading:i,error:v,page:y,pageSize:h,hasNextPage:a.length===h,hasPreviousPage:y>0,setPage:r,q:w,setQ:x=>{b(x),r(0)},refetch:l}}var Aa=ue(require("react"),1);function Ks(e,{refreshKey:t}={}){let{api:s}=ie(),[a,n]=Aa.useState(null),[i,o]=Aa.useState(e!==null),[v,g]=Aa.useState(null),y=Aa.useRef(0),r=Aa.useCallback(async()=>{if(e===null){n(null),o(!1),g(null);return}let h=++y.current;try{o(!0),g(null);let w=await s.getPerson(e);if(h!==y.current)return;n(w)}catch(w){if(h!==y.current)return;g(w instanceof Error?w:new Error("Failed to fetch person"))}finally{h===y.current&&o(!1)}},[s,e,t]);return Aa.useEffect(()=>{r()},[r]),{person:a,isLoading:i,error:v,refetch:r}}var p=require("react/jsx-runtime"),tr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",nl="af-text-xs af-text-muted-foreground";function ys(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ar(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function rl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function il({value:e,label:t}){let[s,a]=ba.useState(!1);return rl()?(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?(0,p.jsx)(ot.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,p.jsx)(ot.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function Ni(e){return(0,p.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,p.jsxs)(Q,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,p.jsx)(Q,{variant:"secondary",children:"Contact form"})]})}function Si(e){return e.name?e.name:e.email?e.email:(0,p.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var ol=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,ll=40;function cl(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),a=t.find(([n,i])=>ol.test(n)&&typeof i=="string"&&i.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=ll).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return a?{message:String(a[1]),rest:t.filter(([n])=>n!==a[0])}:{message:null,rest:t}}function ul(e){return e.replace(/_/g," ")}function dl(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function fl({data:e}){let{message:t,rest:s}=cl(e);return t===null&&s.length===0?(0,p.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,p.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,p.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&(0,p.jsx)("dl",{className:"af-space-y-1",children:s.map(([a,n])=>(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,p.jsx)("dt",{className:Y(nl,"af-w-28 af-shrink-0 af-capitalize"),children:ul(a)}),(0,p.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:dl(n)})]},a))})]})}function _i({formName:e,createdAt:t,data:s}){return(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,p.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)(Q,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,p.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,p.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:ys(t)})]}),(0,p.jsx)(fl,{data:s})]})}function ml(e){return e.charged_total??e.amount_total}function pl({email:e,refreshKey:t,onBack:s}){let{person:a,isLoading:n,error:i,refetch:o}=Ks(e,{refreshKey:t}),v=ar(e,a?.submissions[0]?.form_name);return(0,p.jsxs)("div",{children:[(0,p.jsxs)("div",{className:"af-mb-6",children:[(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,p.jsx)(ot.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,p.jsxs)("div",{className:"af-min-w-0",children:[n?(0,p.jsx)(te,{className:"af-h-7 af-w-48"}):(0,p.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:a?.name||e}),(0,p.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,p.jsx)(il,{value:e,label:"Copy email address"})]})]}),(0,p.jsx)(_,{asChild:!0,children:(0,p.jsxs)("a",{href:v,children:[(0,p.jsx)(ot.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,p.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(g=>(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,p.jsx)(te,{className:"af-w-40"}),(0,p.jsx)(te,{className:"af-mt-2 af-w-64"})]},g)),(0,p.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!a?(0,p.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,p.jsx)(Kt,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,p.jsxs)("div",{className:"af-space-y-6",children:[a.customer&&(0,p.jsxs)("div",{children:[(0,p.jsx)("h4",{className:Y(tr,"af-mb-3"),children:"Customer"}),(0,p.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[a.customer.name&&(0,p.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,p.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,p.jsx)("dd",{children:a.customer.name})]}),a.customer.phone&&(0,p.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,p.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,p.jsx)("dd",{children:a.customer.phone})]}),(0,p.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,p.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,p.jsx)("dd",{children:ys(a.customer.created_at)})]})]})]}),a.orders.length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)("h4",{className:Y(tr,"af-mb-3"),children:"Purchases"}),(0,p.jsx)("div",{className:"af-overflow-x-auto",children:(0,p.jsxs)(Me,{children:[(0,p.jsx)(Ue,{children:(0,p.jsxs)(he,{children:[(0,p.jsx)(U,{children:"Order"}),(0,p.jsx)(U,{children:"Date"}),(0,p.jsx)(U,{className:"af-text-right",children:"Total"}),(0,p.jsx)(U,{children:"Status"})]})}),(0,p.jsx)($e,{children:a.orders.map(g=>(0,p.jsxs)(he,{children:[(0,p.jsx)($,{className:"af-whitespace-nowrap af-font-medium",children:Ua(g)}),(0,p.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ys(g.created_at)}),(0,p.jsx)($,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:q(ml(g),g.currency)}),(0,p.jsx)($,{children:(0,p.jsx)(Ga,{status:g.status})})]},g.id))})]})}),(0,p.jsx)("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."})]}),a.submissions.length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)("h4",{className:Y(tr,"af-mb-3"),children:"Messages"}),(0,p.jsx)("div",{className:"af-space-y-3",children:a.submissions.map(g=>(0,p.jsx)(_i,{formName:g.form_name,createdAt:g.created_at,data:g.data},g.id))})]})]})]})}function gl({submissionId:e,onBack:t}){let{api:s}=ie(),[a,n]=ba.useState(null),[i,o]=ba.useState(!0),[v,g]=ba.useState(null),[y,r]=ba.useState(0);return ba.useEffect(()=>{let h=!1;return o(!0),g(null),s.getSubmission(e).then(w=>{h||n(w)}).catch(w=>{h||g(w instanceof Error?w:new Error("Failed to load submission"))}).finally(()=>{h||o(!1)}),()=>{h=!0}},[s,e,y]),(0,p.jsxs)("div",{children:[(0,p.jsxs)("div",{className:"af-mb-6",children:[(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,p.jsx)(ot.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,p.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,p.jsx)(te,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,p.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:ys(a.metadata.submitted_at)})]}),i?(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,p.jsx)(te,{className:"af-w-40"}),(0,p.jsx)(te,{className:"af-mt-2 af-w-64"}),(0,p.jsx)(te,{className:"af-mt-2 af-w-52"}),(0,p.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):v||!a?(0,p.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,p.jsx)(Kt,{message:"Couldn't load this submission.",onRetry:()=>r(h=>h+1)})}):(0,p.jsxs)("div",{className:"af-space-y-3",children:[(0,p.jsx)(_i,{formName:null,createdAt:a.metadata.submitted_at,data:a.data}),(0,p.jsx)("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 vl={all:"All",customers:"Customers",leads:"Leads"},bl=["all","customers","leads"];function yl(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function sr({refreshKey:e,onBackToWebsite:t,className:s}){let{people:a,isLoading:n,error:i,page:o,pageSize:v,hasNextPage:g,hasPreviousPage:y,setPage:r,q:h,setQ:w,refetch:b}=Ws({refreshKey:e}),[u,l]=ba.useState({kind:"list"}),[x,S]=ba.useState(""),[P,L]=ba.useState("all"),M=D=>{D.email?l({kind:"person",email:D.email}):D.submission_id&&l({kind:"submission",submissionId:D.submission_id})},c=()=>{l({kind:"list"}),b()},N=D=>{let C=D.trim();C!==h&&w(C)},E=a.filter(D=>yl(D,P)),G;if(u.kind==="person")G=(0,p.jsx)(pl,{email:u.email,refreshKey:e,onBack:c});else if(u.kind==="submission")G=(0,p.jsx)(gl,{submissionId:u.submissionId,onBack:c});else{let D=(0,p.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("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:bl.map(C=>(0,p.jsx)("button",{type:"button","aria-pressed":P===C,onClick:()=>L(C),className:Y("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",P===C?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:vl[C]},C))}),(0,p.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,p.jsx)(ot.Search,{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"}),(0,p.jsx)(we,{type:"text",value:x,onChange:C=>S(C.target.value),onBlur:()=>N(x),onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),N(x))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),h&&(0,p.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{S(""),w("")},children:"Clear search"})]});if(n)G=(0,p.jsxs)("div",{children:[D,(0,p.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(C=>(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,p.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,p.jsx)(te,{className:"af-h-4 af-w-32"}),(0,p.jsx)(te,{className:"af-h-4 af-w-16"})]}),(0,p.jsx)(te,{className:"af-mt-2 af-h-5 af-w-28"}),(0,p.jsx)(te,{className:"af-mt-2 af-h-3 af-w-56"})]},C))}),(0,p.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,p.jsxs)(Me,{children:[(0,p.jsx)(Ue,{children:(0,p.jsxs)(he,{children:[(0,p.jsx)(U,{children:"Person"}),(0,p.jsx)(U,{children:"Came from"}),(0,p.jsx)(U,{children:"Latest message"}),(0,p.jsx)(U,{children:"Last activity"}),(0,p.jsx)(U,{className:"af-w-8"}),(0,p.jsx)(U,{className:"af-w-8"})]})}),(0,p.jsx)($e,{"aria-hidden":"true",children:[0,1,2,3,4].map(C=>(0,p.jsxs)(he,{children:[(0,p.jsx)($,{children:(0,p.jsx)(te,{className:"af-h-4 af-w-40"})}),(0,p.jsx)($,{children:(0,p.jsx)(te,{className:"af-h-5 af-w-24"})}),(0,p.jsx)($,{children:(0,p.jsx)(te,{className:"af-h-4 af-w-56"})}),(0,p.jsx)($,{children:(0,p.jsx)(te,{className:"af-h-4 af-w-24"})}),(0,p.jsx)($,{}),(0,p.jsx)($,{})]},C))})]})}),(0,p.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)G=(0,p.jsxs)("div",{children:[D,(0,p.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,p.jsx)(Kt,{message:"Couldn't load your leads.",onRetry:()=>b()})})]});else if(E.length===0&&o===0){let C=!!h||P!=="all";G=(0,p.jsxs)("div",{children:[C&&D,C?(0,p.jsx)(Ta,{children:h?"Nobody matches that search.":P==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,p.jsx)(Ta,{icon:(0,p.jsx)(ot.Users,{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(a.length===0)G=(0,p.jsxs)("div",{children:[D,(0,p.jsx)(Ta,{children:"No more results."}),(0,p.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[(0,p.jsx)(ot.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let C=o*v+1,V=o*v+a.length;G=(0,p.jsxs)("div",{children:[D,(0,p.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:E.map((m,z)=>(0,p.jsxs)("div",{onClick:()=>M(m),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[(0,p.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,p.jsxs)("div",{className:"af-min-w-0",children:[(0,p.jsx)("button",{type:"button",onClick:se=>{se.stopPropagation(),M(m)},"aria-label":`Open ${m.name||m.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Si(m)}),m.name&&m.email&&(0,p.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:m.email})]}),(0,p.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,p.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:ys(m.last_activity_at)}),m.email&&(0,p.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,p.jsx)("a",{href:ar(m.email),onClick:se=>se.stopPropagation(),"aria-label":`Email ${m.email}`,children:(0,p.jsx)(ot.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,p.jsx)("div",{className:"af-mt-2",children:Ni(m)}),m.latest_message_excerpt&&(0,p.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:m.latest_message_excerpt})]},m.email??m.submission_id??z))}),(0,p.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,p.jsxs)(Me,{children:[(0,p.jsx)(Ue,{children:(0,p.jsxs)(he,{children:[(0,p.jsx)(U,{children:"Person"}),(0,p.jsx)(U,{children:"Came from"}),(0,p.jsx)(U,{children:"Latest message"}),(0,p.jsx)(U,{children:"Last activity"}),(0,p.jsx)(U,{className:"af-w-8",children:(0,p.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,p.jsx)(U,{className:"af-w-8"})]})}),(0,p.jsx)($e,{children:E.map((m,z)=>(0,p.jsxs)(he,{onClick:()=>M(m),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,p.jsxs)($,{className:"af-max-w-[260px] af-font-medium",children:[(0,p.jsx)("button",{type:"button",onClick:se=>{se.stopPropagation(),M(m)},"aria-label":`Open ${m.name||m.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Si(m)}),m.name&&m.email&&(0,p.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:m.email})]}),(0,p.jsx)($,{children:Ni(m)}),(0,p.jsx)($,{className:"af-max-w-[320px]",children:m.latest_message_excerpt?(0,p.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:m.latest_message_excerpt}):(0,p.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,p.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:ys(m.last_activity_at)}),(0,p.jsx)($,{className:"af-w-8",children:m.email&&(0,p.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,p.jsx)("a",{href:ar(m.email),onClick:se=>se.stopPropagation(),"aria-label":`Email ${m.email}`,children:(0,p.jsx)(ot.Mail,{className:"af-h-4 af-w-4"})})})}),(0,p.jsx)($,{className:"af-w-8 af-text-right",children:(0,p.jsx)(ot.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},m.email??m.submission_id??z))})]})}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,p.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:P==="all"?`Showing ${C}-${V}`:`${E.length} of ${a.length} on this page`}),(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!y,children:[(0,p.jsx)(ot.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!g,children:["Next",(0,p.jsx)(ot.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return(0,p.jsx)(xt,{title:"Leads",onBackToWebsite:t,hideBackButton:u.kind!=="list",className:s,children:G})}var ls=require("lucide-react");var Bt=ue(require("react"),1);function Js({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ie(),[a,n]=Bt.useState([]),[i,o]=Bt.useState(0),[v,g]=Bt.useState(!0),[y,r]=Bt.useState(null),[h,w]=Bt.useState(0),[b,u]=Bt.useState(e),[l,x]=Bt.useState(void 0),S=Bt.useRef(0),P=Bt.useCallback(async()=>{let M=++S.current;try{g(!0),r(null);let c={limit:b,offset:h*b};l&&(c.status=l);let N=await s.getSubscriptions(c);if(M!==S.current)return;n(N.subscriptions),o(N.total)}catch(c){if(M!==S.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{M===S.current&&g(!1)}},[s,h,b,l,t]);Bt.useEffect(()=>{P()},[P]);let L=Math.ceil(i/b);return{subscriptions:a,total:i,isLoading:v,error:y,page:h,pageSize:b,hasNextPage:h<L-1,hasPreviousPage:h>0,setPage:w,setPageSize:M=>{u(M),w(0)},status:l,setStatus:M=>{x(M),w(0)},refetch:P}}var B=require("react/jsx-runtime");function Ri(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Pi({sub:e}){return e.status==="canceled"?(0,B.jsx)(Q,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,B.jsx)(Q,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,B.jsx)(Q,{variant:"warning",children:"Scheduled to cancel"}):(0,B.jsx)(Q,{variant:"success",children:"Active"}):(0,B.jsx)(Q,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function hl(e,t){let s=q(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function Ci({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,B.jsxs)("div",{children:[(0,B.jsx)("div",{className:"af-font-medium af-tabular-nums",children:hl(e,e.current_amount)}),t&&(0,B.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",q(e.plan_amount,e.currency)]})]})}function Ti(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Ri(e.current_period_end)}`:"Ends at period end":e.current_period_end?Ri(e.current_period_end):"\u2014"}function nr({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:a,total:n,isLoading:i,error:o,page:v,pageSize:g,hasNextPage:y,hasPreviousPage:r,setPage:h,refetch:w}=Js({refreshKey:e}),b;if(i)b=(0,B.jsxs)("div",{children:[(0,B.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,B.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,B.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,B.jsx)(te,{className:"af-h-4 af-w-40"}),(0,B.jsx)(te,{className:"af-h-4 af-w-20"})]}),(0,B.jsx)(te,{className:"af-mt-2 af-h-3 af-w-32"}),(0,B.jsx)(te,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),(0,B.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,B.jsxs)(Me,{children:[(0,B.jsx)(Ue,{children:(0,B.jsxs)(he,{children:[(0,B.jsx)(U,{children:"Subscriber"}),(0,B.jsx)(U,{children:"Plan"}),(0,B.jsx)(U,{className:"af-text-right",children:"Amount"}),(0,B.jsx)(U,{children:"Renews"}),(0,B.jsx)(U,{children:"Status"})]})}),(0,B.jsx)($e,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,B.jsxs)(he,{children:[(0,B.jsx)($,{children:(0,B.jsx)(te,{className:"af-h-4 af-w-44"})}),(0,B.jsx)($,{children:(0,B.jsx)(te,{className:"af-h-4 af-w-32"})}),(0,B.jsx)($,{className:"af-text-right",children:(0,B.jsx)(te,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,B.jsx)($,{children:(0,B.jsx)(te,{className:"af-h-4 af-w-24"})}),(0,B.jsx)($,{children:(0,B.jsx)(te,{className:"af-h-5 af-w-20"})})]},u))})]})}),(0,B.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)b=(0,B.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,B.jsx)(Kt,{message:"Couldn't load your subscriptions.",onRetry:()=>w()})});else if(a.length===0&&v===0)b=(0,B.jsx)(Ta,{icon:(0,B.jsx)(ls.Repeat,{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(a.length===0)b=(0,B.jsxs)("div",{children:[(0,B.jsx)(Ta,{children:"No more results."}),(0,B.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,B.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v-1),children:[(0,B.jsx)(ls.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=v*g+1,l=v*g+a.length;b=(0,B.jsxs)("div",{children:[(0,B.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:a.map(x=>(0,B.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,B.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,B.jsxs)("div",{className:"af-min-w-0",children:[(0,B.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:x.customer_email||(0,B.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,B.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:x.plan_title||"Untitled plan"})]}),(0,B.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,B.jsx)(Ci,{sub:x})})]}),(0,B.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,B.jsx)(Pi,{sub:x}),x.is_test&&(0,B.jsx)(Q,{variant:"outline",children:"Test"}),(0,B.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ti(x)})]}),(0,B.jsx)(wa,{deliveries:x.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},x.id))}),(0,B.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,B.jsxs)(Me,{children:[(0,B.jsx)(Ue,{children:(0,B.jsxs)(he,{children:[(0,B.jsx)(U,{children:"Subscriber"}),(0,B.jsx)(U,{children:"Plan"}),(0,B.jsx)(U,{className:"af-text-right",children:"Amount"}),(0,B.jsx)(U,{children:"Renews"}),(0,B.jsx)(U,{children:"Status"})]})}),(0,B.jsx)($e,{children:a.map(x=>(0,B.jsxs)(he,{children:[(0,B.jsx)($,{className:"af-max-w-[240px]",children:(0,B.jsx)("div",{className:"af-truncate af-font-medium",children:x.customer_email||(0,B.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,B.jsx)($,{className:"af-max-w-[220px]",children:(0,B.jsx)("div",{className:"af-truncate",children:x.plan_title||(0,B.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,B.jsx)($,{className:"af-whitespace-nowrap af-text-right",children:(0,B.jsx)(Ci,{sub:x})}),(0,B.jsx)($,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ti(x)}),(0,B.jsxs)($,{children:[(0,B.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,B.jsx)(Pi,{sub:x}),x.is_test&&(0,B.jsx)(Q,{variant:"outline",children:"Test"})]}),(0,B.jsx)(wa,{deliveries:x.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},x.id))})]})}),(0,B.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,B.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${u}-${l} of ${n}`}),(0,B.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,B.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v-1),disabled:!r,children:[(0,B.jsx)(ls.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,B.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v+1),disabled:!y,children:["Next",(0,B.jsx)(ls.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,B.jsx)(xt,{title:"Subscriptions",onBackToWebsite:t,className:s,children:b})}var rr=ue(require("react"),1);var tt=require("react/jsx-runtime");function ir({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:v,isLoading:g,error:y,refetch:r}=ss({refreshKey:e,initialPageSize:1,includeAggregates:!0}),h=os({refreshKey:e}),[w,b]=rr.useState(!1),[u,l]=rr.useState(null),x=(0,tt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:y||!g&&!v?(0,tt.jsxs)("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. ",(0,tt.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):g||!v?(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsx)(Ze,{label:"Outstanding",children:(0,tt.jsx)(te,{className:"af-h-6 af-w-24"})}),(0,tt.jsx)(Ze,{label:"Overdue",children:(0,tt.jsx)(te,{className:"af-h-6 af-w-24"})}),(0,tt.jsx)(Ze,{label:"Paid this month",children:(0,tt.jsx)(te,{className:"af-h-6 af-w-24"})})]}):(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsx)(Ze,{label:"Outstanding",detail:`${v.outstanding.count} open`,children:q(v.outstanding.amount,v.currency)}),(0,tt.jsx)(Ze,{label:"Overdue",detail:v.overdue.count===0?"Nothing overdue":`${v.overdue.count} overdue`,valueClassName:v.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:q(v.overdue.amount,v.currency)}),(0,tt.jsx)(Ze,{label:"Paid this month",detail:`${v.paid_this_month.count} paid`,children:q(v.paid_this_month.amount,v.currency)})]})});return(0,tt.jsxs)(xt,{title:"Invoices",onBackToWebsite:s,hideBackButton:w,className:o,children:[x,!w&&(0,tt.jsx)(rs,{retainers:h.retainers,isLoading:h.isLoading,error:h.error,onRetry:()=>void h.refetch(),activeRetainerId:u?.id??null,onShowCycles:S=>l(P=>P?.id===S.id?null:S),total:h.total,endedTotal:h.endedTotal,isLoadingMore:h.isLoadingMore,onLoadMore:()=>void h.loadMore(),includeEnded:h.includeEnded,onIncludeEndedChange:h.setIncludeEnded}),(0,tt.jsx)(ns,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:b,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:u?{id:u.id,label:`${u.customer_name??u.customer_email??"Recurring invoices"} \u2014 ${u.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}var Mt=ue(require("react"),1);var xl=2e3,Ft=()=>({data:null,error:null,isLoading:!0});function Ys(e,{refreshKey:t,breakdowns:s=[],filters:a=[]}={}){let{api:n}=ie(),[i,o]=Mt.useState(Ft),[v,g]=Mt.useState(Ft),[y,r]=Mt.useState(Ft),[h,w]=Mt.useState(Ft),b=D=>Object.fromEntries(D.map(C=>[C,Ft()])),[u,l]=Mt.useState(()=>b(s)),x=Mt.useRef(0),S=s.join(","),P=JSON.stringify(a),L=`${e}:${S}:${P}`,[M,c]=Mt.useState({api:n,fetchIdentity:L});(M.api!==n||M.fetchIdentity!==L)&&(c({api:n,fetchIdentity:L}),x.current+=1,o(Ft),g(Ft),r(Ft),w(Ft),l(b(S?S.split(","):[])));let N=Mt.useCallback(async()=>{let D=++x.current,C=S?S.split(","):[];o(Ft),g(Ft),r(Ft),w(Ft),l(Object.fromEntries(C.map(K=>[K,Ft()])));let V=(K,ae)=>ae.then(ce=>{D===x.current&&K({data:ce,error:null,isLoading:!1})},ce=>{D===x.current&&K({data:null,error:ce instanceof Error?ce:new Error("Failed to fetch report"),isLoading:!1})}),m=n.getAnalyticsStatus(),z=V(o,m),se=Symbol("status-timeout"),X,ee=await Promise.race([m.then(K=>K,()=>null),new Promise(K=>{X=setTimeout(()=>K(se),xl)})]);if(clearTimeout(X),D!==x.current)return;if(ee===se&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),ee!==null&&ee!==se&&(ee.collecting!==!0||ee.first_seen===null&&!ee.first_seen_unavailable||ee.first_seen!==null&&ee.first_seen_in_reports===!1)){let K={data:null,error:null,isLoading:!1};g(K),r(K),w(K),l(Object.fromEntries(C.map(ae=>[ae,{...K}]))),await z;return}await Promise.all([ee===se?Promise.resolve():z,V(g,n.getAnalyticsSummary(e,a)),V(r,n.getAnalyticsTimeseries(e,a)),V(w,n.getAnalyticsChannels(e,a)),...C.map(K=>n.getAnalyticsBreakdown(K,e,a).then(ae=>{D===x.current&&l(ce=>({...ce,[K]:{data:ae,error:null,isLoading:!1}}))},ae=>{D===x.current&&l(ce=>({...ce,[K]:{data:null,error:ae instanceof Error?ae:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,S,P]),E=Mt.useCallback(async()=>{let D=x.current;try{let C=await n.getAnalyticsStatus();if(D!==x.current)return;o({data:C,error:null,isLoading:!1})}catch(C){if(D!==x.current)return;o(V=>({data:V.data,error:C instanceof Error?C:new Error("Failed to fetch status"),isLoading:!1}))}},[n]);Mt.useEffect(()=>{N()},[N,t]);let G=i.isLoading||v.isLoading||y.isLoading||h.isLoading||Object.values(u).some(D=>D.isLoading);return{status:i,summary:v,timeseries:y,channels:h,breakdowns:u,isLoading:G,refetch:N,refetchStatus:E}}var gt=ue(require("react"),1);var In=3e4,Dn=3;function Zs(e={}){let t="collecting"in e,{collecting:s,statusFailed:a=!1,identity:n}=e,{api:i}=ie(),[o,v]=gt.useState(null),[g,y]=gt.useState(null),[r,h]=gt.useState(!1),[w,b]=gt.useState(null),[u,l]=gt.useState(!1),[x,S]=gt.useState(!0),[P,L]=gt.useState(0),M=gt.useRef(0),c=gt.useRef(0),N=gt.useRef(void 0);s!==void 0&&(N.current=s);let E=t?N.current===!0||N.current===void 0&&a:!0,[G,D]=gt.useState({api:i,identity:n}),C=n!==void 0&&n!==G.identity;(G.api!==i||C)&&(N.current=void 0,D({api:i,identity:n}),c.current+=1,M.current=0,v(null),y(null),h(!1),b(null),l(!1),S(!0),L(0));let V=gt.useRef(()=>{}),m=gt.useRef(null),z=gt.useCallback(async()=>{if(m.current!==null&&m.current===c.current)return;let se=++c.current;m.current=se;try{let X=await i.getAnalyticsRealtime();if(se!==c.current)return;if(X.status==="unreachable"){l(!0),h(!0),S(!1),L(ee=>ee+1);return}M.current=0,l(!1),v(X.data.current_visitors),y(X.as_of),h(!1),b(null),S(!1),L(ee=>ee+1)}catch(X){if(se!==c.current)return;M.current+=1,S(!1),L(ee=>ee+1),h(!0),M.current>=Dn&&b(X instanceof Error?X:new Error("Realtime unavailable"))}finally{m.current===se&&(m.current=null)}},[i]);return V.current=()=>void z(),gt.useEffect(()=>{let se,X=()=>{se===void 0&&(se=setInterval(()=>V.current(),In))},ee=()=>{se!==void 0&&(clearInterval(se),se=void 0)},fe=()=>{typeof document<"u"&&document.hidden?ee():(V.current(),X())};return E?((typeof document>"u"||!document.hidden)&&(V.current(),X()),document?.addEventListener("visibilitychange",fe),()=>{ee(),document?.removeEventListener("visibilitychange",fe),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",fe)}},[G.api,G.identity,E]),{currentVisitors:o,asOf:g,isStale:r,error:w,isUnreachable:u,isInitialLoad:x,polls:P}}var Ke=ue(require("react"),1);var cs=ue(require("react"),1);var wl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ya(e){let t=Math.abs(e);if(t<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[a,n]of s)if(t>=a){let i=e/a,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&a!==1e9?ya(o*a):`${o}${n}`}return String(e)}function An(e){return`${(e*100).toFixed(1)}%`}function Qs(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Ei(e){let t=Math.max(0,Math.round(e));return t>=3600&&t%3600===0?`${t/3600}h`:t>=60&&t%60===0?`${t/60}m`:Qs(t)}function Ii(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Di(e,t){if(!(!Number.isFinite(e)||e<=0))for(let s of t){let a=Math.ceil(e/s);if(a<=5)return Array.from({length:a+1},(n,i)=>Number((i*s).toPrecision(12)))}}function Xs(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Ai(e){let t=new Date(e);return Number.isNaN(t.getTime())?"as of an unknown time":`as of ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function or(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${wl[t-1]} ${s}`}function ki(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Nl(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Li(e,t,s="UTC"){let a=new Map(t.map(o=>[o.date,o])),n=[],i=ki(e.to,s);for(let o=ki(e.from,s);o<i;o=Nl(o))n.push(a.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Oi(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=new Date(`${e}T00:00:00Z`);if(Number.isNaN(a.getTime()))return e;let n=String(a.getUTCDate()).padStart(2,"0");return`${t[a.getUTCDay()]}, ${n} ${s[a.getUTCMonth()]}`}var Qt=require("react/jsx-runtime");function Bi({what:e="This report",onRetry:t,collecting:s}){return(0,Qt.jsxs)("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:[(0,Qt.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Qt.jsx)("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.`}),t?(0,Qt.jsx)("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function Fi({what:e="No data"}){return(0,Qt.jsx)("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 en({sourced:e,error:t,isLoading:s,what:a,onRetry:n,collecting:i,children:o}){return s?(0,Qt.jsx)("div",{role:"status","aria-label":`Loading ${a}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Qt.jsx)(Bi,{what:a,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,Qt.jsx)(Bi,{what:a,onRetry:n,collecting:i}):(0,Qt.jsx)(Qt.Fragment,{children:o(e.data)})}var je=require("react/jsx-runtime");function lr({rows:e,dimension:t,metric:s,metricLabel:a,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:v,maxRows:g=9}){let[y,r]=cs.useState(!1);if(e.length===0)return(0,je.jsx)(Fi,{what:i});let h=e.reduce((u,l)=>Math.max(u,Number(l[s]??0)),0)||1,w=Math.max(0,e.length-g),b=y?e:e.slice(0,g);return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,je.jsx)("thead",{children:(0,je.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,je.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,je.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:a})]})}),(0,je.jsx)("tbody",{children:b.map((u,l)=>{let x=Number(u[s]??0),S=u[t]??null,P=Xs(S),L=n?u[n]:null,M=S!==null&&(v?v(S,L):!0);return(0,je.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,je.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,je.jsx)("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,x/h*100)}%`}}),S!==null&&o&&M?(0,je.jsx)("button",{type:"button",onClick:()=>o(S,L),title:`Filter by ${P}`,"aria-label":`Filter by ${P}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:P}):(0,je.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:P}),L?(0,je.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:L}):null]}),(0,je.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:ya(x)})]},`${P}-${L??""}-${l}`)})})]}),w>0?(0,je.jsx)("button",{type:"button",onClick:()=>r(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:y?"Show fewer":`Show all ${e.length}`}):null]})}function tn({title:e,tabs:t,defaultTabId:s,headerRight:a}){let[n,i]=cs.useState(s),o=t.find(b=>b.id===n)??t[0],v=cs.useId(),g=b=>`${v}-tab-${b}`,y=b=>`${v}-panel-${b}`,r=cs.useRef(null),h=(b,u)=>{b.preventDefault();let l=(u+t.length)%t.length;i(t[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return(0,je.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,je.jsxs)("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:[(0,je.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:b=>{let u=t.findIndex(l=>l.id===n);b.key==="ArrowRight"&&h(b,u+1),b.key==="ArrowLeft"&&h(b,u-1),b.key==="Home"&&h(b,0),b.key==="End"&&h(b,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(b=>(0,je.jsx)("button",{id:g(b.id),role:"tab",type:"button","aria-selected":b.id===n,"aria-controls":y(b.id),tabIndex:b.id===n?0:-1,onClick:()=>i(b.id),className:b.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:b.label},b.id))}),a]}),o?(0,je.jsx)("div",{id:y(o.id),role:"tabpanel","aria-labelledby":g(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Ut=ue(require("react"),1),Ja=ue(require("@radix-ui/react-popover"),1);var us=3,ds=100;var Ae=require("react/jsx-runtime"),an={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"},Sl=Object.keys(an);function Mi(e){let t=an[e.dimension],s=e.operator==="is_not"?"is not":"is",a=e.values.map(n=>Xs(n)).join(" or ");return`${t} ${s} ${a}`}function cr(e,t){let s=e.findIndex(a=>a.dimension===t.dimension&&(a.operator??"is")===(t.operator??"is"));if(s>=0){let a=[...new Set([...e[s].values,...t.values])];return a.length>100||a.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:a}:n)}return t.values.length>100||e.length>=3?e:[...e,t]}function _l(e,t){let s={};for(let[a,n]of Object.entries(t)){let i=e.get(a)??new Set;for(let o of n)i.add(o);e.set(a,i),s[a]=[...i]}return s}function Ui(e,t){let s=e.findIndex(a=>a.dimension===t.dimension&&(a.operator??"is")===(t.operator??"is"));return s>=0?e.map((a,n)=>n===s?t:a):t.values.length>100||e.length>=3?e:[...e,t]}function Rl(e){return{dimension:e,operator:"is",search:"",picked:[]}}function $i(e,t,s,a={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=_l(e.byDimension,s);for(let[i,o]of Object.entries(a)){let v=e.foldsByLabel.get(i)??new Set;for(let g of o)v.add(g);e.foldsByLabel.set(i,v)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Vi(e){let{filters:t,onChange:s}=e,a=t.length>=3;return Ut.useEffect(()=>{if(t.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)},[t.length,s]),(0,Ae.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,i)=>(0,Ae.jsxs)("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:[(0,Ae.jsx)("span",{className:"af-text-foreground",children:Mi(n)}),(0,Ae.jsx)("button",{type:"button","aria-label":`Remove filter ${Mi(n)}`,onClick:()=>s(t.filter((o,v)=>v!==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"}`)),(0,Ae.jsx)(Pl,{...e,disabled:a}),t.length>0?(0,Ae.jsx)("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 Pl({filters:e,onChange:t,suggestions:s,resetKey:a,disabled:n,expandValues:i}){let[o,v]=Ut.useState(!1),g=Ut.useRef(null),[y,r]=Ut.useState(null);Ut.useEffect(()=>{r(g.current?.closest(".aifeatures-admin")??null)},[]);let[h,w]=Ut.useState(null),[b,u]=Ut.useState("is"),[l,x]=Ut.useState(""),[S,P]=Ut.useState([]);Ut.useEffect(()=>{o||(w(null),u("is"),x(""),P([]))},[o]);let L=Ut.useRef(a);L.current!==a&&(L.current=a,o&&v(!1),h!==null&&w(null),S.length>0&&P([]),l!==""&&x(""),b!=="is"&&u("is"));let M=C=>{let V=Rl(C);w(V.dimension),P(V.picked),x(V.search),u(V.operator)},N=(h?s[h]??[]:[]).filter(C=>C.toLowerCase().includes(l.trim().toLowerCase())),E=h===null||S.length===0?null:cr(e,{dimension:h,operator:b,values:i?i(h,S):S}),G=E!==null&&E!==e,D=()=>{let C=E;!C||C===e||(t(C),v(!1))};return(0,Ae.jsxs)(Ja.Root,{open:o,onOpenChange:v,children:[(0,Ae.jsx)(Ja.Trigger,{asChild:!0,children:(0,Ae.jsx)("button",{ref:g,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"})}),(0,Ae.jsx)(Ja.Portal,{container:y,children:(0,Ae.jsx)(Ja.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:h===null?(0,Ae.jsxs)("div",{children:[(0,Ae.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Ae.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:Sl.filter(C=>s[C]!==void 0).map(C=>{let V=s[C]?.length??0,m=!e.some(z=>z.dimension===C)&&e.length>=3;return(0,Ae.jsxs)("button",{type:"button",onClick:()=>M(C),disabled:V===0||m,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:[(0,Ae.jsx)("span",{children:an[C]}),(0,Ae.jsx)("span",{className:"af-text-muted-foreground",children:V===0?"no data":m?"no room":V})]},C)})})]}):(0,Ae.jsxs)("div",{children:[(0,Ae.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ae.jsx)("button",{type:"button",onClick:()=>M(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Ae.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:an[h]}),(0,Ae.jsxs)("select",{"aria-label":"Operator",value:b,onChange:C=>u(C.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:[(0,Ae.jsx)("option",{value:"is",children:"is"}),(0,Ae.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Ae.jsx)("input",{type:"text",value:l,onChange:C=>x(C.target.value),placeholder:"Search\u2026","aria-label":`Search ${an[h]}`,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"}),(0,Ae.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:N.length===0?(0,Ae.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):N.map(C=>(0,Ae.jsxs)("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:[(0,Ae.jsx)("input",{type:"checkbox",checked:S.includes(C),disabled:!S.includes(C)&&S.length>=100,onChange:V=>P(m=>V.target.checked?[...m,C]:m.filter(z=>z!==C))}),(0,Ae.jsx)("span",{className:"af-break-all",children:Xs(C)})]},C))}),(0,Ae.jsx)("button",{type:"button",onClick:D,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:S.length<=1?"Apply filter":S.length>=100?`Apply filter (${S.length} values \u2014 the maximum)`:`Apply filter (${S.length} values)`})]})})})]})}var Qe=require("react/jsx-runtime"),Cl=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:ya,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:ya,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:ya,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:An,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Qs,chart:"visit_duration_seconds"}];function Tl({current:e,previous:t,downIsGood:s}){if(t===0)return null;let a=(e-t)/t;if(Math.abs(a)<5e-4)return null;let n=a>0,i=s?!n:n,o=`${n?"+":""}${(a*100).toFixed(1)}%`;return(0,Qe.jsx)("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 Hi({summary:e,selected:t,onSelect:s}){return(0,Qe.jsx)("div",{className:"af-@container",children:(0,Qe.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Cl.map(a=>{let n=a.chart===t,i=s!==void 0,o=(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:a.label}),(0,Qe.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,Qe.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:a.format(a.get(e.current))}),e.previous?(0,Qe.jsx)(Tl,{current:a.get(e.current),previous:a.get(e.previous),downIsGood:a.downIsGood}):null]})]});return i?(0,Qe.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>s(a.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},a.key):(0,Qe.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},a.key)})})})}function ur({currentVisitors:e,asOf:t,isStale:s,isUnreachable:a,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!a)return(0,Qe.jsxs)("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:[(0,Qe.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,Qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(a||e===null)return(0,Qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?Ai(t):"freshness unknown",v=i?" across the whole site, not the current filter,":"",g=s?`${e} current visitors${v} ${o} (not updating)`:`${e} current visitors${v} ${o}`;return(0,Qe.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:g,children:[(0,Qe.jsx)("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"}),(0,Qe.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,Qe.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,Qe.jsx)("span",{className:"af-sr-only",children:g})]})}var $t=require("recharts");var at=require("react/jsx-runtime"),Ln={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},fr={visitors:ya,visits:ya,pageviews:ya,views_per_visit:e=>e.toFixed(2),bounce_rate:An,visit_duration_seconds:Qs},kl=new Set(["visitors","visits","pageviews"]),El={...fr,bounce_rate:Ii,visit_duration_seconds:Ei},dr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Il=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Dl=[.01,.02,.05,.1,.2,.25,.5,1],Al=[.25,.5,1,2,5,10,25,50],Ll={visitors:dr,visits:dr,pageviews:dr,views_per_visit:Al,bounce_rate:Dl,visit_duration_seconds:Il};function Ol({active:e,payload:t,label:s,metric:a}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,at.jsxs)("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:[(0,at.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Ln[a]}),(0,at.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,at.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,at.jsx)("span",{className:"af-text-muted-foreground",children:Oi(String(s))}),(0,at.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:fr[a](Number(n[a]??0))})]})]})}function zi({rows:e,window:t,metric:s,timeZone:a="UTC",height:n=260}){let i=Li(t,e,a),o=fr[s],v=El[s],g=Di(i.reduce((r,h)=>Math.max(r,Number(h[s]??0)),0),Ll[s]),y=`${Ln[s]} by day: ${i.map(r=>`${or(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,at.jsxs)("figure",{"aria-label":`${Ln[s]} over time`,className:"af-m-0",children:[(0,at.jsx)($t.ResponsiveContainer,{width:"100%",height:n,children:(0,at.jsxs)($t.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,at.jsx)("defs",{children:(0,at.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,at.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,at.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,at.jsx)($t.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,at.jsx)($t.XAxis,{dataKey:"date",tickFormatter:or,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,at.jsx)($t.YAxis,{allowDecimals:!kl.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...g?{ticks:g,domain:[0,g[g.length-1]]}:{},tickFormatter:r=>v(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,at.jsx)($t.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,at.jsx)(Ol,{metric:s})}),(0,at.jsx)($t.Area,{type:"monotone",dataKey:s,name:Ln[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,at.jsx)("figcaption",{className:"af-sr-only",children:y})]})}var ge=require("react/jsx-runtime"),Bl=3e4,Fl="2026-08-13",Ml=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Ul=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function qi({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:a,className:n,published:i,lastPublishedAt:o}){let[v,g]=Ke.useState(30),y=e!==void 0&&t!==void 0,[r,h]=Ke.useState(e??[]),{api:w}=ie(),[b,u]=Ke.useState(w);b!==w&&(u(w),!y&&r.length>0&&h([]));let l=y?e:r,x=Ke.useCallback(Z=>{t&&t(Z),y||h(Z)},[t,y]),S=Ke.useCallback((Z,re,Re)=>{let T=Array.isArray(re)?re:[re];if(T.length===0)return null;let O=cr(l,{dimension:Z,operator:"is",values:T});if(Re&&(!Re.value||(O=Ui(O,{dimension:Re.dimension,operator:"is",values:[Re.value]}),!O.find(Ie=>Ie.dimension===Re.dimension&&Ie.operator!=="is_not")?.values.includes(Re.value))))return null;let ve=O.find(Le=>Le.dimension===Z&&Le.operator!=="is_not");return T.every(Le=>ve?.values.includes(Le))?JSON.stringify(O)===JSON.stringify(l)?null:O:null},[l]),P=Ke.useCallback((Z,re,Re)=>S(Z,re,Re)!==null,[S]),L=Ke.useCallback((Z,re,Re)=>{let T=S(Z,re,Re);T&&x(T)},[S,x]),[M,c]=Ke.useState("visitors"),N=Ys(v,{refreshKey:s,breakdowns:Ul,filters:l}),E=N.status.data,G=i===!1,D=E!=null&&(!E.collecting||G&&E.first_seen===null&&!E.first_seen_unavailable),C=!D&&E?.collecting===!0&&E.first_seen===null&&!E.first_seen_unavailable,V=E?.collecting===!0&&E.first_seen!==null&&E.first_seen_in_reports===!1,m=C||V,z=Zs({collecting:C||D?!1:E?.collecting,statusFailed:N.status.error!=null,identity:E?.analytics_id}),se=Ke.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),X=Ke.useMemo(()=>{let Z=N.breakdowns.sources?.data,re={};if(!Z||Z.status!=="ok")return re;for(let Re of Z.data){let T=Re.source,O=Re.sources;typeof T=="string"&&Array.isArray(O)&&O.length>0&&(re[T]=O)}return re},[N.breakdowns.sources?.data]),ee=Ke.useMemo(()=>{let Z=(T,O)=>{let ve=N.breakdowns[T]?.data;return!ve||ve.status!=="ok"?[]:[...new Set(ve.data.map(Le=>Le[O]).filter(Le=>typeof Le=="string"&&Le!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(T=>T.channel))]:[],source:Z("sources","source"),campaign:Z("utm/campaign","campaign"),page:Z("pages","pathname"),entry_page:Z("entry-pages","pathname"),exit_page:Z("exit-pages","pathname"),country:Z("countries","country"),browser:Z("browsers","browser"),os:Z("operating-systems","os"),device:Z("devices","device")}},[N.breakdowns,N.channels.data]),[fe,K]=Ke.useState({}),ae=JSON.stringify(ee),[ce,J]=Ke.useState(new Map),Pe=JSON.stringify(X);Ke.useEffect(()=>{let{suggestions:Z,folds:re}=$i(se.current,{api:w,period:v},JSON.parse(ae),JSON.parse(Pe));K(Z),J(re)},[ae,Pe,w,v]);let vt=Ke.useCallback((Z,re)=>Z!=="source"?re:[...new Set(re.flatMap(Re=>{let T=[...ce.get(Re)??[],...X[Re]??[]];return T.length>0?T:[Re]}))],[ce,X]),St=Ke.useMemo(()=>{let Z=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let re of Z){let Re=re?.error;if(Re instanceof Dt&&Re.details?.code==="filter_unsupported")return Re.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),Ce=(Z,re,Re,T,O,ve,Le,Ie,lt)=>()=>{let st=N.breakdowns[Z];return(0,ge.jsx)(en,{sourced:st?.data??null,error:st?.error,isLoading:st?.isLoading,what:re,collecting:E?.collecting,onRetry:N.refetch,children:yt=>{let Ct=ht=>Ie?vt(Ie,[ht]):ht;return(0,ge.jsx)(lr,{rows:yt,dimension:Re,metric:T,metricLabel:O,secondary:ve,emptyCopy:l.length>0?"No data for this filter":Le,canFilter:Ie?(ht,oe)=>P(Ie,Ct(ht),lt?{dimension:lt,value:oe}:void 0):()=>!1,onFilter:Ie?(ht,oe)=>L(Ie,Ct(ht),lt?{dimension:lt,value:oe}:void 0):void 0})}})};Ke.useEffect(()=>{if(!m)return;let Z,re=()=>{Z===void 0&&(Z=setInterval(()=>void N.refetchStatus(),Bl))},Re=()=>{Z!==void 0&&(clearInterval(Z),Z=void 0)},T=()=>{typeof document<"u"&&document.hidden?Re():(N.refetchStatus(),re())};return(typeof document>"u"||!document.hidden)&&re(),document?.addEventListener("visibilitychange",T),()=>{Re(),document?.removeEventListener("visibilitychange",T)}},[m,N.refetchStatus]);let bt=Ke.useRef(void 0);if(Ke.useEffect(()=>{if(!E){bt.current=void 0;return}let Z=bt.current;bt.current=m,Z===!0&&!m&&N.refetch()},[E,m,N.refetch]),D){let Z=!!o&&String(o).slice(0,10)<Fl;return(0,ge.jsx)(xt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,ge.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ge.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,ge.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:G?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":Z?"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 C?(0,ge.jsx)(xt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,ge.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ge.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,ge.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:"Your site is set up and analytics is running. The first visit shows up here shortly after someone lands on a published page."})]})}):V?(0,ge.jsx)(xt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,ge.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ge.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,ge.jsxs)("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",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,ge.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,ge.jsx)(ur,{currentVisitors:z.currentVisitors,asOf:z.asOf,isStale:z.isStale,isUnreachable:z.isUnreachable||z.error!==null,isInitialLoad:z.isInitialLoad})})]})}):(0,ge.jsx)(xt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,ge.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,ge.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,ge.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Ml.map(Z=>(0,ge.jsx)("button",{type:"button","aria-pressed":Z.value===v,onClick:()=>g(Z.value),className:Z.value===v?"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:Z.label},Z.value))}),(0,ge.jsx)(ur,{currentVisitors:z.currentVisitors,asOf:z.asOf,isStale:z.isStale,isUnreachable:z.isUnreachable||z.error!==null,isInitialLoad:z.isInitialLoad,scopeIsSiteWide:l.length>0})]}),(0,ge.jsx)(Vi,{filters:l,onChange:x,suggestions:fe,expandValues:vt,resetKey:w}),St?(0,ge.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,ge.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,ge.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:St}),(0,ge.jsx)("button",{type:"button",onClick:()=>x([]),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,!St&&E?.timezone_defaulted?(0,ge.jsx)("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,St?null:(0,ge.jsxs)(ge.Fragment,{children:[(0,ge.jsx)(en,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:N.refetch,children:Z=>(0,ge.jsxs)(ge.Fragment,{children:[(0,ge.jsx)(Hi,{summary:Z,selected:M,onSelect:c}),Z.previous_unavailable?(0,ge.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[Z.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]})}),(0,ge.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,ge.jsx)(en,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:N.refetch,children:Z=>{let re=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,ge.jsx)(zi,{rows:Z,window:re,metric:M,timeZone:(N.timeseries.data?.status==="ok"?N.timeseries.data.timezone:void 0)??E?.timezone??"UTC"})}})}),(0,ge.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,ge.jsx)(tn,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,ge.jsx)(en,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:N.refetch,children:Z=>(0,ge.jsx)(lr,{rows:Z,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:l.length>0?"No data for this filter":"No data for this period",canFilter:re=>P("channel",re),onFilter:re=>L("channel",re)})})},{id:"sources",label:"Sources",render:Ce("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:Ce("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,ge.jsx)(tn,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:Ce("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:Ce("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:Ce("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,ge.jsx)(tn,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:Ce("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:Ce("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:Ce("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,ge.jsx)(tn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:Ce("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:Ce("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:Ce("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSubmissions,useSubscriptions});
|
|
2
|
+
"use strict";var Xi=Object.create;var rn=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty;var no=(e,t)=>{for(var s in t)rn(e,s,{get:t[s],enumerable:!0})},Sr=(e,t,s,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of to(t))!so.call(e,n)&&n!==s&&rn(e,n,{get:()=>t[n],enumerable:!(a=eo(t,n))||a.enumerable});return e};var de=(e,t,s)=>(s=e!=null?Xi(ao(e)):{},Sr(t||!e||!e.__esModule?rn(s,"default",{value:e,enumerable:!0}):s,e)),ro=e=>Sr(rn({},"__esModule",{value:!0}),e);var zl={};no(zl,{AifeaturesApiError:()=>kt,AifeaturesProvider:()=>Rr,AnalyticsView:()=>Wi,CustomerDetail:()=>js,CustomersList:()=>Gs,FormSettings:()=>Bs,FormSubmissions:()=>Es,FormsDashboard:()=>$n,FormsList:()=>Rs,InvoiceDetail:()=>_n,InvoiceLabelBadge:()=>vs,InvoicesList:()=>rs,InvoicesView:()=>lr,LeadsView:()=>rr,MAX_ANALYTICS_FILTERS:()=>ds,MAX_ANALYTICS_FILTER_VALUES:()=>fs,OrderDetail:()=>zs,OrderStatusBadge:()=>Wa,OrdersList:()=>as,OrdersView:()=>tr,PaymentsDashboard:()=>er,PaymentsSetup:()=>Ws,ProductSettings:()=>$s,ProductsList:()=>Ms,ProductsView:()=>ar,PromosPanel:()=>Xa,REALTIME_FAILURES_BEFORE_ERROR:()=>Ln,REALTIME_POLL_MS:()=>Dn,RetainerStatusBadge:()=>Pn,RetainersPanel:()=>is,SubmissionDetail:()=>Ts,SubscriptionsView:()=>ir,VariantsEditor:()=>Us,ViewShell:()=>Nt,WebhookDeliveries:()=>Ls,WebhookSettings:()=>Os,chargedTotal:()=>Pa,createApiClient:()=>ln,formatPrice:()=>j,isZeroDecimalCurrency:()=>Kt,toMajorUnits:()=>lt,toMinorUnits:()=>Et,useAifeatures:()=>oe,useAifeaturesContext:()=>oe,useAnalytics:()=>Xs,useBusinessSummary:()=>Ks,useCustomers:()=>qs,useEventDestinations:()=>As,useForms:()=>Za,useInvoices:()=>ns,useOrders:()=>Vs,usePaymentsStatus:()=>Ma,usePeople:()=>Ys,usePerson:()=>Zs,useProducts:()=>os,useRealtimeVisitors:()=>en,useRetainers:()=>ls,useSubmissions:()=>Cs,useSubscriptions:()=>Qs});module.exports=ro(zl);var za=de(require("react"),1);function on(e,t){let s=new URLSearchParams({period:String(e)});return t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var kt=class extends Error{constructor(s,a,n){super(s);this.status=a;this.details=n;this.name="AifeaturesApiError"}};function Mn(e,t){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{}return`Request failed with status ${t}`}function ln(e,t="https://aifeatures.dev"){async function s(a,n={}){let i=`${t}${a}`,o=await fetch(i,{...n,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...n.headers}});if(!o.ok){let v;try{v=await o.json()}catch{}throw new kt(Mn(v?.error,o.status),o.status,v)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(a){return s(`/api/v1/forms/${a}`)},async createForm(a){return s("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,n){return s(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteForm(a){await s(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,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(),v=`/api/v1/forms/${a}/submissions${o?`?${o}`:""}`;return s(v)},async getSubmission(a){return s(`/api/v1/submissions/${a}`)},async deleteSubmission(a){await s(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,n){let i=typeof n=="string"?{name:n}:n,o=i.name,v=i.id??i.name,g=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(v)}`,y=await fetch(g,{headers:{Authorization:`Bearer ${e}`}});if(!y.ok){let b;try{b=await y.json()}catch{}throw new kt(Mn(b?.error,y.status),y.status,b)}let r=await y.blob(),h=URL.createObjectURL(r),N=document.createElement("a");N.href=h,N.download=o,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(h)},async getPaymentsStatus(){return s("/api/v1/payments/status")},getPromos(a){let n=new URLSearchParams({limit:"10"});return a&&n.set("cursor",a),s(`/api/v1/promos?${n}`)},getPromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return s("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return s(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,n){return s(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(n)})},async getProducts(a={}){let n=new URLSearchParams;a.include&&n.set("include",a.include);let i=n.toString();return(await s(`/api/v1/products${i?`?${i}`:""}`)).products},async getProduct(a){return s(`/api/v1/products/${a}`)},async createProduct(a){return s("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,n){return s(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteProduct(a){await s(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,n){let i=new FormData;i.append("file",n);let o=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:i});if(!o.ok){let v;try{v=await o.json()}catch{}throw new kt(Mn(v?.error,o.status),o.status,v)}return o.json()},async attachProductFileFromUrl(a,n){return s(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:n})})},async createOption(a,n){return s(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(n)})},async updateOption(a,n){return s(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteOption(a){await s(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,n){return s(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(n)})},async updateVariant(a,n){return s(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteVariant(a){await s(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,n){return s(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(n)})},async adjustVariantInventory(a,n){return s(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(n)})},async getCustomers(a={}){let n=new URLSearchParams;a.email?n.set("email",a.email):a.q&&n.set("q",a.q),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/customers${i?`?${i}`:""}`)},async getCustomer(a){return s(`/api/v1/customers/${a}`)},async getOrders(a={}){let n=new URLSearchParams;a.status&&n.set("status",a.status),a.source&&n.set("source",a.source),a.excludeStatus?.length&&n.set("exclude_status",a.excludeStatus.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.from&&n.set("from",a.from),a.to&&n.set("to",a.to),a.unfulfilledOnly&&n.set("unfulfilled_only","true"),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/orders${i?`?${i}`:""}`)},async getOrder(a){return s(`/api/v1/orders/${a}`)},async getInvoices(a={}){let n=new URLSearchParams;a.labels?.length&&n.set("label",a.labels.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.customerId&&n.set("customer_id",a.customerId),a.q&&n.set("q",a.q),a.from&&n.set("from",a.from),a.to&&n.set("to",a.to),a.includeAggregates&&n.set("include","aggregates"),a.retainerId&&n.set("retainer_id",a.retainerId),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/invoices${i?`?${i}`:""}`)},async getInvoice(a){return s(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return s(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return s("/api/v1/invoice-settings")},async getRetainers(a={}){let n=new URLSearchParams;a.statuses?.length&&n.set("status",a.statuses.join(",")),a.customerEmail&&n.set("customer_email",a.customerEmail),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/retainers${i?`?${i}`:""}`)},async getRetainer(a){return s(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await s(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return s(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,n){return s(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:n.fulfilled,...n.trackingNumber!==void 0?{tracking_number:n.trackingNumber}:{}})})},async getSubscriptions(a={}){let n=new URLSearchParams;a.status&&n.set("status",a.status),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/subscriptions${i?`?${i}`:""}`)},async getAnalyticsStatus(){return s("/api/v1/analytics/status")},async getAnalyticsSummary(a,n){return s(`/api/v1/analytics/summary?${on(a,n)}`)},async getAnalyticsTimeseries(a,n){return s(`/api/v1/analytics/timeseries?${on(a,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,n){return s(`/api/v1/analytics/channels?${on(a,n)}`)},async getAnalyticsConversions(a){return s(`/api/v1/analytics/conversions?period=${String(a)}`)},async getAnalyticsBreakdown(a,n,i){let o=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${on(n,i)}`)},async getBusinessSummary(a){let n=new URLSearchParams;return n.set("tz_offset_minutes",String(a.tzOffsetMinutes)),s(`/api/v1/summary?${n.toString()}`)},async getPeople(a={}){let n=new URLSearchParams;a.since&&n.set("since",a.since),a.q&&n.set("q",a.q),a.limit!==void 0&&n.set("limit",String(a.limit)),a.offset!==void 0&&n.set("offset",String(a.offset));let i=n.toString();return s(`/api/v1/people${i?`?${i}`:""}`)},async getPerson(a){return s(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await s("/api/v1/event-destinations")).destinations},async createEventDestination(a){return s("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,n){return s(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(n)})},async deleteEventDestination(a){await s(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return s(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await s(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,n){let i=n===void 0?"":`?limit=${n}`;return(await s(`/api/v1/event-destinations/${a}/deliveries${i}`)).deliveries},async retryEventDelivery(a,n){return s(`/api/v1/event-destinations/${a}/deliveries/${n}/retry`,{method:"POST"})}}}var Ha=require("react/jsx-runtime"),_r=za.createContext(null);function io(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 Rr({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:a,children:n}){let i=za.useMemo(()=>io(e),[e]),o=za.useMemo(()=>ln(e,t),[e,t]),v=za.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return i?(0,Ha.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:(0,Ha.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Ha.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Ha.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,Ha.jsx)(_r.Provider,{value:v,children:(0,Ha.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:n})})}function oe(){let e=za.useContext(_r);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Ga=de(require("react"),1),ms=require("lucide-react");var cn=de(require("react"),1),ua=de(require("@radix-ui/react-tabs"),1);var Pr=require("clsx"),Cr=require("tailwind-merge"),oo=(0,Cr.extendTailwindMerge)({prefix:"af-"});function Y(...e){return oo((0,Pr.clsx)(e))}var dn=require("react/jsx-runtime"),un=ua.Root,Ss=cn.forwardRef(({className:e,...t},s)=>(0,dn.jsx)(ua.List,{ref:s,className:Y("af-inline-flex af-h-9 af-items-center af-justify-center af-rounded-lg af-bg-muted af-p-1 af-text-muted-foreground",e),...t}));Ss.displayName=ua.List.displayName;var da=cn.forwardRef(({className:e,...t},s)=>(0,dn.jsx)(ua.Trigger,{ref:s,className:Y("af-inline-flex af-items-center af-justify-center af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-ring-offset-background af-transition-all focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2 disabled:af-pointer-events-none disabled:af-opacity-50 data-[state=active]:af-bg-background data-[state=active]:af-text-foreground data-[state=active]:af-shadow",e),...t}));da.displayName=ua.Trigger.displayName;var fa=cn.forwardRef(({className:e,...t},s)=>(0,dn.jsx)(ua.Content,{ref:s,className:Y("af-mt-2 af-ring-offset-background focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring focus-visible:af-ring-offset-2",e),...t}));fa.displayName=ua.Content.displayName;var Tr=de(require("react"),1),kr=require("@radix-ui/react-slot"),Er=require("class-variance-authority");var Ir=require("react/jsx-runtime"),lo=(0,Er.cva)("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"}}),_=Tr.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,...n},i)=>(0,Ir.jsx)(a?kr.Slot:"button",{className:Y(lo({variant:t,size:s,className:e})),ref:i,...n}));_.displayName="Button";var _s=require("lucide-react");var Ba=de(require("react"),1);var wa=require("react/jsx-runtime"),Fe=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,wa.jsx)("table",{ref:s,className:Y("af-w-full af-caption-bottom af-text-sm",e),...t})}));Fe.displayName="Table";var Me=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("thead",{ref:s,className:Y("[&_tr]:af-border-b",e),...t}));Me.displayName="TableHeader";var Ue=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("tbody",{ref:s,className:Y("[&_tr:last-child]:af-border-0",e),...t}));Ue.displayName="TableBody";var co=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("tfoot",{ref:s,className:Y("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));co.displayName="TableFooter";var he=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("tr",{ref:s,className:Y("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));he.displayName="TableRow";var $=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("th",{ref:s,className:Y("af-h-10 af-px-2 af-text-left af-align-middle af-font-medium af-text-muted-foreground [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));$.displayName="TableHead";var V=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("td",{ref:s,className:Y("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));V.displayName="TableCell";var uo=Ba.forwardRef(({className:e,...t},s)=>(0,wa.jsx)("caption",{ref:s,className:Y("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));uo.displayName="TableCaption";var ma=de(require("react"),1);function Za(){let{api:e}=oe(),[t,s]=ma.useState([]),[a,n]=ma.useState(!0),[i,o]=ma.useState(null),v=ma.useCallback(async()=>{try{n(!0),o(null);let h=await e.getForms();s(h)}catch(h){o(h instanceof Error?h:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);ma.useEffect(()=>{v()},[v]);let g=ma.useCallback(async h=>{let N=await e.createForm(h);return s(b=>[...b,N]),N},[e]),y=ma.useCallback(async(h,N)=>{let b=await e.updateForm(h,N);return s(u=>u.map(l=>l.id===h?b:l)),b},[e]),r=ma.useCallback(async h=>{await e.deleteForm(h),s(N=>N.filter(b=>b.id!==h))},[e]);return{forms:t,isLoading:a,error:i,refetch:v,createForm:g,updateForm:y,deleteForm:r}}var $e=require("react/jsx-runtime");function Rs({onSelectForm:e,className:t}){let{forms:s,isLoading:a,error:n}=Za();return a?(0,$e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,$e.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,$e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,$e.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,$e.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,$e.jsx)(_s.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,$e.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,$e.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,$e.jsx)("div",{className:t,children:(0,$e.jsxs)(Fe,{children:[(0,$e.jsx)(Me,{children:(0,$e.jsxs)(he,{children:[(0,$e.jsx)($,{children:"Name"}),(0,$e.jsx)($,{children:"Endpoint"}),(0,$e.jsx)($,{className:"af-text-right",children:"Actions"})]})}),(0,$e.jsx)(Ue,{children:s.map(i=>(0,$e.jsxs)(he,{children:[(0,$e.jsx)(V,{className:"af-font-medium",children:i.name}),(0,$e.jsx)(V,{children:(0,$e.jsx)("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","")})}),(0,$e.jsx)(V,{className:"af-text-right",children:(0,$e.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,$e.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,$e.jsx)(_s.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,$e.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,$e.jsx)(_s.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var Lr=require("lucide-react");var Ar=require("class-variance-authority");var Dr=require("react/jsx-runtime"),fo=(0,Ar.cva)("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 Q({className:e,variant:t,...s}){return(0,Dr.jsx)("div",{className:Y(fo({variant:t}),e),...s})}var zt=require("react/jsx-runtime"),mo={form_notification:"Form notification",purchase_receipt:"Buyer receipt",merchant_sale:"Sale notification",subscription_payment_failed:"Payment reminder",subscription_cancellation:"Cancellation confirmation",subscription_address_change:"Address change confirmation",merchant_subscription_canceled:"Subscription cancellation notice",account_login:"Sign-in email",oversell_refund:"Refund notification",merchant_oversell:"Stock issue notification",dispute_opened:"Dispute notification"};function fn(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 Un(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function po(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 Ps({deliveries:e,label:t="Email needs attention"}){return Un(e)?(0,zt.jsxs)("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:[(0,zt.jsx)(Lr.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Na({deliveries:e,problemsOnly:t=!1,className:s=""}){let a=(e??[]).filter(n=>!t||Un([n]));return a.length?(0,zt.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:a.map(n=>{let i=fn(n),o=po(n);return(0,zt.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,zt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,zt.jsx)("span",{className:"af-font-medium",children:mo[n.kind]??"Email notification"}),(0,zt.jsx)(Q,{variant:i.variant,children:i.label})]}),(0,zt.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",n.recipients.join(", ")]}),n.recipients.length>1&&Un([n])&&(0,zt.jsx)("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&&(0,zt.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,zt.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var ks=de(require("react"),1),Sa=require("lucide-react");var qa=de(require("react"),1),Te=de(require("@radix-ui/react-select"),1),Qa=require("lucide-react");var ot=require("react/jsx-runtime"),aa=Te.Root;var sa=Te.Value,qt=qa.forwardRef(({className:e,children:t,...s},a)=>(0,ot.jsxs)(Te.Trigger,{ref:a,className:Y("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:[t,(0,ot.jsx)(Te.Icon,{asChild:!0,children:(0,ot.jsx)(Qa.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));qt.displayName=Te.Trigger.displayName;var Or=qa.forwardRef(({className:e,...t},s)=>(0,ot.jsx)(Te.ScrollUpButton,{ref:s,className:Y("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,ot.jsx)(Qa.ChevronUp,{className:"af-h-4 af-w-4"})}));Or.displayName=Te.ScrollUpButton.displayName;var Br=qa.forwardRef(({className:e,...t},s)=>(0,ot.jsx)(Te.ScrollDownButton,{ref:s,className:Y("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,ot.jsx)(Qa.ChevronDown,{className:"af-h-4 af-w-4"})}));Br.displayName=Te.ScrollDownButton.displayName;var jt=qa.forwardRef(({className:e,children:t,position:s="popper",...a},n)=>(0,ot.jsx)(Te.Portal,{children:(0,ot.jsxs)(Te.Content,{ref:n,className:Y("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,...a,children:[(0,ot.jsx)(Or,{}),(0,ot.jsx)(Te.Viewport,{className:Y("af-p-1",s==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,ot.jsx)(Br,{})]})}));jt.displayName=Te.Content.displayName;var go=qa.forwardRef(({className:e,...t},s)=>(0,ot.jsx)(Te.Label,{ref:s,className:Y("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));go.displayName=Te.Label.displayName;var je=qa.forwardRef(({className:e,children:t,...s},a)=>(0,ot.jsxs)(Te.Item,{ref:a,className:Y("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:[(0,ot.jsx)("span",{className:"af-absolute af-right-2 af-flex af-h-3.5 af-w-3.5 af-items-center af-justify-center",children:(0,ot.jsx)(Te.ItemIndicator,{children:(0,ot.jsx)(Qa.Check,{className:"af-h-4 af-w-4"})})}),(0,ot.jsx)(Te.ItemText,{children:t})]}));je.displayName=Te.Item.displayName;var vo=qa.forwardRef(({className:e,...t},s)=>(0,ot.jsx)(Te.Separator,{ref:s,className:Y("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));vo.displayName=Te.Separator.displayName;var na=de(require("react"),1);function Cs({formId:e,initialPageSize:t=25}){let{api:s}=oe(),[a,n]=na.useState([]),[i,o]=na.useState(0),[v,g]=na.useState(!0),[y,r]=na.useState(null),[h,N]=na.useState(0),[b,u]=na.useState(t),l=na.useCallback(async()=>{if(e)try{g(!0),r(null);let R={limit:b,offset:h*b},D=await s.getSubmissions(e,R);n(D.submissions),o(D.total)}catch(R){r(R instanceof Error?R:new Error("Failed to fetch submissions"))}finally{g(!1)}},[s,e,h,b]);na.useEffect(()=>{l()},[l]);let x=na.useCallback(async R=>{await s.deleteSubmission(R),n(D=>D.filter(F=>F.id!==R)),o(D=>D-1)},[s]),S=Math.ceil(i/b);return{submissions:a,total:i,isLoading:v,error:y,page:h,pageSize:b,hasNextPage:h<S-1,hasPreviousPage:h>0,setPage:N,setPageSize:R=>{u(R),N(0)},refetch:l,deleteSubmission:x}}var Mr=de(require("react"),1),Ct=require("lucide-react");var xe=require("react/jsx-runtime");function Fr(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function bo(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function Ts({submission:e,onBack:t}){let{api:s}=oe(),[a,n]=Mr.useState(null),i=g=>g.id??g.name,o=async g=>{n(i(g));try{await s.downloadAttachment(e.id,g)}catch(y){console.error("Download failed:",y)}finally{n(null)}},v=Object.entries(e.data).filter(([g])=>!g.startsWith("_"));return(0,xe.jsxs)("div",{children:[(0,xe.jsxs)("div",{className:"af-mb-6",children:[(0,xe.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,xe.jsx)(Ct.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,xe.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,xe.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Fr(e.metadata.submitted_at)]})]}),(0,xe.jsxs)("div",{className:"af-space-y-6",children:[(0,xe.jsx)(Na,{deliveries:e.email_deliveries}),(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,xe.jsxs)("div",{className:"af-space-y-3",children:[v.map(([g,y])=>(0,xe.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,xe.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:g.replace(/_/g," ")}),(0,xe.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof y=="string"&&y.includes(`
|
|
3
|
+
`)?(0,xe.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:y}):String(y)})]},g)),v.length===0&&(0,xe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,xe.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((g,y)=>(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,xe.jsx)(Ct.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,xe.jsx)("span",{className:"af-text-sm",children:g.name}),(0,xe.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",bo(g.size),")"]})]}),(0,xe.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>o(g),disabled:a===i(g),children:[a===i(g)?(0,xe.jsx)(Ct.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,xe.jsx)(Ct.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===i(g)?"Downloading...":"Download"]})]},y))})]}),(0,xe.jsxs)("div",{children:[(0,xe.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,xe.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Ct.Clock,{className:"af-h-4 af-w-4"}),(0,xe.jsx)("span",{children:Fr(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Ct.Globe,{className:"af-h-4 af-w-4"}),(0,xe.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,xe.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Ct.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,xe.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,xe.jsx)(Ct.Mail,{className:"af-h-4 af-w-4"}),(0,xe.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var pe=require("react/jsx-runtime");function yo(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ho(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}function xo(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")&&!n.toLowerCase().includes("email"));if(t.length===0)return"";let[,s]=t[0],a=String(s);return a.length>50?a.slice(0,50)+"...":a}function Es({formId:e,className:t,defaultSubmissionId:s}){let{submissions:a,total:n,isLoading:i,error:o,page:v,pageSize:g,hasNextPage:y,hasPreviousPage:r,setPage:h,setPageSize:N}=Cs({formId:e}),[b,u]=ks.useState("list"),[l,x]=ks.useState(null);ks.useEffect(()=>{if(s&&a.length>0){let c=a.find(w=>w.id===s);c&&(x(c),u("detail"))}},[s,a]);let S=c=>{x(c),u("detail")},R=()=>{u("list"),x(null)};if(b==="detail"&&l)return(0,pe.jsx)("div",{className:t,children:(0,pe.jsx)(Ts,{submission:l,onBack:R})});if(i)return(0,pe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,pe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(o)return(0,pe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,pe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})});if(a.length===0&&v===0)return(0,pe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,pe.jsx)(Sa.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,pe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,pe.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let D=v*g+1,F=Math.min((v+1)*g,n);return(0,pe.jsxs)("div",{className:t,children:[(0,pe.jsxs)(Fe,{children:[(0,pe.jsx)(Me,{children:(0,pe.jsxs)(he,{children:[(0,pe.jsx)($,{children:"Email"}),(0,pe.jsx)($,{children:"Preview"}),(0,pe.jsx)($,{children:"Date"}),(0,pe.jsx)($,{className:"af-text-right",children:"Actions"})]})}),(0,pe.jsx)(Ue,{children:a.map(c=>{let w=ho(c.data),E=xo(c.data);return(0,pe.jsxs)(he,{children:[(0,pe.jsxs)(V,{className:"af-font-medium",children:[(0,pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[w||(0,pe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),c.attachments.length>0&&(0,pe.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${c.attachments.length} attachment(s)`,children:[(0,pe.jsx)(Sa.Paperclip,{className:"af-h-3 af-w-3"}),(0,pe.jsx)("span",{className:"af-text-xs",children:c.attachments.length})]})]}),(0,pe.jsx)(Ps,{deliveries:c.email_deliveries,label:"Notification email needs attention"})]}),(0,pe.jsx)(V,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:E||(0,pe.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,pe.jsx)(V,{className:"af-text-muted-foreground",children:yo(c.metadata.submitted_at)}),(0,pe.jsx)(V,{className:"af-text-right",children:(0,pe.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>S(c),title:"View details",children:(0,pe.jsx)(Sa.Eye,{className:"af-h-4 af-w-4"})})})]},c.id)})})]}),(0,pe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,pe.jsxs)("span",{children:["Showing ",D,"-",F," of ",n]}),(0,pe.jsxs)(aa,{value:String(g),onValueChange:c=>N(Number(c)),children:[(0,pe.jsx)(qt,{className:"af-w-[70px] af-h-8",children:(0,pe.jsx)(sa,{})}),(0,pe.jsxs)(jt,{children:[(0,pe.jsx)(je,{value:"10",children:"10"}),(0,pe.jsx)(je,{value:"25",children:"25"}),(0,pe.jsx)(je,{value:"50",children:"50"}),(0,pe.jsx)(je,{value:"100",children:"100"})]})]}),(0,pe.jsx)("span",{children:"per page"})]}),(0,pe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,pe.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v-1),disabled:!r,children:[(0,pe.jsx)(Sa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,pe.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v+1),disabled:!y,children:["Next",(0,pe.jsx)(Sa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var Wt=de(require("react"),1),ja=require("lucide-react");var Ur=de(require("react"),1);var $r=require("react/jsx-runtime"),we=Ur.forwardRef(({className:e,type:t,...s},a)=>(0,$r.jsx)("input",{type:t,className:Y("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:a,...s}));we.displayName="Input";var Vr=de(require("react"),1),Hr=require("class-variance-authority");var zr=require("react/jsx-runtime"),wo=(0,Hr.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Re=Vr.forwardRef(({className:e,...t},s)=>(0,zr.jsx)("label",{ref:s,className:Y(wo(),e),...t}));Re.displayName="Label";var ra=de(require("react"),1),Tt=require("lucide-react");var Is=de(require("react"),1),bt=de(require("@radix-ui/react-dialog"),1),qr=require("lucide-react");var Ft=require("react/jsx-runtime"),_a=bt.Root;var No=bt.Portal;var jr=Is.forwardRef(({className:e,...t},s)=>(0,Ft.jsx)(bt.Overlay,{ref:s,className:Y("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));jr.displayName=bt.Overlay.displayName;var pa=Is.forwardRef(({className:e,children:t,...s},a)=>(0,Ft.jsx)(No,{children:(0,Ft.jsxs)("div",{className:"aifeatures-admin",children:[(0,Ft.jsx)(jr,{}),(0,Ft.jsxs)(bt.Content,{ref:a,className:Y("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:[t,(0,Ft.jsxs)(bt.Close,{className:"af-absolute af-right-4 af-top-4 af-rounded-sm af-opacity-70 af-ring-offset-background af-transition-opacity hover:af-opacity-100 focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2 disabled:af-pointer-events-none data-[state=open]:af-bg-accent data-[state=open]:af-text-muted-foreground",children:[(0,Ft.jsx)(qr.X,{className:"af-h-4 af-w-4"}),(0,Ft.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));pa.displayName=bt.Content.displayName;var ga=({className:e,...t})=>(0,Ft.jsx)("div",{className:Y("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});ga.displayName="DialogHeader";var va=({className:e,...t})=>(0,Ft.jsx)("div",{className:Y("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});va.displayName="DialogFooter";var ba=Is.forwardRef(({className:e,...t},s)=>(0,Ft.jsx)(bt.Title,{ref:s,className:Y("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));ba.displayName=bt.Title.displayName;var ya=Is.forwardRef(({className:e,...t},s)=>(0,Ft.jsx)(bt.Description,{ref:s,className:Y("af-text-sm af-text-muted-foreground",e),...t}));ya.displayName=bt.Description.displayName;var Gt=de(require("react"),1);function As(){let{api:e}=oe(),[t,s]=Gt.useState([]),[a,n]=Gt.useState(!0),[i,o]=Gt.useState(null),v=Gt.useCallback(async()=>{try{n(!0),o(null),s(await e.getEventDestinations())}catch(b){o(b instanceof Error?b:new Error("Failed to fetch webhooks"))}finally{n(!1)}},[e]);Gt.useEffect(()=>{v()},[v]);let g=Gt.useCallback(async b=>{let u=await e.createEventDestination(b);return s(l=>[u,...l]),u},[e]),y=Gt.useCallback(async(b,u)=>{let l=await e.updateEventDestination(b,u);return s(x=>x.map(S=>S.id===b?l:S)),l},[e]),r=Gt.useCallback(async b=>{await e.deleteEventDestination(b),s(u=>u.filter(l=>l.id!==b))},[e]),h=Gt.useCallback(async b=>{let u=await e.rotateEventDestinationSecret(b);return s(l=>l.map(x=>x.id===b?u:x)),u},[e]),N=Gt.useCallback(b=>e.getEventDestinationSecret(b),[e]);return{destinations:t,isLoading:a,error:i,refetch:v,createDestination:g,updateDestination:y,deleteDestination:r,rotateSecret:h,getSecret:N}}var Fa=de(require("react"),1),Ds=require("lucide-react");var yt=require("react/jsx-runtime");function Ls({destinationId:e,limit:t=25,className:s}){let{api:a}=oe(),[n,i]=Fa.useState([]),[o,v]=Fa.useState(!0),[g,y]=Fa.useState(null),[r,h]=Fa.useState(null),N=Fa.useCallback(async()=>{try{v(!0),y(null),i(await a.getEventDeliveries(e,t))}catch(u){y(u instanceof Error?u.message:"Failed to load deliveries")}finally{v(!1)}},[a,e,t]);Fa.useEffect(()=>{N()},[N]);let b=async u=>{try{h(u.id),y(null);let l=await a.retryEventDelivery(e,u.id);i(x=>x.map(S=>S.id===u.id?l:S))}catch(l){y(l instanceof Error?l.message:"Retry failed")}finally{h(null)}};return o?(0,yt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,yt.jsx)(Ds.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):g?(0,yt.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:g}):n.length===0?(0,yt.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-py-2",children:"Nothing sent yet. Deliveries appear here as submissions come in."}):(0,yt.jsx)("div",{className:s,children:(0,yt.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(u=>{let l=u.delivered_at!==null;return(0,yt.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,yt.jsxs)("div",{className:"af-min-w-0",children:[(0,yt.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[l?(0,yt.jsx)(Q,{variant:"secondary",children:u.last_status??200}):(0,yt.jsx)(Q,{variant:"destructive",children:u.last_status??"failed"}),(0,yt.jsx)("span",{className:"af-text-sm af-truncate",children:u.type})]}),(0,yt.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[u.event_id," \xB7 ",u.created_at,u.attempts>0&&` \xB7 ${u.attempts} failed ${u.attempts===1?"attempt":"attempts"}`]}),!l&&u.last_error&&(0,yt.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:u.last_error})]}),(0,yt.jsx)(_,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===u.id,onClick:()=>b(u),children:r===u.id?(0,yt.jsx)(Ds.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,yt.jsx)(Ds.RotateCw,{className:"af-h-4 af-w-4"})})]},u.id)})})})}var me=require("react/jsx-runtime");function Os({formId:e,topics:t,description:s,className:a}){let{destinations:n,isLoading:i,error:o,createDestination:v,updateDestination:g,deleteDestination:y,rotateSecret:r,getSecret:h}=As(),[N,b]=ra.useState(""),[u,l]=ra.useState(!1),[x,S]=ra.useState(null),[R,D]=ra.useState(null),[F,c]=ra.useState(null),[w,E]=ra.useState(!1),[W,B]=ra.useState(null),[T,z]=ra.useState(null),[m,H]=ra.useState(null),re=ra.useMemo(()=>n.filter(K=>K.form_id===e),[n,e]),X=async()=>{let K=N.trim();if(K){if(!K.startsWith("https://")){S("Webhook URLs must start with https://");return}try{l(!0),S(null),await v({url:K,form_id:e,...t&&t.length>0?{topics:t}:{}}),b("")}catch(_e){S(_e instanceof Error?_e.message:"Failed to add webhook")}finally{l(!1)}}},ce=async K=>{try{z(K.id),S(null),await r(K.id),E(!1),c(await h(K.id))}catch(_e){S(_e instanceof Error?_e.message:"Failed to rotate secret")}finally{z(null)}},ie=async K=>{try{z(K.id),S(null),await g(K.id,{status:"active"})}catch(_e){S(_e instanceof Error?_e.message:"Failed to re-enable")}finally{z(null)}},Z=async()=>{if(W)try{z(W.id),await y(W.id),B(null)}catch(K){S(K instanceof Error?K.message:"Failed to delete")}finally{z(null)}},ae=async K=>{if(R===K.id){D(null),c(null);return}try{z(K.id),S(null),E(!1),D(K.id),c(await h(K.id))}catch(_e){D(null),S(_e instanceof Error?_e.message:"Failed to read secret")}finally{z(null)}},ge=async()=>{if(F)try{await navigator.clipboard.writeText(F),E(!0)}catch{}};return(0,me.jsxs)("div",{className:a,children:[(0,me.jsxs)("div",{className:"af-space-y-1",children:[(0,me.jsx)(Re,{children:"Webhooks"}),(0,me.jsx)("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."})]}),(0,me.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,me.jsx)(we,{value:N,placeholder:"https://hooks.zapier.com/...",onChange:K=>b(K.target.value),onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),X())},disabled:u}),(0,me.jsxs)(_,{onClick:X,disabled:u||!N.trim(),children:[u?(0,me.jsx)(Tt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,me.jsx)(Tt.Plus,{className:"af-h-4 af-w-4"}),(0,me.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(x||o)&&(0,me.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:x||o?.message}),(0,me.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[i&&(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,me.jsx)(Tt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&re.length===0&&(0,me.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),re.map(K=>(0,me.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,me.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,me.jsxs)("div",{className:"af-min-w-0",children:[(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,me.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:K.url}),K.status==="disabled"?(0,me.jsx)(Q,{variant:"destructive",children:"Disabled"}):(0,me.jsx)(Q,{variant:"secondary",children:"Active"})]}),(0,me.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:K.topics.includes("*")?"All events":K.topics.join(", ")})]}),(0,me.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,me.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>H(m===K.id?null:K.id),children:m===K.id?"Hide log":"Deliveries"}),(0,me.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>ae(K),disabled:T===K.id,children:R===K.id?"Hide secret":"Show secret"}),(0,me.jsx)(_,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:T===K.id,onClick:()=>B(K),children:(0,me.jsx)(Tt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),K.status==="disabled"&&(0,me.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2",children:[(0,me.jsx)(Tt.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,me.jsxs)("div",{className:"af-text-sm",children:[(0,me.jsxs)("p",{children:["We stopped sending after repeated failures."," ",K.disabled_reason]}),(0,me.jsx)(_,{variant:"outline",size:"sm",className:"af-mt-2",disabled:T===K.id,onClick:()=>ie(K),children:"Re-enable"})]})]}),R===K.id&&F&&(0,me.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,me.jsx)("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."}),(0,me.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,me.jsx)(we,{readOnly:!0,value:F,className:"af-font-mono"}),(0,me.jsx)(_,{variant:"outline",title:"Copy signing secret",onClick:ge,children:w?(0,me.jsx)(Tt.Check,{className:"af-h-4 af-w-4"}):(0,me.jsx)(Tt.Copy,{className:"af-h-4 af-w-4"})}),(0,me.jsx)(_,{variant:"outline",title:"Rotate signing secret",disabled:T===K.id,onClick:()=>ce(K),children:T===K.id?(0,me.jsx)(Tt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,me.jsx)(Tt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),m===K.id&&(0,me.jsx)(Ls,{destinationId:K.id})]},K.id))]}),(0,me.jsx)(_a,{open:!!W,onOpenChange:K=>{!K&&!T&&B(null)},children:(0,me.jsxs)(pa,{children:[(0,me.jsxs)(ga,{children:[(0,me.jsx)(ba,{children:"Delete this webhook?"}),(0,me.jsxs)(ya,{children:["New submissions will stop being sent to ",W?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,me.jsxs)(va,{children:[(0,me.jsx)(_,{variant:"outline",onClick:()=>B(null),disabled:!!T,children:"Cancel"}),(0,me.jsx)(_,{variant:"destructive",onClick:Z,disabled:!!T,children:T?"Deleting...":"Delete"})]})]})})]})}var Se=require("react/jsx-runtime");function Bs({form:e,onSaved:t,className:s}){let{updateForm:a}=Za(),[n,i]=Wt.useState(!1),[o,v]=Wt.useState(null),[g,y]=Wt.useState(null),[r,h]=Wt.useState(e.name),[N,b]=Wt.useState(e.redirect_url||""),[u,l]=Wt.useState(e.email_recipients),[x,S]=Wt.useState("");Wt.useEffect(()=>{h(e.name),b(e.redirect_url||""),l(e.email_recipients),y(null)},[e]);let R=Wt.useCallback(async E=>{try{i(!0),y(null);let W=await a(e.id,E);v(new Date),t?.(W)}catch(W){y(W instanceof Error?W.message:"Failed to save")}finally{i(!1)}},[e.id,a,t]);Wt.useEffect(()=>{if(o){let E=setTimeout(()=>v(null),2e3);return()=>clearTimeout(E)}},[o]);let D=async()=>{let E=x.trim().toLowerCase();if(!E)return;if(!E.includes("@")){y("Please enter a valid email address");return}if(u.includes(E)){y("This email is already added");return}let W=[...u,E];l(W),S(""),y(null),await R({email_recipients:W})},F=async E=>{let W=u.filter(B=>B!==E);l(W),await R({email_recipients:W})},c=async()=>{r!==e.name&&await R({name:r})},w=async()=>{let E=N||null;E!==e.redirect_url&&await R({redirect_url:E})};return(0,Se.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,Se.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,Se.jsxs)("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:[(0,Se.jsx)(ja.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Se.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Se.jsxs)("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:[(0,Se.jsx)(ja.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Se.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(Re,{htmlFor:"form-name",children:"Form Name"}),(0,Se.jsx)(we,{id:"form-name",value:r,onChange:E=>h(E.target.value),onBlur:c,placeholder:"Contact Form"}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(Re,{children:"Email Recipients"}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Se.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[u.map(E=>(0,Se.jsxs)(Q,{variant:"secondary",className:"af-gap-1",children:[E,(0,Se.jsx)("button",{type:"button",onClick:()=>F(E),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,Se.jsx)(ja.X,{className:"af-h-3 af-w-3"})})]},E)),u.length===0&&(0,Se.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Se.jsx)(we,{type:"email",value:x,onChange:E=>S(E.target.value),placeholder:"Add email address",onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),D())},disabled:n}),(0,Se.jsx)(_,{type:"button",variant:"outline",onClick:D,disabled:!x.trim()||n,children:(0,Se.jsx)(ja.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(Re,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Se.jsx)(we,{id:"redirect-url",value:N,onChange:E=>b(E.target.value),onBlur:w,placeholder:"/thank-you"}),(0,Se.jsx)("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."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(Re,{children:"Form Endpoint"}),(0,Se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Se.jsx)("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})}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Se.jsxs)("div",{className:"af-space-y-2",children:[(0,Se.jsx)(Re,{children:"Captcha Protection"}),(0,Se.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Se.jsx)(Q,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Se.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Se.jsx)(Os,{formId:e.id}),g&&(0,Se.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g})]})}var Ve=require("react/jsx-runtime");function $n({className:e,submissionId:t}){let{api:s}=oe(),[a,n]=Ga.useState("list"),[i,o]=Ga.useState(null),[v,g]=Ga.useState("submissions"),[y,r]=Ga.useState(t),[h,N]=Ga.useState(!!t);Ga.useEffect(()=>{if(!t)return;async function x(){try{let S=await s.getSubmission(t),R=await s.getForm(S.form_id);o(R),n("detail"),g("submissions"),r(t)}catch(S){console.error("Failed to load submission for deep link:",S)}finally{N(!1)}}x()},[t,s]);let b=(x,S)=>{o(x),n("detail"),g(S),r(void 0)},u=()=>{n("list"),o(null),r(void 0)},l=x=>{o(x)};return h?(0,Ve.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,Ve.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Ve.jsxs)("div",{className:e,children:[a==="list"&&(0,Ve.jsxs)("div",{children:[(0,Ve.jsxs)("div",{className:"af-mb-6",children:[(0,Ve.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,Ve.jsx)(Rs,{onSelectForm:b})]}),a==="detail"&&i&&(0,Ve.jsxs)("div",{children:[(0,Ve.jsxs)("div",{className:"af-mb-6",children:[(0,Ve.jsxs)(_,{variant:"ghost",size:"sm",onClick:u,className:"af-mb-2 af--ml-2",children:[(0,Ve.jsx)(ms.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),(0,Ve.jsx)("h2",{className:"af-text-lg af-font-semibold",children:i.name}),(0,Ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:(0,Ve.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:i.endpoint_url})})]}),(0,Ve.jsxs)(un,{value:v,onValueChange:x=>g(x),children:[(0,Ve.jsxs)(Ss,{className:"af-mb-4",children:[(0,Ve.jsxs)(da,{value:"submissions",className:"af-gap-2",children:[(0,Ve.jsx)(ms.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,Ve.jsxs)(da,{value:"settings",className:"af-gap-2",children:[(0,Ve.jsx)(ms.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,Ve.jsx)(fa,{value:"submissions",children:(0,Ve.jsx)(Es,{formId:i.id,defaultSubmissionId:y})}),(0,Ve.jsx)(fa,{value:"settings",children:(0,Ve.jsx)(Bs,{form:i,onSaved:l})})]})]})]})}var Be=de(require("react"),1);var Ra=de(require("react"),1);function Ma(){let{api:e}=oe(),[t,s]=Ra.useState(null),[a,n]=Ra.useState(!0),[i,o]=Ra.useState(null),v=Ra.useRef(0),g=Ra.useCallback(async()=>{let y=++v.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(y!==v.current)return;s(r)}catch(r){if(y!==v.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{y===v.current&&n(!1)}},[e]);return Ra.useEffect(()=>{g()},[g]),{status:t,isLoading:a,error:i,refetch:g}}var So=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function Kt(e){return So.has(e.toLowerCase())}function j(e,t,s){let a=Kt(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(a)}catch{return`${a} ${t.toUpperCase()}`}}function Pa(e){let t=e.exclusive_tax_total??(e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0);return e.amount_total+(e.shipping_total??0)+t}function Et(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let a=Kt(t)?s:s*100;return Math.round(a)}function lt(e,t){return Kt(t)?e:e/100}function mn(e){return e.amount_paid??Math.max(0,Pa(e)-(e.credit_applied??0))}var te=require("react/jsx-runtime");function Fs(e){return e instanceof kt&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function Gr(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${j(e.amount_off,e.currency)} off`:"Discount unavailable"}function Xa(){let{api:e,siteToken:t}=oe();return(0,te.jsx)(_o,{api:e},t)}function _o({api:e}){let{status:t,error:s}=Ma(),[a,n]=Be.useState([]),[i,o]=Be.useState(null),[v,g]=Be.useState(null),[y,r]=Be.useState(!1),[h,N]=Be.useState(!1),[b,u]=Be.useState(""),[l,x]=Be.useState(null),[S,R]=Be.useState(null),[D,F]=Be.useState(!1),c=Be.useRef(0),w=Be.useCallback(async B=>{let T=++c.current;r(!0),u("");try{let z=await e.getPromos(B);if(T!==c.current)return;n(m=>B?[...m,...z.promos.filter(H=>!m.some(re=>re.id===H.id))]:z.promos),o(z.next_cursor),g(z.checkout_enabled)}catch(z){T===c.current&&u(Fs(z))}finally{T===c.current&&r(!1)}},[e]);Be.useEffect(()=>(w(),()=>{c.current++}),[w]);async function E(B){let T=++c.current;r(!0),u(""),F(!1);try{let z=await e.getPromo(B);T===c.current&&x(z)}catch(z){T===c.current&&u(Fs(z))}finally{T===c.current&&r(!1)}}async function W(){if(l){N(!0),r(!0),u("");try{let B=await e.disablePromo(l.id);if(x(B),!["inactive","expired","exhausted"].includes(B.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");F(!1),await w()}catch(B){u(Fs(B))}finally{N(!1),r(!1)}}}return S?(0,te.jsx)(Ro,{currency:t?.currency??void 0,replaces:S.replaces,onCancel:()=>R(null),onSave:async B=>{let T=S.replaces?await e.replacePromo(S.replaces.id,B):await e.createPromo(B),z=await e.getPromo(T.id);if(z.status==="pending"||z.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");x(z),R(null),await w()}}):(0,te.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,te.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,te.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,te.jsx)(_,{disabled:y||!t?.currency,onClick:()=>{u(""),R({})},children:"Create promo code"})]}),(0,te.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"These codes apply across the connected Stripe account. Buyers enter them at Stripe Checkout. Product-specific restrictions are not available here."}),v===!1&&(0,te.jsx)("p",{role:"status",className:"af-rounded-md af-border af-p-3 af-text-sm",children:"Checkout code entry is not enabled yet. You can prepare codes, but buyers cannot enter them in our checkout until it is enabled."}),!t?.currency&&(0,te.jsx)("p",{className:"af-text-sm",children:s?Fs(s):"Connect Stripe and set the payment currency before creating codes."}),b&&(0,te.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[b," ",(0,te.jsx)(_,{variant:"outline",disabled:y,onClick:()=>l?void E(l.id):void w(),children:"Refresh"})]}),l?(0,te.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,te.jsx)(_,{variant:"ghost",disabled:h,onClick:()=>{x(null),F(!1),w()},children:"Back to codes"}),(0,te.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),(0,te.jsxs)("p",{children:[Gr(l)," \xB7 ",l.status]}),(0,te.jsxs)("p",{className:"af-text-sm",children:[l.times_redeemed==null?"Usage unavailable":`${l.times_redeemed} redemptions`,l.max_redemptions!=null?` / ${l.max_redemptions} maximum`:""]}),(0,te.jsxs)("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${j(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,te.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",l.duration==="repeating"?`${l.duration_in_months} months`:l.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,te.jsx)("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),(0,te.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,te.jsx)(_,{variant:"outline",disabled:y,onClick:()=>void E(l.id),children:"Refresh details"}),(0,te.jsx)(_,{variant:"outline",disabled:y||l.status==="pending"||l.status==="unavailable"||!t?.currency,onClick:()=>R({replaces:l}),children:"Replace with new code"}),(0,te.jsx)(_,{variant:"outline",disabled:y||!["active","pending","unavailable"].includes(l.status),onClick:()=>F(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),D&&(0,te.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,te.jsxs)("p",{className:"af-text-sm",children:[l.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${l.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,te.jsx)(_,{disabled:y,onClick:()=>void W(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,te.jsx)(_,{variant:"ghost",disabled:y,onClick:()=>F(!1),children:"Cancel"})]})]}):(0,te.jsxs)(te.Fragment,{children:[a.map(B=>(0,te.jsxs)("button",{type:"button",disabled:y,onClick:()=>void E(B.id),className:"af-w-full af-rounded-lg af-border af-p-4 af-text-left hover:af-bg-muted focus-visible:af-ring-2 focus-visible:af-ring-ring",children:[(0,te.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,te.jsx)("span",{className:"af-font-semibold af-break-all",children:B.code}),(0,te.jsx)("span",{className:"af-text-sm",children:B.status})]}),(0,te.jsxs)("div",{className:"af-text-sm",children:[Gr(B)," \xB7"," ",B.times_redeemed==null?"Usage unavailable":`${B.times_redeemed} redemptions`]})]},B.id)),!y&&!b&&a.length===0&&(0,te.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No promo codes yet. Create a percentage or fixed-amount offer for your customers."}),y&&(0,te.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),i&&(0,te.jsx)(_,{variant:"outline",disabled:y,onClick:()=>void w(i),children:"Load more"})]})]})}function Ro({currency:e,replaces:t,onCancel:s,onSave:a}){let[n,i]=Be.useState(""),[o,v]=Be.useState(t?.name??""),[g,y]=Be.useState(t?.amount_off!=null?"fixed":"percent"),[r,h]=Be.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(lt(t.amount_off,e)):"")),[N,b]=Be.useState(t?.minimum_amount!=null&&e?String(lt(t.minimum_amount,e)):""),[u,l]=Be.useState(()=>{if(!t?.expires_at)return"";let ie=new Date(t.expires_at);return Number.isFinite(ie.getTime())?new Date(ie.getTime()-ie.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[x,S]=Be.useState(t?.max_redemptions?.toString()??""),[R,D]=Be.useState(t?.duration??"once"),[F,c]=Be.useState(t?.duration_in_months?.toString()??"3"),[w,E]=Be.useState(null),[W,B]=Be.useState(!1),[T,z]=Be.useState(""),m=Be.useRef(!1),H=e&&Kt(e)?"1":"0.01";async function re(ie){if(ie.preventDefault(),m.current)return;z("");let Z=w;if(!Z){if(!e){z("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){z("Choose a different code for the replacement.");return}let ae=Et(r,e),ge=N?Et(N,e):null;if(g==="fixed"&&(!ae||ae>999999999999)||N&&(!ge||ge>999999999999)){z("Enter a positive amount within the supported range.");return}if(u&&new Date(u).getTime()<=Date.now()){z("Choose a future expiry.");return}Z={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:R,...g==="percent"?{percent_off:Number(r)}:{amount_off:ae,currency:e},...N?{minimum_amount:ge,currency:e}:{},...u?{expires_at:new Date(u).toISOString()}:{},...x?{max_redemptions:Number(x)}:{},...R==="repeating"?{duration_in_months:Number(F)}:{}},E(Z)}m.current=!0,B(!0);try{await a(Z)}catch(ae){z(Fs(ae)),ae instanceof kt&&ae.status>=400&&ae.status<500&&ae.details?.retryable!==!0&&E(null)}finally{m.current=!1,B(!1)}}let X=(ie,Z,ae,ge={})=>(0,te.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[ie,(0,te.jsx)(we,{"aria-label":ie,value:Z,onChange:K=>ae(K.target.value),...ge})]}),ce="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,te.jsxs)("form",{onSubmit:re,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,te.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,te.jsx)("p",{className:"af-text-sm",children:"Use a different code. The old code will be disabled only after the replacement is created. Existing subscription discounts continue."}),(0,te.jsxs)("fieldset",{disabled:W||!!w,className:"af-grid af-gap-4",children:[X("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),X("Name",o,v,{required:!0,maxLength:40}),(0,te.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,te.jsxs)("select",{"aria-label":"Discount type",className:ce,value:g,onChange:ie=>y(ie.target.value),children:[(0,te.jsx)("option",{value:"percent",children:"Percentage"}),(0,te.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),X("Discount",r,h,{type:"number",required:!0,min:g==="percent"?"0.01":H,max:g==="percent"?"100":void 0,step:g==="percent"?"0.01":H}),X("Minimum order amount",N,b,{type:"number",min:H,step:H,placeholder:e?.toUpperCase()}),(0,te.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Amounts are in ",e?.toUpperCase(),". For subscriptions, the minimum applies to the initial payment only."]}),X("Expires at (local time)",u,l,{type:"datetime-local",step:1}),X("Maximum redemptions",x,S,{type:"number",min:1,max:1e6,step:1}),(0,te.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,te.jsxs)("select",{"aria-label":"Subscription duration",className:ce,value:R,onChange:ie=>D(ie.target.value),children:[(0,te.jsx)("option",{value:"once",children:"First invoice only"}),(0,te.jsx)("option",{value:"forever",children:"Every invoice"}),(0,te.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),R==="repeating"&&X("Months",F,c,{type:"number",required:!0,min:1,max:36,step:1})]}),T&&(0,te.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:T}),w&&!W&&(0,te.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,te.jsx)("span",{className:"af-break-all",children:w.request_id})]}),(0,te.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,te.jsx)(_,{type:"submit",disabled:W,children:W?"Saving\u2026":w?"Retry same request":t?"Create replacement":"Create code"}),(0,te.jsx)(_,{type:"button",variant:"ghost",disabled:W||!!w,onClick:s,children:"Cancel"})]})]})}var bs=de(require("react"),1),ca=require("lucide-react");var pn=de(require("react"),1),Ua=require("lucide-react");var be=require("react/jsx-runtime");function Po(e){if(e.allow_custom_amount){let t=e.min_amount!==null?j(e.min_amount,e.currency):"?",s=e.max_amount!==null?j(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":j(e.unit_amount,e.currency)}function Co(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Ms({productsState:e,onSelectProduct:t,onCreateProduct:s,className:a}){let{products:n,isLoading:i,error:o,deleteProduct:v}=e,[g,y]=pn.useState(null),[r,h]=pn.useState(!1),[N,b]=pn.useState(null),u=async()=>{if(g)try{h(!0),b(null),await v(g.id),y(null)}catch(l){b(l instanceof Error?l.message:"Failed to delete product")}finally{h(!1)}};return i?(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,be.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,be.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,be.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):n.length===0?(0,be.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${a||""}`,children:[(0,be.jsx)(Ua.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,be.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,be.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,be.jsxs)(_,{variant:"outline",onClick:()=>s?.(),children:[(0,be.jsx)(Ua.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,be.jsxs)("div",{className:a,children:[(0,be.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,be.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>s?.(),children:[(0,be.jsx)(Ua.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,be.jsxs)(Fe,{children:[(0,be.jsx)(Me,{children:(0,be.jsxs)(he,{children:[(0,be.jsx)($,{children:"Name"}),(0,be.jsx)($,{children:"Price"}),(0,be.jsx)($,{children:"Fulfillment"}),(0,be.jsx)($,{children:"Status"}),(0,be.jsx)($,{className:"af-text-right",children:"Actions"})]})}),(0,be.jsx)(Ue,{children:n.map(l=>(0,be.jsxs)(he,{children:[(0,be.jsx)(V,{className:"af-font-medium",children:l.name}),(0,be.jsx)(V,{children:Po(l)}),(0,be.jsx)(V,{className:"af-text-muted-foreground",children:Co(l)}),(0,be.jsx)(V,{children:(0,be.jsx)(Q,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),(0,be.jsx)(V,{className:"af-text-right",children:(0,be.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>t?.(l),children:[(0,be.jsx)(Ua.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>{b(null),y(l)},children:[(0,be.jsx)(Ua.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),(0,be.jsx)(_a,{open:!!g,onOpenChange:l=>{!l&&!r&&y(null)},children:(0,be.jsxs)(pa,{children:[(0,be.jsxs)(ga,{children:[(0,be.jsx)(ba,{children:"Delete product?"}),(0,be.jsxs)(ya,{children:['"',g?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),N&&(0,be.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:N}),(0,be.jsxs)(va,{children:[(0,be.jsx)(_,{variant:"outline",onClick:()=>y(null),disabled:r,children:"Cancel"}),(0,be.jsx)(_,{variant:"destructive",onClick:u,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var Je=de(require("react"),1),Jt=require("lucide-react");var mt=de(require("react"),1),ia=require("lucide-react");var k=require("react/jsx-runtime");function Vn(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Us({productId:e,currency:t,className:s}){let{api:a}=oe(),n=Kt(t)?"1":"0.01",[i,o]=mt.useState(null),[v,g]=mt.useState(!0),[y,r]=mt.useState(null),[h,N]=mt.useState(null),[b,u]=mt.useState(!1),l=mt.useRef(!0);mt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let x=mt.useCallback(async()=>{try{let P=await a.getProduct(e);if(!l.current)return;o(P)}catch(P){if(!l.current)return;r(P instanceof Error?P.message:"Failed to load product")}finally{l.current&&g(!1)}},[a,e]);mt.useEffect(()=>{x()},[x]);let S=async P=>{N(null),u(!0);try{await P(),await x()}catch(L){l.current&&N(L instanceof Error?L.message:"Something went wrong")}finally{l.current&&u(!1)}},[R,D]=mt.useState(""),[F,c]=mt.useState(""),[w,E]=mt.useState({}),W=()=>S(async()=>{let P=R.trim(),L=F.split(",").map(fe=>fe.trim()).filter(Boolean);if(!P)throw new Error("Option name is required");if(L.length===0)throw new Error("Add at least one value");await a.createOption(e,{title:P,values:L}),l.current&&(D(""),c(""))}),B=P=>S(async()=>{let L=(w[P.id]??"").trim();if(!L)throw new Error("Enter a value");await a.updateOption(P.id,{add_values:[L]}),l.current&&E(fe=>({...fe,[P.id]:""}))}),T=(P,L)=>S(()=>a.updateOption(P.id,{remove_values:[L]})),z=P=>S(()=>a.deleteOption(P.id)),[m,H]=mt.useState(null),[re,X]=mt.useState(null),[ce,ie]=mt.useState(!1),[Z,ae]=mt.useState(null),ge=i?.options??[],K=i?.variants??[],_e=()=>{X(null),H({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(ge.map(P=>[P.id,P.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},it=P=>{X(null);let L=P.inventory?.on_hand??0,fe=L<0?"":String(L);H({variant:P,title:P.title??"",sku:P.sku??"",unitAmount:P.unit_amount!=null?String(lt(P.unit_amount,t)):"",compareAt:P.compare_at_amount!=null?String(lt(P.compare_at_amount,t)):"",active:P.active,optionValues:{},tracked:P.inventory?.tracked??!1,onHand:fe,initialOnHand:fe,allowBackorder:P.inventory?.allow_backorder??!1})},dt=async()=>{if(!m)return;X(null);let P=m.variant?.allow_custom_amount??!1,L=null,fe=null;if(!P){if(L=Et(m.unitAmount,t),L===null||L<=0){X("Enter a valid price");return}if(m.compareAt.trim()&&(fe=Et(m.compareAt,t),fe===null||fe<=L)){X("Compare-at price must be greater than the price");return}}let ze=m.onHand.trim()!==m.initialOnHand.trim(),Ce=parseInt(m.onHand,10);if(m.tracked&&ze&&(!Number.isFinite(Ce)||Ce<0)){X("On-hand quantity must be zero or more");return}try{if(ie(!0),m.variant)await a.updateVariant(m.variant.id,{title:m.title.trim()||null,sku:m.sku.trim()||null,...P?{}:{unit_amount:L,compare_at_amount:fe},active:m.active}),await a.setVariantInventory(m.variant.id,{tracked:m.tracked,on_hand:m.tracked&&ze?Ce:void 0,allow_backorder:m.allowBackorder});else{let qe={};for(let tt of ge){let ft=m.optionValues[tt.id];if(!ft){X(`Choose a ${tt.title}`),ie(!1);return}qe[tt.title]=ft}await a.createVariant(e,{title:m.title.trim()||null,sku:m.sku.trim()||null,unit_amount:L,compare_at_amount:fe,active:m.active,option_values:ge.length>0?qe:void 0,inventory:m.tracked?{tracked:!0,on_hand:Ce,allow_backorder:m.allowBackorder}:{tracked:!1,allow_backorder:m.allowBackorder}})}await x(),l.current&&H(null)}catch(qe){if(l.current&&X(qe instanceof Error?qe.message:"Failed to save variant"),m.variant)try{let tt=await a.getProduct(e);l.current&&o(tt)}catch{}}finally{l.current&&ie(!1)}},Ie=()=>S(async()=>{Z&&(await a.deleteVariant(Z.id),l.current&&ae(null))}),Pe=m?.variant?.allow_custom_amount??!1,vt=m?.variant!=null&&m.variant.option_values.length===0&&ge.length>0&&!m.variant.active,A=m?.variant?.inventory!=null&&m.variant.inventory.on_hand<0?-m.variant.inventory.on_hand:null;function se(P){let L=P.inventory;if(!L||!L.tracked)return(0,k.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let fe=L.available??L.on_hand;return fe<0?(0,k.jsxs)("span",{children:[-fe," backordered"]}):(0,k.jsxs)("span",{children:[fe," in stock",L.allow_backorder&&(0,k.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return v?(0,k.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,k.jsx)(ia.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):y?(0,k.jsx)("div",{className:s,children:(0,k.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y})}):(0,k.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,k.jsxs)("div",{className:"af-space-y-3",children:[(0,k.jsxs)("div",{children:[(0,k.jsx)(Re,{children:"Options"}),(0,k.jsx)("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."})]}),ge.length>0&&(0,k.jsx)("div",{className:"af-space-y-3",children:ge.map(P=>(0,k.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,k.jsx)("span",{className:"af-text-sm af-font-medium",children:P.title}),(0,k.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>z(P),disabled:b,children:(0,k.jsx)(ia.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,k.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:P.values.map(L=>(0,k.jsxs)(Q,{variant:"secondary",className:"af-gap-1",children:[L.value,(0,k.jsx)("button",{type:"button",onClick:()=>T(P,L.value),className:"af-ml-1 hover:af-text-destructive",disabled:b,title:"Remove value",children:(0,k.jsx)(ia.X,{className:"af-h-3 af-w-3"})})]},L.id))}),(0,k.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,k.jsx)(we,{value:w[P.id]??"",onChange:L=>E(fe=>({...fe,[P.id]:L.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),B(P))},disabled:b}),(0,k.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>B(P),disabled:b||!(w[P.id]??"").trim(),children:(0,k.jsx)(ia.Plus,{className:"af-h-4 af-w-4"})})]})]},P.id))}),(0,k.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(Re,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,k.jsx)(we,{id:"new-option-title",value:R,onChange:P=>D(P.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:b})]}),(0,k.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,k.jsx)(Re,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,k.jsx)(we,{id:"new-option-values",value:F,onChange:P=>c(P.target.value),placeholder:"S, M, L",disabled:b})]}),(0,k.jsxs)(_,{type:"button",variant:"outline",onClick:W,disabled:b||!R.trim()||!F.trim(),children:[(0,k.jsx)(ia.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,k.jsxs)("div",{className:"af-space-y-3",children:[(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,k.jsx)(Re,{children:"Variants"}),(0,k.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:_e,disabled:b||ge.length===0,children:[(0,k.jsx)(ia.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),ge.length===0&&(0,k.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),K.length===0?(0,k.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,k.jsxs)(Fe,{children:[(0,k.jsx)(Me,{children:(0,k.jsxs)(he,{children:[(0,k.jsx)($,{children:"Variant"}),(0,k.jsx)($,{children:"SKU"}),(0,k.jsx)($,{children:"Price"}),(0,k.jsx)($,{children:"Stock"}),(0,k.jsx)($,{children:"Status"}),(0,k.jsx)($,{className:"af-text-right",children:"Actions"})]})}),(0,k.jsx)(Ue,{children:K.map(P=>(0,k.jsxs)(he,{children:[(0,k.jsx)(V,{className:"af-font-medium",children:Vn(P)}),(0,k.jsx)(V,{className:"af-text-muted-foreground",children:P.sku||"-"}),(0,k.jsx)(V,{children:P.unit_amount!=null?(0,k.jsxs)("span",{children:[P.compare_at_amount!=null&&(0,k.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:j(P.compare_at_amount,P.currency)}),j(P.unit_amount,P.currency)]}):P.allow_custom_amount?(0,k.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,k.jsx)(V,{children:se(P)}),(0,k.jsx)(V,{children:(0,k.jsx)(Q,{variant:P.active?"success":"secondary",children:P.active?"Active":"Inactive"})}),(0,k.jsx)(V,{className:"af-text-right",children:(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,k.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>it(P),disabled:b,children:"Edit"}),(0,k.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>ae(P),disabled:b,title:"Delete variant",children:(0,k.jsx)(ia.Trash2,{className:"af-h-4 af-w-4"})})]})})]},P.id))})]})]}),h&&(0,k.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:h}),(0,k.jsx)(_a,{open:m!==null,onOpenChange:P=>{!P&&!ce&&H(null)},children:(0,k.jsxs)(pa,{children:[(0,k.jsxs)(ga,{children:[(0,k.jsx)(ba,{children:m?.variant?"Edit variant":"Add variant"}),(0,k.jsx)(ya,{children:"Price, markdown, and stock live on the variant."})]}),m&&(0,k.jsxs)("div",{className:"af-space-y-3",children:[m.variant?m.variant.option_values.length>0&&(0,k.jsxs)("div",{className:"af-text-sm",children:[(0,k.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),Vn(m.variant)]}):ge.map(P=>(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:P.title}),(0,k.jsxs)(aa,{value:m.optionValues[P.id]??"",onValueChange:L=>H(fe=>fe&&{...fe,optionValues:{...fe.optionValues,[P.id]:L}}),children:[(0,k.jsx)(qt,{children:(0,k.jsx)(sa,{placeholder:`Choose ${P.title}`})}),(0,k.jsx)(jt,{children:P.values.map(L=>(0,k.jsx)(je,{value:L.value,children:L.value},L.id))})]})]},P.id)),Pe?(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,k.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,k.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsxs)(Re,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,k.jsx)(we,{id:"variant-price",type:"number",min:"0",step:n,value:m.unitAmount,onChange:P=>H(L=>L&&{...L,unitAmount:P.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(Re,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,k.jsx)(we,{id:"variant-compare",type:"number",min:"0",step:n,value:m.compareAt,onChange:P=>H(L=>L&&{...L,compareAt:P.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(Re,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,k.jsx)(we,{id:"variant-sku",value:m.sku,onChange:P=>H(L=>L&&{...L,sku:P.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,k.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,k.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,k.jsx)("input",{type:"checkbox",checked:m.tracked,onChange:P=>H(L=>L&&{...L,tracked:P.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),m.tracked&&(0,k.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,k.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsx)(Re,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,k.jsx)(we,{id:"variant-onhand",type:"number",min:"0",step:"1",value:m.onHand,onChange:P=>H(L=>L&&{...L,onHand:P.target.value}),placeholder:A!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,k.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,k.jsx)("input",{type:"checkbox",checked:m.allowBackorder,onChange:P=>H(L=>L&&{...L,allowBackorder:P.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),A!=null&&(0,k.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",A," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,k.jsxs)("div",{className:"af-space-y-1",children:[(0,k.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,k.jsx)("input",{type:"checkbox",checked:m.active,onChange:P=>H(L=>L&&{...L,active:P.target.checked}),className:"af-h-4 af-w-4",disabled:vt}),"Active (buyers can purchase this variant)"]}),vt&&(0,k.jsx)("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."})]}),re&&(0,k.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:re})]}),(0,k.jsxs)(va,{children:[(0,k.jsx)(_,{variant:"outline",onClick:()=>H(null),disabled:ce,children:"Cancel"}),(0,k.jsxs)(_,{onClick:dt,disabled:ce,children:[ce?(0,k.jsx)(ia.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,m?.variant?"Save":"Add variant"]})]})]})}),(0,k.jsx)(_a,{open:Z!==null,onOpenChange:P=>{!P&&!b&&ae(null)},children:(0,k.jsxs)(pa,{children:[(0,k.jsxs)(ga,{children:[(0,k.jsx)(ba,{children:"Delete variant?"}),(0,k.jsx)(ya,{children:Z&&`"${Vn(Z)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,k.jsxs)(va,{children:[(0,k.jsx)(_,{variant:"outline",onClick:()=>ae(null),disabled:b,children:"Cancel"}),(0,k.jsx)(_,{variant:"destructive",onClick:Ie,disabled:b,children:"Delete"})]})]})})]})}var G=require("react/jsx-runtime");function To(e){if(e===0)return"0 B";let t=1024,s=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,a)).toFixed(1))} ${s[a]}`}function $s({productsState:e,product:t,currency:s,onSaved:a,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:v,attachProductFileFromUrl:g}=e,y=!!t,r=t?.currency??s,h=Kt(r)?"1":"0.01",N=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[b,u]=Je.useState(!1),[l,x]=Je.useState(null),S=Je.useRef(!0);Je.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]);let[R,D]=Je.useState(t?.name??""),[F,c]=Je.useState(t?.description??""),[w,E]=Je.useState(t?.allow_custom_amount?"custom":"fixed"),[W,B]=Je.useState(t?.unit_amount!=null?String(lt(t.unit_amount,r)):""),[T,z]=Je.useState(t?.min_amount!=null?String(lt(t.min_amount,r)):""),[m,H]=Je.useState(t?.max_amount!=null?String(lt(t.max_amount,r)):""),[re,X]=Je.useState(String(t?.max_quantity??10)),ce=Je.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(lt(t.unit_amount,r)):"",minAmount:t?.min_amount!=null?String(lt(t.min_amount,r)):"",maxAmount:t?.max_amount!=null?String(lt(t.max_amount,r)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ie,Z]=Je.useState(t?.collect_shipping_address??!1),[ae,ge]=Je.useState(t?.active??!0),[K,_e]=Je.useState(t?.images??[]),[it,dt]=Je.useState(""),[Ie,Pe]=Je.useState(t?.fulfillment??null),[vt,A]=Je.useState(!1),[se,P]=Je.useState(""),[L,fe]=Je.useState(null),ze=Je.useRef(null),Ce=b||vt,qe=()=>{let ne=it.trim();if(ne){if(K.includes(ne)){x("This image URL is already added");return}_e(Ae=>[...Ae,ne]),dt(""),x(null)}},tt=ne=>{_e(Ae=>Ae.filter(Ze=>Ze!==ne))},ft=async()=>{if(x(null),!R.trim()){x("Product name is required");return}let ne=null,Ae=null,Ze=null,xa=!y||w!==ce.pricingMode||(w==="fixed"?W!==ce.unitAmount:T!==ce.minAmount||m!==ce.maxAmount),ta=!y||re!==ce.maxQuantity,Oa=N||w==="fixed";if(!(N||!xa))if(w==="fixed"){if(ne=Et(W,r),ne===null||ne<=0){x("Enter a valid price");return}}else{if(Ae=Et(T,r),Ze=Et(m,r),Ae===null||Ze===null){x("Enter valid minimum and maximum amounts");return}if(Ze<Ae){x("Maximum amount must be at least the minimum amount");return}}let at=parseInt(re,10);if(Oa&&ta&&(!Number.isFinite(at)||at<1)){x("Max quantity must be at least 1");return}try{u(!0);let Qe;if(y&&t){let O={name:R.trim(),description:F.trim()||null,images:K,collect_shipping_address:ie,active:ae};!N&&xa&&(O.allow_custom_amount=w==="custom",w==="fixed"?O.unit_amount=ne:(O.min_amount=Ae,O.max_amount=Ze)),Oa&&ta&&(O.max_quantity=at),Qe=await o(t.id,O),ce.pricingMode=Qe.allow_custom_amount?"custom":"fixed",ce.unitAmount=Qe.unit_amount!=null?String(lt(Qe.unit_amount,r)):"",ce.minAmount=Qe.min_amount!=null?String(lt(Qe.min_amount,r)):"",ce.maxAmount=Qe.max_amount!=null?String(lt(Qe.max_amount,r)):"",ce.maxQuantity=String(Qe.max_quantity)}else{let O={name:R.trim(),allow_custom_amount:w==="custom",collect_shipping_address:ie,active:ae};F.trim()&&(O.description=F.trim()),K.length>0&&(O.images=K),w==="fixed"?(O.unit_amount=ne,O.max_quantity=at):(O.min_amount=Ae,O.max_amount=Ze),Qe=await i(O)}if(!S.current)return;Pe(Qe.fulfillment),a?.(Qe)}catch(Qe){if(!S.current)return;x(Qe instanceof Error?Qe.message:"Failed to save product")}finally{S.current&&u(!1)}},Lt=async ne=>{let Ae=ne.target.files?.[0];if(!(!Ae||!t))try{A(!0),fe(null);let Ze=await v(t.id,Ae);if(!S.current)return;Pe(Ze.fulfillment),a?.(Ze)}catch(Ze){if(!S.current)return;fe(Ze instanceof Error?Ze.message:"Failed to upload file")}finally{S.current&&(A(!1),ze.current&&(ze.current.value=""))}},Ot=async()=>{let ne=se.trim();if(!(!ne||!t))try{A(!0),fe(null);let Ae=await g(t.id,ne);if(!S.current)return;Pe(Ae.fulfillment),P(""),a?.(Ae)}catch(Ae){if(!S.current)return;fe(Ae instanceof Error?Ae.message:"Failed to fetch file")}finally{S.current&&A(!1)}};return(0,G.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsx)(Re,{htmlFor:"product-name",children:"Name"}),(0,G.jsx)(we,{id:"product-name",value:R,onChange:ne=>D(ne.target.value),placeholder:"My product"})]}),(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsx)(Re,{htmlFor:"product-description",children:"Description"}),(0,G.jsx)("textarea",{id:"product-description",value:F,onChange:ne=>c(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"})]}),(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsx)(Re,{children:"Pricing"}),N?(0,G.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This product is priced per variant. Set prices in the Options & Variants editor below."}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(aa,{value:w,onValueChange:ne=>E(ne),children:[(0,G.jsx)(qt,{className:"af-w-[260px]",children:(0,G.jsx)(sa,{})}),(0,G.jsxs)(jt,{children:[(0,G.jsx)(je,{value:"fixed",children:"Fixed price"}),(0,G.jsx)(je,{value:"custom",children:"Buyer chooses the amount"})]})]}),w==="fixed"?(0,G.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,G.jsxs)("div",{className:"af-space-y-1",children:[(0,G.jsxs)(Re,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,G.jsx)(we,{id:"product-price",type:"number",min:"0",step:h,value:W,onChange:ne=>B(ne.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,G.jsxs)("div",{className:"af-space-y-1",children:[(0,G.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,G.jsxs)("div",{className:"af-space-y-1",children:[(0,G.jsxs)(Re,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,G.jsx)(we,{id:"product-min-amount",type:"number",min:"0",step:h,value:T,onChange:ne=>z(ne.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,G.jsxs)("div",{className:"af-space-y-1",children:[(0,G.jsxs)(Re,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,G.jsx)(we,{id:"product-max-amount",type:"number",min:"0",step:h,value:m,onChange:ne=>H(ne.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,G.jsx)("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."})]}),(0,G.jsxs)("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."]})]}),(N||w==="fixed")&&(0,G.jsxs)("div",{className:"af-space-y-1",children:[(0,G.jsx)(Re,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,G.jsx)(we,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:re,onChange:ne=>X(ne.target.value),className:"af-w-[140px]"})]})]}),(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsx)(Re,{children:"Images"}),(0,G.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,G.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[K.map(ne=>(0,G.jsxs)(Q,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,G.jsx)("span",{className:"af-truncate",children:ne}),(0,G.jsx)("button",{type:"button",onClick:()=>tt(ne),className:"af-ml-1 hover:af-text-destructive",disabled:b,children:(0,G.jsx)(Jt.X,{className:"af-h-3 af-w-3"})})]},ne)),K.length===0&&(0,G.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,G.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,G.jsx)(we,{type:"url",value:it,onChange:ne=>dt(ne.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),qe())},disabled:b}),(0,G.jsx)(_,{type:"button",variant:"outline",onClick:qe,disabled:!it.trim()||b,children:(0,G.jsx)(Jt.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsx)(Re,{children:"Digital File"}),(0,G.jsx)("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."}),y?(0,G.jsxs)("div",{className:"af-space-y-3",children:[Ie?.type==="download"&&(0,G.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,G.jsx)(Jt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,G.jsx)("span",{className:"af-text-sm",children:Ie.filename}),Ie.size!=null&&(0,G.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",To(Ie.size),")"]})]}),Ie?.type==="redirect"&&Ie.url&&(0,G.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,G.jsx)(Jt.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,G.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ie.url]})]}),(0,G.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,G.jsx)("input",{ref:ze,type:"file",onChange:Lt,className:"af-hidden",disabled:Ce}),(0,G.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>ze.current?.click(),disabled:Ce,children:[vt?(0,G.jsx)(Jt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,G.jsx)(Jt.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ie?.type==="download"?"Replace file":"Upload file"]}),(0,G.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,G.jsx)(we,{type:"url",value:se,onChange:ne=>P(ne.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:vt}),(0,G.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:Ot,disabled:!se.trim()||Ce,children:"Fetch from URL"})]}),L&&(0,G.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:L})]}):(0,G.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsx)(Re,{children:"Settings"}),(0,G.jsxs)("div",{className:"af-space-y-2",children:[(0,G.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,G.jsx)("input",{type:"checkbox",checked:ie,onChange:ne=>Z(ne.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,G.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,G.jsx)("input",{type:"checkbox",checked:ae,onChange:ne=>ge(ne.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),y&&t&&(0,G.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,G.jsx)(Re,{children:"Options & Variants"}),(0,G.jsx)(Us,{productId:t.id,currency:r})]}),l&&(0,G.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),(0,G.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,G.jsxs)(_,{type:"button",onClick:ft,disabled:Ce,children:[b?(0,G.jsx)(Jt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,y?"Save changes":"Create product"]})})]})}var St=de(require("react"),1),Zt=require("lucide-react");var st=de(require("react"),1);var ko=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Vs({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=oe(),[a,n]=st.useState([]),[i,o]=st.useState(0),[v,g]=st.useState(!0),[y,r]=st.useState(null),[h,N]=st.useState(0),[b,u]=st.useState(e),[l,x]=st.useState(void 0),[S,R]=st.useState(""),[D,F]=st.useState(""),[c,w]=st.useState(""),[E,W]=st.useState(!1),[B,T]=st.useState(!1),[z,m]=st.useState(void 0),H=z?z.join(","):"",re=st.useMemo(()=>{if(!H)return;let Z=new Set(H.split(","));return ko.filter(ae=>!Z.has(ae))},[H]),X=st.useRef(0),ce=st.useCallback(async()=>{let Z=++X.current;try{g(!0),r(null);let ae={limit:b,offset:h*b};l?ae.status=l:re?ae.excludeStatus=re:E||(ae.excludeStatus=["pending","expired"]),S.trim()&&(ae.customerEmail=S.trim()),D.trim()&&(ae.from=D.trim()),c.trim()&&(ae.to=c.trim()),B&&(ae.unfulfilledOnly=!0);let ge=await s.getOrders(ae);if(Z!==X.current)return;n(ge.orders),o(ge.total)}catch(ae){if(Z!==X.current)return;r(ae instanceof Error?ae:new Error("Failed to fetch orders"))}finally{Z===X.current&&g(!1)}},[s,h,b,l,re,E,B,S,D,c,t]);st.useEffect(()=>{ce()},[ce]);let ie=Math.ceil(i/b);return{orders:a,total:i,isLoading:v,error:y,page:h,pageSize:b,hasNextPage:h<ie-1,hasPreviousPage:h>0,setPage:N,setPageSize:Z=>{u(Z),N(0)},status:l,setStatus:Z=>{x(Z),N(0)},statusIn:z,setStatusIn:Z=>{m(Z&&Z.length>0?Z:void 0),N(0)},customerEmail:S,setCustomerEmail:Z=>{R(Z),N(0)},from:D,setFrom:Z=>{F(Z),N(0)},to:c,setTo:Z=>{w(Z),N(0)},showAbandoned:E,setShowAbandoned:Z=>{W(Z),N(0)},unfulfilledOnly:B,setUnfulfilledOnly:Z=>{T(Z),N(0)},clearFilters:()=>{x(void 0),m(void 0),W(!1),T(!1),R(""),F(""),w(""),N(0)},refetch:ce}}var ct=de(require("react"),1),Ee=require("lucide-react");var Wr=de(require("react"),1),Ca=de(require("@radix-ui/react-popover"),1);var gn=require("react/jsx-runtime"),Kr=Ca.Root,Jr=Ca.Trigger;var Hn=Wr.forwardRef(({className:e,align:t="end",sideOffset:s=4,...a},n)=>(0,gn.jsx)(Ca.Portal,{children:(0,gn.jsx)("div",{className:"aifeatures-admin",children:(0,gn.jsx)(Ca.Content,{ref:n,align:t,sideOffset:s,className:Y("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),...a})})}));Hn.displayName=Ca.Content.displayName;var Hs=require("react/jsx-runtime"),Eo={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Io(e){return Eo[e]??e}function Yr(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 es({status:e,className:t}){return(0,Hs.jsx)(Q,{variant:Yr(e),className:t,children:Io(e)})}function Wa({status:e}){return(0,Hs.jsx)(es,{status:e})}function ps({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Hs.jsx)(Q,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Hs.jsx)(Q,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function $a(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var d=require("react/jsx-runtime"),ei="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ts="af-text-xs af-text-muted-foreground";function zn(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ti(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 vn=24,Do=["paid","partially_refunded"],Lo=["paid","partially_refunded","disputed"],Oo=/^[A-Za-z0-9 _-]*$/,Zr=100;function Gn(e,t,s,a,n){let i=Do.includes(a);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="unknown"?{label:"Delivery unknown",variant:"warning",detail:"The email may have arrived. Automatic retries have stopped to avoid sending it twice. Check with the recipient before resending."}:t==="failed"?i?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${s} of ${vn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${vn} tries used). Nothing is being retried while the order is ${a.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?s<vn&&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<vn&&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.`}:t==="suppressed"?{label:"Held back",variant:"outline",detail:`We deliberately did not send this ${a==="refunded"?"because the order was refunded":a==="disputed"?"because the order is disputed":"because the order was not in a sendable state"}. It sends automatically if the order becomes sellable again.`}:t==="none"?{label:"Not sent yet",variant:"secondary",detail:null}:{label:String(t),variant:"secondary",detail:null}}function Qr({title:e,recipient:t,status:s,attempts:a,side:n,orderStatus:i,action:o,delivery:v}){if(v)return(0,d.jsxs)("div",{children:[(0,d.jsx)(Na,{deliveries:[v]}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]});let g=Gn(n,s,a,i,t);return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,d.jsx)(Q,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),o&&(0,d.jsx)("div",{className:"af-mt-2",children:o})]})}function Xr(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=Ao(e.address)?e.address:null;if(s){for(let n of["line1","line2"]){let i=s[n];typeof i=="string"&&i&&t.push(i)}let a=["city","state","postal_code"].map(n=>s[n]).filter(n=>typeof n=="string"&&!!n).join(", ");a&&t.push(a),typeof s.country=="string"&&s.country&&t.push(s.country)}return t.length>0?t:Object.entries(e).map(([a,n])=>`${a}: ${ti(n)}`)}function Bo(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Wn({value:e,label:t,children:s,className:a,size:n="icon"}){let[i,o]=ct.useState(!1);if(!Bo())return null;let v=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},g=i?(0,d.jsx)(Ee.Check,{className:"af-h-3 af-w-3"}):(0,d.jsx)(Ee.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,d.jsx)(_,{variant:"ghost",size:"icon",className:Y("af-h-6 af-w-6 af-shrink-0",a),onClick:v,title:t,"aria-label":t,children:g}):(0,d.jsxs)(_,{variant:"outline",size:"sm",className:a,onClick:v,"aria-label":t,children:[i?(0,d.jsx)(Ee.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,d.jsx)(Ee.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function qn({label:e,value:t}){return(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ts,children:e}),(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,d.jsx)(Wn,{value:t,label:`Copy ${e}`})]})]})}function Fo({src:e}){let[t,s]=ct.useState(!1);return!e||t?(0,d.jsx)("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:(0,d.jsx)(Ee.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,d.jsx)("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 Ta({title:e,action:t,children:s,className:a}){return(0,d.jsxs)("section",{className:Y("af-rounded-lg af-border af-p-4",a),children:[(0,d.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,d.jsx)("h4",{className:ei,children:e}),t]}),(0,d.jsx)("div",{className:"af-mt-3",children:s})]})}function Mt({label:e,emphasis:t,divider:s,children:a}){return(0,d.jsxs)("div",{className:Y("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,d.jsx)("span",{className:t?"af-text-base af-font-semibold":ts,children:e}),(0,d.jsx)("span",{className:Y("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function jn({onSelect:e,disabled:t,icon:s,children:a}){return(0,d.jsxs)(_,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,d.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),a]})}function Mo(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.subscription_history_only?t.push({key:"renewal",text:"Subscription renewal recorded \u2014 no payment collected or items fulfilled",at:e.paid_at}):e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${j(mn(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="purchase_receipt"),a=s?fn(s):Gn("buyer",e.buyer_email_status,e.buyer_email_attempts,e.status,e.customer_email);t.push({key:"buyer-email",text:e.buyer_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let s=e.email_deliveries?.find(n=>n.kind==="merchant_sale"),a=s?fn(s):Gn("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"&&!e.email_deliveries?.some(n=>n.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${a.label.toLowerCase()}`,at:null,tone:a.variant==="destructive"?"destructive":a.variant==="warning"?"warning":void 0})}return typeof e.merchant_fulfilled_at=="string"&&t.push({key:"shipped",text:e.tracking_number?`Marked shipped \u2014 tracking ${e.tracking_number}`:"Marked shipped",at:e.merchant_fulfilled_at}),e.amount_refunded>0&&t.push({key:"refunded",text:`Refunded ${j(e.amount_refunded,e.currency)}`,at:e.refunded_at,tone:"warning"}),e.status==="disputed"&&t.push({key:"disputed",text:"Payment disputed by the buyer",at:null,tone:"destructive"}),t}function zs({order:e,onBack:t,onRefund:s,onOrderUpdated:a,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:v=!1,hasNextOrder:g=!1}){let{api:y}=oe(),[r,h]=ct.useState(e),[N,b]=ct.useState(null),[u,l]=ct.useState(null),[x,S]=ct.useState(!1),[R,D]=ct.useState(!1),[F,c]=ct.useState(!1),[w,E]=ct.useState(!1),[W,B]=ct.useState(""),[T,z]=ct.useState(!1),[m,H]=ct.useState(null),[re,X]=ct.useState(!1),[ce,ie]=ct.useState(""),[Z,ae]=ct.useState([]),[ge,K]=ct.useState(!1),[_e,it]=ct.useState(!1),[dt,Ie]=ct.useState(null);ct.useEffect(()=>{h(e)},[e]);let Pe=I=>{let Oe=I.id===r.id&&I.email_deliveries===void 0?{...I,email_deliveries:r.email_deliveries}:I;h(Oe),a?.(Oe)},vt=Object.entries(r.metadata??{}),A=Math.max(0,mn(r)-r.amount_refunded),se=(r.status==="paid"||r.status==="partially_refunded")&&A>0,P=r.exclusive_tax_total!=null,L=I=>typeof I.amountNet=="number"?I.amountNet+(I.exclusiveTax??0):(typeof I.unitAmount=="number"?I.unitAmount:0)*(typeof I.quantity=="number"&&I.quantity>0?I.quantity:1),fe=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),ze=Z.reduce((I,Oe)=>I+L(r.line_items[Oe]??{}),0)+(ge?fe:0),Ce=r.tax_total??0,qe=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((I,Oe)=>I+(Oe.exclusiveTax??0),0)),tt=P?ge&&fe>0?qe:0: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*ze/(r.amount_total+(r.shipping_total??0)))):0,ft=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(ze+tt,A):ze+tt,Lt=Z.length>0||ge,Ot=Lt?ft:Et(ce,r.currency),ne=Kt(r.currency)?"1":"0.01",Ae=async()=>{try{S(!0),b(null),l(null),await y.resendOrderReceipt(r.id);let I=await y.getOrder(r.id);Pe(I),l("Receipt email queued.")}catch(I){b(I instanceof Error?I.message:"Failed to resend receipt")}finally{S(!1)}},Ze=async()=>{try{D(!0),b(null),l(null);let I=await y.resetOrderDownloads(r.id);Pe(I),c(!1),l("Download count reset.")}catch(I){b(I instanceof Error?I.message:"Failed to reset downloads")}finally{D(!1)}},xa=r.line_items.some(I=>I.collectShippingAddress===!0&&!I.refunded&&!I.unavailableReason),ta=typeof r.merchant_fulfilled_at=="string",Oa=Lo.includes(r.status)||r.status==="refunded"&&r.line_items.some(I=>I.collectShippingAddress===!0&&I.amountNet===0&&!I.refunded&&!I.unavailableReason),at=W.trim(),Qe=Oo.test(at)&&at.length<=Zr,O=async I=>{try{z(!0),H(null),l(null);let Oe=await y.setOrderFulfillment(r.id,{fulfilled:I,...I&&at?{trackingNumber:at}:{}});Pe(Oe),B(""),l(I?"Marked as shipped.":"Marked as not shipped.")}catch(Oe){Oe instanceof kt&&Oe.status===409?H(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):H(Oe instanceof Error?Oe.message:"Failed to update the order")}finally{z(!1)}},Ke=()=>{Ie(null),ie(String(lt(A,r.currency))),ae([]),K(!1),X(!0)},q=I=>ae(Oe=>Oe.includes(I)?Oe.filter(Bt=>Bt!==I):[...Oe,I]),Pt=async(I,Oe)=>{if(s)try{it(!0),Ie(null),await s(r,I,Oe);let Bt=await y.getOrder(r.id);Pe(Bt),X(!1),l("Refund issued.")}catch(Bt){Ie(Bt instanceof Error?Bt.message:"Refund failed")}finally{it(!1)}},Ki=async()=>{if(Lt){if(ft<=0){Ie("The lines you picked were charged nothing");return}if(ft>A){Ie(`That selection exceeds the refundable remainder (${j(A,r.currency)})`);return}await Pt(ft,{...Z.length>0?{line_items:[...Z].sort((Oe,Bt)=>Oe-Bt)}:{},...ge?{shipping:!0}:{}});return}let I=Et(ce,r.currency);if(I===null||I<=0){Ie("Enter a valid refund amount");return}if(I>A){Ie(`Amount exceeds the refundable remainder (${j(A,r.currency)})`);return}await Pt(I,{amount:I})},Ji=()=>Pt(A,{full:!0}),gr=!r.subscription_history_only&&r.fulfillment_type==="download",vr=!r.subscription_history_only&&n&&xa,Yi=Mo(r),Zi=r.shipping_address?Xr(r.shipping_address).join(`
|
|
4
|
+
`):"",br=r.shipping_total!=null,Fn=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),yr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-Fn):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,hr=Fn>0,Qi=yr>0,xr=r.amount_subtotal!=null||br||hr||(r.discount_total??0)>0,Ns=[];return r.subscription_history_only||Ns.push((0,d.jsx)(jn,{icon:x?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,d.jsx)(Ee.Mail,{className:"af-h-4 af-w-4"}),disabled:x||r.fulfillment_status!=="fulfilled",onSelect:()=>{E(!1),Ae()},children:"Resend receipt"},"resend")),gr&&Ns.push((0,d.jsx)(jn,{icon:(0,d.jsx)(Ee.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:R,onSelect:()=>{E(!1),c(!0)},children:"Reset download count"},"reset")),se&&Ns.push((0,d.jsxs)("div",{children:[(0,d.jsx)(jn,{icon:(0,d.jsx)(Ee.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{E(!1),Ke()},children:"Refund\u2026"}),!s&&(0,d.jsx)("p",{className:"af-px-3 af-pb-1 af-text-xs af-text-muted-foreground",children:"Refunds are issued from your site dashboard."})]},"refund")),(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"af-mb-6",children:[(0,d.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,d.jsx)(Ee.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,d.jsx)("h3",{className:"af-text-xl af-font-semibold",children:$a(r)}),(0,d.jsx)(es,{status:r.status}),n&&!r.subscription_history_only&&(0,d.jsx)(ps,{order:r}),r.is_test&&(0,d.jsx)(Q,{variant:"outline",children:"Test"})]}),(0,d.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",zn(r.created_at)]}),r.is_test&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Simulated test purchase \u2014 no payment was collected. Refunding it is simulated too."})]}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&(0,d.jsxs)("div",{className:"af-flex af-items-center",children:[(0,d.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!v,"aria-label":"Previous order",children:(0,d.jsx)(Ee.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,d.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!g,"aria-label":"Next order",children:(0,d.jsx)(Ee.ChevronRight,{className:"af-h-4 af-w-4"})})]}),vr&&(ta?(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${zn(r.merchant_fulfilled_at)}`:""]}),Oa&&(0,d.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>O(!1),disabled:T,children:[T?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ee.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Oa?(0,d.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,d.jsx)(we,{value:W,onChange:I=>B(I.target.value),placeholder:"Tracking number (optional)",maxLength:Zr,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:T}),(0,d.jsxs)(_,{variant:"default",className:"af-shrink-0",onClick:()=>O(!0),disabled:T||!Qe,children:[T?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ee.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Ns.length>0&&(0,d.jsxs)(Kr,{open:w,onOpenChange:E,children:[(0,d.jsx)(Jr,{asChild:!0,children:(0,d.jsx)(_,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,d.jsx)(Ee.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,d.jsx)(Hn,{children:(0,d.jsx)("div",{className:"af-space-y-0.5",children:Ns})})]})]})]}),vr&&!ta&&!Qe&&(0,d.jsx)("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."}),m&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:m}),u&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-border af-border-green-200 af-bg-green-50 af-px-3 af-py-2 af-text-sm af-text-green-800",children:u}),N&&(0,d.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:N})]}),(0,d.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,d.jsxs)("div",{className:"af-space-y-6",children:[r.line_items.length>0&&(0,d.jsx)(Ta,{title:"Items",children:(0,d.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((I,Oe)=>{let Bt=typeof I.name=="string"&&I.name?I.name:"Item",wr=typeof I.quantity=="number"&&I.quantity>0?I.quantity:1,Nr=typeof I.unitAmount=="number";return(0,d.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,d.jsx)(Fo,{src:typeof I.imageUrl=="string"&&I.imageUrl?I.imageUrl:void 0}),(0,d.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,d.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Bt,typeof I.variantTitle=="string"&&I.variantTitle&&(0,d.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",I.variantTitle]})]}),(0,d.jsxs)("div",{className:ts,children:[wr," \xD7"," ",Nr?j(I.unitAmount,r.currency):"\u2014"]}),I.unavailableReason==="oversold"&&!I.refunded&&(0,d.jsx)(Q,{variant:"secondary",className:"af-mt-1",children:I.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),I.refunded===!0&&(0,d.jsx)(Q,{variant:"secondary",className:"af-mt-1",children:I.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,d.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof I.amountNet=="number"||Nr?j(I.amountNet??I.unitAmount*wr,r.currency):"\u2014"})]},Oe)})})}),vt.length>0&&(0,d.jsx)(Ta,{title:"Order details",children:(0,d.jsx)("dl",{className:"af-space-y-2",children:vt.map(([I,Oe])=>(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{className:Y(ts,"af-capitalize"),children:I.replace(/_/g," ")}),(0,d.jsx)("dd",{className:"af-text-sm af-break-words",children:ti(Oe)})]},I))})}),(0,d.jsx)(Ta,{title:"Totals",children:(0,d.jsxs)("div",{className:"af-w-full",children:[xr&&(0,d.jsx)(Mt,{label:"Subtotal",children:j(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&(0,d.jsxs)(Mt,{label:"Discount",children:["\u2212",j(r.discount_total,r.currency)]}),br&&(0,d.jsx)(Mt,{label:"Shipping",children:r.shipping_total===0?"Free":j(r.shipping_total??0,r.currency)}),hr&&(0,d.jsx)(Mt,{label:"Tax",children:j(Fn,r.currency)}),(0,d.jsx)(Mt,{label:"Total",emphasis:!0,divider:xr,children:j(Pa(r),r.currency)}),(r.credit_applied??0)>0&&(0,d.jsxs)(Mt,{label:"Credit applied",children:["\u2212",j(r.credit_applied,r.currency)]}),r.amount_paid!=null&&(0,d.jsx)(Mt,{label:"Amount paid",children:j(r.amount_paid,r.currency)}),Qi&&(0,d.jsx)(Mt,{label:"incl. tax",children:j(yr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,d.jsxs)(Mt,{label:"Your price",children:[j(r.base_amount_total,r.base_currency),(0,d.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(Mt,{label:"Refunded",children:["\u2212",j(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&(0,d.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",j(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,d.jsx)(Mt,{label:"Net",children:(0,d.jsx)("span",{className:"af-font-medium",children:j(Math.max(0,mn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&(0,d.jsxs)(Ta,{title:"Platform fee",children:[r.application_fee_original!=null&&(0,d.jsx)(Mt,{label:"Collected",children:j(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&(0,d.jsx)(Mt,{label:"Returned",children:j(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&(0,d.jsx)(Mt,{label:"Retained",children:j(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&(0,d.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:r.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,d.jsx)(Ta,{title:"Timeline",children:(0,d.jsx)("ol",{className:"af-space-y-3",children:Yi.map(I=>(0,d.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,d.jsx)("span",{"aria-hidden":"true",className:Y("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")}),(0,d.jsxs)("div",{className:"af-min-w-0",children:[(0,d.jsx)("div",{className:"af-text-sm af-break-words",children:I.text}),I.at&&(0,d.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:zn(I.at)})]})]},I.key))})})]}),(0,d.jsxs)("div",{className:"af-space-y-6",children:[(0,d.jsx)(Ta,{title:"Customer",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ts,children:"Email"}),(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,d.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||(0,d.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&(0,d.jsx)(Wn,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ts,children:"Name"}),(0,d.jsx)("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{className:ts,children:"Customer record"}),(0,d.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,d.jsx)("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),(0,d.jsx)(Q,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,d.jsx)(Ta,{title:"Ship to",action:(0,d.jsx)(Wn,{value:Zi,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,d.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Xr(r.shipping_address).map((I,Oe)=>(0,d.jsx)("div",{children:I},Oe))})}),r.subscription_history_only?(0,d.jsx)(Ta,{title:"Subscription history",children:(0,d.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"This renewal had no payment due. No items were fulfilled and no purchase receipt was sent."})}):(0,d.jsxs)(Ta,{title:"Emails",children:[(0,d.jsx)(Na,{deliveries:r.email_deliveries?.filter(I=>!["purchase_receipt","merchant_sale"].includes(I.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(0,d.jsx)(Qr,{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:(0,d.jsxs)(_,{variant:"outline",size:"sm",onClick:Ae,disabled:x||r.fulfillment_status!=="fulfilled",children:[x?(0,d.jsx)(Ee.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,d.jsx)(Ee.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,d.jsx)(Qr,{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&&(0,d.jsx)(Ta,{title:"Download",children:(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,d.jsx)(Ee.Download,{className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&(0,d.jsx)("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"})]})}),(0,d.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,d.jsx)("summary",{className:Y(ei,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,d.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,d.jsx)(qn,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,d.jsx)(qn,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,d.jsx)(qn,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,d.jsx)(_a,{open:F,onOpenChange:I=>{!I&&!R&&c(!1)},children:(0,d.jsxs)(pa,{children:[(0,d.jsxs)(ga,{children:[(0,d.jsx)(ba,{children:"Reset download count?"}),(0,d.jsx)(ya,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,d.jsxs)(va,{children:[(0,d.jsx)(_,{variant:"outline",onClick:()=>c(!1),disabled:R,children:"Cancel"}),(0,d.jsx)(_,{onClick:Ze,disabled:R,children:R?"Resetting...":"Reset"})]})]})}),(0,d.jsx)(_a,{open:re,onOpenChange:I=>{!I&&!_e&&X(!1)},children:(0,d.jsxs)(pa,{children:[(0,d.jsxs)(ga,{children:[(0,d.jsx)(ba,{children:"Refund order"}),(0,d.jsxs)(ya,{children:["Refund up to ",j(A,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,d.jsxs)("div",{className:"af-space-y-4",children:[(r.line_items.length>0||fe>0)&&(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsx)(Re,{children:"Items"}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((I,Oe)=>{let Bt=I.refunded===!0;return(0,d.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,d.jsx)("input",{type:"checkbox",checked:Z.includes(Oe),onChange:()=>q(Oe),disabled:_e||Bt||!!I.unavailableReason||L(I)<=0,className:"af-h-4 af-w-4"}),(0,d.jsxs)("span",{className:Bt?"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}`:""]}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Bt?"Refunded":j(L(I),r.currency)})]},Oe)}),fe>0&&(0,d.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,d.jsx)("input",{type:"checkbox",checked:ge,onChange:I=>K(I.target.checked),disabled:_e,className:"af-h-4 af-w-4"}),(0,d.jsx)("span",{children:"Shipping"}),(0,d.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:j(fe,r.currency)})]})]})]}),(0,d.jsxs)("div",{className:"af-space-y-2",children:[(0,d.jsxs)(Re,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,d.jsx)(we,{id:"refund-amount",type:"number",min:"0",step:ne,value:Lt?String(lt(ft,r.currency)):ce,onChange:I=>ie(I.target.value),disabled:_e||Lt}),Lt&&(0,d.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),dt&&(0,d.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:dt}),(0,d.jsxs)(va,{children:[(0,d.jsx)(_,{variant:"outline",onClick:()=>X(!1),disabled:_e,children:"Cancel"}),(0,d.jsx)(_,{variant:"outline",onClick:Ji,disabled:_e,children:"Refund everything"}),(0,d.jsx)(_,{variant:"destructive",onClick:Ki,disabled:_e,children:_e?"Refunding...":Ot!==null&&Ot>0?`Refund ${j(Ot,r.currency)}`:"Refund"})]})]})})]})}var bn=de(require("react"),1),yn=require("lucide-react");var ht=require("react/jsx-runtime");function Nt({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:a,className:n}){let i=bn.useRef(null);return bn.useEffect(()=>{i.current?.focus()},[]),(0,ht.jsxs)("div",{className:Y("af-bg-background",n),children:[(0,ht.jsxs)("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:[(0,ht.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&(0,ht.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:t,children:[(0,ht.jsx)(yn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,ht.jsx)("div",{className:"af-p-4",children:a})]})}function ee({className:e}){return(0,ht.jsx)("div",{"aria-hidden":"true",className:Y("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Xe({label:e,children:t,detail:s,valueClassName:a}){return(0,ht.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,ht.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,ht.jsx)("div",{className:Y("af-mt-1 af-text-lg af-font-semibold",a),children:t}),s&&(0,ht.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function Yt({message:e,onRetry:t}){return(0,ht.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ht.jsx)("span",{children:e}),(0,ht.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,ht.jsx)(yn.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ka({icon:e,children:t}){return(0,ht.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,ht.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}var C=require("react/jsx-runtime"),Uo={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},ai={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function si(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ni(e){let t=Array.isArray(e.line_items)?e.line_items:[],s=t[0];if(!s)return"\u2014";let a=typeof s.name=="string"&&s.name?s.name:"Item",n=typeof s.quantity=="number"&&s.quantity>0?s.quantity:1,i=n>1?`${a} \xD7${n}`:a;return t.length>1?`${i} +${t.length-1} more`:i}function hn(e){return e.customer?.name||e.customer_name||null}function as({onRefund:e,className:t,refreshKey:s,initialOrderId:a,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o}){let{api:v}=oe(),g=Vs({refreshKey:s}),{orders:y,total:r,isLoading:h,error:N,page:b,pageSize:u,hasNextPage:l,hasPreviousPage:x,setPage:S,setPageSize:R,customerEmail:D,setCustomerEmail:F,setStatusIn:c,from:w,setFrom:E,to:W,setTo:B,showAbandoned:T,setShowAbandoned:z,setUnfulfilledOnly:m,refetch:H}=g,[re,X]=St.useState("list"),[ce,ie]=St.useState(null),[Z,ae]=St.useState(""),[ge,K]=St.useState(""),[_e,it]=St.useState(n?"needs_shipping":"all"),[dt,Ie]=St.useState(!1),[Pe,vt]=St.useState(!!a),[A,se]=St.useState(null);St.useEffect(()=>{if(!a)return;let q=!1;return vt(!0),se(null),v.getOrder(a).then(Pt=>{q||(ie(Pt),X("detail"))}).catch(()=>{q||se("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{q||vt(!1)}),()=>{q=!0}},[v,a]);let P=St.useCallback(q=>{it(q);let Pt=ai[q];c(Pt.statusIn),m(Pt.unfulfilledOnly)},[c,m]);St.useEffect(()=>{n&&m(!0)},[]);let L=St.useRef(!n);St.useEffect(()=>{L.current||h||(L.current=!0,y.length===0&&P("all"))},[h,y.length,P]);let fe=re==="detail"&&!!ce;St.useEffect(()=>{o?.(fe)},[fe,o]);let ze=(w?1:0)+(W?1:0)+(T?1:0),Ce=ze>0||!!D||!!ge,qe=!!w&&!!W&&w>W,tt=q=>{ie(q),X("detail")},ft=()=>{X("list"),ie(null),H()},Lt=q=>{let Pt=q.trim();if(!Pt){K(""),D&&F("");return}if(Pt.startsWith("#")||/^\d+$/.test(Pt)){K(Pt),D&&F("");return}K(""),F(Pt)},Ot=()=>{ae(""),K(""),F(""),E(""),B(""),z(!1),Ie(!1)},ne=ge.replace(/^#/,"").toLowerCase(),Ae=ne?y.filter(q=>String(q.order_number??"")===ne||q.id.toLowerCase().startsWith(ne)):y,Ze=ce?y.findIndex(q=>q.id===ce.id):-1,xa=Ze>0,ta=Ze>=0&&Ze<y.length-1;if(Pe)return(0,C.jsx)("div",{className:t,children:(0,C.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,C.jsx)(Zt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(re==="detail"&&ce)return(0,C.jsx)("div",{className:t,children:(0,C.jsx)(zs,{order:ce,onBack:ft,onRefund:e,onOrderUpdated:q=>ie(q),allowFulfillment:n,onPrevOrder:xa?()=>ie(y[Ze-1]):void 0,onNextOrder:ta?()=>ie(y[Ze+1]):void 0,hasPrevOrder:xa,hasNextOrder:ta},ce.id)});let at=(0,C.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[A&&(0,C.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:A}),(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,C.jsx)("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(q=>(0,C.jsx)("button",{type:"button","aria-pressed":_e===q,onClick:()=>P(q),className:Y("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",_e===q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Uo[q]},q))}),(0,C.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,C.jsx)(Zt.Search,{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"}),(0,C.jsx)(we,{type:"text",value:Z,onChange:q=>ae(q.target.value),onBlur:()=>Lt(Z),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),Lt(Z))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,C.jsxs)(_,{type:"button",variant:ze>0?"secondary":"ghost",size:"sm",onClick:()=>Ie(q=>!q),"aria-expanded":dt,children:[(0,C.jsx)(Zt.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",ze>0&&(0,C.jsx)(Q,{variant:"secondary",className:"af-ml-2",children:ze})]}),Ce&&(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:Ot,children:"Clear filters"})]}),(dt||!!w||!!W)&&(0,C.jsxs)("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:[(0,C.jsx)(Re,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,C.jsx)(we,{id:"orders-from",type:"date",value:w,max:W||void 0,onChange:q=>E(q.target.value),className:"af-w-[170px]"}),(0,C.jsx)(Re,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,C.jsx)(we,{id:"orders-to",type:"date",value:W,min:w||void 0,onChange:q=>B(q.target.value),className:"af-w-[170px]"}),!ai[_e].statusIn&&(0,C.jsx)(_,{type:"button",variant:T?"secondary":"ghost",size:"sm",onClick:()=>z(!T),"aria-pressed":T,children:T?"Hide abandoned":"Show abandoned"})]}),qe&&(0,C.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(h)return(0,C.jsxs)("div",{className:t,children:[at,(0,C.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,C.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,C.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,C.jsx)(ee,{className:"af-h-4 af-w-16"}),(0,C.jsx)(ee,{className:"af-h-4 af-w-14"})]}),(0,C.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-40"}),(0,C.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-24"})]},q))}),(0,C.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,C.jsxs)(Fe,{children:[(0,C.jsx)(Me,{children:(0,C.jsxs)(he,{children:[(0,C.jsx)($,{children:"Order"}),(0,C.jsx)($,{children:"Date"}),(0,C.jsx)($,{children:"Customer"}),(0,C.jsx)($,{children:"Items"}),(0,C.jsx)($,{className:"af-text-right",children:"Total"}),(0,C.jsx)($,{children:"Status"}),(0,C.jsx)($,{className:"af-w-8"})]})}),(0,C.jsx)(Ue,{"aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,C.jsxs)(he,{children:[(0,C.jsx)(V,{children:(0,C.jsx)(ee,{className:"af-h-4 af-w-14"})}),(0,C.jsx)(V,{children:(0,C.jsx)(ee,{className:"af-h-4 af-w-24"})}),(0,C.jsx)(V,{children:(0,C.jsx)(ee,{className:"af-h-4 af-w-40"})}),(0,C.jsx)(V,{children:(0,C.jsx)(ee,{className:"af-h-4 af-w-32"})}),(0,C.jsx)(V,{children:(0,C.jsx)(ee,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,C.jsx)(V,{children:(0,C.jsx)(ee,{className:"af-h-5 af-w-16"})}),(0,C.jsx)(V,{})]},q))})]})}),(0,C.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(N)return(0,C.jsxs)("div",{className:t,children:[at,(0,C.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,C.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>H(),children:"Try again"})]})]});let Qe=_e!=="all";if(Ae.length===0&&b===0)return(0,C.jsxs)("div",{className:t,children:[(Ce||Qe)&&at,(0,C.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,C.jsx)(Zt.Receipt,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,C.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:Ce||Qe?"No orders match these filters.":i??(0,C.jsxs)(C.Fragment,{children:["No orders yet.",(0,C.jsx)("br",{}),"Orders will appear here when someone buys from your website."]})}),!Ce&&!Qe&&(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>z(!0),children:"Show abandoned checkouts"})]})]});let O=b*u+1,Ke=Math.min((b+1)*u,r);return(0,C.jsxs)("div",{className:t,children:[at,(0,C.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ae.map(q=>(0,C.jsxs)("button",{type:"button",onClick:()=>tt(q),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,C.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,C.jsx)("span",{className:"af-font-medium",children:$a(q)}),(0,C.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:j(Pa(q),q.currency)})]}),(0,C.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,C.jsxs)("div",{className:"af-truncate af-text-sm",children:[q.customer_email||(0,C.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),hn(q)&&(0,C.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",hn(q)]})]}),(0,C.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ni(q)}),q.amount_refunded>0&&(0,C.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(q.amount_refunded,q.currency)," refunded"]})]}),(0,C.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,C.jsx)(es,{status:q.status}),(0,C.jsx)(Ps,{deliveries:q.email_deliveries}),q.is_test&&(0,C.jsx)(Q,{variant:"outline",children:"Test"}),n&&(0,C.jsx)(ps,{order:q}),(0,C.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:si(q.created_at)})]})]},q.id))}),(0,C.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,C.jsxs)(Fe,{children:[(0,C.jsx)(Me,{children:(0,C.jsxs)(he,{children:[(0,C.jsx)($,{children:"Order"}),(0,C.jsx)($,{children:"Date"}),(0,C.jsx)($,{children:"Customer"}),(0,C.jsx)($,{children:"Items"}),(0,C.jsx)($,{className:"af-text-right",children:"Total"}),(0,C.jsx)($,{children:"Status"}),(0,C.jsx)($,{className:"af-w-8"})]})}),(0,C.jsx)(Ue,{children:Ae.map(q=>(0,C.jsxs)(he,{onClick:()=>tt(q),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,C.jsxs)(V,{className:"af-whitespace-nowrap af-font-medium",children:[(0,C.jsx)("button",{type:"button",onClick:Pt=>{Pt.stopPropagation(),tt(q)},"aria-label":`Open order ${$a(q)}`,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:$a(q)}),q.is_test&&(0,C.jsx)(Q,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,C.jsx)(V,{className:"af-whitespace-nowrap af-text-muted-foreground",children:si(q.created_at)}),(0,C.jsxs)(V,{className:"af-max-w-[220px]",children:[(0,C.jsx)("div",{className:"af-truncate",children:q.customer_email||(0,C.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),hn(q)&&(0,C.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:hn(q)})]}),(0,C.jsx)(V,{className:"af-max-w-[220px]",children:(0,C.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:ni(q)})}),(0,C.jsxs)(V,{className:"af-whitespace-nowrap af-text-right",children:[(0,C.jsx)("div",{className:"af-font-medium af-tabular-nums",children:j(Pa(q),q.currency)}),q.amount_refunded>0&&(0,C.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",j(q.amount_refunded,q.currency)," ","refunded"]})]}),(0,C.jsx)(V,{children:(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,C.jsx)(es,{status:q.status}),(0,C.jsx)(Ps,{deliveries:q.email_deliveries}),n&&(0,C.jsx)(ps,{order:q})]})}),(0,C.jsx)(V,{className:"af-w-8 af-text-right",children:(0,C.jsx)(Zt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},q.id))})]})}),(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,C.jsx)("span",{children:ne?`${Ae.length} matching this page`:`Showing ${O}-${Ke} of ${r}`}),(0,C.jsxs)(aa,{value:String(u),onValueChange:q=>R(Number(q)),children:[(0,C.jsx)(qt,{className:"af-w-[70px] af-h-8",children:(0,C.jsx)(sa,{})}),(0,C.jsxs)(jt,{children:[(0,C.jsx)(je,{value:"10",children:"10"}),(0,C.jsx)(je,{value:"25",children:"25"}),(0,C.jsx)(je,{value:"50",children:"50"}),(0,C.jsx)(je,{value:"100",children:"100"})]})]}),(0,C.jsx)("span",{children:"per page"})]}),(0,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,C.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>S(b-1),disabled:!x,children:[(0,C.jsx)(Zt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,C.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>S(b+1),disabled:!l,children:["Next",(0,C.jsx)(Zt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var wn=de(require("react"),1),Ea=require("lucide-react");var Ut=de(require("react"),1);function qs({initialPageSize:e=25}={}){let{api:t}=oe(),[s,a]=Ut.useState([]),[n,i]=Ut.useState(0),[o,v]=Ut.useState(!0),[g,y]=Ut.useState(null),[r,h]=Ut.useState(0),[N,b]=Ut.useState(e),[u,l]=Ut.useState(""),x=Ut.useRef(0),S=Ut.useCallback(async()=>{let D=++x.current;try{v(!0),y(null);let F={limit:N,offset:r*N};u.trim()&&(F.email=u.trim());let c=await t.getCustomers(F);if(D!==x.current)return;a(c.customers),i(c.total)}catch(F){if(D!==x.current)return;y(F instanceof Error?F:new Error("Failed to fetch customers"))}finally{D===x.current&&v(!1)}},[t,r,N,u]);Ut.useEffect(()=>{S()},[S]);let R=Math.ceil(n/N);return{customers:s,total:n,isLoading:o,error:g,page:r,pageSize:N,hasNextPage:r<R-1,hasPreviousPage:r>0,setPage:h,setPageSize:D=>{b(D),h(0)},email:u,setEmail:D=>{l(D),h(0)},refetch:S}}var ss=de(require("react"),1),xn=require("lucide-react");var ve=require("react/jsx-runtime");function ri(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function $o(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let s=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return s&&t.push(s),e.country&&t.push(e.country),t}function js({customer:e,onBack:t,className:s}){let{api:a}=oe(),[n,i]=ss.useState(null),[o,v]=ss.useState([]),[g,y]=ss.useState(!0),[r,h]=ss.useState(null);ss.useEffect(()=>{let u=!1;return y(!0),h(null),Promise.all([a.getCustomer(e.id),a.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,x])=>{u||(i(l),v(x.orders))}).catch(l=>{u||h(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{u||y(!1)}),()=>{u=!0}},[a,e.id,e.email]);let N=n?.addresses??[],b=n?.order_count??o.length;return(0,ve.jsxs)("div",{className:s,children:[(0,ve.jsxs)("div",{className:"af-mb-6",children:[(0,ve.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,ve.jsx)(xn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ve.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ve.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",ri(e.created_at)]})]}),g?(0,ve.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ve.jsx)(xn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,ve.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,ve.jsxs)("div",{className:"af-space-y-6",children:[(0,ve.jsx)(Na,{deliveries:n?.email_deliveries}),(0,ve.jsxs)("div",{children:[(0,ve.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ve.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ve.jsx)("span",{children:e.email})]}),e.name&&(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ve.jsx)("span",{children:e.name})]}),e.phone&&(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ve.jsx)("span",{children:e.phone})]}),(0,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ve.jsx)("span",{children:b})]})]})]}),N.length>0&&(0,ve.jsxs)("div",{children:[(0,ve.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ve.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:N.map(u=>(0,ve.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[u.is_default&&(0,ve.jsx)(Q,{variant:"secondary",className:"af-mb-1",children:"Default"}),$o(u).map((l,x)=>(0,ve.jsx)("div",{children:l},x))]},u.id))})]}),(0,ve.jsxs)("div",{children:[(0,ve.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ve.jsxs)(Fe,{children:[(0,ve.jsx)(Me,{children:(0,ve.jsxs)(he,{children:[(0,ve.jsx)($,{children:"Date"}),(0,ve.jsx)($,{children:"Amount"}),(0,ve.jsx)($,{children:"Status"})]})}),(0,ve.jsx)(Ue,{children:o.map(u=>(0,ve.jsxs)(he,{children:[(0,ve.jsx)(V,{className:"af-text-muted-foreground",children:ri(u.created_at)}),(0,ve.jsx)(V,{children:j(Pa(u),u.currency)}),(0,ve.jsx)(V,{children:(0,ve.jsx)(Wa,{status:u.status})})]},u.id))})]})]})]})]})}var ue=require("react/jsx-runtime");function Vo(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Gs({className:e}){let{customers:t,total:s,isLoading:a,error:n,page:i,pageSize:o,hasNextPage:v,hasPreviousPage:g,setPage:y,setPageSize:r,email:h,setEmail:N,refetch:b}=qs(),[u,l]=wn.useState("list"),[x,S]=wn.useState(null),[R,D]=wn.useState(""),F=B=>{S(B),l("detail")},c=()=>{l("list"),S(null),b()};if(u==="detail"&&x)return(0,ue.jsx)("div",{className:e,children:(0,ue.jsx)(js,{customer:x,onBack:c})});let w=(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,ue.jsx)(we,{type:"email",value:R,onChange:B=>D(B.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),N(R.trim()))}}),(0,ue.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>N(R.trim()),children:[(0,ue.jsx)(Ea.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),h&&(0,ue.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{D(""),N("")},children:"Clear"})]});if(a)return(0,ue.jsxs)("div",{className:e,children:[w,(0,ue.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,ue.jsxs)("div",{className:e,children:[w,(0,ue.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ue.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&i===0)return(0,ue.jsxs)("div",{className:e,children:[h&&w,(0,ue.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,ue.jsx)(Ea.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ue.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:h?"No customers match that email.":(0,ue.jsxs)(ue.Fragment,{children:["No customers yet.",(0,ue.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let E=i*o+1,W=Math.min((i+1)*o,s);return(0,ue.jsxs)("div",{className:e,children:[w,(0,ue.jsxs)(Fe,{children:[(0,ue.jsx)(Me,{children:(0,ue.jsxs)(he,{children:[(0,ue.jsx)($,{children:"Email"}),(0,ue.jsx)($,{children:"Name"}),(0,ue.jsx)($,{children:"Customer since"}),(0,ue.jsx)($,{className:"af-text-right",children:"Actions"})]})}),(0,ue.jsx)(Ue,{children:t.map(B=>(0,ue.jsxs)(he,{children:[(0,ue.jsx)(V,{className:"af-font-medium",children:B.email}),(0,ue.jsx)(V,{children:B.name||(0,ue.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,ue.jsx)(V,{className:"af-text-muted-foreground",children:Vo(B.created_at)}),(0,ue.jsx)(V,{className:"af-text-right",children:(0,ue.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>F(B),title:"View customer",children:(0,ue.jsx)(Ea.Eye,{className:"af-h-4 af-w-4"})})})]},B.id))})]}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ue.jsxs)("span",{children:["Showing ",E,"-",W," of ",s]}),(0,ue.jsxs)(aa,{value:String(o),onValueChange:B=>r(Number(B)),children:[(0,ue.jsx)(qt,{className:"af-w-[70px] af-h-8",children:(0,ue.jsx)(sa,{})}),(0,ue.jsxs)(jt,{children:[(0,ue.jsx)(je,{value:"10",children:"10"}),(0,ue.jsx)(je,{value:"25",children:"25"}),(0,ue.jsx)(je,{value:"50",children:"50"}),(0,ue.jsx)(je,{value:"100",children:"100"})]})]}),(0,ue.jsx)("span",{children:"per page"})]}),(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(i-1),disabled:!g,children:[(0,ue.jsx)(Ea.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>y(i+1),disabled:!v,children:["Next",(0,ue.jsx)(Ea.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ke=de(require("react"),1),gt=require("lucide-react");var pt=de(require("react"),1);function ns({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:a}=oe(),[n,i]=pt.useState([]),[o,v]=pt.useState(0),[g,y]=pt.useState(null),[r,h]=pt.useState(!0),[N,b]=pt.useState(null),[u,l]=pt.useState(0),[x,S]=pt.useState(e),[R,D]=pt.useState(void 0),[F,c]=pt.useState(""),[w,E]=pt.useState(""),[W,B]=pt.useState(""),[T,z]=pt.useState(""),[m,H]=pt.useState(""),re=R?R.join(","):"",X=pt.useRef(0),ce=pt.useCallback(async()=>{let Z=++X.current;h(!0),b(null);try{let ae={labels:re?re.split(","):void 0,customerEmail:F||void 0,q:w||void 0,from:W||void 0,to:T||void 0,retainerId:m||void 0,includeAggregates:s,limit:x,offset:u*x},ge=await a.getInvoices(ae);if(Z!==X.current)return;if(u>0&&u*x>=ge.total){l(Math.max(0,Math.ceil(ge.total/x)-1));return}i(ge.invoices),v(ge.total),s&&y(ge.aggregates??null)}catch(ae){if(Z!==X.current)return;b(ae instanceof Error?ae:new Error("Failed to fetch invoices"))}finally{Z===X.current&&h(!1)}},[a,re,F,w,W,T,m,u,x,s]);pt.useEffect(()=>{ce()},[ce,t]);let ie=Z=>ae=>{l(0),Z(ae)};return{invoices:n,total:o,aggregates:g,isLoading:r,error:N,page:u,pageSize:x,hasNextPage:(u+1)*x<o,hasPreviousPage:u>0,setPage:l,setPageSize:ie(S),labels:R,setLabels:ie(D),customerEmail:F,setCustomerEmail:ie(c),q:w,setQ:ie(E),from:W,setFrom:ie(B),to:T,setTo:ie(z),retainerId:m,setRetainerId:ie(H),clearFilters:()=>{l(0),D(void 0),c(""),E(""),B(""),z(""),H("")},refetch:ce}}var f=require("react/jsx-runtime"),Ho={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 Qn(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Ho[e.label]??e.label}function zo(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 Zn={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},qo={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function vs({invoice:e,className:t}){return(0,f.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,f.jsx)(Q,{variant:zo(e.label),className:t,children:Qn(e)}),e.collection_method==="charge_automatically"&&(0,f.jsx)(Q,{variant:"secondary",children:"Managed in Stripe"})]})}function Sn({delivery:e,className:t}){if(!e)return null;let s=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,f.jsx)(Q,{variant:s,className:t,children:Zn[e.state]??e.state})}function gs(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function la(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t);return Number.isNaN(s.getTime())?e:s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var ii={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Kn={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 jo(e){let t=e==null?"":String(e),s=/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),a=s?`'${t}`:t;return s||/[",;\r\n]/.test(a)?`"${a.replace(/"/g,'""')}"`:a}var Jn=100,Yn=5e3;async function Go(e,t){let s=[],a=0;for(let n=0;n<Yn;n+=Jn){let i=await e.getInvoices({...t,limit:Jn,offset:n});if(a=i.total,s.push(...i.invoices),i.invoices.length<Jn||s.length>=a)break}return{invoices:s.slice(0,Yn),total:a,truncated:a>s.length||a>Yn}}function li(e){let t=["id","invoice","status","customer","email","created","due","paid","currency","subtotal","tax","total","amount_due","amount_paid","refunded","payment_method","pay_link","retainer_id","replaces_order_id","replaced_by_order_id","tax_behavior","discount_total","collection_method"],s=e.map(a=>[a.id,gs(a),Qn(a),a.customer_name??"",a.customer_email??"",a.created_at,a.due_at??"",a.paid_at??"",a.currency.toUpperCase(),j(a.amount_subtotal,a.currency),j(a.tax_total,a.currency),j(a.amount_total,a.currency),a.amount_due===null?"":j(a.amount_due,a.currency),a.amount_paid===null?"":j(a.amount_paid,a.currency),j(a.amount_refunded,a.currency),a.payment_method??"",a.pay_url??"",a.retainer_id??"",a.replaces_order_id??"",a.replaced_by_order_id??"",a.tax_behavior??"",a.discount_total===void 0?"":j(a.discount_total,a.currency),a.collection_method??""]);return[t,...s].map(a=>a.map(jo).join(",")).join(`
|
|
5
|
+
`)}function Wo(e){if(typeof document>"u")return;let t=new Blob([li(e)],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(t),a=document.createElement("a");a.href=s,a.download=`invoices-${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function rs({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:a,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:v=null,onClearRetainerFilter:g}){let{api:y}=oe(),{invoices:r,total:h,isLoading:N,error:b,page:u,pageSize:l,hasNextPage:x,hasPreviousPage:S,setPage:R,labels:D,setLabels:F,customerEmail:c,setCustomerEmail:w,q:E,setQ:W,from:B,setFrom:T,to:z,setTo:m,retainerId:H,setRetainerId:re,refetch:X}=ns({refreshKey:t}),[ce,ie]=ke.useState("open"),[Z,ae]=ke.useState(""),[ge,K]=ke.useState(null),_e=ke.useRef(0),it=ke.useCallback(O=>{_e.current++,Ie(!1),K(O)},[]),[dt,Ie]=ke.useState(!1),[Pe,vt]=ke.useState(0),[A,se]=ke.useState(null),[P,L]=ke.useState(!1),[fe,ze]=ke.useState(0);ke.useEffect(()=>{K(O=>{if(!O)return O;let Ke=r.find(q=>q.id===O.id);return Ke&&Ke!==O?Ke:O})},[r]);let[Ce,qe]=ke.useState(!1),[tt,ft]=ke.useState(null),Lt=async()=>{if(!Ce){qe(!0),ft(null);try{let{invoices:O,total:Ke,truncated:q}=await Go(y,{labels:D,customerEmail:c,q:E,from:B,to:z,retainerId:H});Wo(O),ft(q?`Exported the first ${O.length.toLocaleString()} of ${Ke.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{ft("Couldn't export \u2014 try again.")}finally{qe(!1)}}},Ot=!c&&!E&&!B&&!z&&!H,[ne,Ae]=ke.useState(null);ke.useEffect(()=>{if(N||h>0||!Ot||ce!=="open")return;let O=!1;return y.getInvoices({limit:1}).then(Ke=>{O||Ae(Ke.total>0)}).catch(()=>{O||Ae(!0)}),()=>{O=!0}},[y,N,h,Ot,ce,t]),ke.useEffect(()=>{F(Kn.open)},[]),ke.useEffect(()=>{let O=v?.id??"";O!==H&&(re(O),O&&(ie("all"),F(Kn.all),w(""),W(""),ae(""),T(""),m("")))},[v?.id]),ke.useEffect(()=>{let O=!1;return L(!1),y.getInvoiceSettings().then(Ke=>{O||se({payments_active:Ke.payments_active,blocked:Ke.blocked})}).catch(()=>{O||L(!0)}),()=>{O=!0}},[y,t,fe]),ke.useEffect(()=>{if(!s)return;let O=!1,Ke=_e.current;return Ie(!1),y.getInvoice(s).then(q=>{!O&&Ke===_e.current&&K(q)}).catch(()=>{!O&&Ke===_e.current&&Ie(!0)}),()=>{O=!0}},[y,s,Pe]),ke.useEffect(()=>{a?.(ge!==null)},[ge,a]);let Ze=O=>{ie(O),F(Kn[O])},xa=O=>{let Ke=O.trim();if(!Ke){E&&W(""),c&&w("");return}if(Ke.includes("@")){E&&W(""),w(Ke);return}c&&w(""),W(Ke.replace(/^#/,""))},ta=r,Oa=dt&&(0,f.jsxs)("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. ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>vt(O=>O+1),children:"Retry opening invoice"})]});if(ge)return(0,f.jsxs)("div",{className:e,children:[Oa,(0,f.jsx)(_n,{invoice:ge,refreshKey:t,onBack:()=>{it(null),X()}},ge.id)]});let at=(0,f.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[P&&(0,f.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>ze(O=>O+1),children:"Retry setup check"})]}),Oa,A?.blocked&&(0,f.jsxs)("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",A.blocked.reason?`: ${A.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),v&&(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,f.jsxs)(Q,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",v.label]}),g&&(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:g,children:"Clear schedule filter"})]}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsx)("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(ii).map(O=>(0,f.jsx)("button",{type:"button","aria-pressed":ce===O,onClick:()=>Ze(O),className:Y("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",ce===O?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:ii[O]},O))}),(0,f.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,f.jsx)(gt.Search,{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"}),(0,f.jsx)(we,{type:"text",value:Z,onChange:O=>ae(O.target.value),onBlur:()=>xa(Z),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),xa(Z))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,f.jsx)(Re,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,f.jsx)(we,{id:"invoices-from",type:"date",value:B,max:z||void 0,onChange:O=>T(O.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,f.jsx)(Re,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,f.jsx)(we,{id:"invoices-to",type:"date",value:z,min:B||void 0,onChange:O=>m(O.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,f.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>void Lt(),disabled:Ce||N||!!b||h===0,"aria-busy":Ce,children:[(0,f.jsx)(gt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),Ce?"Exporting\u2026":"Export CSV (all matching)"]})]}),tt&&(0,f.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:tt})]});return N?(0,f.jsxs)("div",{className:e,children:[at,(0,f.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(O=>(0,f.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,f.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,f.jsx)(ee,{className:"af-h-4 af-w-20"}),(0,f.jsx)(ee,{className:"af-h-4 af-w-16"})]}),(0,f.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-40"})]},O))})]}):b?(0,f.jsxs)("div",{className:e,children:[at,(0,f.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void X(),children:"Retry"})]})]}):h===0&&Ot&&ne===!1&&ce==="open"?A?.blocked?(0,f.jsxs)("div",{className:e,children:[at,(0,f.jsx)(Nn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,f.jsxs)("div",{className:e,children:[at,(0,f.jsx)(Nn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):A&&!A.payments_active?(0,f.jsxs)("div",{className:e,children:[at,(0,f.jsx)(Nn,{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})]}):(0,f.jsxs)("div",{className:e,children:[at,(0,f.jsx)(Nn,{heading:"No invoices yet",body:!A||P?"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."})]}):(0,f.jsxs)("div",{className:e,children:[at,ta.length===0?(0,f.jsx)("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."}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ta.map(O=>(0,f.jsxs)("button",{type:"button",onClick:()=>it(O),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,f.jsx)("span",{className:"af-font-medium",children:gs(O)}),(0,f.jsx)(vs,{invoice:O})]}),(0,f.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:O.customer_name??O.customer_email??"\u2014"}),O.delivery&&(0,f.jsx)("div",{className:"af-mt-1",children:(0,f.jsx)(Sn,{delivery:O.delivery})}),(0,f.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-gap-2 af-items-center af-justify-between af-text-sm",children:[(0,f.jsx)("span",{children:O.collection_method==="charge_automatically"?"Automatic collection":O.due_at?`Due ${la(O.due_at)}`:"Due on receipt"}),(0,f.jsx)("span",{className:"af-font-medium af-tabular-nums",children:j(O.amount_due??O.amount_total,O.currency)})]})]},O.id))}),(0,f.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,f.jsxs)(Fe,{children:[(0,f.jsx)(Me,{children:(0,f.jsxs)(he,{children:[(0,f.jsx)($,{children:"Invoice"}),(0,f.jsx)($,{children:"Created"}),(0,f.jsx)($,{children:"Customer"}),(0,f.jsx)($,{children:"Due"}),(0,f.jsx)($,{className:"af-text-right",children:"Amount"}),(0,f.jsx)($,{children:"Status"}),(0,f.jsx)($,{children:"Delivery"}),(0,f.jsx)($,{className:"af-w-8"})]})}),(0,f.jsx)(Ue,{children:ta.map(O=>(0,f.jsxs)(he,{className:"af-cursor-pointer",onClick:()=>it(O),children:[(0,f.jsx)(V,{className:"af-font-medium",children:(0,f.jsx)("button",{type:"button",className:"af-text-left hover:af-underline focus-visible:af-ring-2 focus-visible:af-ring-ring",onClick:Ke=>{Ke.stopPropagation(),it(O)},"aria-label":`Open invoice ${gs(O)}`,children:gs(O)})}),(0,f.jsx)(V,{children:la(O.created_at)}),(0,f.jsxs)(V,{children:[(0,f.jsx)("div",{children:O.customer_name??"\u2014"}),(0,f.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:O.customer_email})]}),(0,f.jsx)(V,{children:O.collection_method==="charge_automatically"?"Automatic":O.due_at?la(O.due_at):"On receipt"}),(0,f.jsx)(V,{className:"af-text-right af-tabular-nums",children:j(O.amount_due??O.amount_total,O.currency)}),(0,f.jsx)(V,{children:(0,f.jsx)(vs,{invoice:O})}),(0,f.jsx)(V,{children:(0,f.jsx)(Sn,{delivery:O.delivery})}),(0,f.jsx)(V,{children:(0,f.jsx)(gt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},O.id))})]})}),(0,f.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,f.jsxs)("span",{children:[h," invoice",h===1?"":"s"]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,f.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(u-1),disabled:!S,"aria-label":"Previous page",children:(0,f.jsx)(gt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,f.jsxs)("span",{className:"af-tabular-nums",children:[u*l+1,"\u2013",Math.min((u+1)*l,h)]}),(0,f.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(u+1),disabled:!x,"aria-label":"Next page",children:(0,f.jsx)(gt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Nn({heading:e,body:t,action:s}){return(0,f.jsxs)("div",{className:"af-rounded-md af-border af-px-6 af-py-10 af-text-center",children:[(0,f.jsx)(gt.FileText,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":"true"}),(0,f.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:e}),(0,f.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:t}),s&&(0,f.jsx)(_,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label})]})}var Va="af-text-xs af-text-muted-foreground";function oi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _n({invoice:e,onBack:t,refreshKey:s,className:a}){let{api:n}=oe(),i=ke.useRef(null);ke.useEffect(()=>{i.current?.focus()},[e.id]);let[o,v]=ke.useState(!1),[g,y]=ke.useState(null),[r,h]=ke.useState(!1),[N,b]=ke.useState(!1),u=ke.useRef(0),[l,x]=ke.useState(null),[S,R]=ke.useState(!1),[D,F]=ke.useState(0);ke.useEffect(()=>{let m=!1;return R(!1),n.getInvoice(e.id).then(H=>{m||x({source:e,value:H})}).catch(()=>{m||R(!0)}),()=>{m=!0}},[n,e,s,D]);let c=l?.source===e?l.value:e,w=c.collection_method==="charge_automatically";ke.useEffect(()=>(u.current++,y(null),h(!1),b(!1),v(!1),()=>{u.current++}),[n,c,s]);let E=m=>m==null?"\u2014":j(m,c.currency),W=async()=>{if(!(!c.pay_url||!oi()))try{await navigator.clipboard.writeText(c.pay_url),v(!0),setTimeout(()=>v(!1),1500)}catch{}},B=async()=>{if(g){y(null);return}let m=++u.current;b(!1),h(!0);try{let H=await n.getInvoicePreview(c.id);m===u.current&&y(H)}catch{m===u.current&&b(!0)}finally{m===u.current&&h(!1)}},T=c.bill_to,z=T?[T.company,T.name,T.address?.line1,T.address?.line2,[T.address?.city,T.address?.state,T.address?.postal_code].filter(Boolean).join(", "),T.address?.country,T.tax_id?`${T.tax_id.value}`:null,T.po_number?`PO ${T.po_number}`:null,T.service_period?`Service period: ${T.service_period}`:null].filter(m=>!!m&&m.length>0):[];return(0,f.jsxs)("div",{className:a,children:[(0,f.jsxs)("div",{className:"af-mb-4",children:[(0,f.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,f.jsx)(gt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",gs(c)]}),(0,f.jsx)(vs,{invoice:c}),(0,f.jsx)(Sn,{delivery:c.delivery})]}),(0,f.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[c.customer_name??c.customer_email,c.customer_name&&c.customer_email?` \xB7 ${c.customer_email}`:""]})]}),S&&(0,f.jsxs)("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. ",(0,f.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>F(m=>m+1),children:"Retry details"})]}),c.label==="failed"&&(0,f.jsx)("div",{role:"alert",className:"af-mb-4 af-rounded-md af-border af-p-3 af-text-sm",children:"Couldn't finish creating this invoice. Ask in the chat to retry."}),c.label==="creating"&&(0,f.jsx)("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."}),(0,f.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,f.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,f.jsxs)(Fe,{children:[(0,f.jsx)(Me,{children:(0,f.jsxs)(he,{children:[(0,f.jsx)($,{children:"Description"}),(0,f.jsx)($,{className:"af-text-right",children:"Qty"}),(0,f.jsx)($,{className:"af-text-right",children:"Amount"})]})}),(0,f.jsx)(Ue,{children:c.line_items.map((m,H)=>(0,f.jsxs)(he,{children:[(0,f.jsx)(V,{style:{overflowWrap:"anywhere"},children:m.description}),(0,f.jsx)(V,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:m.quantity}),(0,f.jsx)(V,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:E(m.amount)})]},H))})]}),(0,f.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,f.jsx)(Ka,{label:"Subtotal",value:E(c.amount_subtotal)}),(c.discount_total??0)>0&&(0,f.jsx)(Ka,{label:"Discount",value:`-${E(c.discount_total)}`}),c.tax_total>0&&(0,f.jsx)(Ka,{label:c.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:E(c.tax_total)}),(0,f.jsx)(Ka,{label:"Total",value:E(c.amount_total),strong:!0}),c.credit_applied>0&&(0,f.jsx)(Ka,{label:"Credit applied",value:`-${E(c.credit_applied)}`}),c.amount_due!==null&&c.amount_due!==c.amount_total&&(0,f.jsx)(Ka,{label:"Amount due",value:E(c.amount_due),strong:!0}),c.amount_paid!==null&&c.amount_paid>0&&(0,f.jsx)(Ka,{label:"Amount paid",value:E(c.amount_paid)}),c.amount_refunded>0&&(0,f.jsx)(Ka,{label:"Refunded",value:E(c.amount_refunded)})]}),c.credit_notes?.length>0&&(0,f.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,f.jsx)("div",{className:Va,children:"Credit notes"}),c.credit_notes.map(m=>(0,f.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,f.jsxs)("span",{className:"af-text-muted-foreground",children:[la(m.created_at)," \xB7 ",m.origin==="dashboard"?"issued in Stripe":"refund",m.stripe_credit_note_id?"":" \xB7 being created"]}),(0,f.jsxs)("span",{className:"af-tabular-nums",children:["-",j(m.amount,m.currency)]})]},m.id))]})]}),(c.note||c.footer)&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[c.note&&(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:Va,children:"Note"}),(0,f.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:c.note})]}),c.footer&&(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:Va,children:"Footer"}),(0,f.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:c.footer})]})]}),g&&!w&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,f.jsxs)("div",{className:Y(Va,"af-break-words"),children:["Email preview \u2014 ",g.subject]}),(0,f.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,f.jsx)("iframe",{title:"Invoice email preview",srcDoc:g.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,f.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,f.jsx)(oa,{label:"Created",value:la(c.created_at)}),(0,f.jsx)(oa,{label:"Due",value:c.collection_method==="charge_automatically"?"Managed in Stripe":c.due_at?la(c.due_at):"On receipt"}),c.paid_at&&(0,f.jsx)(oa,{label:"Paid",value:la(c.paid_at)}),c.payment_method&&(0,f.jsx)(oa,{label:"Paid by",value:c.paid_out_of_band?`${c.payment_method} (recorded outside Stripe)`:c.payment_method}),c.payment_state!=="none"&&(0,f.jsx)(oa,{label:"Payment",value:c.payment_state==="processing"?"Processing":c.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),c.delivery&&(0,f.jsx)(oa,{label:"Delivery",value:`${Zn[c.delivery.state]} \xB7 ${c.delivery.recipient}`}),c.marked_uncollectible_at&&(0,f.jsx)(oa,{label:"Written off",value:la(c.marked_uncollectible_at)}),c.correction_reason&&(0,f.jsx)(oa,{label:"Correction",value:c.correction_reason}),c.replaced_by_order_id&&(0,f.jsx)(oa,{label:"Replaced by",value:c.replaced_by_order_id}),c.collection_method==="charge_automatically"?(0,f.jsx)(oa,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):c.retainer_id&&(0,f.jsx)(oa,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),c.replaces_order_id&&(0,f.jsx)(oa,{label:"Replaces",value:c.replaces_order_id})]}),(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,f.jsx)("div",{className:Va,children:"Reminders"}),w?(0,f.jsx)("div",{children:"View automatic payment reminders in Stripe."}):c.reminders.disabled?(0,f.jsx)("div",{children:"Off for this invoice."}):c.reminders.paused_until?(0,f.jsxs)("div",{children:["Paused until ",la(c.reminders.paused_until),"."]}):c.reminders.next_at?(0,f.jsxs)("div",{children:["Next on ",la(c.reminders.next_at),"."]}):c.reminders.final_sent_at?(0,f.jsxs)("div",{children:["Final reminder sent ",la(c.reminders.final_sent_at),"."]}):(0,f.jsx)("div",{children:"None scheduled."}),!w&&(0,f.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",c.reminders.schedule.length===0?"none":c.reminders.schedule.map(m=>m<0?`${-m}d before`:m===0?"due day":`${m}d after`).join(", ")]})]}),c.communications&&c.communications.length>0&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,f.jsx)("div",{className:Va,children:"Email delivery history"}),c.communications.map(m=>(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,f.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[qo[m.kind]??m.kind,m.kind==="reminder"&&m.slot!==null?` #${m.slot}`:"",(0,f.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",m.recipient]})]}),(0,f.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Zn[m.state]??m.state," \xB7 ",la(m.state_at??m.created_at)]})]},m.id))]}),z.length>0&&(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,f.jsx)("div",{className:Va,children:"Bill to"}),z.map((m,H)=>(0,f.jsx)("div",{className:"af-break-words",children:m},H))]}),(0,f.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[c.pay_url&&(0,f.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void W(),disabled:!oi(),children:[(0,f.jsx)(gt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":w?"Copy invoice link":"Copy pay link"]}),c.pdf_url&&(0,f.jsx)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,f.jsxs)("a",{href:c.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,f.jsx)(gt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!w&&(0,f.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void B(),disabled:r,children:[r?(0,f.jsx)(gt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,f.jsx)(gt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),g?"Hide email preview":N?"Retry email preview":"Show email preview"]}),N&&!w&&(0,f.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),c.pay_url&&(0,f.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:c.pay_url}),(0,f.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:w?"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 oa({label:e,value:t}){return(0,f.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,f.jsx)("span",{className:Y(Va,"af-shrink-0"),children:e}),(0,f.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Ka({label:e,value:t,strong:s}){return(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,f.jsx)("dt",{className:Y(Va,s&&"af-font-medium af-text-foreground"),children:e}),(0,f.jsx)("dd",{className:Y("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}var ui=require("lucide-react");var De=require("react/jsx-runtime"),Ko={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},ci={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Jo(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 di(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>ci[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>ci[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Ko[e.status]}function fi(e){let t=e.interval==="year"?"every year":"every month";return`${j(e.amount,e.currency)} ${t}`}function Yo(e){return e.status==="canceled"?`Ended ${Rn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Rn(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 ${Rn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Rn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Rn(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),s=new Date(t);return Number.isNaN(s.getTime())?e.slice(0,10):s.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Pn({retainer:e,className:t}){return(0,De.jsx)(Q,{variant:Jo(e.status),className:Y("af-max-w-full af-whitespace-normal af-break-words",t),children:di(e)})}function is({retainers:e,isLoading:t,error:s,onRetry:a,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:v=0,isLoadingMore:g=!1,onLoadMore:y,includeEnded:r=!1,onIncludeEndedChange:h,className:N}){let b=!!h;if(!t&&!s&&e.length===0&&!(b&&(r||v>0)))return null;let u=o!==void 0?Math.max(0,o-e.length):0;return(0,De.jsxs)("section",{className:Y("af-mb-6",N),"aria-label":"Recurring invoices",children:[(0,De.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,De.jsx)(ui.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,De.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,De.jsx)("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."}),b&&(0,De.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":r,onClick:()=>h?.(!r),children:r?"Hide ended recurring invoices":v>0&&e.length===0?`Show ended recurring invoices (${v})`:"Show ended recurring invoices"})]}),s?(0,De.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your recurring invoices."," ",(0,De.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:a,children:"Retry"})]}):t?(0,De.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(l=>(0,De.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,De.jsx)(ee,{className:"af-h-4 af-w-48"}),(0,De.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-32"})]},l))}):e.length===0?(0,De.jsx)("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."}):(0,De.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(l=>{let x=i===l.id;return(0,De.jsxs)("li",{className:Y("af-rounded-md af-border af-p-3",x&&"af-border-primary af-bg-muted/40"),children:[(0,De.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,De.jsxs)("div",{className:"af-min-w-0",children:[(0,De.jsx)("div",{className:"af-truncate af-font-medium",children:l.customer_name??l.customer_email??"\u2014"}),(0,De.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:l.description})]}),(0,De.jsx)(Pn,{retainer:l})]}),l.collection_method==="charge_automatically"?(0,De.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,De.jsx)(Q,{variant:"secondary",children:"Managed in Stripe"}),(0,De.jsx)("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."})]}):(0,De.jsx)("div",{className:"af-mt-2 af-text-sm",children:fi(l)}),(0,De.jsxs)("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:[(0,De.jsxs)("span",{children:[Yo(l)," \xB7 ",l.cycles.count===0?"no invoices yet":`${l.cycles.paid} paid${l.cycles.open>0?`, ${l.cycles.open} open`:""}`]}),l.cycles.count>0&&(0,De.jsx)(_,{type:"button",variant:x?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":x,children:x?"Showing invoices":"View invoices"})]}),l.status==="failed"&&l.operation?.last_error&&(0,De.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",l.operation.last_error,". Ask in the chat to try again."]})]},l.id)})}),!t&&!s&&u>0&&y&&(0,De.jsx)("div",{className:"af-mt-2",children:(0,De.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:y,disabled:g,children:g?"Loading\u2026":`Load more (${u} more)`})})]})}var mi=de(require("react"),1),Qt=require("lucide-react");var Ne=require("react/jsx-runtime");function Ws({onConnectStripe:e,onUpgradePlan:t,className:s}){let{status:a,isLoading:n,error:i,refetch:o}=Ma(),[v,g]=mi.useState(!1),y=async()=>{g(!0);try{await o()}finally{g(!1)}};return n&&!a?(0,Ne.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ne.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!a?(0,Ne.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Ne.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):a.status==="active"?(0,Ne.jsx)("div",{className:s,children:(0,Ne.jsxs)("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:[(0,Ne.jsx)(Qt.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Ne.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",a.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Ne.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ne.jsx)(Qt.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Ne.jsx)("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?(0,Ne.jsxs)(_,{onClick:e,children:[(0,Ne.jsx)(Qt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),a.reason==="needs_paid_plan"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Ne.jsx)(Qt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your products are saved as drafts. Upgrade to a paid plan to start accepting payments on your site."})]})]}),t?(0,Ne.jsx)(_,{onClick:t,children:"Upgrade plan"}):(0,Ne.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),a.reason==="account_disabled"&&(0,Ne.jsxs)("div",{className:"af-space-y-3",children:[(0,Ne.jsxs)("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:[(0,Ne.jsx)(Qt.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Ne.jsxs)("div",{children:[(0,Ne.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,Ne.jsx)("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."}):(0,Ne.jsx)("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."})]})]}),(0,Ne.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,Ne.jsxs)(_,{onClick:e,children:[(0,Ne.jsx)(Qt.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Ne.jsxs)(_,{variant:"outline",onClick:y,disabled:v,children:[v?(0,Ne.jsx)(Qt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Ne.jsx)(Qt.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var It=de(require("react"),1);function Xn(e,t,s){return e.map(a=>a.id===t?{...a,...s}:a)}function os({includeStats:e=!1,refreshKey:t}={}){let{api:s}=oe(),[a,n]=It.useState([]),[i,o]=It.useState(!0),[v,g]=It.useState(null),y=It.useRef(0),r=It.useCallback(async()=>{let x=++y.current;try{o(!0),g(null);let S=await s.getProducts(e?{include:"stats"}:{});if(x!==y.current)return;n(S)}catch(S){if(x!==y.current)return;g(S instanceof Error?S:new Error("Failed to fetch products"))}finally{x===y.current&&o(!1)}},[s,e,t]);It.useEffect(()=>{r()},[r]);let h=It.useCallback(async x=>{let S=await s.createProduct(x);return n(R=>[S,...R]),S},[s]),N=It.useCallback(async(x,S)=>{let R=await s.updateProduct(x,S);return n(D=>Xn(D,x,R)),R},[s]),b=It.useCallback(async x=>{await s.deleteProduct(x),n(S=>S.filter(R=>R.id!==x))},[s]),u=It.useCallback(async(x,S)=>{let R=await s.attachProductFile(x,S);return n(D=>Xn(D,x,R)),R},[s]),l=It.useCallback(async(x,S)=>{let R=await s.attachProductFileFromUrl(x,S);return n(D=>Xn(D,x,R)),R},[s]);return{products:a,isLoading:i,error:v,refetch:r,createProduct:h,updateProduct:N,deleteProduct:b,attachProductFile:u,attachProductFileFromUrl:l}}var At=de(require("react"),1);var pi=["creating","active","paused","canceling"],Zo=["canceled","failed"];function ls({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:a}=oe(),[n,i]=At.useState([]),[o,v]=At.useState(0),[g,y]=At.useState(0),[r,h]=At.useState(!0),[N,b]=At.useState(!1),[u,l]=At.useState(null),[x,S]=At.useState(t),R=At.useRef(0),D=At.useCallback(async()=>{let c=++R.current;h(!0),b(!1),l(null);try{let w=await a.getRetainers({statuses:x?void 0:pi,limit:s,offset:0});if(c!==R.current)return;if(i(w.retainers),v(w.total),!x&&w.total===0){let E=await a.getRetainers({statuses:Zo,limit:1,offset:0});if(c!==R.current)return;y(E.total)}else y(0)}catch(w){if(c!==R.current)return;l(w instanceof Error?w:new Error("Failed to fetch retainers"))}finally{c===R.current&&h(!1)}},[a,x,s]);At.useEffect(()=>{D()},[D,e]);let F=At.useCallback(async()=>{if(r||N||n.length>=o)return;let c=R.current;b(!0);try{let w=await a.getRetainers({statuses:x?void 0:pi,limit:s,offset:n.length});if(c!==R.current)return;i(E=>{let W=new Set(E.map(B=>B.id));return[...E,...w.retainers.filter(B=>!W.has(B.id))]}),v(w.total)}catch(w){if(c!==R.current)return;l(w instanceof Error?w:new Error("Failed to fetch retainers"))}finally{c===R.current&&b(!1)}},[a,x,s,r,N,n.length,o]);return{retainers:n,total:o,endedTotal:g,hasMore:n.length<o,isLoading:r,isLoadingMore:N,error:u,includeEnded:x,setIncludeEnded:S,loadMore:F,refetch:D}}var ye=require("react/jsx-runtime");function er({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:a,onUpgradePlan:n}){let[i,o]=bs.useState(t),[v,g]=bs.useState("list"),[y,r]=bs.useState(null),h=os(),{status:N,error:b}=Ma(),u=N?.currency,l=D=>{r(D),g("edit")},x=()=>{r(null),g("create")},S=()=>{g("list"),r(null)},R=D=>{r(D),g("edit")};return(0,ye.jsxs)("div",{className:e,children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,ye.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,ye.jsxs)(un,{value:i,onValueChange:D=>o(D),children:[(0,ye.jsxs)(Ss,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,ye.jsxs)(da,{value:"products",className:"af-gap-2",children:[(0,ye.jsx)(ca.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,ye.jsxs)(da,{value:"orders",className:"af-gap-2",children:[(0,ye.jsx)(ca.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,ye.jsxs)(da,{value:"invoices",className:"af-gap-2",children:[(0,ye.jsx)(ca.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,ye.jsxs)(da,{value:"customers",className:"af-gap-2",children:[(0,ye.jsx)(ca.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,ye.jsx)(da,{value:"promos",children:"Promo codes"}),(0,ye.jsxs)(da,{value:"setup",className:"af-gap-2",children:[(0,ye.jsx)(ca.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,ye.jsx)(fa,{value:"products",children:v==="list"?(0,ye.jsx)(Ms,{productsState:h,onSelectProduct:l,onCreateProduct:x}):(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsxs)(_,{variant:"ghost",size:"sm",onClick:S,className:"af-mb-2 af--ml-2",children:[(0,ye.jsx)(ca.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,ye.jsx)("h3",{className:"af-text-lg af-font-semibold",children:v==="create"?"New Product":y?.name})]}),v==="create"&&!u?(0,ye.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:b?(0,ye.jsxs)("div",{className:"af-text-destructive",children:["Error: ",b.message]}):(0,ye.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,ye.jsx)($s,{productsState:h,product:v==="edit"?y:null,currency:u??"usd",onSaved:R},v==="edit"?y?.id??"edit":"new")]})}),(0,ye.jsx)(fa,{value:"orders",children:(0,ye.jsx)(as,{onRefund:a})}),(0,ye.jsx)(fa,{value:"invoices",children:(0,ye.jsx)(Qo,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:N?.reason==="needs_paid_plan"})}),(0,ye.jsx)(fa,{value:"customers",children:(0,ye.jsx)(Gs,{})}),(0,ye.jsx)(fa,{value:"promos",children:(0,ye.jsx)(Xa,{})}),(0,ye.jsx)(fa,{value:"setup",children:(0,ye.jsx)(Ws,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Qo({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let a=ls(),[n,i]=bs.useState(null),[o,v]=bs.useState(!1);return(0,ye.jsxs)(ye.Fragment,{children:[!o&&(0,ye.jsx)(is,{retainers:a.retainers,isLoading:a.isLoading,error:a.error,onRetry:()=>void a.refetch(),activeRetainerId:n?.id??null,onShowCycles:g=>i(y=>y?.id===g.id?null:g),total:a.total,endedTotal:a.endedTotal,isLoadingMore:a.isLoadingMore,onLoadMore:()=>void a.loadMore(),includeEnded:a.includeEnded,onIncludeEndedChange:a.setIncludeEnded}),(0,ye.jsx)(rs,{onDetailOpenChange:v,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s,retainerFilter:n?{id:n.id,label:`${n.customer_name??n.customer_email??"Recurring invoices"} \u2014 ${n.description}`}:null,onClearRetainerFilter:()=>i(null)})]})}var vi=de(require("react"),1);var Ia=de(require("react"),1);function Ks({refreshKey:e}={}){let{api:t}=oe(),[s,a]=Ia.useState(null),[n,i]=Ia.useState(!0),[o,v]=Ia.useState(null),g=Ia.useRef(0),y=Ia.useCallback(async()=>{let r=++g.current;try{i(!0),v(null);let h=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==g.current)return;a(h)}catch(h){if(r!==g.current)return;v(h instanceof Error?h:new Error("Failed to fetch summary"))}finally{r===g.current&&i(!1)}},[t,e]);return Ia.useEffect(()=>{y()},[y]),{summary:s,isLoading:n,error:o,refetch:y}}var He=require("react/jsx-runtime");function gi(e,t){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(a=>`+ ${j(a.gross,a.currency)} in ${a.currency.toUpperCase()}`)}:{headline:j(0,t),extra:[]}}function tr({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:a,onBackToWebsite:n,className:i}){let{summary:o,isLoading:v,error:g,refetch:y}=Ks({refreshKey:e}),[r,h]=vi.useState(!1),N=(0,He.jsx)("div",{className:"af-mb-6",children:g&&!o?(0,He.jsx)(Yt,{message:"Couldn't load your revenue summary.",onRetry:()=>y()}):(0,He.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:v||!o?(0,He.jsxs)(He.Fragment,{children:[(0,He.jsx)(Xe,{label:"This week",children:(0,He.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,He.jsx)(Xe,{label:"Today",children:(0,He.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,He.jsx)(Xe,{label:"Needs attention",children:(0,He.jsx)(ee,{className:"af-h-6 af-w-10"})})]}):(0,He.jsx)(He.Fragment,{children:(()=>{let b=gi(o.revenue.d7,o.currency),u=gi(o.revenue.today,o.currency);return(0,He.jsxs)(He.Fragment,{children:[(0,He.jsx)(Xe,{label:"This week",detail:b.extra.length>0?(0,He.jsx)("div",{children:b.extra.map(l=>(0,He.jsx)("div",{children:l},l))}):void 0,children:b.headline}),(0,He.jsx)(Xe,{label:"Today",detail:u.extra.length>0?(0,He.jsx)("div",{children:u.extra.map(l=>(0,He.jsx)("div",{children:l},l))}):void 0,children:u.headline}),(0,He.jsx)(Xe,{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(0,He.jsxs)(Nt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[N,(0,He.jsx)(as,{refreshKey:e,initialOrderId:t,onDetailOpenChange:h,showFulfillment:!0,onRefund:s?a:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Da=de(require("react"),1),ys=require("lucide-react");var Aa=de(require("react"),1),An=require("lucide-react");var _t=require("react/jsx-runtime"),bi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Ja="af-text-xs af-text-muted-foreground",Cn="af-text-sm af-font-medium af-tabular-nums",Xo=3;function el(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let g=e.min_amount??t?.min_amount??null,y=e.max_amount??t?.max_amount??null;return g!==null&&y!==null?{text:`Buyer chooses (${j(g,s)} \u2013 ${j(y,s)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let n=t?.min_amount??e.unit_amount,i=t?.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)}`,v=t?.compare_at_amount??null;return{text:o,compareAt:v!==null&&v>i?j(v,s):null}}function Tn({product:e,className:t}){let s=el(e);return(0,_t.jsxs)("div",{className:t,children:[(0,_t.jsx)("span",{className:Cn,children:s.text}),s.compareAt&&(0,_t.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function kn({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,_t.jsx)(Q,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,_t.jsxs)(Q,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,_t.jsx)(Q,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,_t.jsxs)(Q,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,_t.jsx)(Q,{variant:"warning",children:"Low stock"}):null}function En(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function In(e){return e.map(t=>j(t.amount,t.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 t=e.inventory;if(!t||!t.tracked)return(0,_t.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?(0,_t.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,_t.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,_t.jsx)(Q,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,_t.jsx)(Q,{variant:"destructive",children:"Out of stock"}):(0,_t.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,_t.jsx)("span",{className:"af-tabular-nums",children:s}),s<=Xo&&(0,_t.jsx)(Q,{variant:"warning",children:"Low"})]})}var J=require("react/jsx-runtime");function Js({title:e,children:t,className:s}){return(0,J.jsxs)("section",{className:Y("af-rounded-lg af-border af-p-4",s),children:[(0,J.jsx)("h4",{className:bi,children:e}),(0,J.jsx)("div",{className:"af-mt-3",children:t})]})}function xi({src:e,className:t}){let[s,a]=Aa.useState(!1);return Aa.useEffect(()=>a(!1),[e]),!e||s?(0,J.jsx)("div",{"aria-hidden":"true",className:Y("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,J.jsx)(An.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,J.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>a(!0),className:Y("af-object-cover",t)})}function wi({product:e,showStats:t=!1,onBack:s}){let{api:a}=oe(),[n,i]=Aa.useState(null),[o,v]=Aa.useState(!0),[g,y]=Aa.useState(null),[r,h]=Aa.useState(0),[N,b]=Aa.useState(0);Aa.useEffect(()=>{let c=!1;return v(!0),y(null),a.getProduct(e.id).then(w=>{c||i(w)}).catch(w=>{c||y(w instanceof Error?w:new Error("Failed to load product"))}).finally(()=>{c||v(!1)}),()=>{c=!0}},[a,e.id,r]);let u=n?{...e,...n}:e,l=u.images.length>0?u.images:e.images,x=l[N]??l[0],S=En(u),R=t?u.stats:void 0,D=n?.variants??[],F=D.length>1;return(0,J.jsxs)("div",{children:[(0,J.jsxs)("div",{className:"af-mb-6",children:[(0,J.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,J.jsx)(An.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,J.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,J.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:u.name}),(0,J.jsx)(Q,{variant:u.active?"success":"secondary",children:u.active?"Active":"Draft"}),(0,J.jsx)(kn,{product:u})]}),(0,J.jsx)(Tn,{product:u,className:"af-mt-1"}),!u.active&&(0,J.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Drafts are hidden from your website and can't be bought."})]}),(0,J.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,J.jsxs)("div",{className:"af-space-y-2",children:[(0,J.jsx)(xi,{src:x,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&(0,J.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((c,w)=>(0,J.jsx)("button",{type:"button",onClick:()=>b(w),"aria-label":`Show photo ${w+1} of ${l.length}`,"aria-pressed":w===N,className:Y("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",w===N?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,J.jsx)(xi,{src:c,className:"af-h-12 af-w-12 af-rounded-md"})},`${c}-${w}`))})]}),(0,J.jsxs)("div",{className:"af-space-y-6",children:[u.description&&(0,J.jsx)(Js,{title:"Description",children:(0,J.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:u.description})}),o?(0,J.jsxs)(Js,{title:"Variants",children:[(0,J.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(c=>(0,J.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,J.jsx)(ee,{className:"af-h-4 af-w-28"}),(0,J.jsx)(ee,{className:"af-h-4 af-w-20"}),(0,J.jsx)(ee,{className:"af-h-4 af-w-16"})]},c))}),(0,J.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):g?(0,J.jsx)(Yt,{message:"Couldn't load this product's variants.",onRetry:()=>h(c=>c+1)}):F?(0,J.jsx)(Js,{title:`Variants \xB7 ${D.length}`,children:(0,J.jsx)("div",{className:"af-overflow-x-auto",children:(0,J.jsxs)(Fe,{children:[(0,J.jsx)(Me,{children:(0,J.jsxs)(he,{children:[(0,J.jsx)($,{children:"Variant"}),(0,J.jsx)($,{children:"SKU"}),(0,J.jsx)($,{className:"af-text-right",children:"Price"}),(0,J.jsx)($,{children:"Stock"})]})}),(0,J.jsx)(Ue,{children:D.map(c=>(0,J.jsxs)(he,{children:[(0,J.jsxs)(V,{className:"af-font-medium",children:[c.title||c.option_values.map(w=>w.value).join(" / ")||"\u2014",!c.active&&(0,J.jsx)(Q,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,J.jsx)(V,{className:"af-text-muted-foreground",children:c.sku?(0,J.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:c.sku}):"\u2014"}),(0,J.jsxs)(V,{className:"af-whitespace-nowrap af-text-right",children:[(0,J.jsx)("div",{className:Cn,children:yi(c)}),c.compare_at_amount!==null&&c.unit_amount!==null&&c.compare_at_amount>c.unit_amount&&(0,J.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:j(c.compare_at_amount,c.currency)})]}),(0,J.jsx)(V,{className:"af-text-sm",children:(0,J.jsx)(hi,{variant:c})})]},c.id))})]})})}):null,(0,J.jsx)(Js,{title:"Details",children:(0,J.jsxs)("dl",{className:"af-space-y-2",children:[(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Delivery"}),(0,J.jsx)("dd",{className:"af-text-sm",children:S==="Digital download"?u.fulfillment.filename??"Digital download":S??"Nothing to deliver"})]}),u.fulfillment.type==="redirect"&&u.fulfillment.url&&(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Sends buyers to"}),(0,J.jsx)("dd",{className:"af-break-all af-text-sm",children:u.fulfillment.url})]}),(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Shipping address"}),(0,J.jsx)("dd",{className:"af-text-sm",children:u.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Most one buyer can order"}),(0,J.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:u.max_quantity})]})]})}),R&&(0,J.jsx)(Js,{title:"Last 30 days",children:(0,J.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Units sold"}),(0,J.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.units_sold})]}),(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Orders"}),(0,J.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:R.orders})]}),(0,J.jsxs)("div",{children:[(0,J.jsx)("dt",{className:Ja,children:"Gross"}),(0,J.jsx)("dd",{className:Cn,children:R.gross.length>0?In(R.gross):"\u2014"})]})]})}),(0,J.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var U=require("react/jsx-runtime"),tl={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},al=["all","active","draft","low_stock","out_of_stock"];function Ni(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function Si(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function sl(e){return e.inventory?.out_of_stock??!1}function nl(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Si(e);case"out_of_stock":return sl(e);default:return!0}}function rl({product:e,showStats:t,onOpen:s}){let a=e.images[0],n=t?e.stats:void 0,i=En(e),o=e.variant_count??0;return(0,U.jsxs)("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:[a?(0,U.jsx)("img",{src:a,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,U.jsx)("div",{"aria-hidden":"true",className:"af-flex af-h-36 af-w-full af-items-center af-justify-center af-bg-muted",children:(0,U.jsx)(ys.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,U.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,U.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,U.jsxs)("div",{className:"af-min-w-0",children:[(0,U.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,U.jsx)(Tn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,U.jsx)(Q,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,U.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,U.jsx)(kn,{product:e}),o>1&&(0,U.jsxs)(Q,{variant:"outline",children:[o," variants"]}),i&&(0,U.jsx)(Q,{variant:"outline",children:i})]}),n&&(0,U.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${In(n.gross)}`:""," ",(0,U.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function il(){return(0,U.jsx)("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=>(0,U.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,U.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,U.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,U.jsx)(ee,{className:"af-w-32"}),(0,U.jsx)(ee,{className:"af-w-16"}),(0,U.jsx)(ee,{className:"af-h-5 af-w-24"})]})]},e))})}function ar({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:a}){let{products:n,isLoading:i,error:o,refetch:v}=os({includeStats:t,refreshKey:e}),[g,y]=Da.useState(!1),[r,h]=Da.useState(null),[N,b]=Da.useState("all"),[u,l]=Da.useState(""),[x,S]=Da.useState("newest"),R=Da.useMemo(()=>{if(!t)return null;let m=null;for(let H of n)!H.stats||H.stats.units_sold===0||(!m||H.stats.units_sold>(m.stats?.units_sold??0))&&(m=H);return m},[n,t]),D=Da.useMemo(()=>n.filter(Si).length,[n]),F=u.trim().toLowerCase(),c=Da.useMemo(()=>{let H=[...n.filter(re=>nl(re,N)&&(!F||re.name.toLowerCase().includes(F)))];return x==="name"?H.sort((re,X)=>re.name.localeCompare(X.name)):x==="best_selling"?H.sort((re,X)=>(X.stats?.units_sold??0)-(re.stats?.units_sold??0)):H.sort((re,X)=>Ni(X.created_at)-Ni(re.created_at)),H},[n,N,F,x]),w=N!=="all"||!!F,E=()=>{b("all"),l("")},W=i||o!==null&&n.length===0,B=(0,U.jsx)("div",{className:"af-mb-6",children:(0,U.jsx)("div",{className:Y("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:W?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Xe,{label:"Products",children:(0,U.jsx)(ee,{className:"af-h-6 af-w-10"})}),t?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Xe,{label:"Best seller",children:(0,U.jsx)(ee,{className:"af-h-6 af-w-28"})}),(0,U.jsx)(Xe,{label:"Low stock",children:(0,U.jsx)(ee,{className:"af-h-6 af-w-10"})})]}):(0,U.jsx)(Xe,{label:"Active",children:(0,U.jsx)(ee,{className:"af-h-6 af-w-10"})})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Xe,{label:"Products",children:n.length}),t?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Xe,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:R?`${R.stats?.units_sold??0} sold, last 30 days`:void 0,children:R?(0,U.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:R.name}):(0,U.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,U.jsx)(Xe,{label:"Low stock",children:D})]}):(0,U.jsx)(Xe,{label:"Active",children:n.filter(m=>m.active).length})]})})}),T=(0,U.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,U.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,U.jsx)("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:al.map(m=>(0,U.jsx)("button",{type:"button","aria-pressed":N===m,onClick:()=>b(m),className:Y("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",N===m?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:tl[m]},m))}),(0,U.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,U.jsx)(ys.Search,{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"}),(0,U.jsx)(we,{type:"text",value:u,onChange:m=>l(m.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,U.jsxs)(aa,{value:x,onValueChange:m=>S(m),children:[(0,U.jsx)(qt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,U.jsx)(sa,{})}),(0,U.jsxs)(jt,{children:[(0,U.jsx)(je,{value:"newest",children:"Newest"}),(0,U.jsx)(je,{value:"name",children:"Name A\u2013Z"}),t&&(0,U.jsx)(je,{value:"best_selling",children:"Best selling"})]})]}),w&&(0,U.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:E,children:"Clear filters"})]}),i&&n.length===0?(0,U.jsx)(ee,{className:"af-h-4 af-w-28"}):(0,U.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:w?`${c.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${D>0?` \xB7 ${D} low stock`:""}`})]}),z;return r?z=(0,U.jsx)(wi,{product:r,showStats:t,onBack:()=>{h(null),v()}},r.id):i&&n.length===0?z=(0,U.jsxs)(U.Fragment,{children:[T,(0,U.jsx)(il,{}),(0,U.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?z=(0,U.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,U.jsx)(Yt,{message:"Couldn't load your products.",onRetry:()=>v()})}):n.length===0?z=(0,U.jsxs)(ka,{icon:(0,U.jsx)(ys.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,U.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):z=(0,U.jsxs)(U.Fragment,{children:[T,o&&(0,U.jsx)("div",{className:"af-mb-4",children:(0,U.jsx)(Yt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>v()})}),c.length===0?(0,U.jsxs)(ka,{children:["No products match these filters.",(0,U.jsx)("br",{}),(0,U.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:E,children:"Show all products"})]}):(0,U.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:c.map(m=>(0,U.jsx)(rl,{product:m,showStats:t,onOpen:()=>h(m)},m.id))})]}),(0,U.jsx)(Nt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:a,children:g?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(_,{variant:"ghost",onClick:()=>y(!1),children:"Back to products"}),(0,U.jsx)(Xa,{})]}):(0,U.jsxs)(U.Fragment,{children:[!r&&(0,U.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,U.jsx)(_,{variant:"outline",onClick:()=>y(!0),children:"Promo codes"})}),!r&&B,z]})})}var ha=de(require("react"),1),ut=require("lucide-react");var Xt=de(require("react"),1);function Ys({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=oe(),[a,n]=Xt.useState([]),[i,o]=Xt.useState(!0),[v,g]=Xt.useState(null),[y,r]=Xt.useState(0),[h]=Xt.useState(e),[N,b]=Xt.useState(""),u=Xt.useRef(0),l=Xt.useCallback(async()=>{let x=++u.current;try{o(!0),g(null);let S={limit:h,offset:y*h};N.trim()&&(S.q=N.trim());let R=await s.getPeople(S);if(x!==u.current)return;n(R.people)}catch(S){if(x!==u.current)return;g(S instanceof Error?S:new Error("Failed to fetch people"))}finally{x===u.current&&o(!1)}},[s,y,h,N,t]);return Xt.useEffect(()=>{l()},[l]),{people:a,isLoading:i,error:v,page:y,pageSize:h,hasNextPage:a.length===h,hasPreviousPage:y>0,setPage:r,q:N,setQ:x=>{b(x),r(0)},refetch:l}}var La=de(require("react"),1);function Zs(e,{refreshKey:t}={}){let{api:s}=oe(),[a,n]=La.useState(null),[i,o]=La.useState(e!==null),[v,g]=La.useState(null),y=La.useRef(0),r=La.useCallback(async()=>{if(e===null){n(null),o(!1),g(null);return}let h=++y.current;try{o(!0),g(null);let N=await s.getPerson(e);if(h!==y.current)return;n(N)}catch(N){if(h!==y.current)return;g(N instanceof Error?N:new Error("Failed to fetch person"))}finally{h===y.current&&o(!1)}},[s,e,t]);return La.useEffect(()=>{r()},[r]),{person:a,isLoading:i,error:v,refetch:r}}var p=require("react/jsx-runtime"),sr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ol="af-text-xs af-text-muted-foreground";function hs(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function nr(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function ll(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function cl({value:e,label:t}){let[s,a]=ha.useState(!1);return ll()?(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[s?(0,p.jsx)(ut.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,p.jsx)(ut.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function _i(e){return(0,p.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,p.jsxs)(Q,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,p.jsx)(Q,{variant:"secondary",children:"Contact form"})]})}function Ri(e){return e.name?e.name:e.email?e.email:(0,p.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var ul=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,dl=40;function fl(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),a=t.find(([n,i])=>ul.test(n)&&typeof i=="string"&&i.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=dl).sort((n,i)=>String(i[1]).trim().length-String(n[1]).trim().length)[0];return a?{message:String(a[1]),rest:t.filter(([n])=>n!==a[0])}:{message:null,rest:t}}function ml(e){return e.replace(/_/g," ")}function pl(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function gl({data:e}){let{message:t,rest:s}=fl(e);return t===null&&s.length===0?(0,p.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,p.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,p.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&(0,p.jsx)("dl",{className:"af-space-y-1",children:s.map(([a,n])=>(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,p.jsx)("dt",{className:Y(ol,"af-w-28 af-shrink-0 af-capitalize"),children:ml(a)}),(0,p.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:pl(n)})]},a))})]})}function Pi({formName:e,createdAt:t,data:s}){return(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,p.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)(Q,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,p.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,p.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:hs(t)})]}),(0,p.jsx)(gl,{data:s})]})}function vl(e){return e.charged_total??e.amount_total}function bl({email:e,refreshKey:t,onBack:s}){let{person:a,isLoading:n,error:i,refetch:o}=Zs(e,{refreshKey:t}),v=nr(e,a?.submissions[0]?.form_name);return(0,p.jsxs)("div",{children:[(0,p.jsxs)("div",{className:"af-mb-6",children:[(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,p.jsx)(ut.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,p.jsxs)("div",{className:"af-min-w-0",children:[n?(0,p.jsx)(ee,{className:"af-h-7 af-w-48"}):(0,p.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:a?.name||e}),(0,p.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,p.jsx)(cl,{value:e,label:"Copy email address"})]})]}),(0,p.jsx)(_,{asChild:!0,children:(0,p.jsxs)("a",{href:v,children:[(0,p.jsx)(ut.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,p.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(g=>(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,p.jsx)(ee,{className:"af-w-40"}),(0,p.jsx)(ee,{className:"af-mt-2 af-w-64"})]},g)),(0,p.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!a?(0,p.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,p.jsx)(Yt,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,p.jsxs)("div",{className:"af-space-y-6",children:[a.customer&&(0,p.jsxs)("div",{children:[(0,p.jsx)("h4",{className:Y(sr,"af-mb-3"),children:"Customer"}),(0,p.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[a.customer.name&&(0,p.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,p.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,p.jsx)("dd",{children:a.customer.name})]}),a.customer.phone&&(0,p.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,p.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,p.jsx)("dd",{children:a.customer.phone})]}),(0,p.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,p.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,p.jsx)("dd",{children:hs(a.customer.created_at)})]})]})]}),a.orders.length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)("h4",{className:Y(sr,"af-mb-3"),children:"Purchases"}),(0,p.jsx)("div",{className:"af-overflow-x-auto",children:(0,p.jsxs)(Fe,{children:[(0,p.jsx)(Me,{children:(0,p.jsxs)(he,{children:[(0,p.jsx)($,{children:"Order"}),(0,p.jsx)($,{children:"Date"}),(0,p.jsx)($,{className:"af-text-right",children:"Total"}),(0,p.jsx)($,{children:"Status"})]})}),(0,p.jsx)(Ue,{children:a.orders.map(g=>(0,p.jsxs)(he,{children:[(0,p.jsx)(V,{className:"af-whitespace-nowrap af-font-medium",children:$a(g)}),(0,p.jsx)(V,{className:"af-whitespace-nowrap af-text-muted-foreground",children:hs(g.created_at)}),(0,p.jsx)(V,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:j(vl(g),g.currency)}),(0,p.jsx)(V,{children:(0,p.jsx)(Wa,{status:g.status})})]},g.id))})]})}),(0,p.jsx)("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."})]}),a.submissions.length>0&&(0,p.jsxs)("div",{children:[(0,p.jsx)("h4",{className:Y(sr,"af-mb-3"),children:"Messages"}),(0,p.jsx)("div",{className:"af-space-y-3",children:a.submissions.map(g=>(0,p.jsx)(Pi,{formName:g.form_name,createdAt:g.created_at,data:g.data},g.id))})]})]})]})}function yl({submissionId:e,onBack:t}){let{api:s}=oe(),[a,n]=ha.useState(null),[i,o]=ha.useState(!0),[v,g]=ha.useState(null),[y,r]=ha.useState(0);return ha.useEffect(()=>{let h=!1;return o(!0),g(null),s.getSubmission(e).then(N=>{h||n(N)}).catch(N=>{h||g(N instanceof Error?N:new Error("Failed to load submission"))}).finally(()=>{h||o(!1)}),()=>{h=!0}},[s,e,y]),(0,p.jsxs)("div",{children:[(0,p.jsxs)("div",{className:"af-mb-6",children:[(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,p.jsx)(ut.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,p.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,p.jsx)(ee,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,p.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:hs(a.metadata.submitted_at)})]}),i?(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,p.jsx)(ee,{className:"af-w-40"}),(0,p.jsx)(ee,{className:"af-mt-2 af-w-64"}),(0,p.jsx)(ee,{className:"af-mt-2 af-w-52"}),(0,p.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):v||!a?(0,p.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,p.jsx)(Yt,{message:"Couldn't load this submission.",onRetry:()=>r(h=>h+1)})}):(0,p.jsxs)("div",{className:"af-space-y-3",children:[(0,p.jsx)(Pi,{formName:null,createdAt:a.metadata.submitted_at,data:a.data}),(0,p.jsx)("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 hl={all:"All",customers:"Customers",leads:"Leads"},xl=["all","customers","leads"];function wl(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function rr({refreshKey:e,onBackToWebsite:t,className:s}){let{people:a,isLoading:n,error:i,page:o,pageSize:v,hasNextPage:g,hasPreviousPage:y,setPage:r,q:h,setQ:N,refetch:b}=Ys({refreshKey:e}),[u,l]=ha.useState({kind:"list"}),[x,S]=ha.useState(""),[R,D]=ha.useState("all"),F=B=>{B.email?l({kind:"person",email:B.email}):B.submission_id&&l({kind:"submission",submissionId:B.submission_id})},c=()=>{l({kind:"list"}),b()},w=B=>{let T=B.trim();T!==h&&N(T)},E=a.filter(B=>wl(B,R)),W;if(u.kind==="person")W=(0,p.jsx)(bl,{email:u.email,refreshKey:e,onBack:c});else if(u.kind==="submission")W=(0,p.jsx)(yl,{submissionId:u.submissionId,onBack:c});else{let B=(0,p.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("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:xl.map(T=>(0,p.jsx)("button",{type:"button","aria-pressed":R===T,onClick:()=>D(T),className:Y("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===T?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:hl[T]},T))}),(0,p.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,p.jsx)(ut.Search,{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"}),(0,p.jsx)(we,{type:"text",value:x,onChange:T=>S(T.target.value),onBlur:()=>w(x),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),w(x))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),h&&(0,p.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{S(""),N("")},children:"Clear search"})]});if(n)W=(0,p.jsxs)("div",{children:[B,(0,p.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(T=>(0,p.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,p.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,p.jsx)(ee,{className:"af-h-4 af-w-32"}),(0,p.jsx)(ee,{className:"af-h-4 af-w-16"})]}),(0,p.jsx)(ee,{className:"af-mt-2 af-h-5 af-w-28"}),(0,p.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-56"})]},T))}),(0,p.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,p.jsxs)(Fe,{children:[(0,p.jsx)(Me,{children:(0,p.jsxs)(he,{children:[(0,p.jsx)($,{children:"Person"}),(0,p.jsx)($,{children:"Came from"}),(0,p.jsx)($,{children:"Latest message"}),(0,p.jsx)($,{children:"Last activity"}),(0,p.jsx)($,{className:"af-w-8"}),(0,p.jsx)($,{className:"af-w-8"})]})}),(0,p.jsx)(Ue,{"aria-hidden":"true",children:[0,1,2,3,4].map(T=>(0,p.jsxs)(he,{children:[(0,p.jsx)(V,{children:(0,p.jsx)(ee,{className:"af-h-4 af-w-40"})}),(0,p.jsx)(V,{children:(0,p.jsx)(ee,{className:"af-h-5 af-w-24"})}),(0,p.jsx)(V,{children:(0,p.jsx)(ee,{className:"af-h-4 af-w-56"})}),(0,p.jsx)(V,{children:(0,p.jsx)(ee,{className:"af-h-4 af-w-24"})}),(0,p.jsx)(V,{}),(0,p.jsx)(V,{})]},T))})]})}),(0,p.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(i)W=(0,p.jsxs)("div",{children:[B,(0,p.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,p.jsx)(Yt,{message:"Couldn't load your leads.",onRetry:()=>b()})})]});else if(E.length===0&&o===0){let T=!!h||R!=="all";W=(0,p.jsxs)("div",{children:[T&&B,T?(0,p.jsx)(ka,{children:h?"Nobody matches that search.":R==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,p.jsx)(ka,{icon:(0,p.jsx)(ut.Users,{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(a.length===0)W=(0,p.jsxs)("div",{children:[B,(0,p.jsx)(ka,{children:"No more results."}),(0,p.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>r(o-1),children:[(0,p.jsx)(ut.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let T=o*v+1,z=o*v+a.length;W=(0,p.jsxs)("div",{children:[B,(0,p.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:E.map((m,H)=>(0,p.jsxs)("div",{onClick:()=>F(m),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[(0,p.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,p.jsxs)("div",{className:"af-min-w-0",children:[(0,p.jsx)("button",{type:"button",onClick:re=>{re.stopPropagation(),F(m)},"aria-label":`Open ${m.name||m.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ri(m)}),m.name&&m.email&&(0,p.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:m.email})]}),(0,p.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,p.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:hs(m.last_activity_at)}),m.email&&(0,p.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,p.jsx)("a",{href:nr(m.email),onClick:re=>re.stopPropagation(),"aria-label":`Email ${m.email}`,children:(0,p.jsx)(ut.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,p.jsx)("div",{className:"af-mt-2",children:_i(m)}),m.latest_message_excerpt&&(0,p.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:m.latest_message_excerpt})]},m.email??m.submission_id??H))}),(0,p.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,p.jsxs)(Fe,{children:[(0,p.jsx)(Me,{children:(0,p.jsxs)(he,{children:[(0,p.jsx)($,{children:"Person"}),(0,p.jsx)($,{children:"Came from"}),(0,p.jsx)($,{children:"Latest message"}),(0,p.jsx)($,{children:"Last activity"}),(0,p.jsx)($,{className:"af-w-8",children:(0,p.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,p.jsx)($,{className:"af-w-8"})]})}),(0,p.jsx)(Ue,{children:E.map((m,H)=>(0,p.jsxs)(he,{onClick:()=>F(m),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,p.jsxs)(V,{className:"af-max-w-[260px] af-font-medium",children:[(0,p.jsx)("button",{type:"button",onClick:re=>{re.stopPropagation(),F(m)},"aria-label":`Open ${m.name||m.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Ri(m)}),m.name&&m.email&&(0,p.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:m.email})]}),(0,p.jsx)(V,{children:_i(m)}),(0,p.jsx)(V,{className:"af-max-w-[320px]",children:m.latest_message_excerpt?(0,p.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:m.latest_message_excerpt}):(0,p.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,p.jsx)(V,{className:"af-whitespace-nowrap af-text-muted-foreground",children:hs(m.last_activity_at)}),(0,p.jsx)(V,{className:"af-w-8",children:m.email&&(0,p.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,p.jsx)("a",{href:nr(m.email),onClick:re=>re.stopPropagation(),"aria-label":`Email ${m.email}`,children:(0,p.jsx)(ut.Mail,{className:"af-h-4 af-w-4"})})})}),(0,p.jsx)(V,{className:"af-w-8 af-text-right",children:(0,p.jsx)(ut.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},m.email??m.submission_id??H))})]})}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,p.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:R==="all"?`Showing ${T}-${z}`:`${E.length} of ${a.length} on this page`}),(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>r(o-1),disabled:!y,children:[(0,p.jsx)(ut.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,p.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>r(o+1),disabled:!g,children:["Next",(0,p.jsx)(ut.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return(0,p.jsx)(Nt,{title:"Leads",onBackToWebsite:t,hideBackButton:u.kind!=="list",className:s,children:W})}var cs=require("lucide-react");var $t=de(require("react"),1);function Qs({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=oe(),[a,n]=$t.useState([]),[i,o]=$t.useState(0),[v,g]=$t.useState(!0),[y,r]=$t.useState(null),[h,N]=$t.useState(0),[b,u]=$t.useState(e),[l,x]=$t.useState(void 0),S=$t.useRef(0),R=$t.useCallback(async()=>{let F=++S.current;try{g(!0),r(null);let c={limit:b,offset:h*b};l&&(c.status=l);let w=await s.getSubscriptions(c);if(F!==S.current)return;n(w.subscriptions),o(w.total)}catch(c){if(F!==S.current)return;r(c instanceof Error?c:new Error("Failed to fetch subscriptions"))}finally{F===S.current&&g(!1)}},[s,h,b,l,t]);$t.useEffect(()=>{R()},[R]);let D=Math.ceil(i/b);return{subscriptions:a,total:i,isLoading:v,error:y,page:h,pageSize:b,hasNextPage:h<D-1,hasPreviousPage:h>0,setPage:N,setPageSize:F=>{u(F),N(0)},status:l,setStatus:F=>{x(F),N(0)},refetch:R}}var M=require("react/jsx-runtime");function Ci(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ti({sub:e}){return e.status==="canceled"?(0,M.jsx)(Q,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,M.jsx)(Q,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,M.jsx)(Q,{variant:"warning",children:"Scheduled to cancel"}):(0,M.jsx)(Q,{variant:"success",children:"Active"}):(0,M.jsx)(Q,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function Nl(e,t){let s=j(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function ki({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,M.jsxs)("div",{children:[(0,M.jsx)("div",{className:"af-font-medium af-tabular-nums",children:Nl(e,e.current_amount)}),t&&(0,M.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",j(e.plan_amount,e.currency)]})]})}function Ei(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Ci(e.current_period_end)}`:"Ends at period end":e.current_period_end?Ci(e.current_period_end):"\u2014"}function ir({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:a,total:n,isLoading:i,error:o,page:v,pageSize:g,hasNextPage:y,hasPreviousPage:r,setPage:h,refetch:N}=Qs({refreshKey:e}),b;if(i)b=(0,M.jsxs)("div",{children:[(0,M.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,M.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,M.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,M.jsx)(ee,{className:"af-h-4 af-w-40"}),(0,M.jsx)(ee,{className:"af-h-4 af-w-20"})]}),(0,M.jsx)(ee,{className:"af-mt-2 af-h-3 af-w-32"}),(0,M.jsx)(ee,{className:"af-mt-2 af-h-5 af-w-24"})]},u))}),(0,M.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,M.jsxs)(Fe,{children:[(0,M.jsx)(Me,{children:(0,M.jsxs)(he,{children:[(0,M.jsx)($,{children:"Subscriber"}),(0,M.jsx)($,{children:"Plan"}),(0,M.jsx)($,{className:"af-text-right",children:"Amount"}),(0,M.jsx)($,{children:"Renews"}),(0,M.jsx)($,{children:"Status"})]})}),(0,M.jsx)(Ue,{"aria-hidden":"true",children:[0,1,2,3,4].map(u=>(0,M.jsxs)(he,{children:[(0,M.jsx)(V,{children:(0,M.jsx)(ee,{className:"af-h-4 af-w-44"})}),(0,M.jsx)(V,{children:(0,M.jsx)(ee,{className:"af-h-4 af-w-32"})}),(0,M.jsx)(V,{className:"af-text-right",children:(0,M.jsx)(ee,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,M.jsx)(V,{children:(0,M.jsx)(ee,{className:"af-h-4 af-w-24"})}),(0,M.jsx)(V,{children:(0,M.jsx)(ee,{className:"af-h-5 af-w-20"})})]},u))})]})}),(0,M.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)b=(0,M.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,M.jsx)(Yt,{message:"Couldn't load your subscriptions.",onRetry:()=>N()})});else if(a.length===0&&v===0)b=(0,M.jsx)(ka,{icon:(0,M.jsx)(cs.Repeat,{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(a.length===0)b=(0,M.jsxs)("div",{children:[(0,M.jsx)(ka,{children:"No more results."}),(0,M.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,M.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v-1),children:[(0,M.jsx)(cs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let u=v*g+1,l=v*g+a.length;b=(0,M.jsxs)("div",{children:[(0,M.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:a.map(x=>(0,M.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,M.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,M.jsxs)("div",{className:"af-min-w-0",children:[(0,M.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:x.customer_email||(0,M.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,M.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:x.plan_title||"Untitled plan"})]}),(0,M.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,M.jsx)(ki,{sub:x})})]}),(0,M.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,M.jsx)(Ti,{sub:x}),x.is_test&&(0,M.jsx)(Q,{variant:"outline",children:"Test"}),(0,M.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Ei(x)})]}),(0,M.jsx)(Na,{deliveries:x.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},x.id))}),(0,M.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,M.jsxs)(Fe,{children:[(0,M.jsx)(Me,{children:(0,M.jsxs)(he,{children:[(0,M.jsx)($,{children:"Subscriber"}),(0,M.jsx)($,{children:"Plan"}),(0,M.jsx)($,{className:"af-text-right",children:"Amount"}),(0,M.jsx)($,{children:"Renews"}),(0,M.jsx)($,{children:"Status"})]})}),(0,M.jsx)(Ue,{children:a.map(x=>(0,M.jsxs)(he,{children:[(0,M.jsx)(V,{className:"af-max-w-[240px]",children:(0,M.jsx)("div",{className:"af-truncate af-font-medium",children:x.customer_email||(0,M.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,M.jsx)(V,{className:"af-max-w-[220px]",children:(0,M.jsx)("div",{className:"af-truncate",children:x.plan_title||(0,M.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,M.jsx)(V,{className:"af-whitespace-nowrap af-text-right",children:(0,M.jsx)(ki,{sub:x})}),(0,M.jsx)(V,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Ei(x)}),(0,M.jsxs)(V,{children:[(0,M.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,M.jsx)(Ti,{sub:x}),x.is_test&&(0,M.jsx)(Q,{variant:"outline",children:"Test"})]}),(0,M.jsx)(Na,{deliveries:x.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},x.id))})]})}),(0,M.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2 af-px-2 af-py-4",children:[(0,M.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${u}-${l} of ${n}`}),(0,M.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,M.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v-1),disabled:!r,children:[(0,M.jsx)(cs.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,M.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>h(v+1),disabled:!y,children:["Next",(0,M.jsx)(cs.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,M.jsx)(Nt,{title:"Subscriptions",onBackToWebsite:t,className:s,children:b})}var or=de(require("react"),1);var nt=require("react/jsx-runtime");function lr({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:v,isLoading:g,error:y,refetch:r}=ns({refreshKey:e,initialPageSize:1,includeAggregates:!0}),h=ls({refreshKey:e}),[N,b]=or.useState(!1),[u,l]=or.useState(null),x=(0,nt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:y||!g&&!v?(0,nt.jsxs)("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. ",(0,nt.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):g||!v?(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.jsx)(Xe,{label:"Outstanding",children:(0,nt.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,nt.jsx)(Xe,{label:"Overdue",children:(0,nt.jsx)(ee,{className:"af-h-6 af-w-24"})}),(0,nt.jsx)(Xe,{label:"Paid this month",children:(0,nt.jsx)(ee,{className:"af-h-6 af-w-24"})})]}):(0,nt.jsxs)(nt.Fragment,{children:[(0,nt.jsx)(Xe,{label:"Outstanding",detail:`${v.outstanding.count} open`,children:j(v.outstanding.amount,v.currency)}),(0,nt.jsx)(Xe,{label:"Overdue",detail:v.overdue.count===0?"Nothing overdue":`${v.overdue.count} overdue`,valueClassName:v.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:j(v.overdue.amount,v.currency)}),(0,nt.jsx)(Xe,{label:"Paid this month",detail:`${v.paid_this_month.count} paid`,children:j(v.paid_this_month.amount,v.currency)})]})});return(0,nt.jsxs)(Nt,{title:"Invoices",onBackToWebsite:s,hideBackButton:N,className:o,children:[x,!N&&(0,nt.jsx)(is,{retainers:h.retainers,isLoading:h.isLoading,error:h.error,onRetry:()=>void h.refetch(),activeRetainerId:u?.id??null,onShowCycles:S=>l(R=>R?.id===S.id?null:S),total:h.total,endedTotal:h.endedTotal,isLoadingMore:h.isLoadingMore,onLoadMore:()=>void h.loadMore(),includeEnded:h.includeEnded,onIncludeEndedChange:h.setIncludeEnded}),(0,nt.jsx)(rs,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:b,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:u?{id:u.id,label:`${u.customer_name??u.customer_email??"Recurring invoices"} \u2014 ${u.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}var xt=de(require("react"),1);var Sl=2e3,Rt=()=>({data:null,error:null,isLoading:!0});function Xs(e,{refreshKey:t,breakdowns:s=[],filters:a=[]}={}){let{api:n}=oe(),[i,o]=xt.useState(Rt),[v,g]=xt.useState(Rt),[y,r]=xt.useState(Rt),[h,N]=xt.useState(Rt),[b,u]=xt.useState(Rt),l=ie=>Object.fromEntries(ie.map(Z=>[Z,Rt()])),[x,S]=xt.useState(()=>l(s)),R=xt.useRef(0),D=xt.useRef(0),F=xt.useRef("idle"),c=s.join(","),w=JSON.stringify(a),E=`${e}:${c}:${w}`,[W,B]=xt.useState({api:n,fetchIdentity:E});(W.api!==n||W.fetchIdentity!==E)&&(B({api:n,fetchIdentity:E}),R.current+=1,o(Rt),g(Rt),r(Rt),N(Rt),S(l(c?c.split(","):[])));let T=`${e}:${String(t??"")}`,[z,m]=xt.useState({api:n,conversionsIdentity:T});(z.api!==n||z.conversionsIdentity!==T)&&(m({api:n,conversionsIdentity:T}),D.current+=1,F.current="idle",u(Rt));let H=xt.useCallback(async ie=>{let Z=++R.current,ae=c?c.split(","):[];o(Rt),g(Rt),r(Rt),N(Rt),S(Object.fromEntries(ae.map(A=>[A,Rt()])));let ge=F.current!=="pending"&&(ie?.force===!0||F.current==="idle"),K=(A,se)=>se.then(P=>{Z===R.current&&A({data:P,error:null,isLoading:!1})},P=>{Z===R.current&&A({data:null,error:P instanceof Error?P:new Error("Failed to fetch report"),isLoading:!1})}),_e=n.getAnalyticsStatus(),it=K(o,_e),dt=Symbol("status-timeout"),Ie,Pe=await Promise.race([_e.then(A=>A,()=>null),new Promise(A=>{Ie=setTimeout(()=>A(dt),Sl)})]);if(clearTimeout(Ie),Z!==R.current)return;if(Pe===dt&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Pe!==null&&Pe!==dt&&(Pe.collecting!==!0||Pe.first_seen===null&&!Pe.first_seen_unavailable||Pe.first_seen!==null&&Pe.first_seen_in_reports===!1)){let A={data:null,error:null,isLoading:!1};g(A),r(A),N(A),S(Object.fromEntries(ae.map(se=>[se,{...A}]))),ge&&(u(A),F.current="done"),await it;return}await Promise.all([Pe===dt?Promise.resolve():it,K(g,n.getAnalyticsSummary(e,a)),K(r,n.getAnalyticsTimeseries(e,a)),K(N,n.getAnalyticsChannels(e,a)),ge?(()=>{F.current="pending";let A=++D.current;return u(Rt),n.getAnalyticsConversions(e).then(se=>{A===D.current&&(u({data:se,error:null,isLoading:!1}),F.current="done")},se=>{A===D.current&&(u({data:null,error:se instanceof Error?se:new Error("Failed to fetch report"),isLoading:!1}),F.current="done")})})():Promise.resolve(),...ae.map(A=>n.getAnalyticsBreakdown(A,e,a).then(se=>{Z===R.current&&S(P=>({...P,[A]:{data:se,error:null,isLoading:!1}}))},se=>{Z===R.current&&S(P=>({...P,[A]:{data:null,error:se instanceof Error?se:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,c,w,T]),re=xt.useCallback(async()=>{let ie=R.current;try{let Z=await n.getAnalyticsStatus();if(ie!==R.current)return;o({data:Z,error:null,isLoading:!1})}catch(Z){if(ie!==R.current)return;o(ae=>({data:ae.data,error:Z instanceof Error?Z:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),X=xt.useCallback(()=>H({force:!0}),[H]);xt.useEffect(()=>{H()},[H,t]);let ce=i.isLoading||v.isLoading||y.isLoading||h.isLoading||b.isLoading||Object.values(x).some(ie=>ie.isLoading);return{status:i,summary:v,timeseries:y,channels:h,conversions:b,breakdowns:x,isLoading:ce,refetch:X,refetchStatus:re}}var wt=de(require("react"),1);var Dn=3e4,Ln=3;function en(e={}){let t="collecting"in e,{collecting:s,statusFailed:a=!1,identity:n}=e,{api:i}=oe(),[o,v]=wt.useState(null),[g,y]=wt.useState(null),[r,h]=wt.useState(!1),[N,b]=wt.useState(null),[u,l]=wt.useState(!1),[x,S]=wt.useState(!0),[R,D]=wt.useState(0),F=wt.useRef(0),c=wt.useRef(0),w=wt.useRef(void 0);s!==void 0&&(w.current=s);let E=t?w.current===!0||w.current===void 0&&a:!0,[W,B]=wt.useState({api:i,identity:n}),T=n!==void 0&&n!==W.identity;(W.api!==i||T)&&(w.current=void 0,B({api:i,identity:n}),c.current+=1,F.current=0,v(null),y(null),h(!1),b(null),l(!1),S(!0),D(0));let z=wt.useRef(()=>{}),m=wt.useRef(null),H=wt.useCallback(async()=>{if(m.current!==null&&m.current===c.current)return;let re=++c.current;m.current=re;try{let X=await i.getAnalyticsRealtime();if(re!==c.current)return;if(X.status==="unreachable"){l(!0),h(!0),S(!1),D(ce=>ce+1);return}F.current=0,l(!1),v(X.data.current_visitors),y(X.as_of),h(!1),b(null),S(!1),D(ce=>ce+1)}catch(X){if(re!==c.current)return;F.current+=1,S(!1),D(ce=>ce+1),h(!0),F.current>=Ln&&b(X instanceof Error?X:new Error("Realtime unavailable"))}finally{m.current===re&&(m.current=null)}},[i]);return z.current=()=>void H(),wt.useEffect(()=>{let re,X=()=>{re===void 0&&(re=setInterval(()=>z.current(),Dn))},ce=()=>{re!==void 0&&(clearInterval(re),re=void 0)},ie=()=>{typeof document<"u"&&document.hidden?ce():(z.current(),X())};return E?((typeof document>"u"||!document.hidden)&&(z.current(),X()),document?.addEventListener("visibilitychange",ie),()=>{ce(),document?.removeEventListener("visibilitychange",ie),c.current+=1}):()=>{document?.removeEventListener("visibilitychange",ie)}},[W.api,W.identity,E]),{currentVisitors:o,asOf:g,isStale:r,error:N,isUnreachable:u,isInitialLoad:x,polls:R}}var We=de(require("react"),1);var us=de(require("react"),1);var _l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Dt(e){let t=Math.abs(e);if(t<1e3)return String(e);let s=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[a,n]of s)if(t>=a){let i=e/a,o=Math.abs(i)<10?Math.round(i*10)/10:Math.round(i);return Math.abs(o)>=1e3&&a!==1e9?Dt(o*a):`${o}${n}`}return String(e)}function xs(e){return`${(e*100).toFixed(1)}%`}function tn(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}function Ai(e){let t=Math.max(0,Math.round(e));return t>=3600&&t%3600===0?`${t/3600}h`:t>=60&&t%60===0?`${t/60}m`:tn(t)}function Di(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Li(e,t){if(!(!Number.isFinite(e)||e<=0))for(let s of t){let a=Math.ceil(e/s);if(a<=5)return Array.from({length:a+1},(n,i)=>Number((i*s).toPrecision(12)))}}function an(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function Oi(e){let t=new Date(e);return Number.isNaN(t.getTime())?"as of an unknown time":`as of ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function cr(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${_l[t-1]} ${s}`}function Ii(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Rl(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Bi(e,t,s="UTC"){let a=new Map(t.map(o=>[o.date,o])),n=[],i=Ii(e.to,s);for(let o=Ii(e.from,s);o<i;o=Rl(o))n.push(a.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return n}function Fi(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=new Date(`${e}T00:00:00Z`);if(Number.isNaN(a.getTime()))return e;let n=String(a.getUTCDate()).padStart(2,"0");return`${t[a.getUTCDay()]}, ${n} ${s[a.getUTCMonth()]}`}var ea=require("react/jsx-runtime");function Mi({what:e="This report",onRetry:t,collecting:s}){return(0,ea.jsxs)("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:[(0,ea.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,ea.jsx)("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.`}),t?(0,ea.jsx)("button",{type:"button",onClick:t,className:"af-mt-2 af-rounded-md af-border af-border-border af-px-3 af-py-1 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted",children:"Try again"}):null]})}function On({what:e="No data"}){return(0,ea.jsx)("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 ws({sourced:e,error:t,isLoading:s,what:a,onRetry:n,collecting:i,children:o}){return s?(0,ea.jsx)("div",{role:"status","aria-label":`Loading ${a}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,ea.jsx)(Mi,{what:a,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,ea.jsx)(Mi,{what:a,onRetry:n,collecting:i}):(0,ea.jsx)(ea.Fragment,{children:o(e.data)})}var Ge=require("react/jsx-runtime");function ur({rows:e,dimension:t,metric:s,metricLabel:a,secondary:n,emptyCopy:i="No data for this period",onFilter:o,canFilter:v,maxRows:g=9}){let[y,r]=us.useState(!1);if(e.length===0)return(0,Ge.jsx)(On,{what:i});let h=e.reduce((u,l)=>Math.max(u,Number(l[s]??0)),0)||1,N=Math.max(0,e.length-g),b=y?e:e.slice(0,g);return(0,Ge.jsxs)(Ge.Fragment,{children:[(0,Ge.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ge.jsx)("thead",{children:(0,Ge.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ge.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Ge.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:a})]})}),(0,Ge.jsx)("tbody",{children:b.map((u,l)=>{let x=Number(u[s]??0),S=u[t]??null,R=an(S),D=n?u[n]:null,F=S!==null&&(v?v(S,D):!0);return(0,Ge.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Ge.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Ge.jsx)("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,x/h*100)}%`}}),S!==null&&o&&F?(0,Ge.jsx)("button",{type:"button",onClick:()=>o(S,D),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}):(0,Ge.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:R}),D?(0,Ge.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:D}):null]}),(0,Ge.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Dt(x)})]},`${R}-${D??""}-${l}`)})})]}),N>0?(0,Ge.jsx)("button",{type:"button",onClick:()=>r(u=>!u),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:y?"Show fewer":`Show all ${e.length}`}):null]})}function sn({title:e,tabs:t,defaultTabId:s,headerRight:a}){let[n,i]=us.useState(s),o=t.find(b=>b.id===n)??t[0],v=us.useId(),g=b=>`${v}-tab-${b}`,y=b=>`${v}-panel-${b}`,r=us.useRef(null),h=(b,u)=>{b.preventDefault();let l=(u+t.length)%t.length;i(t[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return(0,Ge.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Ge.jsxs)("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:[(0,Ge.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:b=>{let u=t.findIndex(l=>l.id===n);b.key==="ArrowRight"&&h(b,u+1),b.key==="ArrowLeft"&&h(b,u-1),b.key==="Home"&&h(b,0),b.key==="End"&&h(b,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(b=>(0,Ge.jsx)("button",{id:g(b.id),role:"tab",type:"button","aria-selected":b.id===n,"aria-controls":y(b.id),tabIndex:b.id===n?0:-1,onClick:()=>i(b.id),className:b.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:b.label},b.id))}),a]}),o?(0,Ge.jsx)("div",{id:y(o.id),role:"tabpanel","aria-labelledby":g(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Vt=de(require("react"),1),Ya=de(require("@radix-ui/react-popover"),1);var ds=3,fs=100;var Le=require("react/jsx-runtime"),nn={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"},Pl=Object.keys(nn);function Ui(e){let t=nn[e.dimension],s=e.operator==="is_not"?"is not":"is",a=e.values.map(n=>an(n)).join(" or ");return`${t} ${s} ${a}`}function dr(e,t){let s=e.findIndex(a=>a.dimension===t.dimension&&(a.operator??"is")===(t.operator??"is"));if(s>=0){let a=[...new Set([...e[s].values,...t.values])];return a.length>100||a.length===e[s].values.length?e:e.map((n,i)=>i===s?{...n,values:a}:n)}return t.values.length>100||e.length>=3?e:[...e,t]}function Cl(e,t){let s={};for(let[a,n]of Object.entries(t)){let i=e.get(a)??new Set;for(let o of n)i.add(o);e.set(a,i),s[a]=[...i]}return s}function $i(e,t){let s=e.findIndex(a=>a.dimension===t.dimension&&(a.operator??"is")===(t.operator??"is"));return s>=0?e.map((a,n)=>n===s?t:a):t.values.length>100||e.length>=3?e:[...e,t]}function Tl(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Vi(e,t,s,a={}){if(e.api!==t.api||e.period!==t.period)return e.api=t.api,e.period=t.period,e.byDimension=new Map,e.foldsByLabel=new Map,{suggestions:{},folds:new Map};let n=Cl(e.byDimension,s);for(let[i,o]of Object.entries(a)){let v=e.foldsByLabel.get(i)??new Set;for(let g of o)v.add(g);e.foldsByLabel.set(i,v)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function Hi(e){let{filters:t,onChange:s}=e,a=t.length>=3;return Vt.useEffect(()=>{if(t.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)},[t.length,s]),(0,Le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((n,i)=>(0,Le.jsxs)("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:[(0,Le.jsx)("span",{className:"af-text-foreground",children:Ui(n)}),(0,Le.jsx)("button",{type:"button","aria-label":`Remove filter ${Ui(n)}`,onClick:()=>s(t.filter((o,v)=>v!==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"}`)),(0,Le.jsx)(kl,{...e,disabled:a}),t.length>0?(0,Le.jsx)("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 kl({filters:e,onChange:t,suggestions:s,resetKey:a,disabled:n,expandValues:i}){let[o,v]=Vt.useState(!1),g=Vt.useRef(null),[y,r]=Vt.useState(null);Vt.useEffect(()=>{r(g.current?.closest(".aifeatures-admin")??null)},[]);let[h,N]=Vt.useState(null),[b,u]=Vt.useState("is"),[l,x]=Vt.useState(""),[S,R]=Vt.useState([]);Vt.useEffect(()=>{o||(N(null),u("is"),x(""),R([]))},[o]);let D=Vt.useRef(a);D.current!==a&&(D.current=a,o&&v(!1),h!==null&&N(null),S.length>0&&R([]),l!==""&&x(""),b!=="is"&&u("is"));let F=T=>{let z=Tl(T);N(z.dimension),R(z.picked),x(z.search),u(z.operator)},w=(h?s[h]??[]:[]).filter(T=>T.toLowerCase().includes(l.trim().toLowerCase())),E=h===null||S.length===0?null:dr(e,{dimension:h,operator:b,values:i?i(h,S):S}),W=E!==null&&E!==e,B=()=>{let T=E;!T||T===e||(t(T),v(!1))};return(0,Le.jsxs)(Ya.Root,{open:o,onOpenChange:v,children:[(0,Le.jsx)(Ya.Trigger,{asChild:!0,children:(0,Le.jsx)("button",{ref:g,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"})}),(0,Le.jsx)(Ya.Portal,{container:y,children:(0,Le.jsx)(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:h===null?(0,Le.jsxs)("div",{children:[(0,Le.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Le.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:Pl.filter(T=>s[T]!==void 0).map(T=>{let z=s[T]?.length??0,m=!e.some(H=>H.dimension===T)&&e.length>=3;return(0,Le.jsxs)("button",{type:"button",onClick:()=>F(T),disabled:z===0||m,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:[(0,Le.jsx)("span",{children:nn[T]}),(0,Le.jsx)("span",{className:"af-text-muted-foreground",children:z===0?"no data":m?"no room":z})]},T)})})]}):(0,Le.jsxs)("div",{children:[(0,Le.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Le.jsx)("button",{type:"button",onClick:()=>F(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Le.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:nn[h]}),(0,Le.jsxs)("select",{"aria-label":"Operator",value:b,onChange:T=>u(T.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,Le.jsx)("option",{value:"is",children:"is"}),(0,Le.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Le.jsx)("input",{type:"text",value:l,onChange:T=>x(T.target.value),placeholder:"Search\u2026","aria-label":`Search ${nn[h]}`,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"}),(0,Le.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:w.length===0?(0,Le.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",l,"\u201D."]}):w.map(T=>(0,Le.jsxs)("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:[(0,Le.jsx)("input",{type:"checkbox",checked:S.includes(T),disabled:!S.includes(T)&&S.length>=100,onChange:z=>R(m=>z.target.checked?[...m,T]:m.filter(H=>H!==T))}),(0,Le.jsx)("span",{className:"af-break-all",children:an(T)})]},T))}),(0,Le.jsx)("button",{type:"button",onClick:B,disabled:!W,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:S.length<=1?"Apply filter":S.length>=100?`Apply filter (${S.length} values \u2014 the maximum)`:`Apply filter (${S.length} values)`})]})})})]})}var et=require("react/jsx-runtime"),El=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Dt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Dt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Dt,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:xs,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:tn,chart:"visit_duration_seconds"}];function Il({current:e,previous:t,downIsGood:s}){if(t===0)return null;let a=(e-t)/t;if(Math.abs(a)<5e-4)return null;let n=a>0,i=s?!n:n,o=`${n?"+":""}${(a*100).toFixed(1)}%`;return(0,et.jsx)("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 zi({summary:e,selected:t,onSelect:s}){return(0,et.jsx)("div",{className:"af-@container",children:(0,et.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:El.map(a=>{let n=a.chart===t,i=s!==void 0,o=(0,et.jsxs)(et.Fragment,{children:[(0,et.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:a.label}),(0,et.jsxs)("dd",{className:"af-mt-1 af-flex af-flex-wrap af-items-baseline af-gap-x-2 af-gap-y-0.5",children:[(0,et.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:a.format(a.get(e.current))}),e.previous?(0,et.jsx)(Il,{current:a.get(e.current),previous:a.get(e.previous),downIsGood:a.downIsGood}):null]})]});return i?(0,et.jsx)("button",{type:"button","aria-pressed":n,onClick:()=>s(a.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},a.key):(0,et.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},a.key)})})})}function fr({currentVisitors:e,asOf:t,isStale:s,isUnreachable:a,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!a)return(0,et.jsxs)("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:[(0,et.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,et.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(a||e===null)return(0,et.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?Oi(t):"freshness unknown",v=i?" across the whole site, not the current filter,":"",g=s?`${e} current visitors${v} ${o} (not updating)`:`${e} current visitors${v} ${o}`;return(0,et.jsxs)("span",{className:"af-inline-flex af-items-center af-gap-2 af-rounded-full af-border af-border-border af-bg-card af-px-3 af-py-1",title:g,children:[(0,et.jsx)("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"}),(0,et.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,et.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,et.jsx)("span",{className:"af-sr-only",children:g})]})}var qi=de(require("react"),1);var Ye=require("react/jsx-runtime");function ji({rows:e,denominator:t,windowPrecedesCollection:s=!1,coverageUnknown:a=!1,emptyCopy:n="No conversions in this period",maxRows:i=9}){let[o,v]=qi.useState(!1);if(e.length===0)return(0,Ye.jsx)(On,{what:n});let g=Math.max(0,e.length-i),y=o?e:e.slice(0,i);return(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ye.jsx)("thead",{children:(0,Ye.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total"}),(0,Ye.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Ye.jsx)("tbody",{children:y.map((r,h)=>(0,Ye.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Ye.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:r.goal}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Dt(r.visitors)}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Dt(r.events)}),(0,Ye.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:r.conversion_rate===null?(0,Ye.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):xs(r.conversion_rate)})]},`${r.goal}-${h}`))})]}),g>0?(0,Ye.jsx)("button",{type:"button",onClick:()=>v(r=>!r),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:o?"Show fewer":`Show all ${e.length}`}):null,(0,Ye.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Dt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),s?(0,Ye.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"This period starts before we began collecting for this site, so these counts cover less time than the dates suggest."}):a?(0,Ye.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"We couldn\u2019t check how far back this site\u2019s history goes, so these counts may not cover the whole period. It should return on its own."}):null]})}var Ht=require("recharts");var rt=require("react/jsx-runtime"),Bn={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:Dt,visits:Dt,pageviews:Dt,views_per_visit:e=>e.toFixed(2),bounce_rate:xs,visit_duration_seconds:tn},Al=new Set(["visitors","visits","pageviews"]),Dl={...pr,bounce_rate:Di,visit_duration_seconds:Ai},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],Ll=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Ol=[.01,.02,.05,.1,.2,.25,.5,1],Bl=[.25,.5,1,2,5,10,25,50],Fl={visitors:mr,visits:mr,pageviews:mr,views_per_visit:Bl,bounce_rate:Ol,visit_duration_seconds:Ll};function Ml({active:e,payload:t,label:s,metric:a}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,rt.jsxs)("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:[(0,rt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:Bn[a]}),(0,rt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,rt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,rt.jsx)("span",{className:"af-text-muted-foreground",children:Fi(String(s))}),(0,rt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:pr[a](Number(n[a]??0))})]})]})}function Gi({rows:e,window:t,metric:s,timeZone:a="UTC",height:n=260}){let i=Bi(t,e,a),o=pr[s],v=Dl[s],g=Li(i.reduce((r,h)=>Math.max(r,Number(h[s]??0)),0),Fl[s]),y=`${Bn[s]} by day: ${i.map(r=>`${cr(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,rt.jsxs)("figure",{"aria-label":`${Bn[s]} over time`,className:"af-m-0",children:[(0,rt.jsx)(Ht.ResponsiveContainer,{width:"100%",height:n,children:(0,rt.jsxs)(Ht.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,rt.jsx)("defs",{children:(0,rt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,rt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,rt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,rt.jsx)(Ht.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,rt.jsx)(Ht.XAxis,{dataKey:"date",tickFormatter:cr,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,rt.jsx)(Ht.YAxis,{allowDecimals:!Al.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...g?{ticks:g,domain:[0,g[g.length-1]]}:{},tickFormatter:r=>v(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,rt.jsx)(Ht.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,rt.jsx)(Ml,{metric:s})}),(0,rt.jsx)(Ht.Area,{type:"monotone",dataKey:s,name:Bn[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,rt.jsx)("figcaption",{className:"af-sr-only",children:y})]})}var le=require("react/jsx-runtime"),Ul=3e4,$l="2026-08-13",Vl=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Hl=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Wi({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:a,className:n,published:i,lastPublishedAt:o}){let[v,g]=We.useState(30),y=e!==void 0&&t!==void 0,[r,h]=We.useState(e??[]),{api:N}=oe(),[b,u]=We.useState(N);b!==N&&(u(N),!y&&r.length>0&&h([]));let l=y?e:r,x=We.useCallback(A=>{t&&t(A),y||h(A)},[t,y]),S=We.useCallback((A,se,P)=>{let L=Array.isArray(se)?se:[se];if(L.length===0)return null;let fe=dr(l,{dimension:A,operator:"is",values:L});if(P&&(!P.value||(fe=$i(fe,{dimension:P.dimension,operator:"is",values:[P.value]}),!fe.find(qe=>qe.dimension===P.dimension&&qe.operator!=="is_not")?.values.includes(P.value))))return null;let ze=fe.find(Ce=>Ce.dimension===A&&Ce.operator!=="is_not");return L.every(Ce=>ze?.values.includes(Ce))?JSON.stringify(fe)===JSON.stringify(l)?null:fe:null},[l]),R=We.useCallback((A,se,P)=>S(A,se,P)!==null,[S]),D=We.useCallback((A,se,P)=>{let L=S(A,se,P);L&&x(L)},[S,x]),[F,c]=We.useState("visitors"),w=Xs(v,{refreshKey:s,breakdowns:Hl,filters:l}),E=w.status.data,W=i===!1,B=E!=null&&(!E.collecting||W&&E.first_seen===null&&!E.first_seen_unavailable),T=!B&&E?.collecting===!0&&E.first_seen===null&&!E.first_seen_unavailable,z=E?.collecting===!0&&E.first_seen!==null&&E.first_seen_in_reports===!1,m=T||z,H=en({collecting:T||B?!1:E?.collecting,statusFailed:w.status.error!=null,identity:E?.analytics_id}),re=We.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),X=We.useMemo(()=>{let A=w.breakdowns.sources?.data,se={};if(!A||A.status!=="ok")return se;for(let P of A.data){let L=P.source,fe=P.sources;typeof L=="string"&&Array.isArray(fe)&&fe.length>0&&(se[L]=fe)}return se},[w.breakdowns.sources?.data]),ce=We.useMemo(()=>{let A=(L,fe)=>{let ze=w.breakdowns[L]?.data;return!ze||ze.status!=="ok"?[]:[...new Set(ze.data.map(Ce=>Ce[fe]).filter(Ce=>typeof Ce=="string"&&Ce!==""))]};return{channel:w.channels.data?.status==="ok"?[...new Set(w.channels.data.data.map(L=>L.channel))]:[],source:A("sources","source"),campaign:A("utm/campaign","campaign"),page:A("pages","pathname"),entry_page:A("entry-pages","pathname"),exit_page:A("exit-pages","pathname"),country:A("countries","country"),browser:A("browsers","browser"),os:A("operating-systems","os"),device:A("devices","device")}},[w.breakdowns,w.channels.data]),[ie,Z]=We.useState({}),ae=JSON.stringify(ce),[ge,K]=We.useState(new Map),_e=JSON.stringify(X);We.useEffect(()=>{let{suggestions:A,folds:se}=Vi(re.current,{api:N,period:v},JSON.parse(ae),JSON.parse(_e));Z(A),K(se)},[ae,_e,N,v]);let it=We.useCallback((A,se)=>A!=="source"?se:[...new Set(se.flatMap(P=>{let L=[...ge.get(P)??[],...X[P]??[]];return L.length>0?L:[P]}))],[ge,X]),dt=We.useMemo(()=>{let A=w.conversions.error;return A instanceof kt&&A.details?.code==="goals_exceed_report_budget"?A.message:null},[w.conversions.error]),Ie=We.useMemo(()=>{let A=[w.summary,w.timeseries,w.channels,...Object.values(w.breakdowns)];for(let se of A){let P=se?.error;if(P instanceof kt&&P.details?.code==="filter_unsupported")return P.message}return null},[w.summary,w.timeseries,w.channels,w.breakdowns]),Pe=(A,se,P,L,fe,ze,Ce,qe,tt)=>()=>{let ft=w.breakdowns[A];return(0,le.jsx)(ws,{sourced:ft?.data??null,error:ft?.error,isLoading:ft?.isLoading,what:se,collecting:E?.collecting,onRetry:w.refetch,children:Lt=>{let Ot=ne=>qe?it(qe,[ne]):ne;return(0,le.jsx)(ur,{rows:Lt,dimension:P,metric:L,metricLabel:fe,secondary:ze,emptyCopy:l.length>0?"No data for this filter":Ce,canFilter:qe?(ne,Ae)=>R(qe,Ot(ne),tt?{dimension:tt,value:Ae}:void 0):()=>!1,onFilter:qe?(ne,Ae)=>D(qe,Ot(ne),tt?{dimension:tt,value:Ae}:void 0):void 0})}})};We.useEffect(()=>{if(!m)return;let A,se=()=>{A===void 0&&(A=setInterval(()=>void w.refetchStatus(),Ul))},P=()=>{A!==void 0&&(clearInterval(A),A=void 0)},L=()=>{typeof document<"u"&&document.hidden?P():(w.refetchStatus(),se())};return(typeof document>"u"||!document.hidden)&&se(),document?.addEventListener("visibilitychange",L),()=>{P(),document?.removeEventListener("visibilitychange",L)}},[m,w.refetchStatus]);let vt=We.useRef(void 0);if(We.useEffect(()=>{if(!E){vt.current=void 0;return}let A=vt.current;vt.current=m,A===!0&&!m&&w.refetch()},[E,m,w.refetch]),B){let A=!!o&&String(o).slice(0,10)<$l;return(0,le.jsx)(Nt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,le.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,le.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,le.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:W?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":A?"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 T?(0,le.jsx)(Nt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,le.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,le.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,le.jsx)("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."})]})}):z?(0,le.jsx)(Nt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,le.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,le.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,le.jsxs)("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",E?.timezone?` ${E.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,le.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,le.jsx)(fr,{currentVisitors:H.currentVisitors,asOf:H.asOf,isStale:H.isStale,isUnreachable:H.isUnreachable||H.error!==null,isInitialLoad:H.isInitialLoad})})]})}):(0,le.jsx)(Nt,{title:"Analytics",onBackToWebsite:a,className:n,children:(0,le.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,le.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Vl.map(A=>(0,le.jsx)("button",{type:"button","aria-pressed":A.value===v,onClick:()=>g(A.value),className:A.value===v?"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:A.label},A.value))}),(0,le.jsx)(fr,{currentVisitors:H.currentVisitors,asOf:H.asOf,isStale:H.isStale,isUnreachable:H.isUnreachable||H.error!==null,isInitialLoad:H.isInitialLoad,scopeIsSiteWide:l.length>0})]}),(0,le.jsx)(Hi,{filters:l,onChange:x,suggestions:ie,expandValues:it,resetKey:N}),Ie?(0,le.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,le.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,le.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:Ie}),(0,le.jsx)("button",{type:"button",onClick:()=>x([]),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,!Ie&&E?.timezone_defaulted?(0,le.jsx)("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,Ie?null:(0,le.jsxs)(le.Fragment,{children:[(0,le.jsx)(ws,{sourced:w.summary.data,error:w.summary.error,isLoading:w.summary.isLoading,what:"The traffic summary",collecting:E?.collecting,onRetry:w.refetch,children:A=>(0,le.jsxs)(le.Fragment,{children:[(0,le.jsx)(zi,{summary:A,selected:F,onSelect:c}),A.previous_unavailable?(0,le.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[A.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]})}),(0,le.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,le.jsx)(ws,{sourced:w.timeseries.data,error:w.timeseries.error,isLoading:w.timeseries.isLoading,what:"The visitors chart",collecting:E?.collecting,onRetry:w.refetch,children:A=>{let se=w.timeseries.data?.status==="ok"?w.timeseries.data.window:{from:"",to:""};return(0,le.jsx)(Gi,{rows:A,window:se,metric:F,timeZone:(w.timeseries.data?.status==="ok"?w.timeseries.data.timezone:void 0)??E?.timezone??"UTC"})}})}),(0,le.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,le.jsx)("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:(0,le.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,le.jsxs)("div",{className:"af-px-3 af-py-2",children:[l.length>0?(0,le.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",l.length===1?"filter":"filters"," above."]}):null,dt!==null?(0,le.jsxs)("div",{role:"status",className:"af-rounded-md af-border af-border-dashed af-border-border af-bg-muted/40 af-px-4 af-py-6 af-text-center",children:[(0,le.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,le.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:dt})]}):(0,le.jsx)(ws,{sourced:w.conversions.data,error:w.conversions.error,isLoading:w.conversions.isLoading,what:"Conversions",collecting:E?.collecting,onRetry:w.refetch,children:A=>{let se=w.conversions.data?.status==="ok"?w.conversions.data:null;return(0,le.jsx)(le.Fragment,{children:(0,le.jsx)(ji,{rows:A,denominator:se?.denominator??0,windowPrecedesCollection:se?.window_precedes_collection??!1,coverageUnknown:se?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]}),(0,le.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,le.jsx)(sn,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,le.jsx)(ws,{sourced:w.channels.data,error:w.channels.error,isLoading:w.channels.isLoading,what:"Channels",collecting:E?.collecting,onRetry:w.refetch,children:A=>(0,le.jsx)(ur,{rows:A,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:l.length>0?"No data for this filter":"No data for this period",canFilter:se=>R("channel",se),onFilter:se=>D("channel",se)})})},{id:"sources",label:"Sources",render:Pe("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:Pe("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,le.jsx)(sn,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:Pe("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:Pe("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:Pe("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,le.jsx)(sn,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:Pe("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:Pe("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:Pe("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,le.jsx)(sn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:Pe("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:Pe("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:Pe("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSubmissions,useSubscriptions});
|