@aifeatures/admin-react 0.19.0 → 0.21.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 CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- "use strict";var Fo=Object.create;var Pn=Object.defineProperty;var Mo=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var Uo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty;var Ho=(e,t)=>{for(var s in t)Pn(e,s,{get:t[s],enumerable:!0})},ei=(e,t,s,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $o(t))!Vo.call(e,n)&&n!==s&&Pn(e,n,{get:()=>t[n],enumerable:!(a=Mo(t,n))||a.enumerable});return e};var le=(e,t,s)=>(s=e!=null?Fo(Uo(e)):{},ei(t||!e||!e.__esModule?Pn(s,"default",{value:e,enumerable:!0}):s,e)),zo=e=>ei(Pn({},"__esModule",{value:!0}),e);var Fc={};Ho(Fc,{AifeaturesApiError:()=>It,AifeaturesProvider:()=>si,AnalyticsView:()=>_o,CustomerDetail:()=>un,CustomersList:()=>dn,DashboardView:()=>Lo,FormSettings:()=>Xs,FormSubmissions:()=>Ws,FormsDashboard:()=>yr,FormsList:()=>zs,InvoiceDetail:()=>Wn,InvoiceLabelBadge:()=>Ds,InvoicesList:()=>Qa,InvoicesView:()=>Fr,LeadsView:()=>vn,MAX_ANALYTICS_FILTERS:()=>Ps,MAX_ANALYTICS_FILTER_VALUES:()=>Cs,OrderDetail:()=>ln,OrderStatusBadge:()=>os,OrdersList:()=>Ja,OrdersView:()=>Ar,PaymentsDashboard:()=>Er,PaymentsSetup:()=>fn,ProductSettings:()=>sn,ProductsList:()=>tn,ProductsView:()=>Ir,PromosPanel:()=>ms,REALTIME_FAILURES_BEFORE_ERROR:()=>sr,REALTIME_POLL_MS:()=>ar,RetainerStatusBadge:()=>Zn,RetainersPanel:()=>ys,SubmissionDetail:()=>Gs,SubscriptionsView:()=>Or,VariantsEditor:()=>an,ViewShell:()=>yt,WebhookDeliveries:()=>Ys,WebhookSettings:()=>Qs,chargedTotal:()=>Ba,createApiClient:()=>Tn,formatPrice:()=>W,isZeroDecimalCurrency:()=>sa,toMajorUnits:()=>pt,toMinorUnits:()=>Mt,useAifeatures:()=>ne,useAifeaturesContext:()=>ne,useAnalytics:()=>Ss,useBusinessSummary:()=>ws,useCustomers:()=>cn,useEventDestinations:()=>Zs,useForms:()=>ds,useInvoices:()=>bs,useOrders:()=>nn,usePaymentsStatus:()=>Wa,usePeople:()=>pn,usePerson:()=>gn,useProducts:()=>hs,useRealtimeVisitors:()=>yn,useRetainers:()=>xs,useSubmissions:()=>js,useSubscriptions:()=>bn});module.exports=zo(Fc);var ns=le(require("react"),1);var fr="aifeatures:analytics:timezone",mr;function Us(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function ti(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function as(){return pr()??Us()}function pr(){if(mr!==void 0)return mr;try{let e=window.localStorage.getItem(fr);return ti(e)?e:null}catch{return null}}function gr(e){if(!(e!==null&&!ti(e))){mr=e;try{e===null?window.localStorage.removeItem(fr):window.localStorage.setItem(fr,e)}catch{}}}function Cn(e,t){let s=new URLSearchParams({period:String(e)}),a=as();return a&&s.set("timezone",a),t&&t.length>0&&s.set("filters",JSON.stringify(t)),s.toString()}var It=class extends Error{constructor(s,a,n){super(s);this.status=a;this.details=n;this.name="AifeaturesApiError"}};function vr(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 Tn(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 d;try{d=await o.json()}catch{}throw new It(vr(d?.error,o.status),o.status,d)}if(o.status!==204)return o.json()}return{async getForms(){return(await s("/api/v1/forms")).forms},async getForm(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(),d=`/api/v1/forms/${a}/submissions${o?`?${o}`:""}`;return s(d)},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,d=i.id??i.name,f=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(d)}`,u=await fetch(f,{headers:{Authorization:`Bearer ${e}`}});if(!u.ok){let b;try{b=await u.json()}catch{}throw new It(vr(b?.error,u.status),u.status,b)}let r=await u.blob(),v=URL.createObjectURL(r),x=document.createElement("a");x.href=v,x.download=o,document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(v)},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 d;try{d=await o.json()}catch{}throw new It(vr(d?.error,o.status),o.status,d)}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(){let a=new URLSearchParams,n=as();n&&a.set("timezone",n);let i=a.toString();return s(`/api/v1/analytics/status${i?`?${i}`:""}`)},async getAnalyticsSummary(a,n){return s(`/api/v1/analytics/summary?${Cn(a,n)}`)},async getAnalyticsTimeseries(a,n){return s(`/api/v1/analytics/timeseries?${Cn(a,n)}`)},async getAnalyticsRealtime(){return s("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,n){return s(`/api/v1/analytics/channels?${Cn(a,n)}`)},async getAnalyticsConversions(a){return s((()=>{let n=new URLSearchParams({period:String(a)}),i=as();return i&&n.set("timezone",i),`/api/v1/analytics/conversions?${n.toString()}`})())},async getAnalyticsGoalTargets(a,n,i){let o=new URLSearchParams({goal:a,period:String(n)}),d=as();return d&&o.set("timezone",d),i!==void 0&&o.set("limit",String(i)),s(`/api/v1/analytics/conversions/targets?${o.toString()}`)},async getAnalyticsBreakdown(a,n,i){let o=a.split("/").map(encodeURIComponent).join("/");return s(`/api/v1/analytics/${o}?${Cn(n,i)}`)},async getBusinessSummary(a){let n=new URLSearchParams;n.set("tz_offset_minutes",String(a.tzOffsetMinutes));let i=as();return i&&n.set("timezone",i),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 ss=require("react/jsx-runtime"),ai=ns.createContext(null);function qo(e){return e?e.startsWith("sk_")?"Invalid token type: You passed an organization API key (sk_xxx) but AifeaturesProvider requires a site token (st_xxx). Site tokens are returned when you create a site via the API.":e.startsWith("st_")?null:`Invalid token format: Expected a site token starting with "st_" but got "${e.slice(0,10)}...". Site tokens are returned when you create a site via the API.`:"No siteToken provided to AifeaturesProvider"}function si({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:s=!1,className:a,children:n}){let i=ns.useMemo(()=>qo(e),[e]),o=ns.useMemo(()=>Tn(e,t),[e,t]),d=ns.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return i?(0,ss.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:(0,ss.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,ss.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,ss.jsx)("p",{className:"af-text-sm af-text-destructive",children:i})]})}):(0,ss.jsx)(ai.Provider,{value:d,children:(0,ss.jsx)("div",{className:`aifeatures-admin ${s?"dark":""} ${a||""}`,children:n})})}function ne(){let e=ns.useContext(ai);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var Ga=le(require("react"),1),ks=require("lucide-react");var kn=le(require("react"),1),wa=le(require("@radix-ui/react-tabs"),1);var ni=require("clsx"),ri=require("tailwind-merge"),jo=(0,ri.extendTailwindMerge)({prefix:"af-"});function te(...e){return jo((0,ni.clsx)(e))}var An=require("react/jsx-runtime"),En=wa.Root,Vs=kn.forwardRef(({className:e,...t},s)=>(0,An.jsx)(wa.List,{ref:s,className:te("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}));Vs.displayName=wa.List.displayName;var Na=kn.forwardRef(({className:e,...t},s)=>(0,An.jsx)(wa.Trigger,{ref:s,className:te("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}));Na.displayName=wa.Trigger.displayName;var Sa=kn.forwardRef(({className:e,...t},s)=>(0,An.jsx)(wa.Content,{ref:s,className:te("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}));Sa.displayName=wa.Content.displayName;var ii=le(require("react"),1),oi=require("@radix-ui/react-slot"),li=require("class-variance-authority");var ci=require("react/jsx-runtime"),Go=(0,li.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"}}),_=ii.forwardRef(({className:e,variant:t,size:s,asChild:a=!1,...n},i)=>(0,ci.jsx)(a?oi.Slot:"button",{className:te(Go({variant:t,size:s,className:e})),ref:i,...n}));_.displayName="Button";var Hs=require("lucide-react");var qa=le(require("react"),1);var Ia=require("react/jsx-runtime"),Ue=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,Ia.jsx)("table",{ref:s,className:te("af-w-full af-caption-bottom af-text-sm",e),...t})}));Ue.displayName="Table";var Ve=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("thead",{ref:s,className:te("[&_tr]:af-border-b",e),...t}));Ve.displayName="TableHeader";var He=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("tbody",{ref:s,className:te("[&_tr:last-child]:af-border-0",e),...t}));He.displayName="TableBody";var Wo=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("tfoot",{ref:s,className:te("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));Wo.displayName="TableFooter";var xe=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("tr",{ref:s,className:te("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));xe.displayName="TableRow";var H=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("th",{ref:s,className:te("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}));H.displayName="TableHead";var z=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("td",{ref:s,className:te("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));z.displayName="TableCell";var Ko=qa.forwardRef(({className:e,...t},s)=>(0,Ia.jsx)("caption",{ref:s,className:te("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));Ko.displayName="TableCaption";var _a=le(require("react"),1);function ds(){let{api:e}=ne(),[t,s]=_a.useState([]),[a,n]=_a.useState(!0),[i,o]=_a.useState(null),d=_a.useCallback(async()=>{try{n(!0),o(null);let v=await e.getForms();s(v)}catch(v){o(v instanceof Error?v:new Error("Failed to fetch forms"))}finally{n(!1)}},[e]);_a.useEffect(()=>{d()},[d]);let f=_a.useCallback(async v=>{let x=await e.createForm(v);return s(b=>[...b,x]),x},[e]),u=_a.useCallback(async(v,x)=>{let b=await e.updateForm(v,x);return s(c=>c.map(l=>l.id===v?b:l)),b},[e]),r=_a.useCallback(async v=>{await e.deleteForm(v),s(x=>x.filter(b=>b.id!==v))},[e]);return{forms:t,isLoading:a,error:i,refetch:d,createForm:f,updateForm:u,deleteForm:r}}var Je=require("react/jsx-runtime");function zs({onSelectForm:e,className:t}){let{forms:s,isLoading:a,error:n}=ds();return a?(0,Je.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Je.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):n?(0,Je.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Je.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})}):s.length===0?(0,Je.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Je.jsx)(Hs.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Je.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Je.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Je.jsx)("div",{className:t,children:(0,Je.jsxs)(Ue,{children:[(0,Je.jsx)(Ve,{children:(0,Je.jsxs)(xe,{children:[(0,Je.jsx)(H,{children:"Name"}),(0,Je.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,Je.jsx)(He,{children:s.map(i=>(0,Je.jsxs)(xe,{children:[(0,Je.jsx)(z,{className:"af-font-medium",children:i.name}),(0,Je.jsx)(z,{className:"af-text-right",children:(0,Je.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Je.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"submissions"),children:[(0,Je.jsx)(Hs.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Je.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>e?.(i,"settings"),children:[(0,Je.jsx)(Hs.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},i.id))})]})})}var fi=require("lucide-react");var ui=require("class-variance-authority");var di=require("react/jsx-runtime"),Zo=(0,ui.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 ae({className:e,variant:t,...s}){return(0,di.jsx)("div",{className:te(Zo({variant:t}),e),...s})}var Qt=require("react/jsx-runtime"),Jo={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 In(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 br(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function Yo(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 qs({deliveries:e,label:t="Email needs attention"}){return br(e)?(0,Qt.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,Qt.jsx)(fi.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Da({deliveries:e,problemsOnly:t=!1,className:s=""}){let a=(e??[]).filter(n=>!t||br([n]));return a.length?(0,Qt.jsx)("div",{className:`af-space-y-3 ${s}`,"aria-label":"Email delivery",children:a.map(n=>{let i=In(n),o=Yo(n);return(0,Qt.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,Qt.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,Qt.jsx)("span",{className:"af-font-medium",children:Jo[n.kind]??"Email notification"}),(0,Qt.jsx)(ae,{variant:i.variant,children:i.label})]}),(0,Qt.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&&br([n])&&(0,Qt.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,Qt.jsx)("p",{className:"af-mt-1",children:i.detail}),o&&(0,Qt.jsx)("p",{className:"af-mt-1",children:o})]},n.id)})}):null}var Ts=le(require("react"),1),pa=require("lucide-react");var rs=le(require("react"),1),Te=le(require("@radix-ui/react-select"),1),fs=require("lucide-react");var mt=require("react/jsx-runtime"),da=Te.Root;var fa=Te.Value,Xt=rs.forwardRef(({className:e,children:t,...s},a)=>(0,mt.jsxs)(Te.Trigger,{ref:a,className:te("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,mt.jsx)(Te.Icon,{asChild:!0,children:(0,mt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));Xt.displayName=Te.Trigger.displayName;var mi=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.ScrollUpButton,{ref:s,className:te("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,mt.jsx)(fs.ChevronUp,{className:"af-h-4 af-w-4"})}));mi.displayName=Te.ScrollUpButton.displayName;var pi=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.ScrollDownButton,{ref:s,className:te("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,mt.jsx)(fs.ChevronDown,{className:"af-h-4 af-w-4"})}));pi.displayName=Te.ScrollDownButton.displayName;var ea=rs.forwardRef(({className:e,children:t,position:s="popper",...a},n)=>(0,mt.jsx)(Te.Portal,{children:(0,mt.jsxs)(Te.Content,{ref:n,className:te("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,mt.jsx)(mi,{}),(0,mt.jsx)(Te.Viewport,{className:te("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,mt.jsx)(pi,{})]})}));ea.displayName=Te.Content.displayName;var Qo=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.Label,{ref:s,className:te("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));Qo.displayName=Te.Label.displayName;var Ye=rs.forwardRef(({className:e,children:t,...s},a)=>(0,mt.jsxs)(Te.Item,{ref:a,className:te("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,mt.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,mt.jsx)(Te.ItemIndicator,{children:(0,mt.jsx)(fs.Check,{className:"af-h-4 af-w-4"})})}),(0,mt.jsx)(Te.ItemText,{children:t})]}));Ye.displayName=Te.Item.displayName;var Xo=rs.forwardRef(({className:e,...t},s)=>(0,mt.jsx)(Te.Separator,{ref:s,className:te("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Xo.displayName=Te.Separator.displayName;var ma=le(require("react"),1);function js({formId:e,initialPageSize:t=25}){let{api:s}=ne(),[a,n]=ma.useState([]),[i,o]=ma.useState(0),[d,f]=ma.useState(!0),[u,r]=ma.useState(null),[v,x]=ma.useState(0),[b,c]=ma.useState(t),l=ma.useCallback(async()=>{if(e)try{f(!0),r(null);let S={limit:b,offset:v*b},O=await s.getSubmissions(e,S);n(O.submissions),o(O.total)}catch(S){r(S instanceof Error?S:new Error("Failed to fetch submissions"))}finally{f(!1)}},[s,e,v,b]);ma.useEffect(()=>{l()},[l]);let y=ma.useCallback(async S=>{await s.deleteSubmission(S),n(O=>O.filter(M=>M.id!==S)),o(O=>O-1)},[s]),N=Math.ceil(i/b);return{submissions:a,total:i,isLoading:d,error:u,page:v,pageSize:b,hasNextPage:v<N-1,hasPreviousPage:v>0,setPage:x,setPageSize:S=>{c(S),x(0)},refetch:l,deleteSubmission:y}}var vi=le(require("react"),1),Ot=require("lucide-react");var we=require("react/jsx-runtime");function gi(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function el(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 Gs({submission:e,onBack:t}){let{api:s}=ne(),[a,n]=vi.useState(null),i=f=>f.id??f.name,o=async f=>{n(i(f));try{await s.downloadAttachment(e.id,f)}catch(u){console.error("Download failed:",u)}finally{n(null)}},d=Object.entries(e.data).filter(([f])=>!f.startsWith("_"));return(0,we.jsxs)("div",{children:[(0,we.jsxs)("div",{className:"af-mb-6",children:[(0,we.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,we.jsx)(Ot.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,we.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,we.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",gi(e.metadata.submitted_at)]})]}),(0,we.jsxs)("div",{className:"af-space-y-6",children:[(0,we.jsx)(Da,{deliveries:e.email_deliveries}),(0,we.jsxs)("div",{children:[(0,we.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,we.jsxs)("div",{className:"af-space-y-3",children:[d.map(([f,u])=>(0,we.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,we.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:f.replace(/_/g," ")}),(0,we.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof u=="string"&&u.includes(`
3
- `)?(0,we.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:u}):String(u)})]},f)),d.length===0&&(0,we.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,we.jsxs)("div",{children:[(0,we.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,we.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((f,u)=>(0,we.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,we.jsx)(Ot.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,we.jsx)("span",{className:"af-text-sm",children:f.name}),(0,we.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",el(f.size),")"]})]}),(0,we.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>o(f),disabled:a===i(f),children:[a===i(f)?(0,we.jsx)(Ot.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,we.jsx)(Ot.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===i(f)?"Downloading...":"Download"]})]},u))})]}),(0,we.jsxs)("div",{children:[(0,we.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,we.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Clock,{className:"af-h-4 af-w-4"}),(0,we.jsx)("span",{children:gi(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Globe,{className:"af-h-4 af-w-4"}),(0,we.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,we.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,we.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,we.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,we.jsx)(Ot.Mail,{className:"af-h-4 af-w-4"}),(0,we.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var ue=require("react/jsx-runtime");function tl(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function al(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let s of t)if(typeof e[s]=="string")return e[s];return null}var sl=["message","comments","comment","inquiry","question","details","body","notes"];function nl(e){let t=Object.entries(e).filter(([i,o])=>!i.startsWith("_")&&!i.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),s=new Map(t.map(([i,o])=>[i.toLowerCase(),o])),n=(sl.map(i=>s.get(i)).find(Boolean)??t.reduce((i,[,o])=>o.length>i.length?o:i,"")).trim().replace(/\s+/g," ");return n.length>80?n.slice(0,80)+"\u2026":n}function Ws({formId:e,className:t,defaultSubmissionId:s,submissionId:a,onSelectSubmission:n}){let{api:i}=ne(),{submissions:o,total:d,isLoading:f,error:u,page:r,pageSize:v,hasNextPage:x,hasPreviousPage:b,setPage:c,setPageSize:l}=js({formId:e}),[y,N]=Ts.useState(s??null),S=n?a??null:y,O=n??N,M=F=>!!F&&F.id===S&&F.form_id===e,m=o.find(M),[R,T]=Ts.useState(null),D=M(R)?R:null,[P,A]=Ts.useState(null);if(Ts.useEffect(()=>{if(A(null),!S||m||D)return;let F=!1;return i.getSubmission(S).then(X=>{if(!F){if(X.form_id!==e){A("This submission could not be found.");return}T(X)}}).catch(()=>{F||A("This submission could not be found.")}),()=>{F=!0}},[i,e,S,m,D]),S){let F=m??D;return F?(0,ue.jsx)("div",{className:t,children:(0,ue.jsx)(Gs,{submission:F,onBack:()=>O(null)})}):P?(0,ue.jsxs)("div",{className:t,children:[(0,ue.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>O(null),className:"af-mb-2 af--ml-2",children:[(0,ue.jsx)(pa.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,ue.jsx)("p",{className:"af-text-sm af-text-destructive",children:P})]}):(0,ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(f)return(0,ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ue.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(u)return(0,ue.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,ue.jsxs)("div",{className:"af-text-destructive",children:["Error: ",u.message]})});if(o.length===0&&r===0)return(0,ue.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,ue.jsx)(pa.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,ue.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,ue.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let U=r*v+1,w=Math.min((r+1)*v,d);return(0,ue.jsxs)("div",{className:t,children:[(0,ue.jsxs)(Ue,{children:[(0,ue.jsx)(Ve,{children:(0,ue.jsxs)(xe,{children:[(0,ue.jsx)(H,{children:"Email"}),(0,ue.jsx)(H,{children:"Preview"}),(0,ue.jsx)(H,{children:"Date"}),(0,ue.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,ue.jsx)(He,{children:o.map(F=>{let X=al(F.data),q=nl(F.data);return(0,ue.jsxs)(xe,{children:[(0,ue.jsxs)(z,{className:"af-font-medium",children:[(0,ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[X||(0,ue.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),F.attachments.length>0&&(0,ue.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${F.attachments.length} attachment(s)`,children:[(0,ue.jsx)(pa.Paperclip,{className:"af-h-3 af-w-3"}),(0,ue.jsx)("span",{className:"af-text-xs",children:F.attachments.length})]})]}),(0,ue.jsx)(qs,{deliveries:F.email_deliveries,label:"Notification email needs attention"})]}),(0,ue.jsx)(z,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:q||(0,ue.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,ue.jsx)(z,{className:"af-text-muted-foreground",children:tl(F.metadata.submitted_at)}),(0,ue.jsx)(z,{className:"af-text-right",children:(0,ue.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>O(F.id),title:"View details",children:(0,ue.jsx)(pa.Eye,{className:"af-h-4 af-w-4"})})})]},F.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 ",U,"-",w," of ",d]}),(0,ue.jsxs)(da,{value:String(v),onValueChange:F=>l(Number(F)),children:[(0,ue.jsx)(Xt,{className:"af-w-[70px] af-h-8",children:(0,ue.jsx)(fa,{})}),(0,ue.jsxs)(ea,{children:[(0,ue.jsx)(Ye,{value:"10",children:"10"}),(0,ue.jsx)(Ye,{value:"25",children:"25"}),(0,ue.jsx)(Ye,{value:"50",children:"50"}),(0,ue.jsx)(Ye,{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:()=>c(r-1),disabled:!b,children:[(0,ue.jsx)(pa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,ue.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>c(r+1),disabled:!x,children:["Next",(0,ue.jsx)(pa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var aa=le(require("react"),1),is=require("lucide-react");var bi=le(require("react"),1);var yi=require("react/jsx-runtime"),Ne=bi.forwardRef(({className:e,type:t,...s},a)=>(0,yi.jsx)("input",{type:t,className:te("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}));Ne.displayName="Input";var hi=le(require("react"),1),xi=require("class-variance-authority");var wi=require("react/jsx-runtime"),rl=(0,xi.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),Re=hi.forwardRef(({className:e,...t},s)=>(0,wi.jsx)("label",{ref:s,className:te(rl(),e),...t}));Re.displayName="Label";var ga=le(require("react"),1),Bt=require("lucide-react");var Ks=le(require("react"),1),Nt=le(require("@radix-ui/react-dialog"),1),Ni=require("lucide-react");var jt=require("react/jsx-runtime"),La=Nt.Root;var il=Nt.Portal;var Si=Ks.forwardRef(({className:e,...t},s)=>(0,jt.jsx)(Nt.Overlay,{ref:s,className:te("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));Si.displayName=Nt.Overlay.displayName;var Ra=Ks.forwardRef(({className:e,children:t,...s},a)=>(0,jt.jsx)(il,{children:(0,jt.jsxs)("div",{className:"aifeatures-admin",children:[(0,jt.jsx)(Si,{}),(0,jt.jsxs)(Nt.Content,{ref:a,className:te("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,jt.jsxs)(Nt.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,jt.jsx)(Ni.X,{className:"af-h-4 af-w-4"}),(0,jt.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Ra.displayName=Nt.Content.displayName;var Pa=({className:e,...t})=>(0,jt.jsx)("div",{className:te("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});Pa.displayName="DialogHeader";var Ca=({className:e,...t})=>(0,jt.jsx)("div",{className:te("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});Ca.displayName="DialogFooter";var Ta=Ks.forwardRef(({className:e,...t},s)=>(0,jt.jsx)(Nt.Title,{ref:s,className:te("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));Ta.displayName=Nt.Title.displayName;var ka=Ks.forwardRef(({className:e,...t},s)=>(0,jt.jsx)(Nt.Description,{ref:s,className:te("af-text-sm af-text-muted-foreground",e),...t}));ka.displayName=Nt.Description.displayName;var ta=le(require("react"),1);function Zs(){let{api:e}=ne(),[t,s]=ta.useState([]),[a,n]=ta.useState(!0),[i,o]=ta.useState(null),d=ta.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]);ta.useEffect(()=>{d()},[d]);let f=ta.useCallback(async b=>{let c=await e.createEventDestination(b);return s(l=>[c,...l]),c},[e]),u=ta.useCallback(async(b,c)=>{let l=await e.updateEventDestination(b,c);return s(y=>y.map(N=>N.id===b?l:N)),l},[e]),r=ta.useCallback(async b=>{await e.deleteEventDestination(b),s(c=>c.filter(l=>l.id!==b))},[e]),v=ta.useCallback(async b=>{let c=await e.rotateEventDestinationSecret(b);return s(l=>l.map(y=>y.id===b?c:y)),c},[e]),x=ta.useCallback(b=>e.getEventDestinationSecret(b),[e]);return{destinations:t,isLoading:a,error:i,refetch:d,createDestination:f,updateDestination:u,deleteDestination:r,rotateSecret:v,getSecret:x}}var ja=le(require("react"),1),Js=require("lucide-react");var St=require("react/jsx-runtime");function Ys({destinationId:e,limit:t=25,className:s}){let{api:a}=ne(),[n,i]=ja.useState([]),[o,d]=ja.useState(!0),[f,u]=ja.useState(null),[r,v]=ja.useState(null),x=ja.useCallback(async()=>{try{d(!0),u(null),i(await a.getEventDeliveries(e,t))}catch(c){u(c instanceof Error?c.message:"Failed to load deliveries")}finally{d(!1)}},[a,e,t]);ja.useEffect(()=>{x()},[x]);let b=async c=>{try{v(c.id),u(null);let l=await a.retryEventDelivery(e,c.id);i(y=>y.map(N=>N.id===c.id?l:N))}catch(l){u(l instanceof Error?l.message:"Retry failed")}finally{v(null)}};return o?(0,St.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,St.jsx)(Js.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):f?(0,St.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:f}):n.length===0?(0,St.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,St.jsx)("div",{className:s,children:(0,St.jsx)("div",{className:"af-divide-y af-border af-rounded",children:n.map(c=>{let l=c.delivered_at!==null;return(0,St.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,St.jsxs)("div",{className:"af-min-w-0",children:[(0,St.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[l?(0,St.jsx)(ae,{variant:"secondary",children:c.last_status??200}):(0,St.jsx)(ae,{variant:"destructive",children:c.last_status??"failed"}),(0,St.jsx)("span",{className:"af-text-sm af-truncate",children:c.type})]}),(0,St.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[c.event_id," \xB7 ",c.created_at,c.attempts>0&&` \xB7 ${c.attempts} failed ${c.attempts===1?"attempt":"attempts"}`]}),!l&&c.last_error&&(0,St.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),(0,St.jsx)(_,{variant:"ghost",size:"sm",title:"Send this event again",disabled:r===c.id,onClick:()=>b(c),children:r===c.id?(0,St.jsx)(Js.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,St.jsx)(Js.RotateCw,{className:"af-h-4 af-w-4"})})]},c.id)})})})}var me=require("react/jsx-runtime");function Qs({formId:e,topics:t,description:s,className:a}){let{destinations:n,isLoading:i,error:o,createDestination:d,updateDestination:f,deleteDestination:u,rotateSecret:r,getSecret:v}=Zs(),[x,b]=ga.useState(""),[c,l]=ga.useState(!1),[y,N]=ga.useState(null),[S,O]=ga.useState(null),[M,m]=ga.useState(null),[R,T]=ga.useState(!1),[D,P]=ga.useState(null),[A,U]=ga.useState(null),[w,F]=ga.useState(null),X=ga.useMemo(()=>n.filter(Y=>Y.form_id===e),[n,e]),q=async()=>{let Y=x.trim();if(Y){if(!Y.startsWith("https://")){N("Webhook URLs must start with https://");return}try{l(!0),N(null),await d({url:Y,form_id:e,...t&&t.length>0?{topics:t}:{}}),b("")}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{l(!1)}}},fe=async Y=>{try{U(Y.id),N(null),await r(Y.id),T(!1),m(await v(Y.id))}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{U(null)}},J=async Y=>{try{U(Y.id),N(null),await f(Y.id,{status:"active"})}catch(Pe){N(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{U(null)}},ee=async()=>{if(D)try{U(D.id),await u(D.id),P(null)}catch(Y){N(Y instanceof Error?Y.message:"Failed to delete")}finally{U(null)}},Z=async Y=>{if(S===Y.id){O(null),m(null);return}try{U(Y.id),N(null),T(!1),O(Y.id),m(await v(Y.id))}catch(Pe){O(null),N(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{U(null)}},oe=async()=>{if(M)try{await navigator.clipboard.writeText(M),T(!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)(Ne,{value:x,placeholder:"https://hooks.zapier.com/...",onChange:Y=>b(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"&&(Y.preventDefault(),q())},disabled:c}),(0,me.jsxs)(_,{onClick:q,disabled:c||!x.trim(),children:[c?(0,me.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,me.jsx)(Bt.Plus,{className:"af-h-4 af-w-4"}),(0,me.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(y||o)&&(0,me.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:y||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)(Bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!i&&X.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."}),X.map(Y=>(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:Y.url}),Y.status==="disabled"?(0,me.jsx)(ae,{variant:"destructive",children:"Disabled"}):(0,me.jsx)(ae,{variant:"secondary",children:"Active"})]}),(0,me.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:Y.topics.includes("*")?"All events":Y.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:()=>F(w===Y.id?null:Y.id),children:w===Y.id?"Hide log":"Deliveries"}),(0,me.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>Z(Y),disabled:A===Y.id,children:S===Y.id?"Hide secret":"Show secret"}),(0,me.jsx)(_,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:A===Y.id,onClick:()=>P(Y),children:(0,me.jsx)(Bt.Trash2,{className:"af-h-4 af-w-4"})})]})]}),Y.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)(Bt.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."," ",Y.disabled_reason]}),(0,me.jsx)(_,{variant:"outline",size:"sm",className:"af-mt-2",disabled:A===Y.id,onClick:()=>J(Y),children:"Re-enable"})]})]}),S===Y.id&&M&&(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)(Ne,{readOnly:!0,value:M,className:"af-font-mono"}),(0,me.jsx)(_,{variant:"outline",title:"Copy signing secret",onClick:oe,children:R?(0,me.jsx)(Bt.Check,{className:"af-h-4 af-w-4"}):(0,me.jsx)(Bt.Copy,{className:"af-h-4 af-w-4"})}),(0,me.jsx)(_,{variant:"outline",title:"Rotate signing secret",disabled:A===Y.id,onClick:()=>fe(Y),children:A===Y.id?(0,me.jsx)(Bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,me.jsx)(Bt.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),w===Y.id&&(0,me.jsx)(Ys,{destinationId:Y.id})]},Y.id))]}),(0,me.jsx)(La,{open:!!D,onOpenChange:Y=>{!Y&&!A&&P(null)},children:(0,me.jsxs)(Ra,{children:[(0,me.jsxs)(Pa,{children:[(0,me.jsx)(Ta,{children:"Delete this webhook?"}),(0,me.jsxs)(ka,{children:["New submissions will stop being sent to ",D?.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)(Ca,{children:[(0,me.jsx)(_,{variant:"outline",onClick:()=>P(null),disabled:!!A,children:"Cancel"}),(0,me.jsx)(_,{variant:"destructive",onClick:ee,disabled:!!A,children:A?"Deleting...":"Delete"})]})]})})]})}var _e=require("react/jsx-runtime");function Xs({form:e,onSaved:t,className:s}){let{updateForm:a}=ds(),[n,i]=aa.useState(!1),[o,d]=aa.useState(null),[f,u]=aa.useState(null),[r,v]=aa.useState(e.name),[x,b]=aa.useState(e.redirect_url||""),[c,l]=aa.useState(e.email_recipients),[y,N]=aa.useState("");aa.useEffect(()=>{v(e.name),b(e.redirect_url||""),l(e.email_recipients),u(null)},[e]);let S=aa.useCallback(async T=>{try{i(!0),u(null);let D=await a(e.id,T);d(new Date),t?.(D)}catch(D){u(D instanceof Error?D.message:"Failed to save")}finally{i(!1)}},[e.id,a,t]);aa.useEffect(()=>{if(o){let T=setTimeout(()=>d(null),2e3);return()=>clearTimeout(T)}},[o]);let O=async()=>{let T=y.trim().toLowerCase();if(!T)return;if(!T.includes("@")){u("Please enter a valid email address");return}if(c.includes(T)){u("This email is already added");return}let D=[...c,T];l(D),N(""),u(null),await S({email_recipients:D})},M=async T=>{let D=c.filter(P=>P!==T);l(D),await S({email_recipients:D})},m=async()=>{r!==e.name&&await S({name:r})},R=async()=>{let T=x||null;T!==e.redirect_url&&await S({redirect_url:T})};return(0,_e.jsxs)("div",{className:`af-space-y-6 af-relative ${s||""}`,children:[(n||o)&&(0,_e.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:n?(0,_e.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,_e.jsx)(is.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,_e.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,_e.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,_e.jsx)(is.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,_e.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{htmlFor:"form-name",children:"Form Name"}),(0,_e.jsx)(Ne,{id:"form-name",value:r,onChange:T=>v(T.target.value),onBlur:m,placeholder:"Contact Form"}),(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{children:"Email Recipients"}),(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,_e.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(T=>(0,_e.jsxs)(ae,{variant:"secondary",className:"af-gap-1",children:[T,(0,_e.jsx)("button",{type:"button",onClick:()=>M(T),className:"af-ml-1 hover:af-text-destructive",disabled:n,children:(0,_e.jsx)(is.X,{className:"af-h-3 af-w-3"})})]},T)),c.length===0&&(0,_e.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,_e.jsx)(Ne,{type:"email",value:y,onChange:T=>N(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),O())},disabled:n}),(0,_e.jsx)(_,{type:"button",variant:"outline",onClick:O,disabled:!y.trim()||n,children:(0,_e.jsx)(is.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,_e.jsx)(Ne,{id:"redirect-url",value:x,onChange:T=>b(T.target.value),onBlur:R,placeholder:"/thank-you"}),(0,_e.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,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{children:"Form Endpoint"}),(0,_e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,_e.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,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,_e.jsxs)("div",{className:"af-space-y-2",children:[(0,_e.jsx)(Re,{children:"Captcha Protection"}),(0,_e.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,_e.jsx)(ae,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,_e.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,_e.jsx)(Qs,{formId:e.id}),f&&(0,_e.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:f})]})}var We=require("react/jsx-runtime");function yr({className:e,location:t,onNavigate:s,submissionId:a}){let{api:n}=ne(),[i,o]=Ga.useState({submissionId:a});Ga.useEffect(()=>{a&&o({submissionId:a})},[a]);let d=s?t??{}:i,f=s??o,[u,r]=Ga.useState(null),v=`${d.formId??""}|${d.submissionId??""}`,[x,b]=Ga.useState(null),c=x?.key===v?x.message:null,l=d.formId??(u&&u.submissionId===d.submissionId?u.formId:void 0);Ga.useEffect(()=>{let T=d.submissionId;if(!T||d.formId)return;let D=!1;return n.getSubmission(T).then(P=>{D||(b(null),r({submissionId:T,formId:P.form_id}))}).catch(()=>{D||b({key:v,message:"This submission could not be found."})}),()=>{D=!0}},[n,d.submissionId,d.formId,v]);let[y,N]=Ga.useState(null);Ga.useEffect(()=>{if(!l||y?.id===l)return;let T=!1;return n.getForm(l).then(D=>{T||(b(null),N(D))}).catch(()=>{T||b({key:v,message:"This form could not be found."})}),()=>{T=!0}},[n,l,y?.id,v]);let S=(T,D)=>{N(T),f({formId:T.id,tab:D})},O=()=>f({});if(!d.formId&&!d.submissionId)return(0,We.jsxs)("div",{className:e,children:[(0,We.jsxs)("div",{className:"af-mb-6",children:[(0,We.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,We.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,We.jsx)(zs,{onSelectForm:S})]});let m=(0,We.jsxs)(_,{variant:"ghost",size:"sm",onClick:O,className:"af-mb-2 af--ml-2",children:[(0,We.jsx)(ks.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(c)return(0,We.jsxs)("div",{className:e,children:[m,(0,We.jsx)("p",{className:"af-text-sm af-text-destructive",children:c})]});if(!l||y?.id!==l)return(0,We.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,We.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let R=d.submissionId?"submissions":d.tab??"submissions";return(0,We.jsxs)("div",{className:e,children:[(0,We.jsxs)("div",{className:"af-mb-6",children:[m,(0,We.jsx)("h2",{className:"af-text-lg af-font-semibold",children:y.name})]}),(0,We.jsxs)(En,{value:R,onValueChange:T=>f({formId:l,tab:T}),children:[(0,We.jsxs)(Vs,{className:"af-mb-4",children:[(0,We.jsxs)(Na,{value:"submissions",className:"af-gap-2",children:[(0,We.jsx)(ks.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,We.jsxs)(Na,{value:"settings",className:"af-gap-2",children:[(0,We.jsx)(ks.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,We.jsx)(Sa,{value:"submissions",children:(0,We.jsx)(Ws,{formId:l,submissionId:d.submissionId,onSelectSubmission:T=>f({formId:l,tab:"submissions",submissionId:T??void 0})})}),(0,We.jsx)(Sa,{value:"settings",children:(0,We.jsx)(Xs,{form:y,onSaved:N})})]})]})}var $e=le(require("react"),1);var Oa=le(require("react"),1);function Wa(){let{api:e}=ne(),[t,s]=Oa.useState(null),[a,n]=Oa.useState(!0),[i,o]=Oa.useState(null),d=Oa.useRef(0),f=Oa.useCallback(async()=>{let u=++d.current;try{n(!0),o(null);let r=await e.getPaymentsStatus();if(u!==d.current)return;s(r)}catch(r){if(u!==d.current)return;o(r instanceof Error?r:new Error("Failed to fetch payments status"))}finally{u===d.current&&n(!1)}},[e]);return Oa.useEffect(()=>{f()},[f]),{status:t,isLoading:a,error:i,refetch:f}}var ol=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function sa(e){return ol.has(e.toLowerCase())}function W(e,t,s){let a=sa(t)?e:e/100;try{return new Intl.NumberFormat(s,{style:"currency",currency:t.toUpperCase()}).format(a)}catch{return`${a} ${t.toUpperCase()}`}}function Ba(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 Mt(e,t){let s=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(s)||s<0)return null;let a=sa(t)?s:s*100;return Math.round(a)}function pt(e,t){return sa(t)?e:e/100}function Dn(e){return e.amount_paid??Math.max(0,Ba(e)-(e.credit_applied??0))}var ie=require("react/jsx-runtime");function en(e){return e instanceof It&&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 _i(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${W(e.amount_off,e.currency)} off`:"Discount unavailable"}function ms(){let{api:e,siteToken:t}=ne();return(0,ie.jsx)(ll,{api:e},t)}function ll({api:e}){let{status:t,error:s}=Wa(),[a,n]=$e.useState([]),[i,o]=$e.useState(null),[d,f]=$e.useState(null),[u,r]=$e.useState(!1),[v,x]=$e.useState(!1),[b,c]=$e.useState(""),[l,y]=$e.useState(null),[N,S]=$e.useState(null),[O,M]=$e.useState(!1),m=$e.useRef(0),R=$e.useCallback(async P=>{let A=++m.current;r(!0),c("");try{let U=await e.getPromos(P);if(A!==m.current)return;n(w=>P?[...w,...U.promos.filter(F=>!w.some(X=>X.id===F.id))]:U.promos),o(U.next_cursor),f(U.checkout_enabled)}catch(U){A===m.current&&c(en(U))}finally{A===m.current&&r(!1)}},[e]);$e.useEffect(()=>(R(),()=>{m.current++}),[R]);async function T(P){let A=++m.current;r(!0),c(""),M(!1);try{let U=await e.getPromo(P);A===m.current&&y(U)}catch(U){A===m.current&&c(en(U))}finally{A===m.current&&r(!1)}}async function D(){if(l){x(!0),r(!0),c("");try{let P=await e.disablePromo(l.id);if(y(P),!["inactive","expired","exhausted"].includes(P.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");M(!1),await R()}catch(P){c(en(P))}finally{x(!1),r(!1)}}}return N?(0,ie.jsx)(cl,{currency:t?.currency??void 0,replaces:N.replaces,onCancel:()=>S(null),onSave:async P=>{let A=N.replaces?await e.replacePromo(N.replaces.id,P):await e.createPromo(P),U=await e.getPromo(A.id);if(U.status==="pending"||U.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");y(U),S(null),await R()}}):(0,ie.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,ie.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,ie.jsx)(_,{disabled:u||!t?.currency,onClick:()=>{c(""),S({})},children:"Create promo code"})]}),(0,ie.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."}),d===!1&&(0,ie.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,ie.jsx)("p",{className:"af-text-sm",children:s?en(s):"Connect Stripe and set the payment currency before creating codes."}),b&&(0,ie.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[b," ",(0,ie.jsx)(_,{variant:"outline",disabled:u,onClick:()=>l?void T(l.id):void R(),children:"Refresh"})]}),l?(0,ie.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,ie.jsx)(_,{variant:"ghost",disabled:v,onClick:()=>{y(null),M(!1),R()},children:"Back to codes"}),(0,ie.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[l.code," \xB7 ",l.name]}),(0,ie.jsxs)("p",{children:[_i(l)," \xB7 ",l.status]}),(0,ie.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,ie.jsxs)("p",{className:"af-text-sm",children:[l.minimum_amount!=null&&l.currency?`Minimum order: ${W(l.minimum_amount,l.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,ie.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,ie.jsx)("p",{className:"af-text-sm",children:l.expires_at?`Expires ${new Date(l.expires_at).toLocaleString()}`:"No expiry"}),(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ie.jsx)(_,{variant:"outline",disabled:u,onClick:()=>void T(l.id),children:"Refresh details"}),(0,ie.jsx)(_,{variant:"outline",disabled:u||l.status==="pending"||l.status==="unavailable"||!t?.currency,onClick:()=>S({replaces:l}),children:"Replace with new code"}),(0,ie.jsx)(_,{variant:"outline",disabled:u||!["active","pending","unavailable"].includes(l.status),onClick:()=>M(!0),children:l.status==="pending"?"Cancel pending offer":"Disable code"})]}),O&&(0,ie.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,ie.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,ie.jsx)(_,{disabled:u,onClick:()=>void D(),children:l.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,ie.jsx)(_,{variant:"ghost",disabled:u,onClick:()=>M(!1),children:"Cancel"})]})]}):(0,ie.jsxs)(ie.Fragment,{children:[a.map(P=>(0,ie.jsxs)("button",{type:"button",disabled:u,onClick:()=>void T(P.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,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,ie.jsx)("span",{className:"af-font-semibold af-break-all",children:P.code}),(0,ie.jsx)("span",{className:"af-text-sm",children:P.status})]}),(0,ie.jsxs)("div",{className:"af-text-sm",children:[_i(P)," \xB7"," ",P.times_redeemed==null?"Usage unavailable":`${P.times_redeemed} redemptions`]})]},P.id)),!u&&!b&&a.length===0&&(0,ie.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."}),u&&(0,ie.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),i&&(0,ie.jsx)(_,{variant:"outline",disabled:u,onClick:()=>void R(i),children:"Load more"})]})]})}function cl({currency:e,replaces:t,onCancel:s,onSave:a}){let[n,i]=$e.useState(""),[o,d]=$e.useState(t?.name??""),[f,u]=$e.useState(t?.amount_off!=null?"fixed":"percent"),[r,v]=$e.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(pt(t.amount_off,e)):"")),[x,b]=$e.useState(t?.minimum_amount!=null&&e?String(pt(t.minimum_amount,e)):""),[c,l]=$e.useState(()=>{if(!t?.expires_at)return"";let J=new Date(t.expires_at);return Number.isFinite(J.getTime())?new Date(J.getTime()-J.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[y,N]=$e.useState(t?.max_redemptions?.toString()??""),[S,O]=$e.useState(t?.duration??"once"),[M,m]=$e.useState(t?.duration_in_months?.toString()??"3"),[R,T]=$e.useState(null),[D,P]=$e.useState(!1),[A,U]=$e.useState(""),w=$e.useRef(!1),F=e&&sa(e)?"1":"0.01";async function X(J){if(J.preventDefault(),w.current)return;U("");let ee=R;if(!ee){if(!e){U("Payment currency is not available.");return}if(t&&n.trim().toUpperCase()===t.code.toUpperCase()){U("Choose a different code for the replacement.");return}let Z=Mt(r,e),oe=x?Mt(x,e):null;if(f==="fixed"&&(!Z||Z>999999999999)||x&&(!oe||oe>999999999999)){U("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){U("Choose a future expiry.");return}ee={request_id:crypto.randomUUID(),code:n.trim().toUpperCase(),name:o.trim(),duration:S,...f==="percent"?{percent_off:Number(r)}:{amount_off:Z,currency:e},...x?{minimum_amount:oe,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...y?{max_redemptions:Number(y)}:{},...S==="repeating"?{duration_in_months:Number(M)}:{}},T(ee)}w.current=!0,P(!0);try{await a(ee)}catch(Z){U(en(Z)),Z instanceof It&&Z.status>=400&&Z.status<500&&Z.details?.retryable!==!0&&T(null)}finally{w.current=!1,P(!1)}}let q=(J,ee,Z,oe={})=>(0,ie.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[J,(0,ie.jsx)(Ne,{"aria-label":J,value:ee,onChange:Y=>Z(Y.target.value),...oe})]}),fe="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,ie.jsxs)("form",{onSubmit:X,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,ie.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,ie.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,ie.jsxs)("fieldset",{disabled:D||!!R,className:"af-grid af-gap-4",children:[q("Code",n,i,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),q("Name",o,d,{required:!0,maxLength:40}),(0,ie.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,ie.jsxs)("select",{"aria-label":"Discount type",className:fe,value:f,onChange:J=>u(J.target.value),children:[(0,ie.jsx)("option",{value:"percent",children:"Percentage"}),(0,ie.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),q("Discount",r,v,{type:"number",required:!0,min:f==="percent"?"0.01":F,max:f==="percent"?"100":void 0,step:f==="percent"?"0.01":F}),q("Minimum order amount",x,b,{type:"number",min:F,step:F,placeholder:e?.toUpperCase()}),(0,ie.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."]}),q("Expires at (local time)",c,l,{type:"datetime-local",step:1}),q("Maximum redemptions",y,N,{type:"number",min:1,max:1e6,step:1}),(0,ie.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,ie.jsxs)("select",{"aria-label":"Subscription duration",className:fe,value:S,onChange:J=>O(J.target.value),children:[(0,ie.jsx)("option",{value:"once",children:"First invoice only"}),(0,ie.jsx)("option",{value:"forever",children:"Every invoice"}),(0,ie.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),S==="repeating"&&q("Months",M,m,{type:"number",required:!0,min:1,max:36,step:1})]}),A&&(0,ie.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:A}),R&&!D&&(0,ie.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,ie.jsx)("span",{className:"af-break-all",children:R.request_id})]}),(0,ie.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,ie.jsx)(_,{type:"submit",disabled:D,children:D?"Saving\u2026":R?"Retry same request":t?"Create replacement":"Create code"}),(0,ie.jsx)(_,{type:"button",variant:"ghost",disabled:D||!!R,onClick:s,children:"Cancel"})]})]})}var Ls=le(require("react"),1),ha=require("lucide-react");var Ln=le(require("react"),1),Ka=require("lucide-react");var be=require("react/jsx-runtime");function ul(e){if(e.allow_custom_amount){let t=e.min_amount!==null?W(e.min_amount,e.currency):"?",s=e.max_amount!==null?W(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${s})`}return e.unit_amount===null?"Varies by variant":W(e.unit_amount,e.currency)}function dl(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function tn({productsState:e,onSelectProduct:t,onCreateProduct:s,className:a}){let{products:n,isLoading:i,error:o,deleteProduct:d}=e,[f,u]=Ln.useState(null),[r,v]=Ln.useState(!1),[x,b]=Ln.useState(null),c=async()=>{if(f)try{v(!0),b(null),await d(f.id),u(null)}catch(l){b(l instanceof Error?l.message:"Failed to delete product")}finally{v(!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)(Ka.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)(Ka.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)(Ka.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,be.jsxs)(Ue,{children:[(0,be.jsx)(Ve,{children:(0,be.jsxs)(xe,{children:[(0,be.jsx)(H,{children:"Name"}),(0,be.jsx)(H,{children:"Price"}),(0,be.jsx)(H,{children:"Fulfillment"}),(0,be.jsx)(H,{children:"Status"}),(0,be.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,be.jsx)(He,{children:n.map(l=>(0,be.jsxs)(xe,{children:[(0,be.jsx)(z,{className:"af-font-medium",children:l.name}),(0,be.jsx)(z,{children:ul(l)}),(0,be.jsx)(z,{className:"af-text-muted-foreground",children:dl(l)}),(0,be.jsx)(z,{children:(0,be.jsx)(ae,{variant:l.active?"success":"secondary",children:l.active?"Active":"Inactive"})}),(0,be.jsx)(z,{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)(Ka.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,be.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>{b(null),u(l)},children:[(0,be.jsx)(Ka.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},l.id))})]}),(0,be.jsx)(La,{open:!!f,onOpenChange:l=>{!l&&!r&&u(null)},children:(0,be.jsxs)(Ra,{children:[(0,be.jsxs)(Pa,{children:[(0,be.jsx)(Ta,{children:"Delete product?"}),(0,be.jsxs)(ka,{children:['"',f?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),x&&(0,be.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:x}),(0,be.jsxs)(Ca,{children:[(0,be.jsx)(_,{variant:"outline",onClick:()=>u(null),disabled:r,children:"Cancel"}),(0,be.jsx)(_,{variant:"destructive",onClick:c,disabled:r,children:r?"Deleting...":"Delete"})]})]})})]})}var et=le(require("react"),1),na=require("lucide-react");var bt=le(require("react"),1),va=require("lucide-react");var E=require("react/jsx-runtime");function hr(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function an({productId:e,currency:t,className:s}){let{api:a}=ne(),n=sa(t)?"1":"0.01",[i,o]=bt.useState(null),[d,f]=bt.useState(!0),[u,r]=bt.useState(null),[v,x]=bt.useState(null),[b,c]=bt.useState(!1),l=bt.useRef(!0);bt.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);let y=bt.useCallback(async()=>{try{let k=await a.getProduct(e);if(!l.current)return;o(k)}catch(k){if(!l.current)return;r(k instanceof Error?k.message:"Failed to load product")}finally{l.current&&f(!1)}},[a,e]);bt.useEffect(()=>{y()},[y]);let N=async k=>{x(null),c(!0);try{await k(),await y()}catch(B){l.current&&x(B instanceof Error?B.message:"Something went wrong")}finally{l.current&&c(!1)}},[S,O]=bt.useState(""),[M,m]=bt.useState(""),[R,T]=bt.useState({}),D=()=>N(async()=>{let k=S.trim(),B=M.split(",").map(L=>L.trim()).filter(Boolean);if(!k)throw new Error("Option name is required");if(B.length===0)throw new Error("Add at least one value");await a.createOption(e,{title:k,values:B}),l.current&&(O(""),m(""))}),P=k=>N(async()=>{let B=(R[k.id]??"").trim();if(!B)throw new Error("Enter a value");await a.updateOption(k.id,{add_values:[B]}),l.current&&T(L=>({...L,[k.id]:""}))}),A=(k,B)=>N(()=>a.updateOption(k.id,{remove_values:[B]})),U=k=>N(()=>a.deleteOption(k.id)),[w,F]=bt.useState(null),[X,q]=bt.useState(null),[fe,J]=bt.useState(!1),[ee,Z]=bt.useState(null),oe=i?.options??[],Y=i?.variants??[],Pe=()=>{q(null),F({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(oe.map(k=>[k.id,k.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Xe=k=>{q(null);let B=k.inventory?.on_hand??0,L=B<0?"":String(B);F({variant:k,title:k.title??"",sku:k.sku??"",unitAmount:k.unit_amount!=null?String(pt(k.unit_amount,t)):"",compareAt:k.compare_at_amount!=null?String(pt(k.compare_at_amount,t)):"",active:k.active,optionValues:{},tracked:k.inventory?.tracked??!1,onHand:L,initialOnHand:L,allowBackorder:k.inventory?.allow_backorder??!1})},lt=async()=>{if(!w)return;q(null);let k=w.variant?.allow_custom_amount??!1,B=null,L=null;if(!k){if(B=Mt(w.unitAmount,t),B===null||B<=0){q("Enter a valid price");return}if(w.compareAt.trim()&&(L=Mt(w.compareAt,t),L===null||L<=B)){q("Compare-at price must be greater than the price");return}}let pe=w.onHand.trim()!==w.initialOnHand.trim(),he=parseInt(w.onHand,10);if(w.tracked&&pe&&(!Number.isFinite(he)||he<0)){q("On-hand quantity must be zero or more");return}try{if(J(!0),w.variant)await a.updateVariant(w.variant.id,{title:w.title.trim()||null,sku:w.sku.trim()||null,...k?{}:{unit_amount:B,compare_at_amount:L},active:w.active}),await a.setVariantInventory(w.variant.id,{tracked:w.tracked,on_hand:w.tracked&&pe?he:void 0,allow_backorder:w.allowBackorder});else{let Ee={};for(let Oe of oe){let st=w.optionValues[Oe.id];if(!st){q(`Choose a ${Oe.title}`),J(!1);return}Ee[Oe.title]=st}await a.createVariant(e,{title:w.title.trim()||null,sku:w.sku.trim()||null,unit_amount:B,compare_at_amount:L,active:w.active,option_values:oe.length>0?Ee:void 0,inventory:w.tracked?{tracked:!0,on_hand:he,allow_backorder:w.allowBackorder}:{tracked:!1,allow_backorder:w.allowBackorder}})}await y(),l.current&&F(null)}catch(Ee){if(l.current&&q(Ee instanceof Error?Ee.message:"Failed to save variant"),w.variant)try{let Oe=await a.getProduct(e);l.current&&o(Oe)}catch{}}finally{l.current&&J(!1)}},Ae=()=>N(async()=>{ee&&(await a.deleteVariant(ee.id),l.current&&Z(null))}),Ge=w?.variant?.allow_custom_amount??!1,at=w?.variant!=null&&w.variant.option_values.length===0&&oe.length>0&&!w.variant.active,Ce=w?.variant?.inventory!=null&&w.variant.inventory.on_hand<0?-w.variant.inventory.on_hand:null;function Et(k){let B=k.inventory;if(!B||!B.tracked)return(0,E.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let L=B.available??B.on_hand;return L<0?(0,E.jsxs)("span",{children:[-L," backordered"]}):(0,E.jsxs)("span",{children:[L," in stock",B.allow_backorder&&(0,E.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return d?(0,E.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${s||""}`,children:(0,E.jsx)(va.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):u?(0,E.jsx)("div",{className:s,children:(0,E.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})}):(0,E.jsxs)("div",{className:`af-space-y-6 ${s||""}`,children:[(0,E.jsxs)("div",{className:"af-space-y-3",children:[(0,E.jsxs)("div",{children:[(0,E.jsx)(Re,{children:"Options"}),(0,E.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."})]}),oe.length>0&&(0,E.jsx)("div",{className:"af-space-y-3",children:oe.map(k=>(0,E.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,E.jsx)("span",{className:"af-text-sm af-font-medium",children:k.title}),(0,E.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>U(k),disabled:b,children:(0,E.jsx)(va.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,E.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:k.values.map(B=>(0,E.jsxs)(ae,{variant:"secondary",className:"af-gap-1",children:[B.value,(0,E.jsx)("button",{type:"button",onClick:()=>A(k,B.value),className:"af-ml-1 hover:af-text-destructive",disabled:b,title:"Remove value",children:(0,E.jsx)(va.X,{className:"af-h-3 af-w-3"})})]},B.id))}),(0,E.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,E.jsx)(Ne,{value:R[k.id]??"",onChange:B=>T(L=>({...L,[k.id]:B.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),P(k))},disabled:b}),(0,E.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>P(k),disabled:b||!(R[k.id]??"").trim(),children:(0,E.jsx)(va.Plus,{className:"af-h-4 af-w-4"})})]})]},k.id))}),(0,E.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,E.jsx)(Ne,{id:"new-option-title",value:S,onChange:k=>O(k.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:b})]}),(0,E.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,E.jsx)(Re,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,E.jsx)(Ne,{id:"new-option-values",value:M,onChange:k=>m(k.target.value),placeholder:"S, M, L",disabled:b})]}),(0,E.jsxs)(_,{type:"button",variant:"outline",onClick:D,disabled:b||!S.trim()||!M.trim(),children:[(0,E.jsx)(va.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,E.jsxs)("div",{className:"af-space-y-3",children:[(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,E.jsx)(Re,{children:"Variants"}),(0,E.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:b||oe.length===0,children:[(0,E.jsx)(va.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),oe.length===0&&(0,E.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),Y.length===0?(0,E.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,E.jsxs)(Ue,{children:[(0,E.jsx)(Ve,{children:(0,E.jsxs)(xe,{children:[(0,E.jsx)(H,{children:"Variant"}),(0,E.jsx)(H,{children:"SKU"}),(0,E.jsx)(H,{children:"Price"}),(0,E.jsx)(H,{children:"Stock"}),(0,E.jsx)(H,{children:"Status"}),(0,E.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,E.jsx)(He,{children:Y.map(k=>(0,E.jsxs)(xe,{children:[(0,E.jsx)(z,{className:"af-font-medium",children:hr(k)}),(0,E.jsx)(z,{className:"af-text-muted-foreground",children:k.sku||"-"}),(0,E.jsx)(z,{children:k.unit_amount!=null?(0,E.jsxs)("span",{children:[k.compare_at_amount!=null&&(0,E.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:W(k.compare_at_amount,k.currency)}),W(k.unit_amount,k.currency)]}):k.allow_custom_amount?(0,E.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,E.jsx)(z,{children:Et(k)}),(0,E.jsx)(z,{children:(0,E.jsx)(ae,{variant:k.active?"success":"secondary",children:k.active?"Active":"Inactive"})}),(0,E.jsx)(z,{className:"af-text-right",children:(0,E.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,E.jsx)(_,{variant:"ghost",size:"sm",onClick:()=>Xe(k),disabled:b,children:"Edit"}),(0,E.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>Z(k),disabled:b,title:"Delete variant",children:(0,E.jsx)(va.Trash2,{className:"af-h-4 af-w-4"})})]})})]},k.id))})]})]}),v&&(0,E.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:v}),(0,E.jsx)(La,{open:w!==null,onOpenChange:k=>{!k&&!fe&&F(null)},children:(0,E.jsxs)(Ra,{children:[(0,E.jsxs)(Pa,{children:[(0,E.jsx)(Ta,{children:w?.variant?"Edit variant":"Add variant"}),(0,E.jsx)(ka,{children:"Price, markdown, and stock live on the variant."})]}),w&&(0,E.jsxs)("div",{className:"af-space-y-3",children:[w.variant?w.variant.option_values.length>0&&(0,E.jsxs)("div",{className:"af-text-sm",children:[(0,E.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),hr(w.variant)]}):oe.map(k=>(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:k.title}),(0,E.jsxs)(da,{value:w.optionValues[k.id]??"",onValueChange:B=>F(L=>L&&{...L,optionValues:{...L.optionValues,[k.id]:B}}),children:[(0,E.jsx)(Xt,{children:(0,E.jsx)(fa,{placeholder:`Choose ${k.title}`})}),(0,E.jsx)(ea,{children:k.values.map(B=>(0,E.jsx)(Ye,{value:B.value,children:B.value},B.id))})]})]},k.id)),Ge?(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,E.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,E.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsxs)(Re,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,E.jsx)(Ne,{id:"variant-price",type:"number",min:"0",step:n,value:w.unitAmount,onChange:k=>F(B=>B&&{...B,unitAmount:k.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,E.jsx)(Ne,{id:"variant-compare",type:"number",min:"0",step:n,value:w.compareAt,onChange:k=>F(B=>B&&{...B,compareAt:k.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,E.jsx)(Ne,{id:"variant-sku",value:w.sku,onChange:k=>F(B=>B&&{...B,sku:k.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,E.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,E.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,E.jsx)("input",{type:"checkbox",checked:w.tracked,onChange:k=>F(B=>B&&{...B,tracked:k.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),w.tracked&&(0,E.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,E.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsx)(Re,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,E.jsx)(Ne,{id:"variant-onhand",type:"number",min:"0",step:"1",value:w.onHand,onChange:k=>F(B=>B&&{...B,onHand:k.target.value}),placeholder:Ce!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,E.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,E.jsx)("input",{type:"checkbox",checked:w.allowBackorder,onChange:k=>F(B=>B&&{...B,allowBackorder:k.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Ce!=null&&(0,E.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Ce," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,E.jsxs)("div",{className:"af-space-y-1",children:[(0,E.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,E.jsx)("input",{type:"checkbox",checked:w.active,onChange:k=>F(B=>B&&{...B,active:k.target.checked}),className:"af-h-4 af-w-4",disabled:at}),"Active (buyers can purchase this variant)"]}),at&&(0,E.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."})]}),X&&(0,E.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:X})]}),(0,E.jsxs)(Ca,{children:[(0,E.jsx)(_,{variant:"outline",onClick:()=>F(null),disabled:fe,children:"Cancel"}),(0,E.jsxs)(_,{onClick:lt,disabled:fe,children:[fe?(0,E.jsx)(va.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,w?.variant?"Save":"Add variant"]})]})]})}),(0,E.jsx)(La,{open:ee!==null,onOpenChange:k=>{!k&&!b&&Z(null)},children:(0,E.jsxs)(Ra,{children:[(0,E.jsxs)(Pa,{children:[(0,E.jsx)(Ta,{children:"Delete variant?"}),(0,E.jsx)(ka,{children:ee&&`"${hr(ee)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,E.jsxs)(Ca,{children:[(0,E.jsx)(_,{variant:"outline",onClick:()=>Z(null),disabled:b,children:"Cancel"}),(0,E.jsx)(_,{variant:"destructive",onClick:Ae,disabled:b,children:"Delete"})]})]})})]})}var K=require("react/jsx-runtime");function fl(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 sn({productsState:e,product:t,currency:s,onSaved:a,className:n}){let{createProduct:i,updateProduct:o,attachProductFile:d,attachProductFileFromUrl:f}=e,u=!!t,r=t?.currency??s,v=sa(r)?"1":"0.01",x=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[b,c]=et.useState(!1),[l,y]=et.useState(null),N=et.useRef(!0);et.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]);let[S,O]=et.useState(t?.name??""),[M,m]=et.useState(t?.description??""),[R,T]=et.useState(t?.allow_custom_amount?"custom":"fixed"),[D,P]=et.useState(t?.unit_amount!=null?String(pt(t.unit_amount,r)):""),[A,U]=et.useState(t?.min_amount!=null?String(pt(t.min_amount,r)):""),[w,F]=et.useState(t?.max_amount!=null?String(pt(t.max_amount,r)):""),[X,q]=et.useState(String(t?.max_quantity??10)),fe=et.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(pt(t.unit_amount,r)):"",minAmount:t?.min_amount!=null?String(pt(t.min_amount,r)):"",maxAmount:t?.max_amount!=null?String(pt(t.max_amount,r)):"",maxQuantity:String(t?.max_quantity??10)}).current,[J,ee]=et.useState(t?.collect_shipping_address??!1),[Z,oe]=et.useState(t?.active??!0),[Y,Pe]=et.useState(t?.images??[]),[Xe,lt]=et.useState(""),[Ae,Ge]=et.useState(t?.fulfillment??null),[at,Ce]=et.useState(!1),[Et,k]=et.useState(""),[B,L]=et.useState(null),pe=et.useRef(null),he=b||at,Ee=()=>{let ce=Xe.trim();if(ce){if(Y.includes(ce)){y("This image URL is already added");return}Pe(Be=>[...Be,ce]),lt(""),y(null)}},Oe=ce=>{Pe(Be=>Be.filter(ct=>ct!==ce))},st=async()=>{if(y(null),!S.trim()){y("Product name is required");return}let ce=null,Be=null,ct=null,Yt=!u||R!==fe.pricingMode||(R==="fixed"?D!==fe.unitAmount:A!==fe.minAmount||w!==fe.maxAmount),wt=!u||X!==fe.maxQuantity,At=x||R==="fixed";if(!(x||!Yt))if(R==="fixed"){if(ce=Mt(D,r),ce===null||ce<=0){y("Enter a valid price");return}}else{if(Be=Mt(A,r),ct=Mt(w,r),Be===null||ct===null){y("Enter valid minimum and maximum amounts");return}if(ct<Be){y("Maximum amount must be at least the minimum amount");return}}let Ht=parseInt(X,10);if(At&&wt&&(!Number.isFinite(Ht)||Ht<1)){y("Max quantity must be at least 1");return}try{c(!0);let qe;if(u&&t){let nt={name:S.trim(),description:M.trim()||null,images:Y,collect_shipping_address:J,active:Z};!x&&Yt&&(nt.allow_custom_amount=R==="custom",R==="fixed"?nt.unit_amount=ce:(nt.min_amount=Be,nt.max_amount=ct)),At&&wt&&(nt.max_quantity=Ht),qe=await o(t.id,nt),fe.pricingMode=qe.allow_custom_amount?"custom":"fixed",fe.unitAmount=qe.unit_amount!=null?String(pt(qe.unit_amount,r)):"",fe.minAmount=qe.min_amount!=null?String(pt(qe.min_amount,r)):"",fe.maxAmount=qe.max_amount!=null?String(pt(qe.max_amount,r)):"",fe.maxQuantity=String(qe.max_quantity)}else{let nt={name:S.trim(),allow_custom_amount:R==="custom",collect_shipping_address:J,active:Z};M.trim()&&(nt.description=M.trim()),Y.length>0&&(nt.images=Y),R==="fixed"?(nt.unit_amount=ce,nt.max_quantity=Ht):(nt.min_amount=Be,nt.max_amount=ct),qe=await i(nt)}if(!N.current)return;Ge(qe.fulfillment),a?.(qe)}catch(qe){if(!N.current)return;y(qe instanceof Error?qe.message:"Failed to save product")}finally{N.current&&c(!1)}},ze=async ce=>{let Be=ce.target.files?.[0];if(!(!Be||!t))try{Ce(!0),L(null);let ct=await d(t.id,Be);if(!N.current)return;Ge(ct.fulfillment),a?.(ct)}catch(ct){if(!N.current)return;L(ct instanceof Error?ct.message:"Failed to upload file")}finally{N.current&&(Ce(!1),pe.current&&(pe.current.value=""))}},Ke=async()=>{let ce=Et.trim();if(!(!ce||!t))try{Ce(!0),L(null);let Be=await f(t.id,ce);if(!N.current)return;Ge(Be.fulfillment),k(""),a?.(Be)}catch(Be){if(!N.current)return;L(Be instanceof Error?Be.message:"Failed to fetch file")}finally{N.current&&Ce(!1)}};return(0,K.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{htmlFor:"product-name",children:"Name"}),(0,K.jsx)(Ne,{id:"product-name",value:S,onChange:ce=>O(ce.target.value),placeholder:"My product"})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{htmlFor:"product-description",children:"Description"}),(0,K.jsx)("textarea",{id:"product-description",value:M,onChange:ce=>m(ce.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,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Pricing"}),x?(0,K.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,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(da,{value:R,onValueChange:ce=>T(ce),children:[(0,K.jsx)(Xt,{className:"af-w-[260px]",children:(0,K.jsx)(fa,{})}),(0,K.jsxs)(ea,{children:[(0,K.jsx)(Ye,{value:"fixed",children:"Fixed price"}),(0,K.jsx)(Ye,{value:"custom",children:"Buyer chooses the amount"})]})]}),R==="fixed"?(0,K.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsxs)(Re,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",r.toUpperCase(),")"]}),(0,K.jsx)(Ne,{id:"product-price",type:"number",min:"0",step:v,value:D,onChange:ce=>P(ce.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,K.jsxs)("div",{className:"af-space-y-1",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.jsxs)(Re,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",r.toUpperCase(),")"]}),(0,K.jsx)(Ne,{id:"product-min-amount",type:"number",min:"0",step:v,value:A,onChange:ce=>U(ce.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsxs)(Re,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",r.toUpperCase(),")"]}),(0,K.jsx)(Ne,{id:"product-max-amount",type:"number",min:"0",step:v,value:w,onChange:ce=>F(ce.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,K.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,K.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."]})]}),(x||R==="fixed")&&(0,K.jsxs)("div",{className:"af-space-y-1",children:[(0,K.jsx)(Re,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,K.jsx)(Ne,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:X,onChange:ce=>q(ce.target.value),className:"af-w-[140px]"})]})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Images"}),(0,K.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,K.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[Y.map(ce=>(0,K.jsxs)(ae,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,K.jsx)("span",{className:"af-truncate",children:ce}),(0,K.jsx)("button",{type:"button",onClick:()=>Oe(ce),className:"af-ml-1 hover:af-text-destructive",disabled:b,children:(0,K.jsx)(na.X,{className:"af-h-3 af-w-3"})})]},ce)),Y.length===0&&(0,K.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,K.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,K.jsx)(Ne,{type:"url",value:Xe,onChange:ce=>lt(ce.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),Ee())},disabled:b}),(0,K.jsx)(_,{type:"button",variant:"outline",onClick:Ee,disabled:!Xe.trim()||b,children:(0,K.jsx)(na.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Digital File"}),(0,K.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."}),u?(0,K.jsxs)("div",{className:"af-space-y-3",children:[Ae?.type==="download"&&(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,K.jsx)(na.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,K.jsx)("span",{className:"af-text-sm",children:Ae.filename}),Ae.size!=null&&(0,K.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",fl(Ae.size),")"]})]}),Ae?.type==="redirect"&&Ae.url&&(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,K.jsx)(na.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,K.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Ae.url]})]}),(0,K.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,K.jsx)("input",{ref:pe,type:"file",onChange:ze,className:"af-hidden",disabled:he}),(0,K.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>pe.current?.click(),disabled:he,children:[at?(0,K.jsx)(na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,K.jsx)(na.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Ae?.type==="download"?"Replace file":"Upload file"]}),(0,K.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,K.jsx)(Ne,{type:"url",value:Et,onChange:ce=>k(ce.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:at}),(0,K.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:Ke,disabled:!Et.trim()||he,children:"Fetch from URL"})]}),B&&(0,K.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:B})]}):(0,K.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,K.jsxs)("div",{className:"af-space-y-2",children:[(0,K.jsx)(Re,{children:"Settings"}),(0,K.jsxs)("div",{className:"af-space-y-2",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:J,onChange:ce=>ee(ce.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,K.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,K.jsx)("input",{type:"checkbox",checked:Z,onChange:ce=>oe(ce.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),u&&t&&(0,K.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,K.jsx)(Re,{children:"Options & Variants"}),(0,K.jsx)(an,{productId:t.id,currency:r})]}),l&&(0,K.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l}),(0,K.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,K.jsxs)(_,{type:"button",onClick:st,disabled:he,children:[b?(0,K.jsx)(na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,u?"Save changes":"Create product"]})})]})}var Pt=le(require("react"),1),ia=require("lucide-react");var ut=le(require("react"),1);var ml=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function nn({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ne(),[a,n]=ut.useState([]),[i,o]=ut.useState(0),[d,f]=ut.useState(!0),[u,r]=ut.useState(null),[v,x]=ut.useState(0),[b,c]=ut.useState(e),[l,y]=ut.useState(void 0),[N,S]=ut.useState(""),[O,M]=ut.useState(""),[m,R]=ut.useState(""),[T,D]=ut.useState(!1),[P,A]=ut.useState(!1),[U,w]=ut.useState(void 0),F=U?U.join(","):"",X=ut.useMemo(()=>{if(!F)return;let ee=new Set(F.split(","));return ml.filter(Z=>!ee.has(Z))},[F]),q=ut.useRef(0),fe=ut.useCallback(async()=>{let ee=++q.current;try{f(!0),r(null);let Z={limit:b,offset:v*b};l?Z.status=l:X?Z.excludeStatus=X:T||(Z.excludeStatus=["pending","expired"]),N.trim()&&(Z.customerEmail=N.trim()),O.trim()&&(Z.from=O.trim()),m.trim()&&(Z.to=m.trim()),P&&(Z.unfulfilledOnly=!0);let oe=await s.getOrders(Z);if(ee!==q.current)return;n(oe.orders),o(oe.total)}catch(Z){if(ee!==q.current)return;r(Z instanceof Error?Z:new Error("Failed to fetch orders"))}finally{ee===q.current&&f(!1)}},[s,v,b,l,X,T,P,N,O,m,t]);ut.useEffect(()=>{fe()},[fe]);let J=Math.ceil(i/b);return{orders:a,total:i,isLoading:d,error:u,page:v,pageSize:b,hasNextPage:v<J-1,hasPreviousPage:v>0,setPage:x,setPageSize:ee=>{c(ee),x(0)},status:l,setStatus:ee=>{y(ee),x(0)},statusIn:U,setStatusIn:ee=>{w(ee&&ee.length>0?ee:void 0),x(0)},customerEmail:N,setCustomerEmail:ee=>{S(ee),x(0)},from:O,setFrom:ee=>{M(ee),x(0)},to:m,setTo:ee=>{R(ee),x(0)},showAbandoned:T,setShowAbandoned:ee=>{D(ee),x(0)},unfulfilledOnly:P,setUnfulfilledOnly:ee=>{A(ee),x(0)},clearFilters:()=>{y(void 0),w(void 0),D(!1),A(!1),S(""),M(""),R(""),x(0)},refetch:fe}}var gt=le(require("react"),1),Ie=require("lucide-react");var Ri=le(require("react"),1),Fa=le(require("@radix-ui/react-popover"),1);var On=require("react/jsx-runtime"),Bn=Fa.Root,Fn=Fa.Trigger;var rn=Ri.forwardRef(({className:e,align:t="end",sideOffset:s=4,...a},n)=>(0,On.jsx)(Fa.Portal,{children:(0,On.jsx)("div",{className:"aifeatures-admin",children:(0,On.jsx)(Fa.Content,{ref:n,align:t,sideOffset:s,className:te("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})})}));rn.displayName=Fa.Content.displayName;var on=require("react/jsx-runtime"),pl={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function gl(e){return pl[e]??e}function Pi(e){switch(e){case"paid":return"success";case"pending":return"secondary";case"refunded":case"partially_refunded":return"warning";case"disputed":return"destructive";default:return"outline"}}function ps({status:e,className:t}){return(0,on.jsx)(ae,{variant:Pi(e),className:t,children:gl(e)})}function os({status:e}){return(0,on.jsx)(ps,{status:e})}function Es({order:e,className:t}){return e.line_items.some(s=>s.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,on.jsx)(ae,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,on.jsx)(ae,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Za(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var p=require("react/jsx-runtime"),Ei="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",gs="af-text-xs af-text-muted-foreground";function xr(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 vl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ai(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 Mn=24,bl=["paid","partially_refunded"],yl=["paid","partially_refunded","disputed"],hl=/^[A-Za-z0-9 _-]*$/,Ci=100;function Sr(e,t,s,a,n){let i=bl.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 ${Mn} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${s} of ${Mn} 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<Mn&&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<Mn&&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 Ti({title:e,recipient:t,status:s,attempts:a,side:n,orderStatus:i,action:o,delivery:d}){if(d)return(0,p.jsxs)("div",{children:[(0,p.jsx)(Da,{deliveries:[d]}),o&&(0,p.jsx)("div",{className:"af-mt-2",children:o})]});let f=Sr(n,s,a,i,t);return(0,p.jsxs)("div",{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)("div",{className:"af-text-sm",children:e}),t&&(0,p.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,p.jsx)(ae,{variant:f.variant,className:"af-shrink-0",children:f.label})]}),f.detail&&(0,p.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:f.detail}),o&&(0,p.jsx)("div",{className:"af-mt-2",children:o})]})}function ki(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let s=vl(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}: ${Ai(n)}`)}function xl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _r({value:e,label:t,children:s,className:a,size:n="icon"}){let[i,o]=gt.useState(!1);if(!xl())return null;let d=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},f=i?(0,p.jsx)(Ie.Check,{className:"af-h-3 af-w-3"}):(0,p.jsx)(Ie.Copy,{className:"af-h-3 af-w-3"});return n==="icon"?(0,p.jsx)(_,{variant:"ghost",size:"icon",className:te("af-h-6 af-w-6 af-shrink-0",a),onClick:d,title:t,"aria-label":t,children:f}):(0,p.jsxs)(_,{variant:"outline",size:"sm",className:a,onClick:d,"aria-label":t,children:[i?(0,p.jsx)(Ie.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,p.jsx)(Ie.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),i?"Copied":s]})}function wr({label:e,value:t}){return(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:e}),(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,p.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,p.jsx)(_r,{value:t,label:`Copy ${e}`})]})]})}function wl({src:e}){let[t,s]=gt.useState(!1);return!e||t?(0,p.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,p.jsx)(Ie.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,p.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 Ma({title:e,action:t,children:s,className:a}){return(0,p.jsxs)("section",{className:te("af-rounded-lg af-border af-p-4",a),children:[(0,p.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,p.jsx)("h4",{className:Ei,children:e}),t]}),(0,p.jsx)("div",{className:"af-mt-3",children:s})]})}function Gt({label:e,emphasis:t,divider:s,children:a}){return(0,p.jsxs)("div",{className:te("af-flex af-items-baseline af-justify-between af-gap-6",s&&"af-mt-2 af-border-t af-pt-2"),children:[(0,p.jsx)("span",{className:t?"af-text-base af-font-semibold":gs,children:e}),(0,p.jsx)("span",{className:te("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function Nr({onSelect:e,disabled:t,icon:s,children:a}){return(0,p.jsxs)(_,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,p.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:s}),a]})}function Nl(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 ${W(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?In(s):Sr("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?In(s):Sr("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 ${W(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 ln({order:e,onBack:t,onRefund:s,onOrderUpdated:a,allowFulfillment:n=!1,onPrevOrder:i,onNextOrder:o,hasPrevOrder:d=!1,hasNextOrder:f=!1}){let{api:u}=ne(),[r,v]=gt.useState(e),[x,b]=gt.useState(null),[c,l]=gt.useState(null),[y,N]=gt.useState(!1),[S,O]=gt.useState(!1),[M,m]=gt.useState(!1),[R,T]=gt.useState(!1),[D,P]=gt.useState(""),[A,U]=gt.useState(!1),[w,F]=gt.useState(null),[X,q]=gt.useState(!1),[fe,J]=gt.useState(""),[ee,Z]=gt.useState([]),[oe,Y]=gt.useState(!1),[Pe,Xe]=gt.useState(!1),[lt,Ae]=gt.useState(null);gt.useEffect(()=>{v(e)},[e]);let Ge=I=>{let Fe=I.id===r.id&&I.email_deliveries===void 0?{...I,email_deliveries:r.email_deliveries}:I;v(Fe),a?.(Fe)},at=Object.entries(r.metadata??{}),Ce=Math.max(0,Dn(r)-r.amount_refunded),Et=(r.status==="paid"||r.status==="partially_refunded")&&Ce>0,k=r.exclusive_tax_total!=null,B=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),L=Math.max(0,(r.shipping_total??0)-(r.shipping_refunded??0)),pe=ee.reduce((I,Fe)=>I+B(r.line_items[Fe]??{}),0)+(oe?L:0),he=r.tax_total??0,Ee=Math.max(0,(r.exclusive_tax_total??0)-r.line_items.reduce((I,Fe)=>I+(Fe.exclusiveTax??0),0)),Oe=k?oe&&L>0?Ee:0:r.automatic_tax&&r.tax_behavior==="exclusive"&&he>0&&r.amount_total+(r.shipping_total??0)>0?Math.min(Math.max(0,he-(r.tax_refunded??0)),Math.round(he*pe/(r.amount_total+(r.shipping_total??0)))):0,st=r.source==="subscription"&&(r.credit_applied??0)>0&&r.line_items.length===1?Math.min(pe+Oe,Ce):pe+Oe,ze=ee.length>0||oe,Ke=ze?st:Mt(fe,r.currency),ce=sa(r.currency)?"1":"0.01",Be=async()=>{try{N(!0),b(null),l(null),await u.resendOrderReceipt(r.id);let I=await u.getOrder(r.id);Ge(I),l("Receipt email queued.")}catch(I){b(I instanceof Error?I.message:"Failed to resend receipt")}finally{N(!1)}},ct=async()=>{try{O(!0),b(null),l(null);let I=await u.resetOrderDownloads(r.id);Ge(I),m(!1),l("Download count reset.")}catch(I){b(I instanceof Error?I.message:"Failed to reset downloads")}finally{O(!1)}},Yt=r.line_items.some(I=>I.collectShippingAddress===!0&&!I.refunded&&!I.unavailableReason),wt=typeof r.merchant_fulfilled_at=="string",At=yl.includes(r.status)||r.status==="refunded"&&r.line_items.some(I=>I.collectShippingAddress===!0&&I.amountNet===0&&!I.refunded&&!I.unavailableReason),Ht=D.trim(),qe=hl.test(Ht)&&Ht.length<=Ci,nt=async I=>{try{U(!0),F(null),l(null);let Fe=await u.setOrderFulfillment(r.id,{fulfilled:I,...I&&Ht?{trackingNumber:Ht}:{}});Ge(Fe),P(""),l(I?"Marked as shipped.":"Marked as not shipped.")}catch(Fe){Fe instanceof It&&Fe.status===409?F(`This order is ${r.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):F(Fe instanceof Error?Fe.message:"Failed to update the order")}finally{U(!1)}},ts=()=>{Ae(null),J(String(pt(Ce,r.currency))),Z([]),Y(!1),q(!0)},Ms=I=>Z(Fe=>Fe.includes(I)?Fe.filter(qt=>qt!==I):[...Fe,I]),Lt=async(I,Fe)=>{if(s)try{Xe(!0),Ae(null),await s(r,I,Fe);let qt=await u.getOrder(r.id);Ge(qt),q(!1),l("Refund issued.")}catch(qt){Ae(qt instanceof Error?qt.message:"Refund failed")}finally{Xe(!1)}},Rn=async()=>{if(ze){if(st<=0){Ae("The lines you picked were charged nothing");return}if(st>Ce){Ae(`That selection exceeds the refundable remainder (${W(Ce,r.currency)})`);return}await Lt(st,{...ee.length>0?{line_items:[...ee].sort((Fe,qt)=>Fe-qt)}:{},...oe?{shipping:!0}:{}});return}let I=Mt(fe,r.currency);if(I===null||I<=0){Ae("Enter a valid refund amount");return}if(I>Ce){Ae(`Amount exceeds the refundable remainder (${W(Ce,r.currency)})`);return}await Lt(I,{amount:I})},j=()=>Lt(Ce,{full:!0}),Ze=!r.subscription_history_only&&r.fulfillment_type==="download",G=!r.subscription_history_only&&n&&Yt,zt=Nl(r),Oo=r.shipping_address?ki(r.shipping_address).join(`
4
- `):"",Kr=r.shipping_total!=null,dr=r.exclusive_tax_total??(r.automatic_tax&&r.tax_behavior==="exclusive"?r.tax_total??0:0),Zr=r.exclusive_tax_total!=null?Math.max(0,(r.tax_total??0)-dr):r.automatic_tax&&r.tax_behavior==="exclusive"?0:r.tax_total??0,Jr=dr>0,Bo=Zr>0,Yr=r.amount_subtotal!=null||Kr||Jr||(r.discount_total??0)>0,$s=[];return r.subscription_history_only||$s.push((0,p.jsx)(Nr,{icon:y?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,p.jsx)(Ie.Mail,{className:"af-h-4 af-w-4"}),disabled:y||r.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Be()},children:"Resend receipt"},"resend")),Ze&&$s.push((0,p.jsx)(Nr,{icon:(0,p.jsx)(Ie.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:S,onSelect:()=>{T(!1),m(!0)},children:"Reset download count"},"reset")),Et&&$s.push((0,p.jsxs)("div",{children:[(0,p.jsx)(Nr,{icon:(0,p.jsx)(Ie.Undo2,{className:"af-h-4 af-w-4"}),disabled:!s,onSelect:()=>{T(!1),ts()},children:"Refund\u2026"}),!s&&(0,p.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,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)(Ie.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(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:[(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Za(r)}),(0,p.jsx)(ps,{status:r.status}),n&&!r.subscription_history_only&&(0,p.jsx)(Es,{order:r}),r.is_test&&(0,p.jsx)(ae,{variant:"outline",children:"Test"})]}),(0,p.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",xr(r.created_at)]}),r.is_test&&(0,p.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,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(i||o)&&(0,p.jsxs)("div",{className:"af-flex af-items-center",children:[(0,p.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:i,disabled:!d,"aria-label":"Previous order",children:(0,p.jsx)(Ie.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,p.jsx)(_,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:o,disabled:!f,"aria-label":"Next order",children:(0,p.jsx)(Ie.ChevronRight,{className:"af-h-4 af-w-4"})})]}),G&&(wt?(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,p.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",r.merchant_fulfilled_at?` \xB7 ${xr(r.merchant_fulfilled_at)}`:""]}),At&&(0,p.jsxs)(_,{variant:"ghost",size:"sm",onClick:()=>nt(!1),disabled:A,children:[A?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,p.jsx)(Ie.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):At?(0,p.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,p.jsx)(Ne,{value:D,onChange:I=>P(I.target.value),placeholder:"Tracking number (optional)",maxLength:Ci,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:A}),(0,p.jsxs)(_,{variant:"default",className:"af-shrink-0",onClick:()=>nt(!0),disabled:A||!qe,children:[A?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,p.jsx)(Ie.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),$s.length>0&&(0,p.jsxs)(Bn,{open:R,onOpenChange:T,children:[(0,p.jsx)(Fn,{asChild:!0,children:(0,p.jsx)(_,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,p.jsx)(Ie.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,p.jsx)(rn,{children:(0,p.jsx)("div",{className:"af-space-y-0.5",children:$s})})]})]})]}),G&&!wt&&!qe&&(0,p.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."}),w&&(0,p.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}),c&&(0,p.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:c}),x&&(0,p.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:x})]}),(0,p.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,p.jsxs)("div",{className:"af-space-y-6",children:[r.line_items.length>0&&(0,p.jsx)(Ma,{title:"Items",children:(0,p.jsx)("ul",{className:"af-space-y-3",children:r.line_items.map((I,Fe)=>{let qt=typeof I.name=="string"&&I.name?I.name:"Item",Qr=typeof I.quantity=="number"&&I.quantity>0?I.quantity:1,Xr=typeof I.unitAmount=="number";return(0,p.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,p.jsx)(wl,{src:typeof I.imageUrl=="string"&&I.imageUrl?I.imageUrl:void 0}),(0,p.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,p.jsxs)("div",{className:"af-text-sm af-font-medium",children:[qt,typeof I.variantTitle=="string"&&I.variantTitle&&(0,p.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",I.variantTitle]})]}),(0,p.jsxs)("div",{className:gs,children:[Qr," \xD7"," ",Xr?W(I.unitAmount,r.currency):"\u2014"]}),I.unavailableReason==="oversold"&&!I.refunded&&(0,p.jsx)(ae,{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,p.jsx)(ae,{variant:"secondary",className:"af-mt-1",children:I.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,p.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof I.amountNet=="number"||Xr?W(I.amountNet??I.unitAmount*Qr,r.currency):"\u2014"})]},Fe)})})}),at.length>0&&(0,p.jsx)(Ma,{title:"Order details",children:(0,p.jsx)("dl",{className:"af-space-y-2",children:at.map(([I,Fe])=>(0,p.jsxs)("div",{children:[(0,p.jsx)("dt",{className:te(gs,"af-capitalize"),children:I.replace(/_/g," ")}),(0,p.jsx)("dd",{className:"af-text-sm af-break-words",children:Ai(Fe)})]},I))})}),(0,p.jsx)(Ma,{title:"Totals",children:(0,p.jsxs)("div",{className:"af-w-full",children:[Yr&&(0,p.jsx)(Gt,{label:"Subtotal",children:W(r.amount_subtotal??r.amount_total+(r.discount_total??0),r.currency)}),(r.discount_total??0)>0&&(0,p.jsxs)(Gt,{label:"Discount",children:["\u2212",W(r.discount_total,r.currency)]}),Kr&&(0,p.jsx)(Gt,{label:"Shipping",children:r.shipping_total===0?"Free":W(r.shipping_total??0,r.currency)}),Jr&&(0,p.jsx)(Gt,{label:"Tax",children:W(dr,r.currency)}),(0,p.jsx)(Gt,{label:"Total",emphasis:!0,divider:Yr,children:W(Ba(r),r.currency)}),(r.credit_applied??0)>0&&(0,p.jsxs)(Gt,{label:"Credit applied",children:["\u2212",W(r.credit_applied,r.currency)]}),r.amount_paid!=null&&(0,p.jsx)(Gt,{label:"Amount paid",children:W(r.amount_paid,r.currency)}),Bo&&(0,p.jsx)(Gt,{label:"incl. tax",children:W(Zr,r.currency)}),r.base_currency!=null&&r.base_amount_total!=null&&(0,p.jsxs)(Gt,{label:"Your price",children:[W(r.base_amount_total,r.base_currency),(0,p.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",r.currency.toUpperCase()]})]}),r.amount_refunded>0&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(Gt,{label:"Refunded",children:["\u2212",W(r.amount_refunded,r.currency),(r.shipping_refunded??0)>0&&(0,p.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",W(r.shipping_refunded??0,r.currency)," ","shipping"]})]}),(0,p.jsx)(Gt,{label:"Net",children:(0,p.jsx)("span",{className:"af-font-medium",children:W(Math.max(0,Dn(r)-r.amount_refunded),r.currency)})})]})]})}),r.application_fee_state&&(0,p.jsxs)(Ma,{title:"Platform fee",children:[r.application_fee_original!=null&&(0,p.jsx)(Gt,{label:"Collected",children:W(r.application_fee_original,r.application_fee_currency??r.currency)}),r.application_fee_returned!=null&&(0,p.jsx)(Gt,{label:"Returned",children:W(r.application_fee_returned,r.application_fee_currency??r.currency)}),r.application_fee_retained!=null&&(0,p.jsx)(Gt,{label:"Retained",children:W(r.application_fee_retained,r.application_fee_currency??r.currency)}),r.application_fee_state!=="complete"&&(0,p.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,p.jsx)(Ma,{title:"Timeline",children:(0,p.jsx)("ol",{className:"af-space-y-3",children:zt.map(I=>(0,p.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,p.jsx)("span",{"aria-hidden":"true",className:te("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,p.jsxs)("div",{className:"af-min-w-0",children:[(0,p.jsx)("div",{className:"af-text-sm af-break-words",children:I.text}),I.at&&(0,p.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:xr(I.at)})]})]},I.key))})})]}),(0,p.jsxs)("div",{className:"af-space-y-6",children:[(0,p.jsx)(Ma,{title:"Customer",children:(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:"Email"}),(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,p.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:r.customer_email||(0,p.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),r.customer_email&&(0,p.jsx)(_r,{value:r.customer_email,label:"Copy email"})]})]}),r.customer_name&&(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:"Name"}),(0,p.jsx)("div",{className:"af-text-sm",children:r.customer_name})]}),r.customer&&(0,p.jsxs)("div",{children:[(0,p.jsx)("div",{className:gs,children:"Customer record"}),(0,p.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,p.jsx)("span",{className:"af-break-all af-text-sm",children:r.customer.name||r.customer.email}),(0,p.jsx)(ae,{variant:"secondary",children:"Linked"})]})]})]})}),r.shipping_address&&(0,p.jsx)(Ma,{title:"Ship to",action:(0,p.jsx)(_r,{value:Oo,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,p.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:ki(r.shipping_address).map((I,Fe)=>(0,p.jsx)("div",{children:I},Fe))})}),r.subscription_history_only?(0,p.jsx)(Ma,{title:"Subscription history",children:(0,p.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,p.jsxs)(Ma,{title:"Emails",children:[(0,p.jsx)(Da,{deliveries:r.email_deliveries?.filter(I=>!["purchase_receipt","merchant_sale"].includes(I.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,p.jsxs)("div",{className:"af-space-y-4",children:[(0,p.jsx)(Ti,{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,p.jsxs)(_,{variant:"outline",size:"sm",onClick:Be,disabled:y||r.fulfillment_status!=="fulfilled",children:[y?(0,p.jsx)(Ie.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,p.jsx)(Ie.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,p.jsx)(Ti,{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})]})]}),Ze&&(0,p.jsx)(Ma,{title:"Download",children:(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,p.jsx)(Ie.Download,{className:"af-h-4 af-w-4"}),(0,p.jsxs)("span",{children:["Downloaded ",r.download_count," time",r.download_count===1?"":"s"]})]}),r.download_url&&(0,p.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,p.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,p.jsx)("summary",{className:te(Ei,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,p.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,p.jsx)(wr,{label:"Order ID",value:r.id}),r.stripe_checkout_session_id&&(0,p.jsx)(wr,{label:"Checkout session",value:r.stripe_checkout_session_id}),r.stripe_payment_intent_id&&(0,p.jsx)(wr,{label:"Payment",value:r.stripe_payment_intent_id})]})]})]})]}),(0,p.jsx)(La,{open:M,onOpenChange:I=>{!I&&!S&&m(!1)},children:(0,p.jsxs)(Ra,{children:[(0,p.jsxs)(Pa,{children:[(0,p.jsx)(Ta,{children:"Reset download count?"}),(0,p.jsx)(ka,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,p.jsxs)(Ca,{children:[(0,p.jsx)(_,{variant:"outline",onClick:()=>m(!1),disabled:S,children:"Cancel"}),(0,p.jsx)(_,{onClick:ct,disabled:S,children:S?"Resetting...":"Reset"})]})]})}),(0,p.jsx)(La,{open:X,onOpenChange:I=>{!I&&!Pe&&q(!1)},children:(0,p.jsxs)(Ra,{children:[(0,p.jsxs)(Pa,{children:[(0,p.jsx)(Ta,{children:"Refund order"}),(0,p.jsxs)(ka,{children:["Refund up to ",W(Ce,r.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,p.jsxs)("div",{className:"af-space-y-4",children:[(r.line_items.length>0||L>0)&&(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsx)(Re,{children:"Items"}),(0,p.jsxs)("div",{className:"af-space-y-2",children:[r.line_items.map((I,Fe)=>{let qt=I.refunded===!0;return(0,p.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,p.jsx)("input",{type:"checkbox",checked:ee.includes(Fe),onChange:()=>Ms(Fe),disabled:Pe||qt||!!I.unavailableReason||B(I)<=0,className:"af-h-4 af-w-4"}),(0,p.jsxs)("span",{className:qt?"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,p.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:qt?"Refunded":W(B(I),r.currency)})]},Fe)}),L>0&&(0,p.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,p.jsx)("input",{type:"checkbox",checked:oe,onChange:I=>Y(I.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,p.jsx)("span",{children:"Shipping"}),(0,p.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:W(L,r.currency)})]})]})]}),(0,p.jsxs)("div",{className:"af-space-y-2",children:[(0,p.jsxs)(Re,{htmlFor:"refund-amount",children:["Amount (",r.currency.toUpperCase(),")"]}),(0,p.jsx)(Ne,{id:"refund-amount",type:"number",min:"0",step:ce,value:ze?String(pt(st,r.currency)):fe,onChange:I=>J(I.target.value),disabled:Pe||ze}),ze&&(0,p.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),lt&&(0,p.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:lt}),(0,p.jsxs)(Ca,{children:[(0,p.jsx)(_,{variant:"outline",onClick:()=>q(!1),disabled:Pe,children:"Cancel"}),(0,p.jsx)(_,{variant:"outline",onClick:j,disabled:Pe,children:"Refund everything"}),(0,p.jsx)(_,{variant:"destructive",onClick:Rn,disabled:Pe,children:Pe?"Refunding...":Ke!==null&&Ke>0?`Refund ${W(Ke,r.currency)}`:"Refund"})]})]})})]})}var $n=le(require("react"),1),Un=require("lucide-react");var tt=require("react/jsx-runtime");function yt({title:e,onBackToWebsite:t,hideBackButton:s=!1,children:a,className:n}){let i=$n.useRef(null);return $n.useEffect(()=>{i.current?.focus()},[]),(0,tt.jsxs)("div",{className:te("af-bg-background",n),children:[(0,tt.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,tt.jsx)("h2",{ref:i,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!s&&(0,tt.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,tt.jsx)(Un.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,tt.jsx)("div",{className:"af-p-4",children:a})]})}function se({className:e}){return(0,tt.jsx)("div",{"aria-hidden":"true",className:te("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function rt({label:e,children:t,detail:s,valueClassName:a}){return(0,tt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,tt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,tt.jsx)("div",{className:te("af-mt-1 af-text-lg af-font-semibold",a),children:t}),s&&(0,tt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:s})]})}function ra({message:e,onRetry:t}){return(0,tt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,tt.jsx)("span",{children:e}),(0,tt.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,tt.jsx)(Un.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function Ea({icon:e,children:t}){return(0,tt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,tt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function As({icon:e,heading:t,body:s,action:a,className:n,children:i}){return(0,tt.jsxs)("div",{className:te("af-px-6 af-py-10 af-text-center",n),children:[(0,tt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,tt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,tt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:s}),a&&(0,tt.jsx)(_,{type:"button",className:"af-mt-4",onClick:a.onClick,children:a.label}),i]})}var C=require("react/jsx-runtime"),Sl={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Ii={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function Di(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 Li(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 Vn(e){return e.customer?.name||e.customer_name||null}function _l({onRefund:e,className:t,refreshKey:s,initialOrderId:a,showFulfillment:n=!1,emptyMessage:i,onDetailOpenChange:o,maxRows:d,onViewAll:f}){let u=typeof d=="number",{api:r}=ne(),v=nn({refreshKey:s}),{orders:x,total:b,isLoading:c,error:l,page:y,pageSize:N,hasNextPage:S,hasPreviousPage:O,setPage:M,setPageSize:m,customerEmail:R,setCustomerEmail:T,setStatusIn:D,from:P,setFrom:A,to:U,setTo:w,showAbandoned:F,setShowAbandoned:X,setUnfulfilledOnly:q,refetch:fe}=v,[J,ee]=Pt.useState("list"),[Z,oe]=Pt.useState(null),[Y,Pe]=Pt.useState(""),[Xe,lt]=Pt.useState(""),[Ae,Ge]=Pt.useState(!u&&n?"needs_shipping":"all"),[at,Ce]=Pt.useState(!1),[Et,k]=Pt.useState(!!a&&!u),[B,L]=Pt.useState(null);Pt.useEffect(()=>{if(!a||u)return;let G=!1;return k(!0),L(null),r.getOrder(a).then(zt=>{G||(oe(zt),ee("detail"))}).catch(()=>{G||L("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{G||k(!1)}),()=>{G=!0}},[r,a,u]);let pe=Pt.useCallback(G=>{Ge(G);let zt=Ii[G];D(zt.statusIn),q(zt.unfulfilledOnly)},[D,q]);Pt.useEffect(()=>{n&&!u&&q(!0)},[]);let he=Pt.useRef(!n);Pt.useEffect(()=>{he.current||c||(he.current=!0,x.length===0&&pe("all"))},[c,x.length,pe]);let Ee=J==="detail"&&!!Z;Pt.useEffect(()=>{o?.(Ee)},[Ee,o]);let Oe=(P?1:0)+(U?1:0)+(F?1:0),st=Oe>0||!!R||!!Xe,ze=!!P&&!!U&&P>U,Ke=!u||!!f,ce=G=>{if(u){f?.();return}oe(G),ee("detail")},Be=()=>{ee("list"),oe(null),fe()},ct=G=>{let zt=G.trim();if(!zt){lt(""),R&&T("");return}if(zt.startsWith("#")||/^\d+$/.test(zt)){lt(zt),R&&T("");return}lt(""),T(zt)},Yt=()=>{Pe(""),lt(""),T(""),A(""),w(""),X(!1),Ce(!1)},wt=Xe.replace(/^#/,"").toLowerCase(),At=wt?x.filter(G=>String(G.order_number??"")===wt||G.id.toLowerCase().startsWith(wt)):x,Ht=u?At.slice(0,d):At,qe=Z?x.findIndex(G=>G.id===Z.id):-1,nt=qe>0,ts=qe>=0&&qe<x.length-1;if(Et)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)(ia.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(J==="detail"&&Z)return(0,C.jsx)("div",{className:t,children:(0,C.jsx)(ln,{order:Z,onBack:Be,onRefund:e,onOrderUpdated:G=>oe(G),allowFulfillment:n,onPrevOrder:nt?()=>oe(x[qe-1]):void 0,onNextOrder:ts?()=>oe(x[qe+1]):void 0,hasPrevOrder:nt,hasNextOrder:ts},Z.id)});let Lt=(0,C.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[B&&(0,C.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:B}),(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(G=>(0,C.jsx)("button",{type:"button","aria-pressed":Ae===G,onClick:()=>pe(G),className:te("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",Ae===G?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Sl[G]},G))}),(0,C.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,C.jsx)(ia.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)(Ne,{type:"text",value:Y,onChange:G=>Pe(G.target.value),onBlur:()=>ct(Y),onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),ct(Y))},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:Oe>0?"secondary":"ghost",size:"sm",onClick:()=>Ce(G=>!G),"aria-expanded":at,children:[(0,C.jsx)(ia.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Oe>0&&(0,C.jsx)(ae,{variant:"secondary",className:"af-ml-2",children:Oe})]}),st&&(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:Yt,children:"Clear filters"})]}),(at||!!P||!!U)&&(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)(Ne,{id:"orders-from",type:"date",value:P,max:U||void 0,onChange:G=>A(G.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)(Ne,{id:"orders-to",type:"date",value:U,min:P||void 0,onChange:G=>w(G.target.value),className:"af-w-[170px]"}),!Ii[Ae].statusIn&&(0,C.jsx)(_,{type:"button",variant:F?"secondary":"ghost",size:"sm",onClick:()=>X(!F),"aria-pressed":F,children:F?"Hide abandoned":"Show abandoned"})]}),ze&&(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(c)return(0,C.jsxs)("div",{className:t,children:[u?null:Lt,(0,C.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(G=>(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)(se,{className:"af-h-4 af-w-16"}),(0,C.jsx)(se,{className:"af-h-4 af-w-14"})]}),(0,C.jsx)(se,{className:"af-mt-2 af-h-3 af-w-40"}),(0,C.jsx)(se,{className:"af-mt-2 af-h-3 af-w-24"})]},G))}),(0,C.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,C.jsxs)(Ue,{children:[(0,C.jsx)(Ve,{children:(0,C.jsxs)(xe,{children:[(0,C.jsx)(H,{children:"Order"}),(0,C.jsx)(H,{children:"Date"}),(0,C.jsx)(H,{children:"Customer"}),(0,C.jsx)(H,{children:"Items"}),(0,C.jsx)(H,{className:"af-text-right",children:"Total"}),(0,C.jsx)(H,{children:"Status"}),(0,C.jsx)(H,{className:"af-w-8"})]})}),(0,C.jsx)(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(G=>(0,C.jsxs)(xe,{children:[(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-14"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-40"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-4 af-w-32"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,C.jsx)(z,{children:(0,C.jsx)(se,{className:"af-h-5 af-w-16"})}),(0,C.jsx)(z,{})]},G))})]})}),(0,C.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(l)return(0,C.jsxs)("div",{className:t,children:[u?null:Lt,(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:()=>fe(),children:"Try again"})]})]});let Rn=Ae!=="all";if(At.length===0&&y===0)return st||Rn?(0,C.jsxs)("div",{className:t,children:[!u&&Lt,(0,C.jsx)(Ea,{children:"No orders match these filters."})]}):(0,C.jsx)("div",{className:t,children:(0,C.jsx)(As,{icon:ia.Receipt,heading:"No orders yet",body:i??"Orders will appear here when someone buys from your website.",children:!u&&(0,C.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>X(!0),children:"Show abandoned checkouts"})})});let j=y*N+1,Ze=Math.min((y+1)*N,b);return(0,C.jsxs)("div",{className:t,children:[u?null:Lt,(0,C.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ht.map(G=>(0,C.jsxs)("button",{type:"button",onClick:()=>ce(G),disabled:!Ke,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ke?" 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:Za(G)}),(0,C.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:W(Ba(G),G.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:[G.customer_email||(0,C.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),Vn(G)&&(0,C.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",Vn(G)]})]}),(0,C.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Li(G)}),G.amount_refunded>0&&(0,C.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(G.amount_refunded,G.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)(ps,{status:G.status}),(0,C.jsx)(qs,{deliveries:G.email_deliveries}),G.is_test&&(0,C.jsx)(ae,{variant:"outline",children:"Test"}),n&&(0,C.jsx)(Es,{order:G}),(0,C.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Di(G.created_at)})]})]},G.id))}),(0,C.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,C.jsxs)(Ue,{children:[(0,C.jsx)(Ve,{children:(0,C.jsxs)(xe,{children:[(0,C.jsx)(H,{children:"Order"}),(0,C.jsx)(H,{children:"Date"}),(0,C.jsx)(H,{children:"Customer"}),(0,C.jsx)(H,{children:"Items"}),(0,C.jsx)(H,{className:"af-text-right",children:"Total"}),(0,C.jsx)(H,{children:"Status"}),(0,C.jsx)(H,{className:"af-w-8"})]})}),(0,C.jsx)(He,{children:Ht.map(G=>(0,C.jsxs)(xe,{onClick:Ke?()=>ce(G):void 0,className:Ke?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,C.jsxs)(z,{className:"af-whitespace-nowrap af-font-medium",children:[(0,C.jsx)("button",{type:"button",onClick:zt=>{zt.stopPropagation(),ce(G)},disabled:!Ke,"aria-label":`Open order ${Za(G)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ke?" hover:af-underline":""}`,children:Za(G)}),G.is_test&&(0,C.jsx)(ae,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,C.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Di(G.created_at)}),(0,C.jsxs)(z,{className:"af-max-w-[220px]",children:[(0,C.jsx)("div",{className:"af-truncate",children:G.customer_email||(0,C.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),Vn(G)&&(0,C.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:Vn(G)})]}),(0,C.jsx)(z,{className:"af-max-w-[220px]",children:(0,C.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:Li(G)})}),(0,C.jsxs)(z,{className:"af-whitespace-nowrap af-text-right",children:[(0,C.jsx)("div",{className:"af-font-medium af-tabular-nums",children:W(Ba(G),G.currency)}),G.amount_refunded>0&&(0,C.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",W(G.amount_refunded,G.currency)," ","refunded"]})]}),(0,C.jsx)(z,{children:(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,C.jsx)(ps,{status:G.status}),(0,C.jsx)(qs,{deliveries:G.email_deliveries}),n&&(0,C.jsx)(Es,{order:G})]})}),(0,C.jsx)(z,{className:"af-w-8 af-text-right",children:(0,C.jsx)(ia.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},G.id))})]})}),u?null:(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:wt?`${At.length} matching this page`:`Showing ${j}-${Ze} of ${b}`}),(0,C.jsxs)(da,{value:String(N),onValueChange:G=>m(Number(G)),children:[(0,C.jsx)(Xt,{className:"af-w-[70px] af-h-8",children:(0,C.jsx)(fa,{})}),(0,C.jsxs)(ea,{children:[(0,C.jsx)(Ye,{value:"10",children:"10"}),(0,C.jsx)(Ye,{value:"25",children:"25"}),(0,C.jsx)(Ye,{value:"50",children:"50"}),(0,C.jsx)(Ye,{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:()=>M(y-1),disabled:!O,children:[(0,C.jsx)(ia.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,C.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>M(y+1),disabled:!S,children:["Next",(0,C.jsx)(ia.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function Ja(e){return(0,C.jsx)(_l,{...e},e.maxRows==null?"full":"compact")}var zn=le(require("react"),1),$a=require("lucide-react");var Wt=le(require("react"),1);function cn({initialPageSize:e=25}={}){let{api:t}=ne(),[s,a]=Wt.useState([]),[n,i]=Wt.useState(0),[o,d]=Wt.useState(!0),[f,u]=Wt.useState(null),[r,v]=Wt.useState(0),[x,b]=Wt.useState(e),[c,l]=Wt.useState(""),y=Wt.useRef(0),N=Wt.useCallback(async()=>{let O=++y.current;try{d(!0),u(null);let M={limit:x,offset:r*x};c.trim()&&(M.email=c.trim());let m=await t.getCustomers(M);if(O!==y.current)return;a(m.customers),i(m.total)}catch(M){if(O!==y.current)return;u(M instanceof Error?M:new Error("Failed to fetch customers"))}finally{O===y.current&&d(!1)}},[t,r,x,c]);Wt.useEffect(()=>{N()},[N]);let S=Math.ceil(n/x);return{customers:s,total:n,isLoading:o,error:f,page:r,pageSize:x,hasNextPage:r<S-1,hasPreviousPage:r>0,setPage:v,setPageSize:O=>{b(O),v(0)},email:c,setEmail:O=>{l(O),v(0)},refetch:N}}var vs=le(require("react"),1),Hn=require("lucide-react");var ge=require("react/jsx-runtime");function Oi(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 Rl(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 un({customer:e,onBack:t,className:s}){let{api:a}=ne(),[n,i]=vs.useState(null),[o,d]=vs.useState([]),[f,u]=vs.useState(!0),[r,v]=vs.useState(null);vs.useEffect(()=>{let c=!1;return u(!0),v(null),Promise.all([a.getCustomer(e.id),a.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([l,y])=>{c||(i(l),d(y.orders))}).catch(l=>{c||v(l instanceof Error?l.message:"Failed to load customer")}).finally(()=>{c||u(!1)}),()=>{c=!0}},[a,e.id,e.email]);let x=n?.addresses??[],b=n?.order_count??o.length;return(0,ge.jsxs)("div",{className:s,children:[(0,ge.jsxs)("div",{className:"af-mb-6",children:[(0,ge.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,ge.jsx)(Hn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,ge.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,ge.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Oi(e.created_at)]})]}),f?(0,ge.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,ge.jsx)(Hn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):r?(0,ge.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r}):(0,ge.jsxs)("div",{className:"af-space-y-6",children:[(0,ge.jsx)(Da,{deliveries:n?.email_deliveries}),(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,ge.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,ge.jsx)("span",{children:e.email})]}),e.name&&(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,ge.jsx)("span",{children:e.name})]}),e.phone&&(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,ge.jsx)("span",{children:e.phone})]}),(0,ge.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ge.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,ge.jsx)("span",{children:b})]})]})]}),x.length>0&&(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,ge.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:x.map(c=>(0,ge.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&(0,ge.jsx)(ae,{variant:"secondary",className:"af-mb-1",children:"Default"}),Rl(c).map((l,y)=>(0,ge.jsx)("div",{children:l},y))]},c.id))})]}),(0,ge.jsxs)("div",{children:[(0,ge.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,ge.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,ge.jsxs)(Ue,{children:[(0,ge.jsx)(Ve,{children:(0,ge.jsxs)(xe,{children:[(0,ge.jsx)(H,{children:"Date"}),(0,ge.jsx)(H,{children:"Amount"}),(0,ge.jsx)(H,{children:"Status"})]})}),(0,ge.jsx)(He,{children:o.map(c=>(0,ge.jsxs)(xe,{children:[(0,ge.jsx)(z,{className:"af-text-muted-foreground",children:Oi(c.created_at)}),(0,ge.jsx)(z,{children:W(Ba(c),c.currency)}),(0,ge.jsx)(z,{children:(0,ge.jsx)(os,{status:c.status})})]},c.id))})]})]})]})]})}var de=require("react/jsx-runtime");function Pl(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 dn({className:e}){let{customers:t,total:s,isLoading:a,error:n,page:i,pageSize:o,hasNextPage:d,hasPreviousPage:f,setPage:u,setPageSize:r,email:v,setEmail:x,refetch:b}=cn(),[c,l]=zn.useState("list"),[y,N]=zn.useState(null),[S,O]=zn.useState(""),M=P=>{N(P),l("detail")},m=()=>{l("list"),N(null),b()};if(c==="detail"&&y)return(0,de.jsx)("div",{className:e,children:(0,de.jsx)(un,{customer:y,onBack:m})});let R=(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,de.jsx)(Ne,{type:"email",value:S,onChange:P=>O(P.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),x(S.trim()))}}),(0,de.jsxs)(_,{type:"button",variant:"outline",size:"sm",onClick:()=>x(S.trim()),children:[(0,de.jsx)($a.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),v&&(0,de.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{O(""),x("")},children:"Clear"})]});if(a)return(0,de.jsxs)("div",{className:e,children:[R,(0,de.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(n)return(0,de.jsxs)("div",{className:e,children:[R,(0,de.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,de.jsxs)("div",{className:"af-text-destructive",children:["Error: ",n.message]})})]});if(t.length===0&&i===0)return(0,de.jsxs)("div",{className:e,children:[v&&R,(0,de.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,de.jsx)($a.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,de.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:v?"No customers match that email.":(0,de.jsxs)(de.Fragment,{children:["No customers yet.",(0,de.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let T=i*o+1,D=Math.min((i+1)*o,s);return(0,de.jsxs)("div",{className:e,children:[R,(0,de.jsxs)(Ue,{children:[(0,de.jsx)(Ve,{children:(0,de.jsxs)(xe,{children:[(0,de.jsx)(H,{children:"Email"}),(0,de.jsx)(H,{children:"Name"}),(0,de.jsx)(H,{children:"Customer since"}),(0,de.jsx)(H,{className:"af-text-right",children:"Actions"})]})}),(0,de.jsx)(He,{children:t.map(P=>(0,de.jsxs)(xe,{children:[(0,de.jsx)(z,{className:"af-font-medium",children:P.email}),(0,de.jsx)(z,{children:P.name||(0,de.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,de.jsx)(z,{className:"af-text-muted-foreground",children:Pl(P.created_at)}),(0,de.jsx)(z,{className:"af-text-right",children:(0,de.jsx)(_,{variant:"ghost",size:"icon",onClick:()=>M(P),title:"View customer",children:(0,de.jsx)($a.Eye,{className:"af-h-4 af-w-4"})})})]},P.id))})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,de.jsxs)("span",{children:["Showing ",T,"-",D," of ",s]}),(0,de.jsxs)(da,{value:String(o),onValueChange:P=>r(Number(P)),children:[(0,de.jsx)(Xt,{className:"af-w-[70px] af-h-8",children:(0,de.jsx)(fa,{})}),(0,de.jsxs)(ea,{children:[(0,de.jsx)(Ye,{value:"10",children:"10"}),(0,de.jsx)(Ye,{value:"25",children:"25"}),(0,de.jsx)(Ye,{value:"50",children:"50"}),(0,de.jsx)(Ye,{value:"100",children:"100"})]})]}),(0,de.jsx)("span",{children:"per page"})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,de.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>u(i-1),disabled:!f,children:[(0,de.jsx)($a.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,de.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>u(i+1),disabled:!d,children:["Next",(0,de.jsx)($a.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ke=le(require("react"),1),xt=require("lucide-react");var ht=le(require("react"),1);function bs({initialPageSize:e=25,refreshKey:t,includeAggregates:s=!1}={}){let{api:a}=ne(),[n,i]=ht.useState([]),[o,d]=ht.useState(0),[f,u]=ht.useState(null),[r,v]=ht.useState(!0),[x,b]=ht.useState(null),[c,l]=ht.useState(0),[y,N]=ht.useState(e),[S,O]=ht.useState(void 0),[M,m]=ht.useState(""),[R,T]=ht.useState(""),[D,P]=ht.useState(""),[A,U]=ht.useState(""),[w,F]=ht.useState(""),X=S?S.join(","):"",q=ht.useRef(0),fe=ht.useCallback(async()=>{let ee=++q.current;v(!0),b(null);try{let Z={labels:X?X.split(","):void 0,customerEmail:M||void 0,q:R||void 0,from:D||void 0,to:A||void 0,retainerId:w||void 0,includeAggregates:s,limit:y,offset:c*y},oe=await a.getInvoices(Z);if(ee!==q.current)return;if(c>0&&c*y>=oe.total){l(Math.max(0,Math.ceil(oe.total/y)-1));return}i(oe.invoices),d(oe.total),s&&u(oe.aggregates??null)}catch(Z){if(ee!==q.current)return;b(Z instanceof Error?Z:new Error("Failed to fetch invoices"))}finally{ee===q.current&&v(!1)}},[a,X,M,R,D,A,w,c,y,s]);ht.useEffect(()=>{fe()},[fe,t]);let J=ee=>Z=>{l(0),ee(Z)};return{invoices:n,total:o,aggregates:f,isLoading:r,error:x,page:c,pageSize:y,hasNextPage:(c+1)*y<o,hasPreviousPage:c>0,setPage:l,setPageSize:J(N),labels:S,setLabels:J(O),customerEmail:M,setCustomerEmail:J(m),q:R,setQ:J(T),from:D,setFrom:J(P),to:A,setTo:J(U),retainerId:w,setRetainerId:J(F),clearFilters:()=>{l(0),O(void 0),m(""),T(""),P(""),U(""),F("")},refetch:fe}}var g=require("react/jsx-runtime"),Cl={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function Tr(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Cl[e.label]??e.label}function Tl(e){switch(e){case"paid":case"paid_outside_stripe":case"paid_by_credit":return"success";case"overdue":case"disputed":case"failed":return"destructive";case"partially_refunded":case"refunded":case"payment_processing":case"awaiting_authentication":return"warning";case"awaiting_payment":return"secondary";default:return"outline"}}var Cr={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},kl={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function Ds({invoice:e,className:t}){return(0,g.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,g.jsx)(ae,{variant:Tl(e.label),className:t,children:Tr(e)}),e.collection_method==="charge_automatically"&&(0,g.jsx)(ae,{variant:"secondary",children:"Managed in Stripe"})]})}function Gn({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,g.jsx)(ae,{variant:s,className:t,children:Cr[e.state]??e.state})}function Is(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function ya(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 Bi={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},qn={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 El(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 Rr=100,Pr=5e3;async function Al(e,t){let s=[],a=0;for(let n=0;n<Pr;n+=Rr){let i=await e.getInvoices({...t,limit:Rr,offset:n});if(a=i.total,s.push(...i.invoices),i.invoices.length<Rr||s.length>=a)break}return{invoices:s.slice(0,Pr),total:a,truncated:a>s.length||a>Pr}}function Mi(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,Is(a),Tr(a),a.customer_name??"",a.customer_email??"",a.created_at,a.due_at??"",a.paid_at??"",a.currency.toUpperCase(),W(a.amount_subtotal,a.currency),W(a.tax_total,a.currency),W(a.amount_total,a.currency),a.amount_due===null?"":W(a.amount_due,a.currency),a.amount_paid===null?"":W(a.amount_paid,a.currency),W(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?"":W(a.discount_total,a.currency),a.collection_method??""]);return[t,...s].map(a=>a.map(El).join(",")).join(`
5
- `)}function Il(e){if(typeof document>"u")return;let t=new Blob([Mi(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 Dl({className:e,refreshKey:t,initialInvoiceId:s,onDetailOpenChange:a,onConnectStripe:n,onUpgradePlan:i,needsPaidPlan:o=!1,retainerFilter:d=null,onClearRetainerFilter:f,maxRows:u,onViewAll:r}){let v=typeof u=="number",{api:x}=ne(),{invoices:b,total:c,isLoading:l,error:y,page:N,pageSize:S,hasNextPage:O,hasPreviousPage:M,setPage:m,labels:R,setLabels:T,customerEmail:D,setCustomerEmail:P,q:A,setQ:U,from:w,setFrom:F,to:X,setTo:q,retainerId:fe,setRetainerId:J,refetch:ee}=bs({refreshKey:t}),[Z,oe]=ke.useState(typeof u=="number"?"all":"open"),[Y,Pe]=ke.useState(""),[Xe,lt]=ke.useState(null),Ae=ke.useRef(0),Ge=!v||!!r,at=ke.useCallback(j=>{if(v){r?.();return}Ae.current++,Et(!1),lt(j)},[v,r]),[Ce,Et]=ke.useState(!1),[k,B]=ke.useState(0),[L,pe]=ke.useState(null),[he,Ee]=ke.useState(!1),[Oe,st]=ke.useState(0);ke.useEffect(()=>{lt(j=>{if(!j)return j;let Ze=b.find(G=>G.id===j.id);return Ze&&Ze!==j?Ze:j})},[b]);let[ze,Ke]=ke.useState(!1),[ce,Be]=ke.useState(null),ct=async()=>{if(!ze){Ke(!0),Be(null);try{let{invoices:j,total:Ze,truncated:G}=await Al(x,{labels:R,customerEmail:D,q:A,from:w,to:X,retainerId:fe});Il(j),Be(G?`Exported the first ${j.length.toLocaleString()} of ${Ze.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Be("Couldn't export \u2014 try again.")}finally{Ke(!1)}}},Yt=!D&&!A&&!w&&!X&&!fe,[wt,At]=ke.useState(null);ke.useEffect(()=>{if(l||c>0||!Yt||Z!=="open")return;let j=!1;return x.getInvoices({limit:1}).then(Ze=>{j||At(Ze.total>0)}).catch(()=>{j||At(!0)}),()=>{j=!0}},[x,l,c,Yt,Z,t]),ke.useEffect(()=>{T(v?qn.all:qn.open)},[]),ke.useEffect(()=>{let j=d?.id??"";j!==fe&&(J(j),j&&(oe("all"),T(qn.all),P(""),U(""),Pe(""),F(""),q("")))},[d?.id]),ke.useEffect(()=>{let j=!1;return Ee(!1),x.getInvoiceSettings().then(Ze=>{j||pe({payments_active:Ze.payments_active,blocked:Ze.blocked})}).catch(()=>{j||Ee(!0)}),()=>{j=!0}},[x,t,Oe]),ke.useEffect(()=>{if(!s||v)return;let j=!1,Ze=Ae.current;return Et(!1),x.getInvoice(s).then(G=>{!j&&Ze===Ae.current&&lt(G)}).catch(()=>{!j&&Ze===Ae.current&&Et(!0)}),()=>{j=!0}},[x,s,k,v]),ke.useEffect(()=>{a?.(Xe!==null)},[Xe,a]);let Ht=j=>{oe(j),T(qn[j])},qe=j=>{let Ze=j.trim();if(!Ze){A&&U(""),D&&P("");return}if(Ze.includes("@")){A&&U(""),P(Ze);return}D&&P(""),U(Ze.replace(/^#/,""))},nt=b,ts=v?nt.slice(0,u):nt,Ms=Ce&&(0,g.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,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>B(j=>j+1),children:"Retry opening invoice"})]});if(Xe)return(0,g.jsxs)("div",{className:e,children:[Ms,(0,g.jsx)(Wn,{invoice:Xe,refreshKey:t,onBack:()=>{at(null),ee()}},Xe.id)]});let Lt=(0,g.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[he&&(0,g.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>st(j=>j+1),children:"Retry setup check"})]}),Ms,L?.blocked&&(0,g.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",L.blocked.reason?`: ${L.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),d&&(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,g.jsxs)(ae,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",d.label]}),f&&(0,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:f,children:"Clear schedule filter"})]}),(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,g.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(Bi).map(j=>(0,g.jsx)("button",{type:"button","aria-pressed":Z===j,onClick:()=>Ht(j),className:te("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Z===j?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Bi[j]},j))}),(0,g.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,g.jsx)(xt.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,g.jsx)(Ne,{type:"text",value:Y,onChange:j=>Pe(j.target.value),onBlur:()=>qe(Y),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),qe(Y))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,g.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,g.jsx)(Re,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,g.jsx)(Ne,{id:"invoices-from",type:"date",value:w,max:X||void 0,onChange:j=>F(j.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,g.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,g.jsx)(Re,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,g.jsx)(Ne,{id:"invoices-to",type:"date",value:X,min:w||void 0,onChange:j=>q(j.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,g.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>void ct(),disabled:ze||l||!!y||c===0,"aria-busy":ze,children:[(0,g.jsx)(xt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),ze?"Exporting\u2026":"Export CSV (all matching)"]})]}),ce&&(0,g.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:ce})]});return l?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(j=>(0,g.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,g.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,g.jsx)(se,{className:"af-h-4 af-w-20"}),(0,g.jsx)(se,{className:"af-h-4 af-w-16"})]}),(0,g.jsx)(se,{className:"af-mt-2 af-h-3 af-w-40"})]},j))})]}):y?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void ee(),children:"Retry"})]})]}):c===0&&Yt&&(Z==="all"||wt===!1)&&(Z==="open"||Z==="all")?L?.blocked?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:i?{label:"Upgrade",onClick:i}:void 0})]}):L&&!L.payments_active?(0,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{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,g.jsxs)("div",{className:e,children:[v?null:Lt,(0,g.jsx)(jn,{heading:"No invoices yet",body:!L||he?"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,g.jsxs)("div",{className:e,children:[v?null:Lt,ts.length===0?(0,g.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,g.jsxs)(g.Fragment,{children:[(0,g.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ts.map(j=>(0,g.jsxs)("button",{type:"button",onClick:()=>at(j),disabled:!Ge,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ge?" hover:af-bg-muted/50":""}`,children:[(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,g.jsx)("span",{className:"af-font-medium",children:Is(j)}),(0,g.jsx)(Ds,{invoice:j})]}),(0,g.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:j.customer_name??j.customer_email??"\u2014"}),j.delivery&&(0,g.jsx)("div",{className:"af-mt-1",children:(0,g.jsx)(Gn,{delivery:j.delivery})}),(0,g.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,g.jsx)("span",{children:j.collection_method==="charge_automatically"?"Automatic collection":j.due_at?`Due ${ya(j.due_at)}`:"Due on receipt"}),(0,g.jsx)("span",{className:"af-font-medium af-tabular-nums",children:W(j.amount_due??j.amount_total,j.currency)})]})]},j.id))}),(0,g.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,g.jsxs)(Ue,{children:[(0,g.jsx)(Ve,{children:(0,g.jsxs)(xe,{children:[(0,g.jsx)(H,{children:"Invoice"}),(0,g.jsx)(H,{children:"Created"}),(0,g.jsx)(H,{children:"Customer"}),(0,g.jsx)(H,{children:"Due"}),(0,g.jsx)(H,{className:"af-text-right",children:"Amount"}),(0,g.jsx)(H,{children:"Status"}),(0,g.jsx)(H,{children:"Delivery"}),(0,g.jsx)(H,{className:"af-w-8"})]})}),(0,g.jsx)(He,{children:ts.map(j=>(0,g.jsxs)(xe,{className:Ge?"af-cursor-pointer":void 0,onClick:Ge?()=>at(j):void 0,children:[(0,g.jsx)(z,{className:"af-font-medium",children:(0,g.jsx)("button",{type:"button",disabled:!Ge,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${Ge?" hover:af-underline":""}`,onClick:Ze=>{Ze.stopPropagation(),at(j)},"aria-label":`Open invoice ${Is(j)}`,children:Is(j)})}),(0,g.jsx)(z,{children:ya(j.created_at)}),(0,g.jsxs)(z,{children:[(0,g.jsx)("div",{children:j.customer_name??"\u2014"}),(0,g.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:j.customer_email})]}),(0,g.jsx)(z,{children:j.collection_method==="charge_automatically"?"Automatic":j.due_at?ya(j.due_at):"On receipt"}),(0,g.jsx)(z,{className:"af-text-right af-tabular-nums",children:W(j.amount_due??j.amount_total,j.currency)}),(0,g.jsx)(z,{children:(0,g.jsx)(Ds,{invoice:j})}),(0,g.jsx)(z,{children:(0,g.jsx)(Gn,{delivery:j.delivery})}),(0,g.jsx)(z,{children:(0,g.jsx)(xt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},j.id))})]})}),v?null:(0,g.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,g.jsxs)("span",{children:[c," invoice",c===1?"":"s"]}),(0,g.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,g.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>m(N-1),disabled:!M,"aria-label":"Previous page",children:(0,g.jsx)(xt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,g.jsxs)("span",{className:"af-tabular-nums",children:[N*S+1,"\u2013",Math.min((N+1)*S,c)]}),(0,g.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>m(N+1),disabled:!O,"aria-label":"Next page",children:(0,g.jsx)(xt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function jn({heading:e,body:t,action:s}){return(0,g.jsx)(As,{icon:xt.FileText,heading:e,body:t,action:s})}function Qa(e){return(0,g.jsx)(Dl,{...e},e.maxRows==null?"full":"compact")}var Ya="af-text-xs af-text-muted-foreground";function Fi(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Wn({invoice:e,onBack:t,refreshKey:s,className:a}){let{api:n}=ne(),i=ke.useRef(null);ke.useEffect(()=>{i.current?.focus()},[e.id]);let[o,d]=ke.useState(!1),[f,u]=ke.useState(null),[r,v]=ke.useState(!1),[x,b]=ke.useState(!1),c=ke.useRef(0),[l,y]=ke.useState(null),[N,S]=ke.useState(!1),[O,M]=ke.useState(0);ke.useEffect(()=>{let w=!1;return S(!1),n.getInvoice(e.id).then(F=>{w||y({source:e,value:F})}).catch(()=>{w||S(!0)}),()=>{w=!0}},[n,e,s,O]);let m=l?.source===e?l.value:e,R=m.collection_method==="charge_automatically";ke.useEffect(()=>(c.current++,u(null),v(!1),b(!1),d(!1),()=>{c.current++}),[n,m,s]);let T=w=>w==null?"\u2014":W(w,m.currency),D=async()=>{if(!(!m.pay_url||!Fi()))try{await navigator.clipboard.writeText(m.pay_url),d(!0),setTimeout(()=>d(!1),1500)}catch{}},P=async()=>{if(f){u(null);return}let w=++c.current;b(!1),v(!0);try{let F=await n.getInvoicePreview(m.id);w===c.current&&u(F)}catch{w===c.current&&b(!0)}finally{w===c.current&&v(!1)}},A=m.bill_to,U=A?[A.company,A.name,A.address?.line1,A.address?.line2,[A.address?.city,A.address?.state,A.address?.postal_code].filter(Boolean).join(", "),A.address?.country,A.tax_id?`${A.tax_id.value}`:null,A.po_number?`PO ${A.po_number}`:null,A.service_period?`Service period: ${A.service_period}`:null].filter(w=>!!w&&w.length>0):[];return(0,g.jsxs)("div",{className:a,children:[(0,g.jsxs)("div",{className:"af-mb-4",children:[(0,g.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,g.jsx)(xt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,g.jsxs)("h3",{ref:i,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",Is(m)]}),(0,g.jsx)(Ds,{invoice:m}),(0,g.jsx)(Gn,{delivery:m.delivery})]}),(0,g.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[m.customer_name??m.customer_email,m.customer_name&&m.customer_email?` \xB7 ${m.customer_email}`:""]})]}),N&&(0,g.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,g.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>M(w=>w+1),children:"Retry details"})]}),m.label==="failed"&&(0,g.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."}),m.label==="creating"&&(0,g.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,g.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,g.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,g.jsxs)(Ue,{children:[(0,g.jsx)(Ve,{children:(0,g.jsxs)(xe,{children:[(0,g.jsx)(H,{children:"Description"}),(0,g.jsx)(H,{className:"af-text-right",children:"Qty"}),(0,g.jsx)(H,{className:"af-text-right",children:"Amount"})]})}),(0,g.jsx)(He,{children:m.line_items.map((w,F)=>(0,g.jsxs)(xe,{children:[(0,g.jsx)(z,{style:{overflowWrap:"anywhere"},children:w.description}),(0,g.jsx)(z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:w.quantity}),(0,g.jsx)(z,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(w.amount)})]},F))})]}),(0,g.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,g.jsx)(ls,{label:"Subtotal",value:T(m.amount_subtotal)}),(m.discount_total??0)>0&&(0,g.jsx)(ls,{label:"Discount",value:`-${T(m.discount_total)}`}),m.tax_total>0&&(0,g.jsx)(ls,{label:m.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(m.tax_total)}),(0,g.jsx)(ls,{label:"Total",value:T(m.amount_total),strong:!0}),m.credit_applied>0&&(0,g.jsx)(ls,{label:"Credit applied",value:`-${T(m.credit_applied)}`}),m.amount_due!==null&&m.amount_due!==m.amount_total&&(0,g.jsx)(ls,{label:"Amount due",value:T(m.amount_due),strong:!0}),m.amount_paid!==null&&m.amount_paid>0&&(0,g.jsx)(ls,{label:"Amount paid",value:T(m.amount_paid)}),m.amount_refunded>0&&(0,g.jsx)(ls,{label:"Refunded",value:T(m.amount_refunded)})]}),m.credit_notes?.length>0&&(0,g.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Credit notes"}),m.credit_notes.map(w=>(0,g.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,g.jsxs)("span",{className:"af-text-muted-foreground",children:[ya(w.created_at)," \xB7 ",w.origin==="dashboard"?"issued in Stripe":"refund",w.stripe_credit_note_id?"":" \xB7 being created"]}),(0,g.jsxs)("span",{className:"af-tabular-nums",children:["-",W(w.amount,w.currency)]})]},w.id))]})]}),(m.note||m.footer)&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[m.note&&(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:Ya,children:"Note"}),(0,g.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:m.note})]}),m.footer&&(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:Ya,children:"Footer"}),(0,g.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:m.footer})]})]}),f&&!R&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,g.jsxs)("div",{className:te(Ya,"af-break-words"),children:["Email preview \u2014 ",f.subject]}),(0,g.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,g.jsx)("iframe",{title:"Invoice email preview",srcDoc:f.html,sandbox:"",className:"af-mt-2 af-h-[560px] af-w-full af-rounded af-border af-bg-white"})]})]}),(0,g.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,g.jsx)(ba,{label:"Created",value:ya(m.created_at)}),(0,g.jsx)(ba,{label:"Due",value:m.collection_method==="charge_automatically"?"Managed in Stripe":m.due_at?ya(m.due_at):"On receipt"}),m.paid_at&&(0,g.jsx)(ba,{label:"Paid",value:ya(m.paid_at)}),m.payment_method&&(0,g.jsx)(ba,{label:"Paid by",value:m.paid_out_of_band?`${m.payment_method} (recorded outside Stripe)`:m.payment_method}),m.payment_state!=="none"&&(0,g.jsx)(ba,{label:"Payment",value:m.payment_state==="processing"?"Processing":m.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),m.delivery&&(0,g.jsx)(ba,{label:"Delivery",value:`${Cr[m.delivery.state]} \xB7 ${m.delivery.recipient}`}),m.marked_uncollectible_at&&(0,g.jsx)(ba,{label:"Written off",value:ya(m.marked_uncollectible_at)}),m.correction_reason&&(0,g.jsx)(ba,{label:"Correction",value:m.correction_reason}),m.replaced_by_order_id&&(0,g.jsx)(ba,{label:"Replaced by",value:m.replaced_by_order_id}),m.collection_method==="charge_automatically"?(0,g.jsx)(ba,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):m.retainer_id&&(0,g.jsx)(ba,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),m.replaces_order_id&&(0,g.jsx)(ba,{label:"Replaces",value:m.replaces_order_id})]}),(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Reminders"}),R?(0,g.jsx)("div",{children:"View automatic payment reminders in Stripe."}):m.reminders.disabled?(0,g.jsx)("div",{children:"Off for this invoice."}):m.reminders.paused_until?(0,g.jsxs)("div",{children:["Paused until ",ya(m.reminders.paused_until),"."]}):m.reminders.next_at?(0,g.jsxs)("div",{children:["Next on ",ya(m.reminders.next_at),"."]}):m.reminders.final_sent_at?(0,g.jsxs)("div",{children:["Final reminder sent ",ya(m.reminders.final_sent_at),"."]}):(0,g.jsx)("div",{children:"None scheduled."}),!R&&(0,g.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",m.reminders.schedule.length===0?"none":m.reminders.schedule.map(w=>w<0?`${-w}d before`:w===0?"due day":`${w}d after`).join(", ")]})]}),m.communications&&m.communications.length>0&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Email delivery history"}),m.communications.map(w=>(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,g.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[kl[w.kind]??w.kind,w.kind==="reminder"&&w.slot!==null?` #${w.slot}`:"",(0,g.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",w.recipient]})]}),(0,g.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[Cr[w.state]??w.state," \xB7 ",ya(w.state_at??w.created_at)]})]},w.id))]}),U.length>0&&(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,g.jsx)("div",{className:Ya,children:"Bill to"}),U.map((w,F)=>(0,g.jsx)("div",{className:"af-break-words",children:w},F))]}),(0,g.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[m.pay_url&&(0,g.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void D(),disabled:!Fi(),children:[(0,g.jsx)(xt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":R?"Copy invoice link":"Copy pay link"]}),m.pdf_url&&(0,g.jsx)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,g.jsxs)("a",{href:m.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,g.jsx)(xt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!R&&(0,g.jsxs)(_,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void P(),disabled:r,children:[r?(0,g.jsx)(xt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,g.jsx)(xt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),f?"Hide email preview":x?"Retry email preview":"Show email preview"]}),x&&!R&&(0,g.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),m.pay_url&&(0,g.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:m.pay_url}),(0,g.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:R?"Manage automatic charging and payment reminders for this invoice in Stripe.":"To resend, remind, void, or mark this invoice paid, ask in the chat."})]})]})]})]})}function ba({label:e,value:t}){return(0,g.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,g.jsx)("span",{className:te(Ya,"af-shrink-0"),children:e}),(0,g.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function ls({label:e,value:t,strong:s}){return(0,g.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,g.jsx)("dt",{className:te(Ya,s&&"af-font-medium af-text-foreground"),children:e}),(0,g.jsx)("dd",{className:te("af-tabular-nums",s&&"af-font-semibold"),children:t})]})}var Ui=require("lucide-react");var De=require("react/jsx-runtime"),Ll={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},$i={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Ol(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 Vi(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>$i[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>$i[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":Ll[e.status]}function Hi(e){let t=e.interval==="year"?"every year":"every month";return`${W(e.amount,e.currency)} ${t}`}function Bl(e){return e.status==="canceled"?`Ended ${Kn(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Kn(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 ${Kn(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Kn(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Kn(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 Zn({retainer:e,className:t}){return(0,De.jsx)(ae,{variant:Ol(e.status),className:te("af-max-w-full af-whitespace-normal af-break-words",t),children:Vi(e)})}function ys({retainers:e,isLoading:t,error:s,onRetry:a,onShowCycles:n,activeRetainerId:i,total:o,endedTotal:d=0,isLoadingMore:f=!1,onLoadMore:u,includeEnded:r=!1,onIncludeEndedChange:v,className:x}){let b=!!v;if(!t&&!s&&e.length===0&&!(b&&(r||d>0)))return null;let c=o!==void 0?Math.max(0,o-e.length):0;return(0,De.jsxs)("section",{className:te("af-mb-6",x),"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:()=>v?.(!r),children:r?"Hide ended recurring invoices":d>0&&e.length===0?`Show ended recurring invoices (${d})`:"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)(se,{className:"af-h-4 af-w-48"}),(0,De.jsx)(se,{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 y=i===l.id;return(0,De.jsxs)("li",{className:te("af-rounded-md af-border af-p-3",y&&"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)(Zn,{retainer:l})]}),l.collection_method==="charge_automatically"?(0,De.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,De.jsx)(ae,{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:Hi(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:[Bl(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:y?"secondary":"ghost",size:"sm",onClick:()=>n(l),"aria-pressed":y,children:y?"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&&c>0&&u&&(0,De.jsx)("div",{className:"af-mt-2",children:(0,De.jsx)(_,{type:"button",variant:"outline",size:"sm",onClick:u,disabled:f,children:f?"Loading\u2026":`Load more (${c} more)`})})]})}var zi=le(require("react"),1),oa=require("lucide-react");var Se=require("react/jsx-runtime");function fn({onConnectStripe:e,onUpgradePlan:t,className:s}){let{status:a,isLoading:n,error:i,refetch:o}=Wa(),[d,f]=zi.useState(!1),u=async()=>{f(!0);try{await o()}finally{f(!1)}};return n&&!a?(0,Se.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Se.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):i||!a?(0,Se.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,Se.jsxs)("div",{className:"af-text-destructive",children:["Error: ",i?.message||"Failed to load payment status"]})}):a.status==="active"?(0,Se.jsx)("div",{className:s,children:(0,Se.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,Se.jsx)(oa.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Se.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,Se.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Se.jsx)(oa.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Se.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,Se.jsxs)(_,{onClick:e,children:[(0,Se.jsx)(oa.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Se.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,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Se.jsx)(oa.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Se.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,Se.jsx)(_,{onClick:t,children:"Upgrade plan"}):(0,Se.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,Se.jsxs)("div",{className:"af-space-y-3",children:[(0,Se.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,Se.jsx)(oa.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Se.jsxs)("div",{children:[(0,Se.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,Se.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,Se.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,Se.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,Se.jsxs)(_,{onClick:e,children:[(0,Se.jsx)(oa.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Se.jsxs)(_,{variant:"outline",onClick:u,disabled:d,children:[d?(0,Se.jsx)(oa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Se.jsx)(oa.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var $t=le(require("react"),1);function kr(e,t,s){return e.map(a=>a.id===t?{...a,...s}:a)}function hs({includeStats:e=!1,refreshKey:t}={}){let{api:s}=ne(),[a,n]=$t.useState([]),[i,o]=$t.useState(!0),[d,f]=$t.useState(null),u=$t.useRef(0),r=$t.useCallback(async()=>{let y=++u.current;try{o(!0),f(null);let N=await s.getProducts(e?{include:"stats"}:{});if(y!==u.current)return;n(N)}catch(N){if(y!==u.current)return;f(N instanceof Error?N:new Error("Failed to fetch products"))}finally{y===u.current&&o(!1)}},[s,e,t]);$t.useEffect(()=>{r()},[r]);let v=$t.useCallback(async y=>{let N=await s.createProduct(y);return n(S=>[N,...S]),N},[s]),x=$t.useCallback(async(y,N)=>{let S=await s.updateProduct(y,N);return n(O=>kr(O,y,S)),S},[s]),b=$t.useCallback(async y=>{await s.deleteProduct(y),n(N=>N.filter(S=>S.id!==y))},[s]),c=$t.useCallback(async(y,N)=>{let S=await s.attachProductFile(y,N);return n(O=>kr(O,y,S)),S},[s]),l=$t.useCallback(async(y,N)=>{let S=await s.attachProductFileFromUrl(y,N);return n(O=>kr(O,y,S)),S},[s]);return{products:a,isLoading:i,error:d,refetch:r,createProduct:v,updateProduct:x,deleteProduct:b,attachProductFile:c,attachProductFileFromUrl:l}}var Ut=le(require("react"),1);var qi=["creating","active","paused","canceling"],Fl=["canceled","failed"];function xs({refreshKey:e,includeEnded:t=!1,limit:s=50}={}){let{api:a}=ne(),[n,i]=Ut.useState([]),[o,d]=Ut.useState(0),[f,u]=Ut.useState(0),[r,v]=Ut.useState(!0),[x,b]=Ut.useState(!1),[c,l]=Ut.useState(null),[y,N]=Ut.useState(t),S=Ut.useRef(0),O=Ut.useCallback(async()=>{let m=++S.current;v(!0),b(!1),l(null);try{let R=await a.getRetainers({statuses:y?void 0:qi,limit:s,offset:0});if(m!==S.current)return;if(i(R.retainers),d(R.total),!y&&R.total===0){let T=await a.getRetainers({statuses:Fl,limit:1,offset:0});if(m!==S.current)return;u(T.total)}else u(0)}catch(R){if(m!==S.current)return;l(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{m===S.current&&v(!1)}},[a,y,s]);Ut.useEffect(()=>{O()},[O,e]);let M=Ut.useCallback(async()=>{if(r||x||n.length>=o)return;let m=S.current;b(!0);try{let R=await a.getRetainers({statuses:y?void 0:qi,limit:s,offset:n.length});if(m!==S.current)return;i(T=>{let D=new Set(T.map(P=>P.id));return[...T,...R.retainers.filter(P=>!D.has(P.id))]}),d(R.total)}catch(R){if(m!==S.current)return;l(R instanceof Error?R:new Error("Failed to fetch retainers"))}finally{m===S.current&&b(!1)}},[a,y,s,r,x,n.length,o]);return{retainers:n,total:o,endedTotal:f,hasMore:n.length<o,isLoading:r,isLoadingMore:x,error:c,includeEnded:y,setIncludeEnded:N,loadMore:M,refetch:O}}var ye=require("react/jsx-runtime");function Er({className:e,defaultTab:t="products",onConnectStripe:s,onRefund:a,onUpgradePlan:n}){let[i,o]=Ls.useState(t),[d,f]=Ls.useState("list"),[u,r]=Ls.useState(null),v=hs(),{status:x,error:b}=Wa(),c=x?.currency,l=O=>{r(O),f("edit")},y=()=>{r(null),f("create")},N=()=>{f("list"),r(null)},S=O=>{r(O),f("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)(En,{value:i,onValueChange:O=>o(O),children:[(0,ye.jsxs)(Vs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,ye.jsxs)(Na,{value:"products",className:"af-gap-2",children:[(0,ye.jsx)(ha.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,ye.jsxs)(Na,{value:"orders",className:"af-gap-2",children:[(0,ye.jsx)(ha.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,ye.jsxs)(Na,{value:"invoices",className:"af-gap-2",children:[(0,ye.jsx)(ha.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,ye.jsxs)(Na,{value:"customers",className:"af-gap-2",children:[(0,ye.jsx)(ha.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,ye.jsx)(Na,{value:"promos",children:"Promo codes"}),(0,ye.jsxs)(Na,{value:"setup",className:"af-gap-2",children:[(0,ye.jsx)(ha.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,ye.jsx)(Sa,{value:"products",children:d==="list"?(0,ye.jsx)(tn,{productsState:v,onSelectProduct:l,onCreateProduct:y}):(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{className:"af-mb-6",children:[(0,ye.jsxs)(_,{variant:"ghost",size:"sm",onClick:N,className:"af-mb-2 af--ml-2",children:[(0,ye.jsx)(ha.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:d==="create"?"New Product":u?.name})]}),d==="create"&&!c?(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)(sn,{productsState:v,product:d==="edit"?u:null,currency:c??"usd",onSaved:S},d==="edit"?u?.id??"edit":"new")]})}),(0,ye.jsx)(Sa,{value:"orders",children:(0,ye.jsx)(Ja,{onRefund:a})}),(0,ye.jsx)(Sa,{value:"invoices",children:(0,ye.jsx)(Ml,{onConnectStripe:s,onUpgradePlan:n,needsPaidPlan:x?.reason==="needs_paid_plan"})}),(0,ye.jsx)(Sa,{value:"customers",children:(0,ye.jsx)(dn,{})}),(0,ye.jsx)(Sa,{value:"promos",children:(0,ye.jsx)(ms,{})}),(0,ye.jsx)(Sa,{value:"setup",children:(0,ye.jsx)(fn,{onConnectStripe:s,onUpgradePlan:n})})]})]})}function Ml({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:s}){let a=xs(),[n,i]=Ls.useState(null),[o,d]=Ls.useState(!1);return(0,ye.jsxs)(ye.Fragment,{children:[!o&&(0,ye.jsx)(ys,{retainers:a.retainers,isLoading:a.isLoading,error:a.error,onRetry:()=>void a.refetch(),activeRetainerId:n?.id??null,onShowCycles:f=>i(u=>u?.id===f.id?null:f),total:a.total,endedTotal:a.endedTotal,isLoadingMore:a.isLoadingMore,onLoadMore:()=>void a.loadMore(),includeEnded:a.includeEnded,onIncludeEndedChange:a.setIncludeEnded}),(0,ye.jsx)(Qa,{onDetailOpenChange:d,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 Gi=le(require("react"),1);var Ua=le(require("react"),1);function ws({refreshKey:e}={}){let{api:t}=ne(),[s,a]=Ua.useState(null),[n,i]=Ua.useState(!0),[o,d]=Ua.useState(null),f=Ua.useRef(0),u=Ua.useCallback(async()=>{let r=++f.current;try{i(!0),d(null);let v=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(r!==f.current)return;a(v)}catch(v){if(r!==f.current)return;d(v instanceof Error?v:new Error("Failed to fetch summary"))}finally{r===f.current&&i(!1)}},[t,e]);return Ua.useEffect(()=>{u()},[u]),{summary:s,isLoading:n,error:o,refetch:u}}var je=require("react/jsx-runtime");function ji(e,t){if(e.settled.complete)return{headline:W(e.settled.gross,e.settled.currency),extra:[]};let s=e.totals[0];return s?{headline:W(s.gross,s.currency),extra:e.totals.slice(1).map(a=>`+ ${W(a.gross,a.currency)} in ${a.currency.toUpperCase()}`)}:{headline:W(0,t),extra:[]}}function Ar({refreshKey:e,initialOrderId:t,isOwner:s=!1,onRefund:a,onBackToWebsite:n,className:i}){let{summary:o,isLoading:d,error:f,refetch:u}=ws({refreshKey:e}),[r,v]=Gi.useState(!1),x=(0,je.jsx)("div",{className:"af-mb-6",children:f&&!o?(0,je.jsx)(ra,{message:"Couldn't load your revenue summary.",onRetry:()=>u()}):(0,je.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!o?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(rt,{label:"This week",children:(0,je.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,je.jsx)(rt,{label:"Today",children:(0,je.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,je.jsx)(rt,{label:"Needs attention",children:(0,je.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,je.jsx)(je.Fragment,{children:(()=>{let b=ji(o.revenue.d7,o.currency),c=ji(o.revenue.today,o.currency);return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(rt,{label:"This week",detail:b.extra.length>0?(0,je.jsx)("div",{children:b.extra.map(l=>(0,je.jsx)("div",{children:l},l))}):void 0,children:b.headline}),(0,je.jsx)(rt,{label:"Today",detail:c.extra.length>0?(0,je.jsx)("div",{children:c.extra.map(l=>(0,je.jsx)("div",{children:l},l))}):void 0,children:c.headline}),(0,je.jsx)(rt,{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,je.jsxs)(yt,{title:"Orders",onBackToWebsite:n,hideBackButton:r,className:i,children:[x,(0,je.jsx)(Ja,{refreshKey:e,initialOrderId:t,onDetailOpenChange:v,showFulfillment:!0,onRefund:s?a:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Ha=le(require("react"),1),Os=require("lucide-react");var Va=le(require("react"),1),tr=require("lucide-react");var Ct=require("react/jsx-runtime"),Wi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",cs="af-text-xs af-text-muted-foreground",Jn="af-text-sm af-font-medium af-tabular-nums",$l=3;function Ul(e){let t=e.pricing,s=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let f=e.min_amount??t?.min_amount??null,u=e.max_amount??t?.max_amount??null;return f!==null&&u!==null?{text:`Buyer chooses (${W(f,s)} \u2013 ${W(u,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?W(n,s):`${W(n,s)} \u2013 ${W(i,s)}`,d=t?.compare_at_amount??null;return{text:o,compareAt:d!==null&&d>i?W(d,s):null}}function Yn({product:e,className:t}){let s=Ul(e);return(0,Ct.jsxs)("div",{className:t,children:[(0,Ct.jsx)("span",{className:Jn,children:s.text}),s.compareAt&&(0,Ct.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:s.compareAt})]})}function Qn({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,Ct.jsx)(ae,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,Ct.jsxs)(ae,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,Ct.jsx)(ae,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,Ct.jsxs)(ae,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,Ct.jsx)(ae,{variant:"warning",children:"Low stock"}):null}function Xn(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function er(e){return e.map(t=>W(t.amount,t.currency)).join(" + ")}function Ki(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${W(e.min_amount,e.currency)} \u2013 ${W(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":W(e.unit_amount,e.currency)}function Zi({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,Ct.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let s=t.available??0;return t.allow_backorder?(0,Ct.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Ct.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,s)}),(0,Ct.jsx)(ae,{variant:"secondary",children:s<0?`${Math.abs(s)} on backorder`:"Backorder"})]}):s<=0?(0,Ct.jsx)(ae,{variant:"destructive",children:"Out of stock"}):(0,Ct.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,Ct.jsx)("span",{className:"af-tabular-nums",children:s}),s<=$l&&(0,Ct.jsx)(ae,{variant:"warning",children:"Low"})]})}var Q=require("react/jsx-runtime");function mn({title:e,children:t,className:s}){return(0,Q.jsxs)("section",{className:te("af-rounded-lg af-border af-p-4",s),children:[(0,Q.jsx)("h4",{className:Wi,children:e}),(0,Q.jsx)("div",{className:"af-mt-3",children:t})]})}function Ji({src:e,className:t}){let[s,a]=Va.useState(!1);return Va.useEffect(()=>a(!1),[e]),!e||s?(0,Q.jsx)("div",{"aria-hidden":"true",className:te("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,Q.jsx)(tr.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,Q.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>a(!0),className:te("af-object-cover",t)})}function Yi({product:e,showStats:t=!1,onBack:s}){let{api:a}=ne(),[n,i]=Va.useState(null),[o,d]=Va.useState(!0),[f,u]=Va.useState(null),[r,v]=Va.useState(0),[x,b]=Va.useState(0);Va.useEffect(()=>{let m=!1;return d(!0),u(null),a.getProduct(e.id).then(R=>{m||i(R)}).catch(R=>{m||u(R instanceof Error?R:new Error("Failed to load product"))}).finally(()=>{m||d(!1)}),()=>{m=!0}},[a,e.id,r]);let c=n?{...e,...n}:e,l=c.images.length>0?c.images:e.images,y=l[x]??l[0],N=Xn(c),S=t?c.stats:void 0,O=n?.variants??[],M=O.length>1;return(0,Q.jsxs)("div",{children:[(0,Q.jsxs)("div",{className:"af-mb-6",children:[(0,Q.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,Q.jsx)(tr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,Q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Q.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),(0,Q.jsx)(ae,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),(0,Q.jsx)(Qn,{product:c})]}),(0,Q.jsx)(Yn,{product:c,className:"af-mt-1"}),!c.active&&(0,Q.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,Q.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,Q.jsxs)("div",{className:"af-space-y-2",children:[(0,Q.jsx)(Ji,{src:y,className:"af-h-48 af-w-full af-rounded-md af-border"}),l.length>1&&(0,Q.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:l.map((m,R)=>(0,Q.jsx)("button",{type:"button",onClick:()=>b(R),"aria-label":`Show photo ${R+1} of ${l.length}`,"aria-pressed":R===x,className:te("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",R===x?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,Q.jsx)(Ji,{src:m,className:"af-h-12 af-w-12 af-rounded-md"})},`${m}-${R}`))})]}),(0,Q.jsxs)("div",{className:"af-space-y-6",children:[c.description&&(0,Q.jsx)(mn,{title:"Description",children:(0,Q.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?(0,Q.jsxs)(mn,{title:"Variants",children:[(0,Q.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(m=>(0,Q.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,Q.jsx)(se,{className:"af-h-4 af-w-28"}),(0,Q.jsx)(se,{className:"af-h-4 af-w-20"}),(0,Q.jsx)(se,{className:"af-h-4 af-w-16"})]},m))}),(0,Q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):f?(0,Q.jsx)(ra,{message:"Couldn't load this product's variants.",onRetry:()=>v(m=>m+1)}):M?(0,Q.jsx)(mn,{title:`Variants \xB7 ${O.length}`,children:(0,Q.jsx)("div",{className:"af-overflow-x-auto",children:(0,Q.jsxs)(Ue,{children:[(0,Q.jsx)(Ve,{children:(0,Q.jsxs)(xe,{children:[(0,Q.jsx)(H,{children:"Variant"}),(0,Q.jsx)(H,{children:"SKU"}),(0,Q.jsx)(H,{className:"af-text-right",children:"Price"}),(0,Q.jsx)(H,{children:"Stock"})]})}),(0,Q.jsx)(He,{children:O.map(m=>(0,Q.jsxs)(xe,{children:[(0,Q.jsxs)(z,{className:"af-font-medium",children:[m.title||m.option_values.map(R=>R.value).join(" / ")||"\u2014",!m.active&&(0,Q.jsx)(ae,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,Q.jsx)(z,{className:"af-text-muted-foreground",children:m.sku?(0,Q.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:m.sku}):"\u2014"}),(0,Q.jsxs)(z,{className:"af-whitespace-nowrap af-text-right",children:[(0,Q.jsx)("div",{className:Jn,children:Ki(m)}),m.compare_at_amount!==null&&m.unit_amount!==null&&m.compare_at_amount>m.unit_amount&&(0,Q.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:W(m.compare_at_amount,m.currency)})]}),(0,Q.jsx)(z,{className:"af-text-sm",children:(0,Q.jsx)(Zi,{variant:m})})]},m.id))})]})})}):null,(0,Q.jsx)(mn,{title:"Details",children:(0,Q.jsxs)("dl",{className:"af-space-y-2",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Delivery"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:N==="Digital download"?c.fulfillment.filename??"Digital download":N??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Sends buyers to"}),(0,Q.jsx)("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Shipping address"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Most one buyer can order"}),(0,Q.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),S&&(0,Q.jsx)(mn,{title:"Last 30 days",children:(0,Q.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Units sold"}),(0,Q.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.units_sold})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Orders"}),(0,Q.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.orders})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:cs,children:"Gross"}),(0,Q.jsx)("dd",{className:Jn,children:S.gross.length>0?er(S.gross):"\u2014"})]})]})}),(0,Q.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var V=require("react/jsx-runtime"),Vl={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Hl=["all","active","draft","low_stock","out_of_stock"];function Qi(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,s=new Date(t).getTime();return Number.isNaN(s)?0:s}function Xi(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function zl(e){return e.inventory?.out_of_stock??!1}function ql(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Xi(e);case"out_of_stock":return zl(e);default:return!0}}function jl({product:e,showStats:t,onOpen:s}){let a=e.images[0],n=t?e.stats:void 0,i=Xn(e),o=e.variant_count??0;return(0,V.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,V.jsx)("img",{src:a,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,V.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,V.jsx)(Os.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,V.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,V.jsxs)("div",{className:"af-min-w-0",children:[(0,V.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,V.jsx)(Yn,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,V.jsx)(ae,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Qn,{product:e}),o>1&&(0,V.jsxs)(ae,{variant:"outline",children:[o," variants"]}),i&&(0,V.jsx)(ae,{variant:"outline",children:i})]}),n&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[n.units_sold," sold",n.gross.length>0?` \xB7 ${er(n.gross)}`:""," ",(0,V.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Gl(){return(0,V.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,V.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,V.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,V.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,V.jsx)(se,{className:"af-w-32"}),(0,V.jsx)(se,{className:"af-w-16"}),(0,V.jsx)(se,{className:"af-h-5 af-w-24"})]})]},e))})}function Ir({refreshKey:e,showStats:t=!1,onBackToWebsite:s,className:a}){let{products:n,isLoading:i,error:o,refetch:d}=hs({includeStats:t,refreshKey:e}),[f,u]=Ha.useState(!1),[r,v]=Ha.useState(null),[x,b]=Ha.useState("all"),[c,l]=Ha.useState(""),[y,N]=Ha.useState("newest"),S=Ha.useMemo(()=>{if(!t)return null;let w=null;for(let F of n)!F.stats||F.stats.units_sold===0||(!w||F.stats.units_sold>(w.stats?.units_sold??0))&&(w=F);return w},[n,t]),O=Ha.useMemo(()=>n.filter(Xi).length,[n]),M=c.trim().toLowerCase(),m=Ha.useMemo(()=>{let F=[...n.filter(X=>ql(X,x)&&(!M||X.name.toLowerCase().includes(M)))];return y==="name"?F.sort((X,q)=>X.name.localeCompare(q.name)):y==="best_selling"?F.sort((X,q)=>(q.stats?.units_sold??0)-(X.stats?.units_sold??0)):F.sort((X,q)=>Qi(q.created_at)-Qi(X.created_at)),F},[n,x,M,y]),R=x!=="all"||!!M,T=()=>{b("all"),l("")},D=i||o!==null&&n.length===0,P=(0,V.jsx)("div",{className:"af-mb-6",children:(0,V.jsx)("div",{className:te("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:D?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Products",children:(0,V.jsx)(se,{className:"af-h-6 af-w-10"})}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Best seller",children:(0,V.jsx)(se,{className:"af-h-6 af-w-28"})}),(0,V.jsx)(rt,{label:"Low stock",children:(0,V.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,V.jsx)(rt,{label:"Active",children:(0,V.jsx)(se,{className:"af-h-6 af-w-10"})})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Products",children:n.length}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(rt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:S?`${S.stats?.units_sold??0} sold, last 30 days`:void 0,children:S?(0,V.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:S.name}):(0,V.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,V.jsx)(rt,{label:"Low stock",children:O})]}):(0,V.jsx)(rt,{label:"Active",children:n.filter(w=>w.active).length})]})})}),A=(0,V.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,V.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:Hl.map(w=>(0,V.jsx)("button",{type:"button","aria-pressed":x===w,onClick:()=>b(w),className:te("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",x===w?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Vl[w]},w))}),(0,V.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,V.jsx)(Os.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,V.jsx)(Ne,{type:"text",value:c,onChange:w=>l(w.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,V.jsxs)(da,{value:y,onValueChange:w=>N(w),children:[(0,V.jsx)(Xt,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,V.jsx)(fa,{})}),(0,V.jsxs)(ea,{children:[(0,V.jsx)(Ye,{value:"newest",children:"Newest"}),(0,V.jsx)(Ye,{value:"name",children:"Name A\u2013Z"}),t&&(0,V.jsx)(Ye,{value:"best_selling",children:"Best selling"})]})]}),R&&(0,V.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:T,children:"Clear filters"})]}),i&&n.length===0?(0,V.jsx)(se,{className:"af-h-4 af-w-28"}):(0,V.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:R?`${m.length} of ${n.length} products`:`${n.length} ${n.length===1?"product":"products"}${O>0?` \xB7 ${O} low stock`:""}`})]}),U;return r?U=(0,V.jsx)(Yi,{product:r,showStats:t,onBack:()=>{v(null),d()}},r.id):i&&n.length===0?U=(0,V.jsxs)(V.Fragment,{children:[A,(0,V.jsx)(Gl,{}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&n.length===0?U=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)(ra,{message:"Couldn't load your products.",onRetry:()=>d()})}):n.length===0?U=(0,V.jsxs)(Ea,{icon:(0,V.jsx)(Os.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,V.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):U=(0,V.jsxs)(V.Fragment,{children:[A,o&&(0,V.jsx)("div",{className:"af-mb-4",children:(0,V.jsx)(ra,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>d()})}),m.length===0?(0,V.jsxs)(Ea,{children:["No products match these filters.",(0,V.jsx)("br",{}),(0,V.jsx)(_,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:T,children:"Show all products"})]}):(0,V.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:m.map(w=>(0,V.jsx)(jl,{product:w,showStats:t,onOpen:()=>v(w)},w.id))})]}),(0,V.jsx)(yt,{title:"Products",onBackToWebsite:s,hideBackButton:!!r,className:a,children:f?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(_,{variant:"ghost",onClick:()=>u(!1),children:"Back to products"}),(0,V.jsx)(ms,{})]}):(0,V.jsxs)(V.Fragment,{children:[!r&&(0,V.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,V.jsx)(_,{variant:"outline",onClick:()=>u(!0),children:"Promo codes"})}),!r&&P,U]})})}var Aa=le(require("react"),1),vt=require("lucide-react");var la=le(require("react"),1);function pn({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ne(),[a,n]=la.useState([]),[i,o]=la.useState(!0),[d,f]=la.useState(null),[u,r]=la.useState(0),[v]=la.useState(e),[x,b]=la.useState(""),c=la.useRef(0),l=la.useCallback(async()=>{let y=++c.current;try{o(!0),f(null);let N={limit:v,offset:u*v};x.trim()&&(N.q=x.trim());let S=await s.getPeople(N);if(y!==c.current)return;n(S.people)}catch(N){if(y!==c.current)return;f(N instanceof Error?N:new Error("Failed to fetch people"))}finally{y===c.current&&o(!1)}},[s,u,v,x,t]);return la.useEffect(()=>{l()},[l]),{people:a,isLoading:i,error:d,page:u,pageSize:v,hasNextPage:a.length===v,hasPreviousPage:u>0,setPage:r,q:x,setQ:y=>{b(y),r(0)},refetch:l}}var za=le(require("react"),1);function gn(e,{refreshKey:t}={}){let{api:s}=ne(),[a,n]=za.useState(null),[i,o]=za.useState(e!==null),[d,f]=za.useState(null),u=za.useRef(0),r=za.useCallback(async()=>{if(e===null){n(null),o(!1),f(null);return}let v=++u.current;try{o(!0),f(null);let x=await s.getPerson(e);if(v!==u.current)return;n(x)}catch(x){if(v!==u.current)return;f(x instanceof Error?x:new Error("Failed to fetch person"))}finally{v===u.current&&o(!1)}},[s,e,t]);return za.useEffect(()=>{r()},[r]),{person:a,isLoading:i,error:d,refetch:r}}var h=require("react/jsx-runtime"),Dr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Wl="af-text-xs af-text-muted-foreground";function Bs(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 Lr(e,t){let s=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(s)}`}function Kl(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function Zl({value:e,label:t}){let[s,a]=Aa.useState(!1);return Kl()?(0,h.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,h.jsx)(vt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(vt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),s?"Copied":"Copy email"]}):null}function eo(e){return(0,h.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,h.jsxs)(ae,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,h.jsx)(ae,{variant:"secondary",children:"Contact form"})]})}function to(e){return e.name?e.name:e.email?e.email:(0,h.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var Jl=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,Yl=40;function Ql(e){let t=Object.entries(e).filter(([n])=>!n.startsWith("_")),a=t.find(([n,i])=>Jl.test(n)&&typeof i=="string"&&i.trim())??t.filter(([,n])=>typeof n=="string"&&n.trim().length>=Yl).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 Xl(e){return e.replace(/_/g," ")}function ec(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function tc({data:e}){let{message:t,rest:s}=Ql(e);return t===null&&s.length===0?(0,h.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,h.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,h.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),s.length>0&&(0,h.jsx)("dl",{className:"af-space-y-1",children:s.map(([a,n])=>(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,h.jsx)("dt",{className:te(Wl,"af-w-28 af-shrink-0 af-capitalize"),children:Xl(a)}),(0,h.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:ec(n)})]},a))})]})}function ao({formName:e,createdAt:t,data:s}){return(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,h.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)(ae,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,h.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,h.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:Bs(t)})]}),(0,h.jsx)(tc,{data:s})]})}function ac(e){return e.charged_total??e.amount_total}function sc({email:e,refreshKey:t,onBack:s}){let{person:a,isLoading:n,error:i,refetch:o}=gn(e,{refreshKey:t}),d=Lr(e,a?.submissions[0]?.form_name);return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(_,{variant:"ghost",size:"sm",onClick:s,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(vt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[n?(0,h.jsx)(se,{className:"af-h-7 af-w-48"}):(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:a?.name||e}),(0,h.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,h.jsx)(Zl,{value:e,label:"Copy email address"})]})]}),(0,h.jsx)(_,{asChild:!0,children:(0,h.jsxs)("a",{href:d,children:[(0,h.jsx)(vt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),n?(0,h.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(f=>(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,h.jsx)(se,{className:"af-w-40"}),(0,h.jsx)(se,{className:"af-mt-2 af-w-64"})]},f)),(0,h.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):i||!a?(0,h.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,h.jsx)(ra,{message:"Couldn't load this person.",onRetry:()=>o()})}):(0,h.jsxs)("div",{className:"af-space-y-6",children:[a.customer&&(0,h.jsxs)("div",{children:[(0,h.jsx)("h4",{className:te(Dr,"af-mb-3"),children:"Customer"}),(0,h.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[a.customer.name&&(0,h.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,h.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,h.jsx)("dd",{children:a.customer.name})]}),a.customer.phone&&(0,h.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,h.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,h.jsx)("dd",{children:a.customer.phone})]}),(0,h.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,h.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,h.jsx)("dd",{children:Bs(a.customer.created_at)})]})]})]}),a.orders.length>0&&(0,h.jsxs)("div",{children:[(0,h.jsx)("h4",{className:te(Dr,"af-mb-3"),children:"Purchases"}),(0,h.jsx)("div",{className:"af-overflow-x-auto",children:(0,h.jsxs)(Ue,{children:[(0,h.jsx)(Ve,{children:(0,h.jsxs)(xe,{children:[(0,h.jsx)(H,{children:"Order"}),(0,h.jsx)(H,{children:"Date"}),(0,h.jsx)(H,{className:"af-text-right",children:"Total"}),(0,h.jsx)(H,{children:"Status"})]})}),(0,h.jsx)(He,{children:a.orders.map(f=>(0,h.jsxs)(xe,{children:[(0,h.jsx)(z,{className:"af-whitespace-nowrap af-font-medium",children:Za(f)}),(0,h.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bs(f.created_at)}),(0,h.jsx)(z,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:W(ac(f),f.currency)}),(0,h.jsx)(z,{children:(0,h.jsx)(os,{status:f.status})})]},f.id))})]})}),(0,h.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,h.jsxs)("div",{children:[(0,h.jsx)("h4",{className:te(Dr,"af-mb-3"),children:"Messages"}),(0,h.jsx)("div",{className:"af-space-y-3",children:a.submissions.map(f=>(0,h.jsx)(ao,{formName:f.form_name,createdAt:f.created_at,data:f.data},f.id))})]})]})]})}function nc({submissionId:e,onBack:t}){let{api:s}=ne(),[a,n]=Aa.useState(null),[i,o]=Aa.useState(!0),[d,f]=Aa.useState(null),[u,r]=Aa.useState(0);return Aa.useEffect(()=>{let v=!1;return o(!0),f(null),s.getSubmission(e).then(x=>{v||n(x)}).catch(x=>{v||f(x instanceof Error?x:new Error("Failed to load submission"))}).finally(()=>{v||o(!1)}),()=>{v=!0}},[s,e,u]),(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(_,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(vt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),i?(0,h.jsx)(se,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,h.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:Bs(a.metadata.submitted_at)})]}),i?(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,h.jsx)(se,{className:"af-w-40"}),(0,h.jsx)(se,{className:"af-mt-2 af-w-64"}),(0,h.jsx)(se,{className:"af-mt-2 af-w-52"}),(0,h.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):d||!a?(0,h.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,h.jsx)(ra,{message:"Couldn't load this submission.",onRetry:()=>r(v=>v+1)})}):(0,h.jsxs)("div",{className:"af-space-y-3",children:[(0,h.jsx)(ao,{formName:null,createdAt:a.metadata.submitted_at,data:a.data}),(0,h.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 rc={all:"All",customers:"Customers",leads:"Leads"},ic=["all","customers","leads"];function oc(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function lc({refreshKey:e,onBackToWebsite:t,className:s,maxRows:a,onViewAll:n}){let i=typeof a=="number",{people:o,isLoading:d,error:f,page:u,pageSize:r,hasNextPage:v,hasPreviousPage:x,setPage:b,q:c,setQ:l,refetch:y}=pn({refreshKey:e}),[N,S]=Aa.useState({kind:"list"}),[O,M]=Aa.useState(""),[m,R]=Aa.useState("all"),T=!i||!!n,D=X=>{if(i){n?.();return}X.email?S({kind:"person",email:X.email}):X.submission_id&&S({kind:"submission",submissionId:X.submission_id})},P=()=>{S({kind:"list"}),y()},A=X=>{let q=X.trim();q!==c&&l(q)},U=o.filter(X=>oc(X,m)),w=i?U.slice(0,a):U,F;if(N.kind==="person")F=(0,h.jsx)(sc,{email:N.email,refreshKey:e,onBack:P});else if(N.kind==="submission")F=(0,h.jsx)(nc,{submissionId:N.submissionId,onBack:P});else{let X=(0,h.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.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:ic.map(q=>(0,h.jsx)("button",{type:"button","aria-pressed":m===q,onClick:()=>R(q),className:te("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",m===q?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:rc[q]},q))}),(0,h.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,h.jsx)(vt.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,h.jsx)(Ne,{type:"text",value:O,onChange:q=>M(q.target.value),onBlur:()=>A(O),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),A(O))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&(0,h.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>{M(""),l("")},children:"Clear search"})]});if(d)F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,h.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,h.jsx)(se,{className:"af-h-4 af-w-32"}),(0,h.jsx)(se,{className:"af-h-4 af-w-16"})]}),(0,h.jsx)(se,{className:"af-mt-2 af-h-5 af-w-28"}),(0,h.jsx)(se,{className:"af-mt-2 af-h-3 af-w-56"})]},q))}),(0,h.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,h.jsxs)(Ue,{children:[(0,h.jsx)(Ve,{children:(0,h.jsxs)(xe,{children:[(0,h.jsx)(H,{children:"Person"}),(0,h.jsx)(H,{children:"Came from"}),(0,h.jsx)(H,{children:"Latest message"}),(0,h.jsx)(H,{children:"Last activity"}),(0,h.jsx)(H,{className:"af-w-8"}),(0,h.jsx)(H,{className:"af-w-8"})]})}),(0,h.jsx)(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(q=>(0,h.jsxs)(xe,{children:[(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-4 af-w-40"})}),(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-5 af-w-24"})}),(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-4 af-w-56"})}),(0,h.jsx)(z,{children:(0,h.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,h.jsx)(z,{}),(0,h.jsx)(z,{})]},q))})]})}),(0,h.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(f)F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,h.jsx)(ra,{message:"Couldn't load your leads.",onRetry:()=>y()})})]});else if(w.length===0&&u===0){let q=!!c||m!=="all";F=(0,h.jsxs)("div",{children:[q&&X,q?(0,h.jsx)(Ea,{children:c?"Nobody matches that search.":m==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,h.jsx)(As,{icon:vt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)(Ea,{children:"No more results."}),(0,h.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>b(u-1),children:[(0,h.jsx)(vt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let q=u*r+1,fe=u*r+o.length;F=(0,h.jsxs)("div",{children:[i?null:X,(0,h.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:w.map((J,ee)=>(0,h.jsxs)("div",{onClick:T?()=>D(J):void 0,className:`af-rounded-md af-border af-p-3${T?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,h.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("button",{type:"button",onClick:Z=>{Z.stopPropagation(),D(J)},disabled:!T,"aria-label":`Open ${J.name||J.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${T?" hover:af-underline":""}`,children:to(J)}),J.name&&J.email&&(0,h.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:J.email})]}),(0,h.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,h.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:Bs(J.last_activity_at)}),J.email&&(0,h.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,h.jsx)("a",{href:Lr(J.email),onClick:Z=>Z.stopPropagation(),"aria-label":`Email ${J.email}`,children:(0,h.jsx)(vt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,h.jsx)("div",{className:"af-mt-2",children:eo(J)}),J.latest_message_excerpt&&(0,h.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:J.latest_message_excerpt})]},J.email??J.submission_id??ee))}),(0,h.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,h.jsxs)(Ue,{children:[(0,h.jsx)(Ve,{children:(0,h.jsxs)(xe,{children:[(0,h.jsx)(H,{children:"Person"}),(0,h.jsx)(H,{children:"Came from"}),(0,h.jsx)(H,{children:"Latest message"}),(0,h.jsx)(H,{children:"Last activity"}),(0,h.jsx)(H,{className:"af-w-8",children:(0,h.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,h.jsx)(H,{className:"af-w-8"})]})}),(0,h.jsx)(He,{children:w.map((J,ee)=>(0,h.jsxs)(xe,{onClick:T?()=>D(J):void 0,className:T?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,h.jsxs)(z,{className:"af-max-w-[260px] af-font-medium",children:[(0,h.jsx)("button",{type:"button",onClick:Z=>{Z.stopPropagation(),D(J)},disabled:!T,"aria-label":`Open ${J.name||J.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${T?" hover:af-underline":""}`,children:to(J)}),J.name&&J.email&&(0,h.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:J.email})]}),(0,h.jsx)(z,{children:eo(J)}),(0,h.jsx)(z,{className:"af-max-w-[320px]",children:J.latest_message_excerpt?(0,h.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:J.latest_message_excerpt}):(0,h.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,h.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:Bs(J.last_activity_at)}),(0,h.jsx)(z,{className:"af-w-8",children:J.email&&(0,h.jsx)(_,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,h.jsx)("a",{href:Lr(J.email),onClick:Z=>Z.stopPropagation(),"aria-label":`Email ${J.email}`,children:(0,h.jsx)(vt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,h.jsx)(z,{className:"af-w-8 af-text-right",children:(0,h.jsx)(vt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},J.email??J.submission_id??ee))})]})}),!i&&(0,h.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,h.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:m==="all"?`Showing ${q}-${fe}`:`${w.length} of ${o.length} on this page`}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>b(u-1),disabled:!x,children:[(0,h.jsx)(vt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,h.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>b(u+1),disabled:!v,children:["Next",(0,h.jsx)(vt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return i?(0,h.jsx)("div",{className:s,children:F}):(0,h.jsx)(yt,{title:"Leads",onBackToWebsite:t,hideBackButton:N.kind!=="list",className:s,children:F})}function vn(e){return(0,h.jsx)(lc,{...e},e.maxRows==null?"full":"compact")}var Ns=require("lucide-react");var Kt=le(require("react"),1);function bn({initialPageSize:e=25,refreshKey:t}={}){let{api:s}=ne(),[a,n]=Kt.useState([]),[i,o]=Kt.useState(0),[d,f]=Kt.useState(!0),[u,r]=Kt.useState(null),[v,x]=Kt.useState(0),[b,c]=Kt.useState(e),[l,y]=Kt.useState(void 0),N=Kt.useRef(0),S=Kt.useCallback(async()=>{let M=++N.current;try{f(!0),r(null);let m={limit:b,offset:v*b};l&&(m.status=l);let R=await s.getSubscriptions(m);if(M!==N.current)return;n(R.subscriptions),o(R.total)}catch(m){if(M!==N.current)return;r(m instanceof Error?m:new Error("Failed to fetch subscriptions"))}finally{M===N.current&&f(!1)}},[s,v,b,l,t]);Kt.useEffect(()=>{S()},[S]);let O=Math.ceil(i/b);return{subscriptions:a,total:i,isLoading:d,error:u,page:v,pageSize:b,hasNextPage:v<O-1,hasPreviousPage:v>0,setPage:x,setPageSize:M=>{c(M),x(0)},status:l,setStatus:M=>{y(M),x(0)},refetch:S}}var $=require("react/jsx-runtime");function so(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 no({sub:e}){return e.status==="canceled"?(0,$.jsx)(ae,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,$.jsx)(ae,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,$.jsx)(ae,{variant:"warning",children:"Scheduled to cancel"}):(0,$.jsx)(ae,{variant:"success",children:"Active"}):(0,$.jsx)(ae,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function cc(e,t){let s=W(t,e.currency);return e.plan_interval_count===1?`${s} / ${e.plan_interval}`:`${s} every ${e.plan_interval_count} ${e.plan_interval}s`}function ro({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-font-medium af-tabular-nums",children:cc(e,e.current_amount)}),t&&(0,$.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",W(e.plan_amount,e.currency)]})]})}function io(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${so(e.current_period_end)}`:"Ends at period end":e.current_period_end?so(e.current_period_end):"\u2014"}function Or({refreshKey:e,onBackToWebsite:t,className:s}){let{subscriptions:a,total:n,isLoading:i,error:o,page:d,pageSize:f,hasNextPage:u,hasPreviousPage:r,setPage:v,refetch:x}=bn({refreshKey:e}),b;if(i)b=(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(c=>(0,$.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,$.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,$.jsx)(se,{className:"af-h-4 af-w-40"}),(0,$.jsx)(se,{className:"af-h-4 af-w-20"})]}),(0,$.jsx)(se,{className:"af-mt-2 af-h-3 af-w-32"}),(0,$.jsx)(se,{className:"af-mt-2 af-h-5 af-w-24"})]},c))}),(0,$.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,$.jsxs)(Ue,{children:[(0,$.jsx)(Ve,{children:(0,$.jsxs)(xe,{children:[(0,$.jsx)(H,{children:"Subscriber"}),(0,$.jsx)(H,{children:"Plan"}),(0,$.jsx)(H,{className:"af-text-right",children:"Amount"}),(0,$.jsx)(H,{children:"Renews"}),(0,$.jsx)(H,{children:"Status"})]})}),(0,$.jsx)(He,{"aria-hidden":"true",children:[0,1,2,3,4].map(c=>(0,$.jsxs)(xe,{children:[(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-4 af-w-44"})}),(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-4 af-w-32"})}),(0,$.jsx)(z,{className:"af-text-right",children:(0,$.jsx)(se,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-4 af-w-24"})}),(0,$.jsx)(z,{children:(0,$.jsx)(se,{className:"af-h-5 af-w-20"})})]},c))})]})}),(0,$.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)b=(0,$.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,$.jsx)(ra,{message:"Couldn't load your subscriptions.",onRetry:()=>x()})});else if(a.length===0&&d===0)b=(0,$.jsx)(Ea,{icon:(0,$.jsx)(Ns.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,$.jsxs)("div",{children:[(0,$.jsx)(Ea,{children:"No more results."}),(0,$.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,$.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>v(d-1),children:[(0,$.jsx)(Ns.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let c=d*f+1,l=d*f+a.length;b=(0,$.jsxs)("div",{children:[(0,$.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:a.map(y=>(0,$.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,$.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,$.jsxs)("div",{className:"af-min-w-0",children:[(0,$.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:y.customer_email||(0,$.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,$.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:y.plan_title||"Untitled plan"})]}),(0,$.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,$.jsx)(ro,{sub:y})})]}),(0,$.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,$.jsx)(no,{sub:y}),y.is_test&&(0,$.jsx)(ae,{variant:"outline",children:"Test"}),(0,$.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:io(y)})]}),(0,$.jsx)(Da,{deliveries:y.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},y.id))}),(0,$.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,$.jsxs)(Ue,{children:[(0,$.jsx)(Ve,{children:(0,$.jsxs)(xe,{children:[(0,$.jsx)(H,{children:"Subscriber"}),(0,$.jsx)(H,{children:"Plan"}),(0,$.jsx)(H,{className:"af-text-right",children:"Amount"}),(0,$.jsx)(H,{children:"Renews"}),(0,$.jsx)(H,{children:"Status"})]})}),(0,$.jsx)(He,{children:a.map(y=>(0,$.jsxs)(xe,{children:[(0,$.jsx)(z,{className:"af-max-w-[240px]",children:(0,$.jsx)("div",{className:"af-truncate af-font-medium",children:y.customer_email||(0,$.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,$.jsx)(z,{className:"af-max-w-[220px]",children:(0,$.jsx)("div",{className:"af-truncate",children:y.plan_title||(0,$.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,$.jsx)(z,{className:"af-whitespace-nowrap af-text-right",children:(0,$.jsx)(ro,{sub:y})}),(0,$.jsx)(z,{className:"af-whitespace-nowrap af-text-muted-foreground",children:io(y)}),(0,$.jsxs)(z,{children:[(0,$.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,$.jsx)(no,{sub:y}),y.is_test&&(0,$.jsx)(ae,{variant:"outline",children:"Test"})]}),(0,$.jsx)(Da,{deliveries:y.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},y.id))})]})}),(0,$.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,$.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${c}-${l} of ${n}`}),(0,$.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,$.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>v(d-1),disabled:!r,children:[(0,$.jsx)(Ns.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,$.jsxs)(_,{variant:"outline",size:"sm",onClick:()=>v(d+1),disabled:!u,children:["Next",(0,$.jsx)(Ns.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,$.jsx)(yt,{title:"Subscriptions",onBackToWebsite:t,className:s,children:b})}var Br=le(require("react"),1);var dt=require("react/jsx-runtime");function Fr({refreshKey:e,initialInvoiceId:t,onBackToWebsite:s,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,className:o}){let{aggregates:d,isLoading:f,error:u,refetch:r}=bs({refreshKey:e,initialPageSize:1,includeAggregates:!0}),v=xs({refreshKey:e}),[x,b]=Br.useState(!1),[c,l]=Br.useState(null),y=(0,dt.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!f&&!d?(0,dt.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,dt.jsx)(_,{type:"button",variant:"link",size:"sm",onClick:()=>void r(),children:"Retry totals"})]}):f||!d?(0,dt.jsxs)(dt.Fragment,{children:[(0,dt.jsx)(rt,{label:"Outstanding",children:(0,dt.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,dt.jsx)(rt,{label:"Overdue",children:(0,dt.jsx)(se,{className:"af-h-6 af-w-24"})}),(0,dt.jsx)(rt,{label:"Paid this month",children:(0,dt.jsx)(se,{className:"af-h-6 af-w-24"})})]}):(0,dt.jsxs)(dt.Fragment,{children:[(0,dt.jsx)(rt,{label:"Outstanding",detail:`${d.outstanding.count} open`,children:W(d.outstanding.amount,d.currency)}),(0,dt.jsx)(rt,{label:"Overdue",detail:d.overdue.count===0?"Nothing overdue":`${d.overdue.count} overdue`,valueClassName:d.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:W(d.overdue.amount,d.currency)}),(0,dt.jsx)(rt,{label:"Paid this month",detail:`${d.paid_this_month.count} paid`,children:W(d.paid_this_month.amount,d.currency)})]})});return(0,dt.jsxs)(yt,{title:"Invoices",onBackToWebsite:s,hideBackButton:x,className:o,children:[y,!x&&(0,dt.jsx)(ys,{retainers:v.retainers,isLoading:v.isLoading,error:v.error,onRetry:()=>void v.refetch(),activeRetainerId:c?.id??null,onShowCycles:N=>l(S=>S?.id===N.id?null:N),total:v.total,endedTotal:v.endedTotal,isLoadingMore:v.isLoadingMore,onLoadMore:()=>void v.loadMore(),includeEnded:v.includeEnded,onIncludeEndedChange:v.setIncludeEnded}),(0,dt.jsx)(Qa,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:b,onConnectStripe:a,onUpgradePlan:n,needsPaidPlan:i,retainerFilter:c?{id:c.id,label:`${c.customer_name??c.customer_email??"Recurring invoices"} \u2014 ${c.description}`}:null,onClearRetainerFilter:()=>l(null)})]})}var _t=le(require("react"),1);var uc=2e3,Dt=()=>({data:null,error:null,isLoading:!0});function Ss(e,{refreshKey:t,breakdowns:s=[],filters:a=[]}={}){let{api:n}=ne(),[i,o]=_t.useState(Dt),[d,f]=_t.useState(Dt),[u,r]=_t.useState(Dt),[v,x]=_t.useState(Dt),[b,c]=_t.useState(Dt),l=Z=>Object.fromEntries(Z.map(oe=>[oe,Dt()])),[y,N]=_t.useState(()=>l(s)),S=_t.useRef(0),O=_t.useRef(0),M=_t.useRef("idle"),m=s.join(","),R=as()??"",T=JSON.stringify(a),D=`${e}:${m}:${T}:${R}`,[P,A]=_t.useState({api:n,fetchIdentity:D});(P.api!==n||P.fetchIdentity!==D)&&(A({api:n,fetchIdentity:D}),S.current+=1,o(Dt),f(Dt),r(Dt),x(Dt),N(l(m?m.split(","):[])));let U=`${e}:${String(t??"")}:${R}`,[w,F]=_t.useState({api:n,conversionsIdentity:U});(w.api!==n||w.conversionsIdentity!==U)&&(F({api:n,conversionsIdentity:U}),O.current+=1,M.current="idle",c(Dt));let X=_t.useCallback(async Z=>{let oe=++S.current,Y=m?m.split(","):[];o(Dt),f(Dt),r(Dt),x(Dt),N(Object.fromEntries(Y.map(k=>[k,Dt()])));let Pe=M.current!=="pending"&&(Z?.force===!0||M.current==="idle"),Xe=(k,B)=>B.then(L=>{oe===S.current&&k({data:L,error:null,isLoading:!1})},L=>{oe===S.current&&k({data:null,error:L instanceof Error?L:new Error("Failed to fetch report"),isLoading:!1})}),lt=n.getAnalyticsStatus(),Ae=Xe(o,lt),Ge=Symbol("status-timeout"),at,Ce=await Promise.race([lt.then(k=>k,()=>null),new Promise(k=>{at=setTimeout(()=>k(Ge),uc)})]);if(clearTimeout(at),oe!==S.current)return;if(Ce===Ge&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Ce!==null&&Ce!==Ge&&(Ce.collecting!==!0||Ce.first_seen===null&&!Ce.first_seen_unavailable||Ce.first_seen!==null&&Ce.first_seen_in_reports===!1)){let k={data:null,error:null,isLoading:!1};f(k),r(k),x(k),N(Object.fromEntries(Y.map(B=>[B,{...k}]))),Pe&&(c(k),M.current="done"),await Ae;return}await Promise.all([Ce===Ge?Promise.resolve():Ae,Xe(f,n.getAnalyticsSummary(e,a)),Xe(r,n.getAnalyticsTimeseries(e,a)),Xe(x,n.getAnalyticsChannels(e,a)),Pe?(()=>{M.current="pending";let k=++O.current;return c(Dt),n.getAnalyticsConversions(e).then(B=>{k===O.current&&(c({data:B,error:null,isLoading:!1}),M.current="done")},B=>{k===O.current&&(c({data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1}),M.current="done")})})():Promise.resolve(),...Y.map(k=>n.getAnalyticsBreakdown(k,e,a).then(B=>{oe===S.current&&N(L=>({...L,[k]:{data:B,error:null,isLoading:!1}}))},B=>{oe===S.current&&N(L=>({...L,[k]:{data:null,error:B instanceof Error?B:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[n,e,m,T,U,R]),q=_t.useCallback(async()=>{let Z=S.current;try{let oe=await n.getAnalyticsStatus();if(Z!==S.current)return;o({data:oe,error:null,isLoading:!1})}catch(oe){if(Z!==S.current)return;o(Y=>({data:Y.data,error:oe instanceof Error?oe:new Error("Failed to fetch status"),isLoading:!1}))}},[n]),fe=_t.useCallback(()=>X({force:!0}),[X]);_t.useEffect(()=>{X()},[X,t]);let J=i.isLoading||d.isLoading||u.isLoading||v.isLoading||b.isLoading||Object.values(y).some(Z=>Z.isLoading),ee=[u,d,v,b,...Object.values(y)].map(Z=>Z.data?.status==="ok"?Z.data.timezone:void 0).find(Z=>Z!==void 0);return{status:i,summary:d,timeseries:u,channels:v,conversions:b,breakdowns:y,reportedZone:ee,isLoading:J,refetch:fe,refetchStatus:q}}var Rt=le(require("react"),1);var ar=3e4,sr=3;function yn(e={}){let t="collecting"in e,{collecting:s,statusFailed:a=!1,identity:n}=e,{api:i}=ne(),[o,d]=Rt.useState(null),[f,u]=Rt.useState(null),[r,v]=Rt.useState(!1),[x,b]=Rt.useState(null),[c,l]=Rt.useState(!1),[y,N]=Rt.useState(!0),[S,O]=Rt.useState(0),M=Rt.useRef(0),m=Rt.useRef(0),R=Rt.useRef(void 0);s!==void 0&&(R.current=s);let T=t?R.current===!0||R.current===void 0&&a:!0,[D,P]=Rt.useState({api:i,identity:n}),A=n!==void 0&&n!==D.identity;(D.api!==i||A)&&(R.current=void 0,P({api:i,identity:n}),m.current+=1,M.current=0,d(null),u(null),v(!1),b(null),l(!1),N(!0),O(0));let U=Rt.useRef(()=>{}),w=Rt.useRef(null),F=Rt.useCallback(async()=>{if(w.current!==null&&w.current===m.current)return;let X=++m.current;w.current=X;try{let q=await i.getAnalyticsRealtime();if(X!==m.current)return;if(q.status==="unreachable"){l(!0),v(!0),N(!1),O(fe=>fe+1);return}M.current=0,l(!1),d(q.data.current_visitors),u(q.as_of),v(!1),b(null),N(!1),O(fe=>fe+1)}catch(q){if(X!==m.current)return;M.current+=1,N(!1),O(fe=>fe+1),v(!0),M.current>=sr&&b(q instanceof Error?q:new Error("Realtime unavailable"))}finally{w.current===X&&(w.current=null)}},[i]);return U.current=()=>void F(),Rt.useEffect(()=>{let X,q=()=>{X===void 0&&(X=setInterval(()=>U.current(),ar))},fe=()=>{X!==void 0&&(clearInterval(X),X=void 0)},J=()=>{typeof document<"u"&&document.hidden?fe():(U.current(),q())};return T?((typeof document>"u"||!document.hidden)&&(U.current(),q()),document?.addEventListener("visibilitychange",J),()=>{fe(),document?.removeEventListener("visibilitychange",J),m.current+=1}):()=>{document?.removeEventListener("visibilitychange",J)}},[D.api,D.identity,T]),{currentVisitors:o,asOf:f,isStale:r,error:x,isUnreachable:c,isInitialLoad:y,polls:S}}var ot=le(require("react"),1);var oo=le(require("react"),1);var _s=require("react/jsx-runtime");function dc(){try{let e=Intl.supportedValuesOf?.("timeZone");if(e&&e.length>0)return e.includes("UTC")?e:["UTC",...e]}catch{}return["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Madrid","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Australia/Sydney"]}function Mr({value:e,chosen:t,onChange:s}){let a=Us(),n=t===null&&a!==null&&e===a,i=oo.useMemo(()=>{let o=dc();return o.includes(e)?o:[e,...o]},[e]);return(0,_s.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,_s.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,_s.jsxs)("select",{value:n?"":e,onChange:o=>s(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,_s.jsx)("option",{value:"",children:a?`${a.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),i.map(o=>(0,_s.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var nr=(e,{published:t}={})=>{let s=t===!1,a=e!=null&&(!e.collecting||s&&e.first_seen===null&&!e.first_seen_unavailable),n=!a&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,i=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=n||i;return{notCollecting:a,awaitingFirstVisit:n,firstVisitTooRecent:i,holdingForFirstData:o,nothingToReport:a||o}};var hn=le(require("react"),1),fc=3e4;function rr({status:e,holdingForFirstData:t,refetchStatus:s,refetch:a}){hn.useEffect(()=>{if(!t)return;let i,o=()=>{i===void 0&&(i=setInterval(()=>void s(),fc))},d=()=>{i!==void 0&&(clearInterval(i),i=void 0)},f=()=>{typeof document<"u"&&document.hidden?d():(s(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",f),()=>{d(),document?.removeEventListener("visibilitychange",f)}},[t,s]);let n=hn.useRef(void 0);hn.useEffect(()=>{if(!e){n.current=void 0;return}let i=n.current;n.current=t,i===!0&&!t&&a()},[e,t,a])}var Rs=le(require("react"),1);var mc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vt(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?Vt(o*a):`${o}${n}`}return String(e)}function Fs(e){return`${(e*100).toFixed(1)}%`}function xn(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 co(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`:xn(t)}function uo(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function fo(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 wn(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function mo(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 $r(e){let t=Number(e.slice(5,7)),s=Number(e.slice(8,10));return`${mc[t-1]} ${s}`}function lo(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function pc(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function po(e,t,s="UTC"){let a=new Map(t.map(o=>[o.date,o])),n=[],i=lo(e.to,s);for(let o=lo(e.from,s);o<i;o=pc(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 go(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 ca=require("react/jsx-runtime");function vo({what:e="This report",onRetry:t,collecting:s}){return(0,ca.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,ca.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,ca.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,ca.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 ir({what:e="No data"}){return(0,ca.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 Xa({sourced:e,error:t,isLoading:s,what:a,onRetry:n,collecting:i,children:o}){return s?(0,ca.jsx)("div",{role:"status","aria-label":`Loading ${a}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,ca.jsx)(vo,{what:a,onRetry:n,collecting:i}):!e||e.status==="unreachable"?(0,ca.jsx)(vo,{what:a,onRetry:n,collecting:i}):(0,ca.jsx)(ca.Fragment,{children:o(e.data)})}var Qe=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:d,maxRows:f=9}){let[u,r]=Rs.useState(!1);if(e.length===0)return(0,Qe.jsx)(ir,{what:i});let v=e.reduce((c,l)=>Math.max(c,Number(l[s]??0)),0)||1,x=Math.max(0,e.length-f),b=u?e:e.slice(0,f);return(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Qe.jsx)("thead",{children:(0,Qe.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Qe.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,Qe.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:a})]})}),(0,Qe.jsx)("tbody",{children:b.map((c,l)=>{let y=Number(c[s]??0),N=c[t]??null,S=wn(N),O=n?c[n]:null,M=N!==null&&(d?d(N,O):!0);return(0,Qe.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,Qe.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,Qe.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,y/v*100)}%`}}),N!==null&&o&&M?(0,Qe.jsx)("button",{type:"button",onClick:()=>o(N,O),title:`Filter by ${S}`,"aria-label":`Filter by ${S}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:S}):(0,Qe.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:S}),O?(0,Qe.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:O}):null]}),(0,Qe.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(y)})]},`${S}-${O??""}-${l}`)})})]}),x>0?(0,Qe.jsx)("button",{type:"button",onClick:()=>r(c=>!c),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:u?"Show fewer":`Show all ${e.length}`}):null]})}function Nn({title:e,tabs:t,defaultTabId:s,headerRight:a}){let[n,i]=Rs.useState(s),o=t.find(b=>b.id===n)??t[0],d=Rs.useId(),f=b=>`${d}-tab-${b}`,u=b=>`${d}-panel-${b}`,r=Rs.useRef(null),v=(b,c)=>{b.preventDefault();let l=(c+t.length)%t.length;i(t[l].id),r.current?.querySelectorAll('[role="tab"]')?.[l]?.focus()};return(0,Qe.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,Qe.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,Qe.jsx)("div",{ref:r,role:"tablist","aria-label":e,onKeyDown:b=>{let c=t.findIndex(l=>l.id===n);b.key==="ArrowRight"&&v(b,c+1),b.key==="ArrowLeft"&&v(b,c-1),b.key==="Home"&&v(b,0),b.key==="End"&&v(b,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(b=>(0,Qe.jsx)("button",{id:f(b.id),role:"tab",type:"button","aria-selected":b.id===n,"aria-controls":u(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,Qe.jsx)("div",{id:u(o.id),role:"tabpanel","aria-labelledby":f(o.id),tabIndex:0,className:"af-px-3 af-py-2",children:o.render()},o.id):null]})}var Zt=le(require("react"),1),us=le(require("@radix-ui/react-popover"),1);var Ps=3,Cs=100;var Le=require("react/jsx-runtime"),Sn={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"},gc=Object.keys(Sn);function bo(e){let t=Sn[e.dimension],s=e.operator==="is_not"?"is not":"is",a=e.values.map(n=>wn(n)).join(" or ");return`${t} ${s} ${a}`}function Vr(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 vc(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 yo(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 bc(e){return{dimension:e,operator:"is",search:"",picked:[]}}function ho(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=vc(e.byDimension,s);for(let[i,o]of Object.entries(a)){let d=e.foldsByLabel.get(i)??new Set;for(let f of o)d.add(f);e.foldsByLabel.set(i,d)}return{suggestions:n,folds:new Map([...e.foldsByLabel].map(([i,o])=>[i,[...o]]))}}function xo(e){let{filters:t,onChange:s}=e,a=t.length>=3;return Zt.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:bo(n)}),(0,Le.jsx)("button",{type:"button","aria-label":`Remove filter ${bo(n)}`,onClick:()=>s(t.filter((o,d)=>d!==i)),className:"af-rounded-full af-px-1.5 af-py-0.5 af-text-muted-foreground hover:af-bg-background hover:af-text-foreground",children:"\xD7"})]},`${n.dimension}-${n.operator??"is"}`)),(0,Le.jsx)(yc,{...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 yc({filters:e,onChange:t,suggestions:s,resetKey:a,disabled:n,expandValues:i}){let[o,d]=Zt.useState(!1),f=Zt.useRef(null),[u,r]=Zt.useState(null);Zt.useEffect(()=>{r(f.current?.closest(".aifeatures-admin")??null)},[]);let[v,x]=Zt.useState(null),[b,c]=Zt.useState("is"),[l,y]=Zt.useState(""),[N,S]=Zt.useState([]);Zt.useEffect(()=>{o||(x(null),c("is"),y(""),S([]))},[o]);let O=Zt.useRef(a);O.current!==a&&(O.current=a,o&&d(!1),v!==null&&x(null),N.length>0&&S([]),l!==""&&y(""),b!=="is"&&c("is"));let M=A=>{let U=bc(A);x(U.dimension),S(U.picked),y(U.search),c(U.operator)},R=(v?s[v]??[]:[]).filter(A=>A.toLowerCase().includes(l.trim().toLowerCase())),T=v===null||N.length===0?null:Vr(e,{dimension:v,operator:b,values:i?i(v,N):N}),D=T!==null&&T!==e,P=()=>{let A=T;!A||A===e||(t(A),d(!1))};return(0,Le.jsxs)(us.Root,{open:o,onOpenChange:d,children:[(0,Le.jsx)(us.Trigger,{asChild:!0,children:(0,Le.jsx)("button",{ref:f,type:"button",disabled:!1,title:n?`At most ${3} filters at once`:"Filter this report",className:"af-rounded-md af-border af-border-dashed af-border-border af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground disabled:af-opacity-50",children:"+ Filter"})}),(0,Le.jsx)(us.Portal,{container:u,children:(0,Le.jsx)(us.Content,{role:"dialog","aria-label":"Add a filter",align:"start",sideOffset:6,className:"af-z-50 af-w-72 af-rounded-lg af-border af-border-border af-bg-card af-p-3 af-shadow-lg",children:v===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:gc.filter(A=>s[A]!==void 0).map(A=>{let U=s[A]?.length??0,w=!e.some(F=>F.dimension===A)&&e.length>=3;return(0,Le.jsxs)("button",{type:"button",onClick:()=>M(A),disabled:U===0||w,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:Sn[A]}),(0,Le.jsx)("span",{className:"af-text-muted-foreground",children:U===0?"no data":w?"no room":U})]},A)})})]}):(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:()=>M(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:Sn[v]}),(0,Le.jsxs)("select",{"aria-label":"Operator",value:b,onChange:A=>c(A.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(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:A=>y(A.target.value),placeholder:"Search\u2026","aria-label":`Search ${Sn[v]}`,className:"af-mb-2 af-w-full af-rounded-md af-border af-border-border af-bg-background af-px-2 af-py-1 af-text-xs af-text-foreground"}),(0,Le.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:R.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."]}):R.map(A=>(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:N.includes(A),disabled:!N.includes(A)&&N.length>=100,onChange:U=>S(w=>U.target.checked?[...w,A]:w.filter(F=>F!==A))}),(0,Le.jsx)("span",{className:"af-break-all",children:wn(A)})]},A))}),(0,Le.jsx)("button",{type:"button",onClick:P,disabled:!D,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:N.length<=1?"Apply filter":N.length>=100?`Apply filter (${N.length} values \u2014 the maximum)`:`Apply filter (${N.length} values)`})]})})})]})}var it=require("react/jsx-runtime"),hc=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Vt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Vt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Vt,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:Fs,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:xn,chart:"visit_duration_seconds"}];function xc({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,it.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 wo({summary:e,selected:t,onSelect:s}){return(0,it.jsx)("div",{className:"af-@container",children:(0,it.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:hc.map(a=>{let n=a.chart===t,i=s!==void 0,o=(0,it.jsxs)(it.Fragment,{children:[(0,it.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:a.label}),(0,it.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,it.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,it.jsx)(xc,{current:a.get(e.current),previous:a.get(e.previous),downIsGood:a.downIsGood}):null]})]});return i?(0,it.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,it.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},a.key)})})})}function Hr({currentVisitors:e,asOf:t,isStale:s,isUnreachable:a,isInitialLoad:n=!1,scopeIsSiteWide:i=!1}){if(n&&!a)return(0,it.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,it.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,it.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(a||e===null)return(0,it.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?mo(t):"freshness unknown",d=i?" across the whole site, not the current filter,":"",f=s?`${e} current visitors${d} ${o} (not updating)`:`${e} current visitors${d} ${o}`;return(0,it.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:f,children:[(0,it.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,it.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,it.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:i?"current visitors, site-wide":"current visitors"}),(0,it.jsx)("span",{className:"af-sr-only",children:f})]})}var No=le(require("react"),1),So=require("lucide-react");var Me=require("react/jsx-runtime");function or(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function lr({rows:e,denominator:t,windowPrecedesCollection:s=!1,coverageUnknown:a=!1,emptyCopy:n="No conversions in this period",maxRows:i=9,primaryConversion:o}){let[d,f]=No.useState(!1),u=e.filter(y=>!y.implicit||y.visitors>0||y.events>0||or(y,o)),r=s?(0,Me.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,Me.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;if(u.length===0)return(0,Me.jsxs)(Me.Fragment,{children:[(0,Me.jsx)(ir,{what:n}),r]});let v=u.slice(0,i),x=o?u.find(y=>or(y,o)):void 0,b=x&&!v.includes(x)?u.filter(y=>v.includes(y)||y===x).slice(0,Math.max(0,i-1)).concat(x):v,c=d?e:b,l=Math.max(0,e.length-b.length);return(0,Me.jsxs)(Me.Fragment,{children:[(0,Me.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Me.jsx)("thead",{children:(0,Me.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Me.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Me.jsx)("tbody",{children:c.map((y,N)=>(0,Me.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":or(y,o)?"true":void 0,children:[(0,Me.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:or(y,o)?(0,Me.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Me.jsx)(So.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Me.jsx)("span",{className:"af-font-medium af-text-foreground",children:y.goal}),(0,Me.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):y.goal}),(0,Me.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(y.visitors)}),(0,Me.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Vt(y.events)}),(0,Me.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:y.conversion_rate===null?(0,Me.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):Fs(y.conversion_rate)})]},`${y.goal}-${N}`))})]}),l>0?(0,Me.jsx)("button",{type:"button",onClick:()=>f(y=>!y),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:d?"Show fewer":`Show all ${e.length} goals`}):null,(0,Me.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Vt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),r]})}var Jt=require("recharts");var ft=require("react/jsx-runtime"),cr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},qr={visitors:Vt,visits:Vt,pageviews:Vt,views_per_visit:e=>e.toFixed(2),bounce_rate:Fs,visit_duration_seconds:xn},wc=31,Nc=new Set(["visitors","visits","pageviews"]),Sc={...qr,bounce_rate:uo,visit_duration_seconds:co},zr=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],_c=[5,10,15,30,60,120,300,600,900,1800,3600,7200],Rc=[.01,.02,.05,.1,.2,.25,.5,1],Pc=[.25,.5,1,2,5,10,25,50],Cc={visitors:zr,visits:zr,pageviews:zr,views_per_visit:Pc,bounce_rate:Rc,visit_duration_seconds:_c};function Tc({active:e,payload:t,label:s,metric:a}){if(!e||!t||t.length===0)return null;let n=t[0].payload;return(0,ft.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,ft.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:cr[a]}),(0,ft.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,ft.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,ft.jsx)("span",{className:"af-text-muted-foreground",children:go(String(s))}),(0,ft.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:qr[a](Number(n[a]??0))})]})]})}function ur({rows:e,window:t,metric:s,timeZone:a="UTC",height:n=260}){let i=po(t,e,a),o=qr[s],d=Sc[s],f=fo(i.reduce((r,v)=>Math.max(r,Number(v[s]??0)),0),Cc[s]),u=`${cr[s]} by day: ${i.map(r=>`${$r(r.date)}: ${o(Number(r[s]??0))}`).join("; ")}.`;return(0,ft.jsxs)("figure",{"aria-label":`${cr[s]} over time`,className:"af-m-0",children:[(0,ft.jsx)(Jt.ResponsiveContainer,{width:"100%",height:n,children:(0,ft.jsxs)(Jt.AreaChart,{data:i,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,ft.jsx)("defs",{children:(0,ft.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,ft.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,ft.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,ft.jsx)(Jt.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,ft.jsx)(Jt.XAxis,{dataKey:"date",tickFormatter:$r,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,ft.jsx)(Jt.YAxis,{allowDecimals:!Nc.has(s),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...f?{ticks:f,domain:[0,f[f.length-1]]}:{},tickFormatter:r=>d(r),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,ft.jsx)(Jt.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,ft.jsx)(Tc,{metric:s})}),(0,ft.jsx)(Jt.Area,{type:"linear",dataKey:s,name:cr[s],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:i.length<=wc?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,ft.jsx)("figcaption",{className:"af-sr-only",children:u})]})}var re=require("react/jsx-runtime"),kc="2026-08-13",Ec=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Ac=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function _o({filters:e,onFiltersChange:t,refreshKey:s,onBackToWebsite:a,primaryConversion:n,className:i,published:o,lastPublishedAt:d}){let[f,u]=ot.useState(30),[r,v]=ot.useState(()=>pr()),x=e!==void 0&&t!==void 0,[b,c]=ot.useState(e??[]),{api:l}=ne(),[y,N]=ot.useState(l);y!==l&&(N(l),!x&&b.length>0&&c([]));let S=x?e:b,O=ot.useCallback(L=>{t&&t(L),x||c(L)},[t,x]),M=ot.useCallback((L,pe,he)=>{let Ee=Array.isArray(pe)?pe:[pe];if(Ee.length===0)return null;let Oe=Vr(S,{dimension:L,operator:"is",values:Ee});if(he&&(!he.value||(Oe=yo(Oe,{dimension:he.dimension,operator:"is",values:[he.value]}),!Oe.find(Ke=>Ke.dimension===he.dimension&&Ke.operator!=="is_not")?.values.includes(he.value))))return null;let st=Oe.find(ze=>ze.dimension===L&&ze.operator!=="is_not");return Ee.every(ze=>st?.values.includes(ze))?JSON.stringify(Oe)===JSON.stringify(S)?null:Oe:null},[S]),m=ot.useCallback((L,pe,he)=>M(L,pe,he)!==null,[M]),R=ot.useCallback((L,pe,he)=>{let Ee=M(L,pe,he);Ee&&O(Ee)},[M,O]),[T,D]=ot.useState("visitors"),P=Ss(f,{refreshKey:s,breakdowns:Ac,filters:S}),A=P.status.data,U=P.reportedZone??A?.timezone,w=U??r??Us()??"UTC",{notCollecting:F,awaitingFirstVisit:X,firstVisitTooRecent:q,holdingForFirstData:fe}=nr(A,{published:o}),J=o===!1,ee=yn({collecting:X||F?!1:A?.collecting,statusFailed:P.status.error!=null,identity:A?.analytics_id}),Z=ot.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),oe=ot.useMemo(()=>{let L=P.breakdowns.sources?.data,pe={};if(!L||L.status!=="ok")return pe;for(let he of L.data){let Ee=he.source,Oe=he.sources;typeof Ee=="string"&&Array.isArray(Oe)&&Oe.length>0&&(pe[Ee]=Oe)}return pe},[P.breakdowns.sources?.data]),Y=ot.useMemo(()=>{let L=(Ee,Oe)=>{let st=P.breakdowns[Ee]?.data;return!st||st.status!=="ok"?[]:[...new Set(st.data.map(ze=>ze[Oe]).filter(ze=>typeof ze=="string"&&ze!==""))]};return{channel:P.channels.data?.status==="ok"?[...new Set(P.channels.data.data.map(Ee=>Ee.channel))]:[],source:L("sources","source"),campaign:L("utm/campaign","campaign"),page:L("pages","pathname"),entry_page:L("entry-pages","pathname"),exit_page:L("exit-pages","pathname"),country:L("countries","country"),browser:L("browsers","browser"),os:L("operating-systems","os"),device:L("devices","device")}},[P.breakdowns,P.channels.data]),[Pe,Xe]=ot.useState({}),lt=JSON.stringify(Y),[Ae,Ge]=ot.useState(new Map),at=JSON.stringify(oe);ot.useEffect(()=>{let{suggestions:L,folds:pe}=ho(Z.current,{api:l,period:f},JSON.parse(lt),JSON.parse(at));Xe(L),Ge(pe)},[lt,at,l,f]);let Ce=ot.useCallback((L,pe)=>L!=="source"?pe:[...new Set(pe.flatMap(he=>{let Ee=[...Ae.get(he)??[],...oe[he]??[]];return Ee.length>0?Ee:[he]}))],[Ae,oe]),Et=ot.useMemo(()=>{let L=P.conversions.error;return L instanceof It&&L.details?.code==="goals_exceed_report_budget"?L.message:null},[P.conversions.error]),k=ot.useMemo(()=>{let L=[P.summary,P.timeseries,P.channels,...Object.values(P.breakdowns)];for(let pe of L){let he=pe?.error;if(he instanceof It&&he.details?.code==="filter_unsupported")return he.message}return null},[P.summary,P.timeseries,P.channels,P.breakdowns]),B=(L,pe,he,Ee,Oe,st,ze,Ke,ce)=>()=>{let Be=P.breakdowns[L];return(0,re.jsx)(Xa,{sourced:Be?.data??null,error:Be?.error,isLoading:Be?.isLoading,what:pe,collecting:A?.collecting,onRetry:P.refetch,children:ct=>{let Yt=wt=>Ke?Ce(Ke,[wt]):wt;return(0,re.jsx)(Ur,{rows:ct,dimension:he,metric:Ee,metricLabel:Oe,secondary:st,emptyCopy:S.length>0?"No data for this filter":ze,canFilter:Ke?(wt,At)=>m(Ke,Yt(wt),ce?{dimension:ce,value:At}:void 0):()=>!1,onFilter:Ke?(wt,At)=>R(Ke,Yt(wt),ce?{dimension:ce,value:At}:void 0):void 0})}})};if(rr({status:A,holdingForFirstData:fe,refetchStatus:P.refetchStatus,refetch:P.refetch}),F){let L=!!d&&String(d).slice(0,10)<kc;return(0,re.jsx)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,re.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:J?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":L?"Your site was last published before analytics existed, so its pages don\u2019t carry the tracker yet. Republish to start collecting.":"This site has no analytics identity yet, so no visits can be recorded. Republishing will set one up."})]})})}return X?(0,re.jsx)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,re.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."})]})}):q?(0,re.jsxs)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:[(0,re.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,re.jsx)(Mr,{value:w,chosen:r,onChange:L=>{gr(L),v(L)}})}),(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,re.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",A?.timezone?` ${A.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,re.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,re.jsx)(Hr,{currentVisitors:ee.currentVisitors,asOf:ee.asOf,isStale:ee.isStale,isUnreachable:ee.isUnreachable||ee.error!==null,isInitialLoad:ee.isInitialLoad})})]})]}):(0,re.jsx)(yt,{title:"Analytics",onBackToWebsite:a,className:i,children:(0,re.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,re.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,re.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Ec.map(L=>(0,re.jsx)("button",{type:"button","aria-pressed":L.value===f,onClick:()=>u(L.value),className:L.value===f?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:L.label},L.value))}),(0,re.jsx)(Mr,{value:w,chosen:r,onChange:L=>{gr(L),v(L)}}),(0,re.jsx)(Hr,{currentVisitors:ee.currentVisitors,asOf:ee.asOf,isStale:ee.isStale,isUnreachable:ee.isUnreachable||ee.error!==null,isInitialLoad:ee.isInitialLoad,scopeIsSiteWide:S.length>0})]}),(0,re.jsx)(xo,{filters:S,onChange:O,suggestions:Pe,expandValues:Ce,resetKey:l}),k?(0,re.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,re.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:k}),(0,re.jsx)("button",{type:"button",onClick:()=>O([]),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,!k&&A?.timezone_defaulted?(0,re.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,k?null:(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)(Xa,{sourced:P.summary.data,error:P.summary.error,isLoading:P.summary.isLoading,what:"The traffic summary",collecting:A?.collecting,onRetry:P.refetch,children:L=>(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)(wo,{summary:L,selected:T,onSelect:D}),L.previous_unavailable?(0,re.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[L.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,re.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,re.jsx)(Xa,{sourced:P.timeseries.data,error:P.timeseries.error,isLoading:P.timeseries.isLoading,what:"The visitors chart",collecting:A?.collecting,onRetry:P.refetch,children:L=>{let pe=P.timeseries.data?.status==="ok"?P.timeseries.data.window:{from:"",to:""};return(0,re.jsx)(ur,{rows:L,window:pe,metric:T,timeZone:U??"UTC"})}})}),(0,re.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,re.jsx)(Nn,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,re.jsx)(Xa,{sourced:P.channels.data,error:P.channels.error,isLoading:P.channels.isLoading,what:"Channels",collecting:A?.collecting,onRetry:P.refetch,children:L=>(0,re.jsx)(Ur,{rows:L,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:S.length>0?"No data for this filter":"No data for this period",canFilter:pe=>m("channel",pe),onFilter:pe=>R("channel",pe)})})},{id:"sources",label:"Sources",render:B("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:B("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,re.jsx)(Nn,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:B("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:B("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:B("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,re.jsx)(Nn,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:B("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:B("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:B("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,re.jsx)(Nn,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:B("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:B("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:B("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,re.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,re.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,re.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,re.jsxs)("div",{className:"af-px-3 af-py-2",children:[S.length>0?(0,re.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",S.length===1?"filter":"filters"," above."]}):null,Et!==null?(0,re.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,re.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,re.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Et})]}):(0,re.jsx)(Xa,{sourced:P.conversions.data,error:P.conversions.error,isLoading:P.conversions.isLoading,what:"Conversions",collecting:A?.collecting,onRetry:P.refetch,children:L=>{let pe=P.conversions.data?.status==="ok"?P.conversions.data:null;return(0,re.jsx)(re.Fragment,{children:(0,re.jsx)(lr,{rows:L,primaryConversion:n,denominator:pe?.denominator??0,windowPrecedesCollection:pe?.window_precedes_collection??!1,coverageUnknown:pe?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Eo=le(require("react"),1),Tt=require("lucide-react");var xa=le(require("react"),1),es=require("lucide-react");var ve=require("react/jsx-runtime"),Ro=90,Po=100;function Ic(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Co(e){return!!e.label&&e.label!==e.target}function Dc(e,t,s){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:a,with_a_value:n}=t;return a===0?e===0?"Nothing specific has converted here yet.":null:n===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":n<a?s?`These cover ${n.toLocaleString()} of ${a.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${n.toLocaleString()} of ${a.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function _n(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function To({current:e,onChange:t,onClose:s}){let{api:a}=ne(),[n,i]=xa.useState(null),[o,d]=xa.useState(!1),[f,u]=xa.useState({at:"goals"}),[r,v]=xa.useState(null),[x,b]=xa.useState(null),[c,l]=xa.useState(!1),[y,N]=xa.useState(null),S=xa.useRef(0);xa.useEffect(()=>{let R=!0;return i(null),d(!1),u({at:"goals"}),v(null),b(null),l(!1),N(null),S.current+=1,a.getAnalyticsConversions(Ro).then(T=>{if(R){if(T.status!=="ok"){d(!0);return}i(T.data)}}).catch(()=>{R&&d(!0)}),()=>{R=!1}},[a]);let O=R=>{u({at:"targets",row:R}),v(null),b(null),l(!1),N(null);let T=++S.current;a.getAnalyticsGoalTargets(R.goal,Ro,Po).then(D=>{if(T===S.current){if(D.status!=="ok"){b("failed");return}v(D.data),l(D.truncated===!0),N(D.coverage??null)}}).catch(D=>{if(T!==S.current)return;let P=D instanceof It?D.details?.code:void 0;b(P==="goal_has_no_targets"?"no-values":"failed")})},M=R=>{t(R),s()};if(o)return(0,ve.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!n)return(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,ve.jsx)(es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,ve.jsx)("span",{children:"Loading your conversions\u2026"})]});if(f.at==="targets"){let R=f.row,T=new Map;for(let D of r??[])T.set(D.label,(T.get(D.label)??0)+1);return(0,ve.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,ve.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,ve.jsxs)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({at:"goals"}),children:[(0,ve.jsx)(es.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,ve.jsx)("span",{children:"All conversions"})]})}),(0,ve.jsxs)("button",{type:"button","aria-current":e&&_n(R,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>M({goal:R.goal,implicit:R.implicit}),children:[e&&_n(R,e)&&!e.target&&(0,ve.jsx)(es.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ve.jsxs)("span",{children:["Any ",R.goal.toLowerCase()]})]}),x==="no-values"&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),x==="failed"&&(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,ve.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,ve.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(R),children:"Try again"})]}),!r&&x===null&&(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,ve.jsx)(es.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,ve.jsx)("span",{children:"Loading\u2026"})]}),r&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Dc(r.length,y,c)}),c&&(0,ve.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Po,". If what you want isn\u2019t here, pick the conversion itself instead."]}),r?.some(Co)&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),r?.map(D=>{let P=!!(e&&_n(R,e)&&e.target===D.target),A=T.get(D.label)>1;return Co(D)?(0,ve.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,ve.jsxs)("span",{className:"af-min-w-0",children:[(0,ve.jsx)("span",{className:"af-block af-truncate",children:D.label}),A&&(0,ve.jsx)("span",{className:"af-block af-truncate af-text-xs",children:D.target})]}),(0,ve.jsx)("span",{className:"af-shrink-0 af-text-xs",children:D.visitors.toLocaleString()})]},D.target):(0,ve.jsxs)("button",{type:"button","aria-current":P?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>M({goal:R.goal,implicit:R.implicit,target:D.target,...D.label&&D.label!==D.target?{label:D.label}:{}}),children:[(0,ve.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[P&&(0,ve.jsx)(es.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ve.jsxs)("span",{className:"af-min-w-0",children:[(0,ve.jsx)("span",{className:"af-block af-truncate",children:D.label}),A&&(0,ve.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:D.target})]})]}),(0,ve.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:D.visitors.toLocaleString()})]},D.target)})]})}let m=e?.goal&&!n.some(R=>_n(R,e));return(0,ve.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[m&&(0,ve.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),n.length===0&&(0,ve.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),n.map(R=>{let T=e?_n(R,e):!1;return(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,ve.jsxs)("button",{type:"button","aria-current":T?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>M({goal:R.goal,implicit:R.implicit}),children:[(0,ve.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[T&&(0,ve.jsx)(es.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ve.jsx)("span",{className:"af-truncate",children:R.goal})]}),(0,ve.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:R.visitors.toLocaleString()})]}),Ic(R)&&(0,ve.jsx)(_,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${R.goal}`,onClick:()=>O(R),children:"Narrow"})]},R.goal)}),e?.goal&&(0,ve.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>M(null),children:"No main conversion"})]})}var ua=require("react/jsx-runtime");function Lc(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let s of t)try{let{hostname:a}=new URL(s);if(a)return a.toLowerCase().replace(/^www\./,"")}catch{}return null}function Oc(e){if(jr(e,"whatsapp"))return!0;let t=Lc(e);return t===null?!1:["wa.me","whatsapp.com"].some(s=>t===s||t.endsWith(`.${s}`))}function jr(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var ko=[{goal:"Contact",target:e=>jr(e,"tel"),icon:Tt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>jr(e,"mailto"),icon:Tt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:Tt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Oc(e),icon:Tt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Tt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Tt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Tt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Tt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:Tt.Download,line:"This site is set up to get your file downloaded."}];function Ao(e){let{goal:t,target:s}=e;return e.implicit!==!0?null:(s?ko.find(n=>n.goal===t&&n.target?.(s)):void 0)??ko.find(n=>n.goal===t&&!n.target)??null}function Bc(e){return Ao(e)?.icon??Tt.Target}function Io({primaryConversion:e,onChange:t}){let[s,a]=Eo.useState(!1);if(!!!e?.goal&&!t)return null;let i=e?Ao(e):null,o=e?.label?.trim(),d=e?Bc(e):Tt.Target,f=e?.goal?o?`Your main conversion is ${o}.`:i?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",u=(0,ua.jsxs)(ua.Fragment,{children:[(0,ua.jsx)(d,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,ua.jsx)("span",{children:f})]});return t?(0,ua.jsxs)(Bn,{open:s,onOpenChange:a,children:[(0,ua.jsx)(Fn,{asChild:!0,children:(0,ua.jsx)("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:u})}),(0,ua.jsx)(rn,{align:"start",className:"af-w-80 af-p-1",children:s&&(0,ua.jsx)(To,{current:e,onChange:t,onClose:()=>a(!1)})})]}):(0,ua.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:u})}var Ft=require("react/jsx-runtime");function Do({refreshKey:e,onViewAll:t,primaryConversion:s}){let a=Ss(7,{refreshKey:e,breakdowns:[]}),n=a.status.data??void 0,{nothingToReport:i,notCollecting:o,holdingForFirstData:d}=nr(n);return rr({status:n,holdingForFirstData:d,refetchStatus:a.refetchStatus,refetch:a.refetch}),(0,Ft.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Ft.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Ft.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,Ft.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),i?(0,Ft.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:o?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,Ft.jsxs)(Ft.Fragment,{children:[(0,Ft.jsx)(Xa,{sourced:a.timeseries.data,error:a.timeseries.error,isLoading:a.timeseries.isLoading,what:"The visitors chart",collecting:n?.collecting,onRetry:a.refetch,children:f=>{let u=a.timeseries.data?.status==="ok"?a.timeseries.data:null;return(0,Ft.jsx)(ur,{rows:f,window:u?.window??{from:"",to:""},metric:"visitors",timeZone:u?.timezone,height:140})}}),(0,Ft.jsxs)("div",{className:"af-mt-3",children:[(0,Ft.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,Ft.jsx)(Xa,{sourced:a.conversions.data,error:a.conversions.error,isLoading:a.conversions.isLoading,what:"Conversions",collecting:n?.collecting,onRetry:a.refetch,children:f=>{let u=a.conversions.data?.status==="ok"?a.conversions.data:null;return(0,Ft.jsx)(lr,{rows:f,primaryConversion:s,denominator:u?.denominator??0,windowPrecedesCollection:u?.window_precedes_collection??!1,coverageUnknown:u?.first_seen_unavailable??!1})}})]})]})]})}var kt=require("react/jsx-runtime"),Gr=5;function Wr({title:e,viewAllLabel:t,onViewAll:s}){return(0,kt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,kt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),s&&(0,kt.jsx)(_,{type:"button",variant:"ghost",size:"sm",onClick:s,children:t})]})}function Lo({refreshKey:e,onBackToWebsite:t,primaryConversion:s,onChangePrimaryConversion:a,onOpenSurface:n,needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:d}){let f=ws({refreshKey:e}),u=(f.summary?.products.count??0)>0||(f.summary?.commerce?.storefront_orders??!1),r=u||(f.summary?.commerce?.invoicing??!1);return(0,kt.jsx)(yt,{title:"Dashboard",onBackToWebsite:t,children:(0,kt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,kt.jsx)(Io,{primaryConversion:s,onChange:a}),(0,kt.jsx)(Do,{refreshKey:e,onViewAll:n&&(()=>n("analytics")),primaryConversion:s}),(0,kt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,kt.jsx)(Wr,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:n&&(()=>n("leads"))}),(0,kt.jsx)(vn,{refreshKey:e,maxRows:Gr,onViewAll:n&&(()=>n("leads"))})]}),u&&(0,kt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,kt.jsx)(Wr,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:n&&(()=>n("orders"))}),(0,kt.jsx)(Ja,{refreshKey:e,maxRows:Gr,onViewAll:n&&(()=>n("orders"))})]}),r&&(0,kt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,kt.jsx)(Wr,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:n&&(()=>n("invoices"))}),(0,kt.jsx)(Qa,{refreshKey:e,maxRows:Gr,onViewAll:n&&(()=>n("invoices")),needsPaidPlan:i,onUpgradePlan:o,onConnectStripe:d})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,DashboardView,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 Kl=Object.create;var tr=Object.defineProperty;var Zl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var Yl=Object.getPrototypeOf,Xl=Object.prototype.hasOwnProperty;var Ql=(e,t)=>{for(var n in t)tr(e,n,{get:t[n],enumerable:!0})},zi=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Jl(t))!Xl.call(e,a)&&a!==n&&tr(e,a,{get:()=>t[a],enumerable:!(s=Zl(t,a))||s.enumerable});return e};var re=(e,t,n)=>(n=e!=null?Kl(Yl(e)):{},zi(t||!e||!e.__esModule?tr(n,"default",{value:e,enumerable:!0}):n,e)),ec=e=>zi(tr({},"__esModule",{value:!0}),e);var td={};Ql(td,{AifeaturesApiError:()=>ht,AifeaturesProvider:()=>Ki,AnalyticsView:()=>Bl,CustomerDetail:()=>Ms,CustomersList:()=>$s,DashboardView:()=>Gl,ExportCsvButton:()=>Bt,FormSettings:()=>ks,FormSubmissions:()=>Rs,FormsDashboard:()=>ei,FormsList:()=>ys,InvoiceDetail:()=>_r,InvoiceLabelBadge:()=>ss,InvoiceSettingsPanel:()=>Ws,InvoicesList:()=>pn,InvoicesView:()=>Ci,LeadsView:()=>qs,MAX_ANALYTICS_FILTERS:()=>Zn,MAX_ANALYTICS_FILTER_VALUES:()=>Jn,NotificationRecipientsSettings:()=>Pi,OrderDetail:()=>Fs,OrderStatusBadge:()=>_n,OrdersList:()=>fn,OrdersView:()=>pi,PaymentsDashboard:()=>mi,PaymentsSetup:()=>Mn,ProductSettings:()=>Ds,ProductsList:()=>Is,ProductsView:()=>gi,PromosPanel:()=>Dn,REALTIME_FAILURES_BEFORE_ERROR:()=>Ur,REALTIME_POLL_MS:()=>Fr,RetainerStatusBadge:()=>Cr,RetainersPanel:()=>Un,StoreSettings:()=>_i,SubmissionDetail:()=>Ss,SubscriptionsView:()=>yi,VariantsEditor:()=>As,ViewShell:()=>wt,WebhookDeliveries:()=>Cs,WebhookSettings:()=>Ts,chargedTotal:()=>Ja,createApiClient:()=>sr,formatPrice:()=>K,isZeroDecimalCurrency:()=>ha,toMajorUnits:()=>nt,toMinorUnits:()=>It,useAifeatures:()=>ae,useAifeaturesContext:()=>ae,useAnalytics:()=>Gn,useBusinessSummary:()=>Hn,useCsvExport:()=>Ns,useCustomers:()=>Us,useEventDestinations:()=>_s,useForms:()=>En,useInvoices:()=>Fn,useOrders:()=>Ls,usePaymentsStatus:()=>cn,usePeople:()=>Hs,usePerson:()=>zs,useProducts:()=>$n,useRealtimeVisitors:()=>Ks,useRetainers:()=>Vn,useSiteSettings:()=>gn,useSubmissions:()=>xs,useSubscriptions:()=>js});module.exports=ec(td);var wn=re(require("react"),1);var Zr="aifeatures:analytics:timezone",Jr;function ps(){try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e&&e.length>0?e:null}catch{return null}}function qi(e){if(!e||/^[+-]/.test(e))return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function hn(){return Yr()??ps()}function Yr(){if(Jr!==void 0)return Jr;try{let e=window.localStorage.getItem(Zr);return qi(e)?e:null}catch{return null}}function Xr(e){if(!(e!==null&&!qi(e))){Jr=e;try{e===null?window.localStorage.removeItem(Zr):window.localStorage.setItem(Zr,e)}catch{}}}function ar(e,t){let n=new URLSearchParams({period:String(e)}),s=hn();return s&&n.set("timezone",s),t&&t.length>0&&n.set("filters",JSON.stringify(t)),n.toString()}var ht=class extends Error{constructor(n,s,a){super(n);this.status=s;this.details=a;this.name="AifeaturesApiError"}};function nr(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 gs(e,t){let n=t.toString();return n?`${e}?${n}`:e}function ji(e){let t=new URLSearchParams;return e.status&&t.set("status",e.status),e.source&&t.set("source",e.source),e.excludeStatus?.length&&t.set("exclude_status",e.excludeStatus.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.unfulfilledOnly&&t.set("unfulfilled_only","true"),t}function Gi(e){let t=new URLSearchParams;return e.statuses?.length&&t.set("status",e.statuses.join(",")),e.customerEmail&&t.set("customer_email",e.customerEmail),t}function sr(e,t="https://aifeatures.dev"){async function n(a,r={}){let o=`${t}${a}`,u=await fetch(o,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!u.ok){let g;try{g=await u.json()}catch{}throw new ht(nr(g?.error,u.status),u.status,g)}if(u.status!==204)return u.json()}async function s(a){let r=await fetch(`${t}${a}`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){let o;try{o=await r.json()}catch{}throw new ht(nr(o?.error,r.status),r.status,o)}return r.blob()}return{async getForms(){return(await n("/api/v1/forms")).forms},async getForm(a){return n(`/api/v1/forms/${a}`)},async createForm(a){return n("/api/v1/forms",{method:"POST",body:JSON.stringify(a)})},async updateForm(a,r){return n(`/api/v1/forms/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(a){await n(`/api/v1/forms/${a}`,{method:"DELETE"})},async getSubmissions(a,r={}){let o=new URLSearchParams;r.limit!==void 0&&o.set("limit",String(r.limit)),r.offset!==void 0&&o.set("offset",String(r.offset));let u=o.toString(),g=`/api/v1/forms/${a}/submissions${u?`?${u}`:""}`;return n(g)},async getSubmission(a){return n(`/api/v1/submissions/${a}`)},async exportSubmissionsCsv(a,r={}){let o=new URLSearchParams;return r.includeSpam&&o.set("include_spam","true"),s(gs(`/api/v1/forms/${encodeURIComponent(a)}/submissions/export`,o))},async deleteSubmission(a){await n(`/api/v1/submissions/${a}`,{method:"DELETE"})},async downloadAttachment(a,r){let o=typeof r=="string"?{name:r}:r,u=o.name,g=o.id??o.name,l=`${t}/api/v1/submissions/${a}/attachments/${encodeURIComponent(g)}`,i=await fetch(l,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok){let c;try{c=await i.json()}catch{}throw new ht(nr(c?.error,i.status),i.status,c)}let d=await i.blob(),b=URL.createObjectURL(d),f=document.createElement("a");f.href=b,f.download=u,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(b)},async getSite(a){return n(`/api/v1/sites/${encodeURIComponent(a)}`)},async updateSite(a,r){return n(`/api/v1/sites/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify(r)})},async getPaymentsStatus(){return n("/api/v1/payments/status")},getPromos(a){let r=new URLSearchParams({limit:"10"});return a&&r.set("cursor",a),n(`/api/v1/promos?${r}`)},getPromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}`)},createPromo(a){return n("/api/v1/promos",{method:"POST",body:JSON.stringify(a)})},disablePromo(a){return n(`/api/v1/promos/${encodeURIComponent(a)}/disable`,{method:"POST"})},replacePromo(a,r){return n(`/api/v1/promos/${encodeURIComponent(a)}/replace`,{method:"POST",body:JSON.stringify(r)})},async getProducts(a={}){let r=new URLSearchParams;a.include&&r.set("include",a.include);let o=r.toString();return(await n(`/api/v1/products${o?`?${o}`:""}`)).products},async getProduct(a){return n(`/api/v1/products/${a}`)},async createProduct(a){return n("/api/v1/products",{method:"POST",body:JSON.stringify(a)})},async updateProduct(a,r){return n(`/api/v1/products/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(a){await n(`/api/v1/products/${a}`,{method:"DELETE"})},async attachProductFile(a,r){let o=new FormData;o.append("file",r);let u=await fetch(`${t}/api/v1/products/${a}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:o});if(!u.ok){let g;try{g=await u.json()}catch{}throw new ht(nr(g?.error,u.status),u.status,g)}return u.json()},async attachProductFileFromUrl(a,r){return n(`/api/v1/products/${a}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(a,r){return n(`/api/v1/products/${a}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(a,r){return n(`/api/v1/options/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(a){await n(`/api/v1/options/${a}`,{method:"DELETE"})},async createVariant(a,r){return n(`/api/v1/products/${a}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(a,r){return n(`/api/v1/variants/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(a){await n(`/api/v1/variants/${a}`,{method:"DELETE"})},async setVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(a,r){return n(`/api/v1/variants/${a}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(a={}){let r=new URLSearchParams;a.email?r.set("email",a.email):a.q&&r.set("q",a.q),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/customers${o?`?${o}`:""}`)},async getCustomer(a){return n(`/api/v1/customers/${a}`)},async exportProductsCsv(){return s("/api/v1/products/export")},async exportCustomersCsv(){return s("/api/v1/customers/export")},async getOrders(a={}){let r=ji(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/orders${o?`?${o}`:""}`)},async exportOrdersCsv(a={}){return s(gs("/api/v1/orders/export",ji(a)))},async getOrder(a){return n(`/api/v1/orders/${a}`)},async getInvoices(a={}){let r=new URLSearchParams;a.labels?.length&&r.set("label",a.labels.join(",")),a.customerEmail&&r.set("customer_email",a.customerEmail),a.customerId&&r.set("customer_id",a.customerId),a.q&&r.set("q",a.q),a.from&&r.set("from",a.from),a.to&&r.set("to",a.to),a.includeAggregates&&r.set("include","aggregates"),a.retainerId&&r.set("retainer_id",a.retainerId),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/invoices${o?`?${o}`:""}`)},async getInvoice(a){return n(`/api/v1/invoices/${a}`)},async getInvoicePreview(a){return n(`/api/v1/invoices/${a}/preview`)},async getInvoiceSettings(){return n("/api/v1/invoice-settings")},async getRetainers(a={}){let r=Gi(a);a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/retainers${o?`?${o}`:""}`)},async exportRetainersCsv(a={}){return s(gs("/api/v1/retainers/export",Gi(a)))},async getRetainer(a){return n(`/api/v1/retainers/${a}`)},async resendOrderReceipt(a){await n(`/api/v1/orders/${a}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(a){return n(`/api/v1/orders/${a}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(a,r){return n(`/api/v1/orders/${a}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getSubscriptions(a={}){let r=new URLSearchParams;a.status&&r.set("status",a.status),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/subscriptions${o?`?${o}`:""}`)},async exportSubscriptionsCsv(a={}){let r=new URLSearchParams;return a.status&&r.set("status",a.status),s(gs("/api/v1/subscriptions/export",r))},async getAnalyticsStatus(){let a=new URLSearchParams,r=hn();r&&a.set("timezone",r);let o=a.toString();return n(`/api/v1/analytics/status${o?`?${o}`:""}`)},async getAnalyticsSummary(a,r){return n(`/api/v1/analytics/summary?${ar(a,r)}`)},async getAnalyticsTimeseries(a,r){return n(`/api/v1/analytics/timeseries?${ar(a,r)}`)},async getAnalyticsRealtime(){return n("/api/v1/analytics/realtime")},async getAnalyticsChannels(a,r){return n(`/api/v1/analytics/channels?${ar(a,r)}`)},async getAnalyticsConversions(a){return n((()=>{let r=new URLSearchParams({period:String(a)}),o=hn();return o&&r.set("timezone",o),`/api/v1/analytics/conversions?${r.toString()}`})())},async getAnalyticsGoalTargets(a,r,o){let u=new URLSearchParams({goal:a,period:String(r)}),g=hn();return g&&u.set("timezone",g),o!==void 0&&u.set("limit",String(o)),n(`/api/v1/analytics/conversions/targets?${u.toString()}`)},async getAnalyticsBreakdown(a,r,o){let u=a.split("/").map(encodeURIComponent).join("/");return n(`/api/v1/analytics/${u}?${ar(r,o)}`)},async getBusinessSummary(a){let r=new URLSearchParams;r.set("tz_offset_minutes",String(a.tzOffsetMinutes));let o=hn();return o&&r.set("timezone",o),n(`/api/v1/summary?${r.toString()}`)},async getPeople(a={}){let r=new URLSearchParams;a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),a.limit!==void 0&&r.set("limit",String(a.limit)),a.offset!==void 0&&r.set("offset",String(a.offset));let o=r.toString();return n(`/api/v1/people${o?`?${o}`:""}`)},async exportPeopleCsv(a={}){let r=new URLSearchParams;return a.since&&r.set("since",a.since),a.q&&r.set("q",a.q),a.source&&r.set("source",a.source),s(gs("/api/v1/people/export",r))},async getPerson(a){return n(`/api/v1/people/${encodeURIComponent(a)}`)},async getEventDestinations(){return(await n("/api/v1/event-destinations")).destinations},async createEventDestination(a){return n("/api/v1/event-destinations",{method:"POST",body:JSON.stringify(a)})},async updateEventDestination(a,r){return n(`/api/v1/event-destinations/${a}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteEventDestination(a){await n(`/api/v1/event-destinations/${a}`,{method:"DELETE"})},async rotateEventDestinationSecret(a){return n(`/api/v1/event-destinations/${a}/rotate-secret`,{method:"POST"})},async getEventDestinationSecret(a){return(await n(`/api/v1/event-destinations/${a}/secret`)).secret},async getEventDeliveries(a,r){let o=r===void 0?"":`?limit=${r}`;return(await n(`/api/v1/event-destinations/${a}/deliveries${o}`)).deliveries},async retryEventDelivery(a,r){return n(`/api/v1/event-destinations/${a}/deliveries/${r}/retry`,{method:"POST"})}}}var xn=require("react/jsx-runtime"),Wi=wn.createContext(null);function tc(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 Ki({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:n=!1,className:s,children:a}){let r=wn.useMemo(()=>tc(e),[e]),o=wn.useMemo(()=>sr(e,t),[e,t]),u=wn.useMemo(()=>({siteToken:e,apiUrl:t,api:o}),[e,t,o]);return r?(0,xn.jsx)("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:(0,xn.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,xn.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,xn.jsx)("p",{className:"af-text-sm af-text-destructive",children:r})]})}):(0,xn.jsx)(Wi.Provider,{value:u,children:(0,xn.jsx)("div",{className:`aifeatures-admin ${n?"dark":""} ${s||""}`,children:a})})}function ae(){let e=wn.useContext(Wi);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ln=re(require("react"),1),Qn=require("lucide-react");var rr=re(require("react"),1),Ma=re(require("@radix-ui/react-tabs"),1);var Zi=require("clsx"),Ji=require("tailwind-merge"),ac=(0,Ji.extendTailwindMerge)({prefix:"af-"});function ee(...e){return ac((0,Zi.clsx)(e))}var or=require("react/jsx-runtime"),ir=Ma.Root,vs=rr.forwardRef(({className:e,...t},n)=>(0,or.jsx)(Ma.List,{ref:n,className:ee("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}));vs.displayName=Ma.List.displayName;var $a=rr.forwardRef(({className:e,...t},n)=>(0,or.jsx)(Ma.Trigger,{ref:n,className:ee("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}));$a.displayName=Ma.Trigger.displayName;var Va=rr.forwardRef(({className:e,...t},n)=>(0,or.jsx)(Ma.Content,{ref:n,className:ee("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}));Va.displayName=Ma.Content.displayName;var Yi=re(require("react"),1),Xi=require("@radix-ui/react-slot"),Qi=require("class-variance-authority");var eo=require("react/jsx-runtime"),nc=(0,Qi.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"}}),R=Yi.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...a},r)=>(0,eo.jsx)(s?Xi.Slot:"button",{className:ee(nc({variant:t,size:n,className:e})),ref:r,...a}));R.displayName="Button";var bs=require("lucide-react");var rn=re(require("react"),1);var Wa=require("react/jsx-runtime"),qe=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,Wa.jsx)("table",{ref:n,className:ee("af-w-full af-caption-bottom af-text-sm",e),...t})}));qe.displayName="Table";var je=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("thead",{ref:n,className:ee("[&_tr]:af-border-b",e),...t}));je.displayName="TableHeader";var Ge=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("tbody",{ref:n,className:ee("[&_tr:last-child]:af-border-0",e),...t}));Ge.displayName="TableBody";var sc=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("tfoot",{ref:n,className:ee("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));sc.displayName="TableFooter";var Re=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("tr",{ref:n,className:ee("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));Re.displayName="TableRow";var j=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("th",{ref:n,className:ee("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}));j.displayName="TableHead";var G=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("td",{ref:n,className:ee("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));G.displayName="TableCell";var rc=rn.forwardRef(({className:e,...t},n)=>(0,Wa.jsx)("caption",{ref:n,className:ee("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));rc.displayName="TableCaption";var Ha=re(require("react"),1);function En(){let{api:e}=ae(),[t,n]=Ha.useState([]),[s,a]=Ha.useState(!0),[r,o]=Ha.useState(null),u=Ha.useCallback(async()=>{try{a(!0),o(null);let d=await e.getForms();n(d)}catch(d){o(d instanceof Error?d:new Error("Failed to fetch forms"))}finally{a(!1)}},[e]);Ha.useEffect(()=>{u()},[u]);let g=Ha.useCallback(async d=>{let b=await e.createForm(d);return n(f=>[...f,b]),b},[e]),l=Ha.useCallback(async(d,b)=>{let f=await e.updateForm(d,b);return n(c=>c.map(m=>m.id===d?f:m)),f},[e]),i=Ha.useCallback(async d=>{await e.deleteForm(d),n(b=>b.filter(f=>f.id!==d))},[e]);return{forms:t,isLoading:s,error:r,refetch:u,createForm:g,updateForm:l,deleteForm:i}}var Qe=require("react/jsx-runtime");function ys({onSelectForm:e,className:t}){let{forms:n,isLoading:s,error:a}=En();return s?(0,Qe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Qe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):a?(0,Qe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,Qe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})}):n.length===0?(0,Qe.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,Qe.jsx)(bs.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,Qe.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,Qe.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,Qe.jsx)("div",{className:t,children:(0,Qe.jsxs)(qe,{children:[(0,Qe.jsx)(je,{children:(0,Qe.jsxs)(Re,{children:[(0,Qe.jsx)(j,{children:"Name"}),(0,Qe.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,Qe.jsx)(Ge,{children:n.map(r=>(0,Qe.jsxs)(Re,{children:[(0,Qe.jsx)(G,{className:"af-font-medium",children:r.name}),(0,Qe.jsx)(G,{className:"af-text-right",children:(0,Qe.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,Qe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"submissions"),children:[(0,Qe.jsx)(bs.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,Qe.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>e?.(r,"settings"),children:[(0,Qe.jsx)(bs.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},r.id))})]})})}var no=require("lucide-react");var to=require("class-variance-authority");var ao=require("react/jsx-runtime"),ic=(0,to.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 ne({className:e,variant:t,...n}){return(0,ao.jsx)("div",{className:ee(ic({variant:t}),e),...n})}var ca=require("react/jsx-runtime"),oc={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 lr(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 Qr(e=[]){return e.some(t=>!["sending","sent","delivered"].includes(t.state))}function lc(e){return["sending","sent","delivered","delivery_delayed","unknown","complained"].includes(e.state)?null:e.kind==="form_notification"?"Check this form\u2019s notification email addresses in its settings. The submission is saved here.":e.kind==="merchant_sale"||e.kind==="merchant_oversell"?"Check your notification email addresses. You can view and fulfill this order here.":e.kind==="dispute_opened"?"Check your notification email addresses and review this dispute in Stripe.":e.kind==="merchant_subscription_canceled"?"Check your notification email addresses. The subscription status is still shown here.":e.kind==="account_login"?"Ask the customer to confirm their email address and request a new sign-in link once the delivery problem is resolved.":e.kind==="purchase_receipt"?"Contact the buyer another way to confirm their email address. Payment and download details are still available on this order.":"Contact the customer another way to confirm their email address. Email delivery does not change their subscription or payment status."}function hs({deliveries:e,label:t="Email needs attention"}){return Qr(e)?(0,ca.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,ca.jsx)(no.AlertTriangle,{"aria-hidden":"true",className:"af-h-3 af-w-3 af-shrink-0"}),t]}):null}function Ka({deliveries:e,problemsOnly:t=!1,className:n=""}){let s=(e??[]).filter(a=>!t||Qr([a]));return s.length?(0,ca.jsx)("div",{className:`af-space-y-3 ${n}`,"aria-label":"Email delivery",children:s.map(a=>{let r=lr(a),o=lc(a);return(0,ca.jsxs)("div",{className:"af-rounded-md af-border af-p-3 af-text-sm",children:[(0,ca.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,ca.jsx)("span",{className:"af-font-medium",children:oc[a.kind]??"Email notification"}),(0,ca.jsx)(ne,{variant:r.variant,children:r.label})]}),(0,ca.jsxs)("p",{className:"af-mt-1 af-break-words af-text-xs af-text-muted-foreground",children:["To: ",a.recipients.join(", ")]}),a.recipients.length>1&&Qr([a])&&(0,ca.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."}),r.detail&&(0,ca.jsx)("p",{className:"af-mt-1",children:r.detail}),o&&(0,ca.jsx)("p",{className:"af-mt-1",children:o})]},a.id)})}):null}var Nn=re(require("react"),1),ka=require("lucide-react");var Sn=re(require("react"),1),Ae=re(require("@radix-ui/react-select"),1),In=require("lucide-react");var vt=require("react/jsx-runtime"),Pa=Ae.Root;var Ca=Ae.Value,ua=Sn.forwardRef(({className:e,children:t,...n},s)=>(0,vt.jsxs)(Ae.Trigger,{ref:s,className:ee("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),...n,children:[t,(0,vt.jsx)(Ae.Icon,{asChild:!0,children:(0,vt.jsx)(In.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));ua.displayName=Ae.Trigger.displayName;var so=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.ScrollUpButton,{ref:n,className:ee("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,vt.jsx)(In.ChevronUp,{className:"af-h-4 af-w-4"})}));so.displayName=Ae.ScrollUpButton.displayName;var ro=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.ScrollDownButton,{ref:n,className:ee("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,vt.jsx)(In.ChevronDown,{className:"af-h-4 af-w-4"})}));ro.displayName=Ae.ScrollDownButton.displayName;var da=Sn.forwardRef(({className:e,children:t,position:n="popper",...s},a)=>(0,vt.jsx)(Ae.Portal,{children:(0,vt.jsxs)(Ae.Content,{ref:a,className:ee("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",n==="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:n,...s,children:[(0,vt.jsx)(so,{}),(0,vt.jsx)(Ae.Viewport,{className:ee("af-p-1",n==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,vt.jsx)(ro,{})]})}));da.displayName=Ae.Content.displayName;var cc=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.Label,{ref:n,className:ee("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));cc.displayName=Ae.Label.displayName;var et=Sn.forwardRef(({className:e,children:t,...n},s)=>(0,vt.jsxs)(Ae.Item,{ref:s,className:ee("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),...n,children:[(0,vt.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,vt.jsx)(Ae.ItemIndicator,{children:(0,vt.jsx)(In.Check,{className:"af-h-4 af-w-4"})})}),(0,vt.jsx)(Ae.ItemText,{children:t})]}));et.displayName=Ae.Item.displayName;var uc=Sn.forwardRef(({className:e,...t},n)=>(0,vt.jsx)(Ae.Separator,{ref:n,className:ee("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));uc.displayName=Ae.Separator.displayName;var Gt=re(require("react"),1);function xs({formId:e,initialPageSize:t=25}){let{api:n}=ae(),[s,a]=Gt.useState([]),[r,o]=Gt.useState(0),[u,g]=Gt.useState(!0),[l,i]=Gt.useState(null),[d,b]=Gt.useState(0),[f,c]=Gt.useState(t),m=Gt.useRef(0),p=Gt.useCallback(async()=>{if(!e)return;let E=++m.current;try{g(!0),i(null);let v={limit:f,offset:d*f},_=await n.getSubmissions(e,v);if(E!==m.current)return;if(_.submissions.length===0&&d>0){b(Math.max(0,Math.ceil(_.total/f)-1));return}a(_.submissions),o(_.total)}catch(v){if(E!==m.current)return;i(v instanceof Error?v:new Error("Failed to fetch submissions"))}finally{E===m.current&&g(!1)}},[n,e,d,f]);Gt.useEffect(()=>{p()},[p]);let y=Gt.useRef(p);y.current=p;let S=Gt.useCallback(async E=>{await n.deleteSubmission(E),y.current()},[n]),C=Math.ceil(r/f);return{submissions:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<C-1,hasPreviousPage:d>0,setPage:b,setPageSize:E=>{c(E),b(0)},refetch:p,deleteSubmission:S}}var cr=re(require("react"),1),lo=require("lucide-react");var ws=re(require("react"),1),Rt=re(require("@radix-ui/react-dialog"),1),io=require("lucide-react");var Qt=require("react/jsx-runtime"),Ta=Rt.Root;var dc=Rt.Portal;var oo=ws.forwardRef(({className:e,...t},n)=>(0,Qt.jsx)(Rt.Overlay,{ref:n,className:ee("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));oo.displayName=Rt.Overlay.displayName;var fa=ws.forwardRef(({className:e,children:t,...n},s)=>(0,Qt.jsx)(dc,{children:(0,Qt.jsxs)("div",{className:"aifeatures-admin",children:[(0,Qt.jsx)(oo,{}),(0,Qt.jsxs)(Rt.Content,{ref:s,className:ee("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),...n,children:[t,(0,Qt.jsxs)(Rt.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,Qt.jsx)(io.X,{className:"af-h-4 af-w-4"}),(0,Qt.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));fa.displayName=Rt.Content.displayName;var ma=({className:e,...t})=>(0,Qt.jsx)("div",{className:ee("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,Qt.jsx)("div",{className:ee("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=ws.forwardRef(({className:e,...t},n)=>(0,Qt.jsx)(Rt.Title,{ref:n,className:ee("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));ga.displayName=Rt.Title.displayName;var va=ws.forwardRef(({className:e,...t},n)=>(0,Qt.jsx)(Rt.Description,{ref:n,className:ee("af-text-sm af-text-muted-foreground",e),...t}));va.displayName=Rt.Description.displayName;var $t=require("react/jsx-runtime");function Yn({onDelete:e,iconOnly:t}){let[n,s]=cr.useState(!1),[a,r]=cr.useState(!1),[o,u]=cr.useState(null);return(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsxs)(R,{variant:"ghost",size:t?"icon":"sm",title:"Delete submission","aria-label":t?"Delete submission":void 0,onClick:()=>{u(null),s(!0)},children:[(0,$t.jsx)(lo.Trash2,{className:t?"af-h-4 af-w-4":"af-h-4 af-w-4 af-mr-1"}),!t&&"Delete"]}),(0,$t.jsx)(Ta,{open:n,onOpenChange:l=>{!l&&!a&&s(!1)},children:(0,$t.jsxs)(fa,{children:[(0,$t.jsxs)(ma,{children:[(0,$t.jsx)(ga,{children:"Delete this submission?"}),(0,$t.jsx)(va,{children:"The submission and any files attached to it are removed permanently. This can't be undone."})]}),o&&(0,$t.jsx)("p",{className:"af-text-sm af-text-destructive",children:o}),(0,$t.jsxs)(pa,{children:[(0,$t.jsx)(R,{variant:"outline",onClick:()=>s(!1),disabled:a,children:"Cancel"}),(0,$t.jsx)(R,{variant:"destructive",onClick:async()=>{r(!0),u(null);try{await e(),s(!1)}catch(l){u(l instanceof Error?l.message:"Failed to delete submission")}finally{r(!1)}},disabled:a,children:a?"Deleting...":"Delete"})]})]})})]})}var uo=re(require("react"),1),Vt=require("lucide-react");var he=require("react/jsx-runtime");function co(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function fc(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function Ss({submission:e,onBack:t,onDelete:n}){let{api:s}=ae(),[a,r]=uo.useState(null),o=l=>l.id??l.name,u=async l=>{r(o(l));try{await s.downloadAttachment(e.id,l)}catch(i){console.error("Download failed:",i)}finally{r(null)}},g=Object.entries(e.data).filter(([l])=>!l.startsWith("_"));return(0,he.jsxs)("div",{children:[(0,he.jsxs)("div",{className:"af-mb-6",children:[(0,he.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,he.jsx)(Vt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,he.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,he.jsxs)("div",{children:[(0,he.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,he.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",co(e.metadata.submitted_at)]})]}),n&&(0,he.jsx)(Yn,{onDelete:n})]})]}),(0,he.jsxs)("div",{className:"af-space-y-6",children:[(0,he.jsx)(Ka,{deliveries:e.email_deliveries}),(0,he.jsxs)("div",{children:[(0,he.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,he.jsxs)("div",{className:"af-space-y-3",children:[g.map(([l,i])=>(0,he.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,he.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:l.replace(/_/g," ")}),(0,he.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof i=="string"&&i.includes(`
3
+ `)?(0,he.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:i}):String(i)})]},l)),g.length===0&&(0,he.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,he.jsxs)("div",{children:[(0,he.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,he.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((l,i)=>(0,he.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,he.jsx)(Vt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,he.jsx)("span",{className:"af-text-sm",children:l.name}),(0,he.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",fc(l.size),")"]})]}),(0,he.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>u(l),disabled:a===o(l),children:[a===o(l)?(0,he.jsx)(Vt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,he.jsx)(Vt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),a===o(l)?"Downloading...":"Download"]})]},i))})]}),(0,he.jsxs)("div",{children:[(0,he.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,he.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Clock,{className:"af-h-4 af-w-4"}),(0,he.jsx)("span",{children:co(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Globe,{className:"af-h-4 af-w-4"}),(0,he.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,he.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,he.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,he.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,he.jsx)(Vt.Mail,{className:"af-h-4 af-w-4"}),(0,he.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var mo=require("lucide-react");var An=re(require("react"),1);var mc=/^\+[1-9]\d{1,14}$/;function fo(e){let t=e==null?"":String(e),n=!mc.test(t)&&/^[\s\u0000-\u001f]*[=+\-@=+-@]|^[\t\r\n]/u.test(t),s=n?`'${t}`:t;return n||/[",;\r\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function ur(e,t=new Date){return`${e}-${t.toISOString().slice(0,10)}.csv`}function dr(e,t){if(typeof document>"u")return;let n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}function Ns({fetchCsv:e,filename:t}){let[n,s]=An.useState(!1),[a,r]=An.useState(null),o=An.useRef(!1);return{exportCsv:An.useCallback(async()=>{if(!o.current){o.current=!0,s(!0),r(null);try{let g=await e();dr(g,ur(t))}catch(g){r(g instanceof Error?g:new Error("Export failed"))}finally{o.current=!1,s(!1)}}},[e,t]),exporting:n,error:a}}var Xn=require("react/jsx-runtime");function Bt({fetchCsv:e,filename:t,label:n="Export CSV",disabled:s,className:a}){let{exportCsv:r,exporting:o,error:u}=Ns({fetchCsv:e,filename:t});return(0,Xn.jsxs)("span",{className:a,children:[(0,Xn.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>void r(),disabled:s||o,"aria-busy":o,children:[(0,Xn.jsx)(mo.Download,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Exporting\u2026":n]}),u&&(0,Xn.jsx)("span",{role:"status",className:"af-ml-2 af-text-xs af-text-destructive",children:"Couldn't export \u2014 try again."})]})}var de=require("react/jsx-runtime");function pc(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gc(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let n of t)if(typeof e[n]=="string")return e[n];return null}var vc=["message","comments","comment","inquiry","question","details","body","notes"];function bc(e){let t=Object.entries(e).filter(([r,o])=>!r.startsWith("_")&&!r.toLowerCase().includes("email")&&typeof o=="string"&&o.trim()),n=new Map(t.map(([r,o])=>[r.toLowerCase(),o])),a=(vc.map(r=>n.get(r)).find(Boolean)??t.reduce((r,[,o])=>o.length>r.length?o:r,"")).trim().replace(/\s+/g," ");return a.length>80?a.slice(0,80)+"\u2026":a}function Rs({formId:e,className:t,defaultSubmissionId:n,submissionId:s,onSelectSubmission:a}){let{api:r}=ae(),{submissions:o,total:u,isLoading:g,error:l,page:i,pageSize:d,hasNextPage:b,hasPreviousPage:f,setPage:c,setPageSize:m,deleteSubmission:p}=xs({formId:e}),y=Nn.useCallback(()=>r.exportSubmissionsCsv(e),[r,e]),[S,C]=Nn.useState(n??null),E=a?s??null:S,v=a??C,_=q=>!!q&&q.id===E&&q.form_id===e,T=o.find(_),[A,N]=Nn.useState(null),k=_(A)?A:null,[L,P]=Nn.useState(null);if(Nn.useEffect(()=>{if(P(null),!E||T||k)return;let q=!1;return r.getSubmission(E).then(se=>{if(!q){if(se.form_id!==e){P("This submission could not be found.");return}N(se)}}).catch(()=>{q||P("This submission could not be found.")}),()=>{q=!0}},[r,e,E,T,k]),E){let q=T??k;return q?(0,de.jsx)("div",{className:t,children:(0,de.jsx)(Ss,{submission:q,onBack:()=>v(null),onDelete:async()=>{await p(q.id),v(null)}})}):L?(0,de.jsxs)("div",{className:t,children:[(0,de.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>v(null),className:"af-mb-2 af--ml-2",children:[(0,de.jsx)(ka.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,de.jsx)("p",{className:"af-text-sm af-text-destructive",children:L})]}):(0,de.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submission..."})})}if(g)return(0,de.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(l)return(0,de.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,de.jsxs)("div",{className:"af-text-destructive",children:["Error: ",l.message]})});if(o.length===0&&i===0)return(0,de.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,de.jsx)(ka.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,de.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,de.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let Y=i*d+1,J=Math.min((i+1)*d,u);return(0,de.jsxs)("div",{className:t,children:[(0,de.jsx)("div",{className:"af-mb-2 af-flex af-justify-end",children:(0,de.jsx)(Bt,{fetchCsv:y,filename:"submissions"})}),(0,de.jsxs)(qe,{children:[(0,de.jsx)(je,{children:(0,de.jsxs)(Re,{children:[(0,de.jsx)(j,{children:"Email"}),(0,de.jsx)(j,{children:"Preview"}),(0,de.jsx)(j,{children:"Date"}),(0,de.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,de.jsx)(Ge,{children:o.map(q=>{let se=gc(q.data),ce=bc(q.data);return(0,de.jsxs)(Re,{children:[(0,de.jsxs)(G,{className:"af-font-medium",children:[(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[se||(0,de.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),q.attachments.length>0&&(0,de.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${q.attachments.length} attachment(s)`,children:[(0,de.jsx)(ka.Paperclip,{className:"af-h-3 af-w-3"}),(0,de.jsx)("span",{className:"af-text-xs",children:q.attachments.length})]})]}),(0,de.jsx)(hs,{deliveries:q.email_deliveries,label:"Notification email needs attention"})]}),(0,de.jsx)(G,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:ce||(0,de.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,de.jsx)(G,{className:"af-text-muted-foreground",children:pc(q.metadata.submitted_at)}),(0,de.jsxs)(G,{className:"af-text-right",children:[(0,de.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>v(q.id),title:"View details",children:(0,de.jsx)(ka.Eye,{className:"af-h-4 af-w-4"})}),(0,de.jsx)(Yn,{iconOnly:!0,onDelete:()=>p(q.id)})]})]},q.id)})})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,de.jsxs)("span",{children:["Showing ",Y,"-",J," of ",u]}),(0,de.jsxs)(Pa,{value:String(d),onValueChange:q=>m(Number(q)),children:[(0,de.jsx)(ua,{className:"af-w-[70px] af-h-8",children:(0,de.jsx)(Ca,{})}),(0,de.jsxs)(da,{children:[(0,de.jsx)(et,{value:"10",children:"10"}),(0,de.jsx)(et,{value:"25",children:"25"}),(0,de.jsx)(et,{value:"50",children:"50"}),(0,de.jsx)(et,{value:"100",children:"100"})]})]}),(0,de.jsx)("span",{children:"per page"})]}),(0,de.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,de.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>c(i-1),disabled:!f,children:[(0,de.jsx)(ka.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,de.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>c(i+1),disabled:!b,children:["Next",(0,de.jsx)(ka.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var ya=re(require("react"),1),Rn=require("lucide-react");var po=re(require("react"),1);var go=require("react/jsx-runtime"),pe=po.forwardRef(({className:e,type:t,...n},s)=>(0,go.jsx)("input",{type:t,className:ee("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:s,...n}));pe.displayName="Input";var vo=re(require("react"),1),bo=require("class-variance-authority");var yo=require("react/jsx-runtime"),yc=(0,bo.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ke=vo.forwardRef(({className:e,...t},n)=>(0,yo.jsx)("label",{ref:n,className:ee(yc(),e),...t}));ke.displayName="Label";var Ea=re(require("react"),1),Ht=require("lucide-react");var ba=re(require("react"),1);function _s(){let{api:e}=ae(),[t,n]=ba.useState([]),[s,a]=ba.useState(!0),[r,o]=ba.useState(null),u=ba.useCallback(async()=>{try{a(!0),o(null),n(await e.getEventDestinations())}catch(f){o(f instanceof Error?f:new Error("Failed to fetch webhooks"))}finally{a(!1)}},[e]);ba.useEffect(()=>{u()},[u]);let g=ba.useCallback(async f=>{let c=await e.createEventDestination(f);return n(m=>[c,...m]),c},[e]),l=ba.useCallback(async(f,c)=>{let m=await e.updateEventDestination(f,c);return n(p=>p.map(y=>y.id===f?m:y)),m},[e]),i=ba.useCallback(async f=>{await e.deleteEventDestination(f),n(c=>c.filter(m=>m.id!==f))},[e]),d=ba.useCallback(async f=>{let c=await e.rotateEventDestinationSecret(f);return n(m=>m.map(p=>p.id===f?c:p)),c},[e]),b=ba.useCallback(f=>e.getEventDestinationSecret(f),[e]);return{destinations:t,isLoading:s,error:r,refetch:u,createDestination:g,updateDestination:l,deleteDestination:i,rotateSecret:d,getSecret:b}}var on=re(require("react"),1),Ps=require("lucide-react");var _t=require("react/jsx-runtime");function Cs({destinationId:e,limit:t=25,className:n}){let{api:s}=ae(),[a,r]=on.useState([]),[o,u]=on.useState(!0),[g,l]=on.useState(null),[i,d]=on.useState(null),b=on.useCallback(async()=>{try{u(!0),l(null),r(await s.getEventDeliveries(e,t))}catch(c){l(c instanceof Error?c.message:"Failed to load deliveries")}finally{u(!1)}},[s,e,t]);on.useEffect(()=>{b()},[b]);let f=async c=>{try{d(c.id),l(null);let m=await s.retryEventDelivery(e,c.id);r(p=>p.map(y=>y.id===c.id?m:y))}catch(m){l(m instanceof Error?m.message:"Retry failed")}finally{d(null)}};return o?(0,_t.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground af-py-2",children:[(0,_t.jsx)(Ps.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading deliveries..."]}):g?(0,_t.jsx)("div",{className:"af-text-sm af-text-destructive af-py-2",children:g}):a.length===0?(0,_t.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,_t.jsx)("div",{className:n,children:(0,_t.jsx)("div",{className:"af-divide-y af-border af-rounded",children:a.map(c=>{let m=c.delivered_at!==null;return(0,_t.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3 af-px-3 af-py-2",children:[(0,_t.jsxs)("div",{className:"af-min-w-0",children:[(0,_t.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[m?(0,_t.jsx)(ne,{variant:"secondary",children:c.last_status??200}):(0,_t.jsx)(ne,{variant:"destructive",children:c.last_status??"failed"}),(0,_t.jsx)("span",{className:"af-text-sm af-truncate",children:c.type})]}),(0,_t.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-mt-0.5 af-font-mono af-truncate",children:[c.event_id," \xB7 ",c.created_at,c.attempts>0&&` \xB7 ${c.attempts} failed ${c.attempts===1?"attempt":"attempts"}`]}),!m&&c.last_error&&(0,_t.jsx)("p",{className:"af-text-xs af-text-destructive af-mt-0.5 af-truncate",children:c.last_error})]}),(0,_t.jsx)(R,{variant:"ghost",size:"sm",title:"Send this event again",disabled:i===c.id,onClick:()=>f(c),children:i===c.id?(0,_t.jsx)(Ps.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,_t.jsx)(Ps.RotateCw,{className:"af-h-4 af-w-4"})})]},c.id)})})})}var ve=require("react/jsx-runtime");function Ts({formId:e,topics:t,description:n,className:s}){let{destinations:a,isLoading:r,error:o,createDestination:u,updateDestination:g,deleteDestination:l,rotateSecret:i,getSecret:d}=_s(),[b,f]=Ea.useState(""),[c,m]=Ea.useState(!1),[p,y]=Ea.useState(null),[S,C]=Ea.useState(null),[E,v]=Ea.useState(null),[_,T]=Ea.useState(!1),[A,N]=Ea.useState(null),[k,L]=Ea.useState(null),[P,Y]=Ea.useState(null),J=Ea.useMemo(()=>a.filter(U=>U.form_id===e),[a,e]),q=async()=>{let U=b.trim();if(U){if(!U.startsWith("https://")){y("Webhook URLs must start with https://");return}try{m(!0),y(null),await u({url:U,form_id:e,...t&&t.length>0?{topics:t}:{}}),f("")}catch(Pe){y(Pe instanceof Error?Pe.message:"Failed to add webhook")}finally{m(!1)}}},se=async U=>{try{L(U.id),y(null),await i(U.id),T(!1),v(await d(U.id))}catch(Pe){y(Pe instanceof Error?Pe.message:"Failed to rotate secret")}finally{L(null)}},ce=async U=>{try{L(U.id),y(null),await g(U.id,{status:"active"})}catch(Pe){y(Pe instanceof Error?Pe.message:"Failed to re-enable")}finally{L(null)}},ge=async()=>{if(A)try{L(A.id),await l(A.id),N(null)}catch(U){y(U instanceof Error?U.message:"Failed to delete")}finally{L(null)}},$=async U=>{if(S===U.id){C(null),v(null);return}try{L(U.id),y(null),T(!1),C(U.id),v(await d(U.id))}catch(Pe){C(null),y(Pe instanceof Error?Pe.message:"Failed to read secret")}finally{L(null)}},te=async()=>{if(E)try{await navigator.clipboard.writeText(E),T(!0)}catch{}};return(0,ve.jsxs)("div",{className:s,children:[(0,ve.jsxs)("div",{className:"af-space-y-1",children:[(0,ve.jsx)(ke,{children:"Webhooks"}),(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:n??"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,ve.jsxs)("div",{className:"af-flex af-gap-2 af-mt-4",children:[(0,ve.jsx)(pe,{value:b,placeholder:"https://hooks.zapier.com/...",onChange:U=>f(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),q())},disabled:c}),(0,ve.jsxs)(R,{onClick:q,disabled:c||!b.trim(),children:[c?(0,ve.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ve.jsx)(Ht.Plus,{className:"af-h-4 af-w-4"}),(0,ve.jsx)("span",{className:"af-ml-1",children:"Add"})]})]}),(p||o)&&(0,ve.jsx)("div",{className:"af-mt-2 af-text-sm af-text-destructive",children:p||o?.message}),(0,ve.jsxs)("div",{className:"af-mt-4 af-space-y-2",children:[r&&(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ve.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),"Loading webhooks..."]}),!r&&J.length===0&&(0,ve.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No webhooks yet. Submissions still arrive by email and in your dashboard."}),J.map(U=>(0,ve.jsxs)("div",{className:"af-rounded af-border af-p-3 af-space-y-2",children:[(0,ve.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,ve.jsxs)("div",{className:"af-min-w-0",children:[(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,ve.jsx)("span",{className:"af-font-mono af-text-sm af-truncate",children:U.url}),U.status==="disabled"?(0,ve.jsx)(ne,{variant:"destructive",children:"Disabled"}):(0,ve.jsx)(ne,{variant:"secondary",children:"Active"})]}),(0,ve.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:U.topics.includes("*")?"All events":U.topics.join(", ")})]}),(0,ve.jsxs)("div",{className:"af-flex af-items-center af-gap-1 af-shrink-0",children:[(0,ve.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>Y(P===U.id?null:U.id),children:P===U.id?"Hide log":"Deliveries"}),(0,ve.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>$(U),disabled:k===U.id,children:S===U.id?"Hide secret":"Show secret"}),(0,ve.jsx)(R,{variant:"ghost",size:"sm",title:"Delete webhook",disabled:k===U.id,onClick:()=>N(U),children:(0,ve.jsx)(Ht.Trash2,{className:"af-h-4 af-w-4"})})]})]}),U.status==="disabled"&&(0,ve.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,ve.jsx)(Ht.AlertTriangle,{className:"af-h-4 af-w-4 af-text-destructive af-mt-0.5 af-shrink-0"}),(0,ve.jsxs)("div",{className:"af-text-sm",children:[(0,ve.jsxs)("p",{children:["We stopped sending after repeated failures."," ",U.disabled_reason]}),(0,ve.jsx)(R,{variant:"outline",size:"sm",className:"af-mt-2",disabled:k===U.id,onClick:()=>ce(U),children:"Re-enable"})]})]}),S===U.id&&E&&(0,ve.jsxs)("div",{className:"af-rounded af-bg-muted af-px-3 af-py-2 af-space-y-2",children:[(0,ve.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,ve.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ve.jsx)(pe,{readOnly:!0,value:E,className:"af-font-mono"}),(0,ve.jsx)(R,{variant:"outline",title:"Copy signing secret",onClick:te,children:_?(0,ve.jsx)(Ht.Check,{className:"af-h-4 af-w-4"}):(0,ve.jsx)(Ht.Copy,{className:"af-h-4 af-w-4"})}),(0,ve.jsx)(R,{variant:"outline",title:"Rotate signing secret",disabled:k===U.id,onClick:()=>se(U),children:k===U.id?(0,ve.jsx)(Ht.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,ve.jsx)(Ht.RefreshCw,{className:"af-h-4 af-w-4"})})]})]}),P===U.id&&(0,ve.jsx)(Cs,{destinationId:U.id})]},U.id))]}),(0,ve.jsx)(Ta,{open:!!A,onOpenChange:U=>{!U&&!k&&N(null)},children:(0,ve.jsxs)(fa,{children:[(0,ve.jsxs)(ma,{children:[(0,ve.jsx)(ga,{children:"Delete this webhook?"}),(0,ve.jsxs)(va,{children:["New submissions will stop being sent to ",A?.url,". Its delivery history is removed too. Submissions themselves are not affected \u2014 they stay in your dashboard and still go out by email."]})]}),(0,ve.jsxs)(pa,{children:[(0,ve.jsx)(R,{variant:"outline",onClick:()=>N(null),disabled:!!k,children:"Cancel"}),(0,ve.jsx)(R,{variant:"destructive",onClick:ge,disabled:!!k,children:k?"Deleting...":"Delete"})]})]})})]})}var Ce=require("react/jsx-runtime");function ks({form:e,onSaved:t,className:n}){let{updateForm:s}=En(),[a,r]=ya.useState(!1),[o,u]=ya.useState(null),[g,l]=ya.useState(null),[i,d]=ya.useState(e.name),[b,f]=ya.useState(e.redirect_url||""),[c,m]=ya.useState(e.email_recipients),[p,y]=ya.useState("");ya.useEffect(()=>{d(e.name),f(e.redirect_url||""),m(e.email_recipients),l(null)},[e]);let S=ya.useCallback(async T=>{try{r(!0),l(null);let A=await s(e.id,T);u(new Date),t?.(A)}catch(A){l(A instanceof Error?A.message:"Failed to save")}finally{r(!1)}},[e.id,s,t]);ya.useEffect(()=>{if(o){let T=setTimeout(()=>u(null),2e3);return()=>clearTimeout(T)}},[o]);let C=async()=>{let T=p.trim().toLowerCase();if(!T)return;if(!T.includes("@")){l("Please enter a valid email address");return}if(c.includes(T)){l("This email is already added");return}let A=[...c,T];m(A),y(""),l(null),await S({email_recipients:A})},E=async T=>{let A=c.filter(N=>N!==T);m(A),await S({email_recipients:A})},v=async()=>{i!==e.name&&await S({name:i})},_=async()=>{let T=b||null;T!==e.redirect_url&&await S({redirect_url:T})};return(0,Ce.jsxs)("div",{className:`af-space-y-6 af-relative ${n||""}`,children:[(a||o)&&(0,Ce.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:a?(0,Ce.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,Ce.jsx)(Rn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,Ce.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,Ce.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,Ce.jsx)(Rn.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,Ce.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{htmlFor:"form-name",children:"Form Name"}),(0,Ce.jsx)(pe,{id:"form-name",value:i,onChange:T=>d(T.target.value),onBlur:v,placeholder:"Contact Form"}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{children:"Email Recipients"}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,Ce.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[c.map(T=>(0,Ce.jsxs)(ne,{variant:"secondary",className:"af-gap-1",children:[T,(0,Ce.jsx)("button",{type:"button",onClick:()=>E(T),className:"af-ml-1 hover:af-text-destructive",disabled:a,children:(0,Ce.jsx)(Rn.X,{className:"af-h-3 af-w-3"})})]},T)),c.length===0&&(0,Ce.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,Ce.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Ce.jsx)(pe,{type:"email",value:p,onChange:T=>y(T.target.value),placeholder:"Add email address",onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),C())},disabled:a}),(0,Ce.jsx)(R,{type:"button",variant:"outline",onClick:C,disabled:!p.trim()||a,children:(0,Ce.jsx)(Rn.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,Ce.jsx)(pe,{id:"redirect-url",value:b,onChange:T=>f(T.target.value),onBlur:_,placeholder:"/thank-you"}),(0,Ce.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,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{children:"Form Endpoint"}),(0,Ce.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Ce.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,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,Ce.jsxs)("div",{className:"af-space-y-2",children:[(0,Ce.jsx)(ke,{children:"Captcha Protection"}),(0,Ce.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Ce.jsx)(ne,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,Ce.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),(0,Ce.jsx)(Ts,{formId:e.id}),g&&(0,Ce.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:g})]})}var Ze=require("react/jsx-runtime");function ei({className:e,location:t,onNavigate:n,submissionId:s}){let{api:a}=ae(),[r,o]=ln.useState({submissionId:s});ln.useEffect(()=>{s&&o({submissionId:s})},[s]);let u=n?t??{}:r,g=n??o,[l,i]=ln.useState(null),d=`${u.formId??""}|${u.submissionId??""}`,[b,f]=ln.useState(null),c=b?.key===d?b.message:null,m=u.formId??(l&&l.submissionId===u.submissionId?l.formId:void 0);ln.useEffect(()=>{let T=u.submissionId;if(!T||u.formId)return;let A=!1;return a.getSubmission(T).then(N=>{A||(f(null),i({submissionId:T,formId:N.form_id}))}).catch(()=>{A||f({key:d,message:"This submission could not be found."})}),()=>{A=!0}},[a,u.submissionId,u.formId,d]);let[p,y]=ln.useState(null);ln.useEffect(()=>{if(!m||p?.id===m)return;let T=!1;return a.getForm(m).then(A=>{T||(f(null),y(A))}).catch(()=>{T||f({key:d,message:"This form could not be found."})}),()=>{T=!0}},[a,m,p?.id,d]);let S=(T,A)=>{y(T),g({formId:T.id,tab:A})},C=()=>g({});if(!u.formId&&!u.submissionId)return(0,Ze.jsxs)("div",{className:e,children:[(0,Ze.jsxs)("div",{className:"af-mb-6",children:[(0,Ze.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,Ze.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,Ze.jsx)(ys,{onSelectForm:S})]});let v=(0,Ze.jsxs)(R,{variant:"ghost",size:"sm",onClick:C,className:"af-mb-2 af--ml-2",children:[(0,Ze.jsx)(Qn.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]});if(c)return(0,Ze.jsxs)("div",{className:e,children:[v,(0,Ze.jsx)("p",{className:"af-text-sm af-text-destructive",children:c})]});if(!m||p?.id!==m)return(0,Ze.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,Ze.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})});let _=u.submissionId?"submissions":u.tab??"submissions";return(0,Ze.jsxs)("div",{className:e,children:[(0,Ze.jsxs)("div",{className:"af-mb-6",children:[v,(0,Ze.jsx)("h2",{className:"af-text-lg af-font-semibold",children:p.name})]}),(0,Ze.jsxs)(ir,{value:_,onValueChange:T=>g({formId:m,tab:T}),children:[(0,Ze.jsxs)(vs,{className:"af-mb-4",children:[(0,Ze.jsxs)($a,{value:"submissions",className:"af-gap-2",children:[(0,Ze.jsx)(Qn.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,Ze.jsxs)($a,{value:"settings",className:"af-gap-2",children:[(0,Ze.jsx)(Qn.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,Ze.jsx)(Va,{value:"submissions",children:(0,Ze.jsx)(Rs,{formId:m,submissionId:u.submissionId,onSelectSubmission:T=>g({formId:m,tab:"submissions",submissionId:T??void 0})})}),(0,Ze.jsx)(Va,{value:"settings",children:(0,Ze.jsx)(ks,{form:p,onSaved:y})})]})]})}var ze=re(require("react"),1);var Za=re(require("react"),1);function cn(){let{api:e}=ae(),[t,n]=Za.useState(null),[s,a]=Za.useState(!0),[r,o]=Za.useState(null),u=Za.useRef(0),g=Za.useCallback(async()=>{let l=++u.current;try{a(!0),o(null);let i=await e.getPaymentsStatus();if(l!==u.current)return;n(i)}catch(i){if(l!==u.current)return;o(i instanceof Error?i:new Error("Failed to fetch payments status"))}finally{l===u.current&&a(!1)}},[e]);return Za.useEffect(()=>{g()},[g]),{status:t,isLoading:s,error:r,refetch:g}}var hc=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function ha(e){return hc.has(e.toLowerCase())}function K(e,t,n){let s=ha(t)?e:e/100;try{return new Intl.NumberFormat(n,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function Ja(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 It(e,t){let n=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(n)||n<0)return null;let s=ha(t)?n:n*100;return Math.round(s)}function nt(e,t){return ha(t)?e:e/100}function fr(e){return e.amount_paid??Math.max(0,Ja(e)-(e.credit_applied??0))}var le=require("react/jsx-runtime");function Es(e){return e instanceof ht&&e.status===404?"Promo management is not available yet. Try again after the service is updated.":e instanceof Error?e.message:"Could not complete the request."}function ho(e){return e.percent_off!=null?`${e.percent_off}% off`:e.amount_off!=null&&e.currency?`${K(e.amount_off,e.currency)} off`:"Discount unavailable"}function Dn(){let{api:e,siteToken:t}=ae();return(0,le.jsx)(xc,{api:e},t)}function xc({api:e}){let{status:t,error:n}=cn(),[s,a]=ze.useState([]),[r,o]=ze.useState(null),[u,g]=ze.useState(null),[l,i]=ze.useState(!1),[d,b]=ze.useState(!1),[f,c]=ze.useState(""),[m,p]=ze.useState(null),[y,S]=ze.useState(null),[C,E]=ze.useState(!1),v=ze.useRef(0),_=ze.useCallback(async N=>{let k=++v.current;i(!0),c("");try{let L=await e.getPromos(N);if(k!==v.current)return;a(P=>N?[...P,...L.promos.filter(Y=>!P.some(J=>J.id===Y.id))]:L.promos),o(L.next_cursor),g(L.checkout_enabled)}catch(L){k===v.current&&c(Es(L))}finally{k===v.current&&i(!1)}},[e]);ze.useEffect(()=>(_(),()=>{v.current++}),[_]);async function T(N){let k=++v.current;i(!0),c(""),E(!1);try{let L=await e.getPromo(N);k===v.current&&p(L)}catch(L){k===v.current&&c(Es(L))}finally{k===v.current&&i(!1)}}async function A(){if(m){b(!0),i(!0),c("");try{let N=await e.disablePromo(m.id);if(p(N),!["inactive","expired","exhausted"].includes(N.status))throw new Error("The code could not be confirmed disabled. Refresh its details or retry disabling it.");E(!1),await _()}catch(N){c(Es(N))}finally{b(!1),i(!1)}}}return y?(0,le.jsx)(wc,{currency:t?.currency??void 0,replaces:y.replaces,onCancel:()=>S(null),onSave:async N=>{let k=y.replaces?await e.replacePromo(y.replaces.id,N):await e.createPromo(N),L=await e.getPromo(k.id);if(L.status==="pending"||L.status==="unavailable")throw new Error("The promotion could not be confirmed. Retry the same request.");p(L),S(null),await _()}}):(0,le.jsxs)("section",{className:"af-space-y-4","aria-label":"Promo codes",children:[(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-3",children:[(0,le.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Promo codes"}),(0,le.jsx)(R,{disabled:l||!t?.currency,onClick:()=>{c(""),S({})},children:"Create promo code"})]}),(0,le.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."}),u===!1&&(0,le.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,le.jsx)("p",{className:"af-text-sm",children:n?Es(n):"Connect Stripe and set the payment currency before creating codes."}),f&&(0,le.jsxs)("div",{role:"alert",className:"af-text-sm af-text-destructive",children:[f," ",(0,le.jsx)(R,{variant:"outline",disabled:l,onClick:()=>m?void T(m.id):void _(),children:"Refresh"})]}),m?(0,le.jsxs)("div",{className:"af-space-y-3 af-rounded-lg af-border af-p-4",children:[(0,le.jsx)(R,{variant:"ghost",disabled:d,onClick:()=>{p(null),E(!1),_()},children:"Back to codes"}),(0,le.jsxs)("h4",{className:"af-font-semibold af-break-all",children:[m.code," \xB7 ",m.name]}),(0,le.jsxs)("p",{children:[ho(m)," \xB7 ",m.status]}),(0,le.jsxs)("p",{className:"af-text-sm",children:[m.times_redeemed==null?"Usage unavailable":`${m.times_redeemed} redemptions`,m.max_redemptions!=null?` / ${m.max_redemptions} maximum`:""]}),(0,le.jsxs)("p",{className:"af-text-sm",children:[m.minimum_amount!=null&&m.currency?`Minimum order: ${K(m.minimum_amount,m.currency)}. `:"No minimum order. ","For subscriptions, the minimum applies to the initial payment only."]}),(0,le.jsxs)("p",{className:"af-text-sm",children:["Subscription discount:"," ",m.duration==="repeating"?`${m.duration_in_months} months`:m.duration==="forever"?"every invoice":"first invoice only",". One-time purchases receive one discount."]}),(0,le.jsx)("p",{className:"af-text-sm",children:m.expires_at?`Expires ${new Date(m.expires_at).toLocaleString()}`:"No expiry"}),(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,le.jsx)(R,{variant:"outline",disabled:l,onClick:()=>void T(m.id),children:"Refresh details"}),(0,le.jsx)(R,{variant:"outline",disabled:l||m.status==="pending"||m.status==="unavailable"||!t?.currency,onClick:()=>S({replaces:m}),children:"Replace with new code"}),(0,le.jsx)(R,{variant:"outline",disabled:l||!["active","pending","unavailable"].includes(m.status),onClick:()=>E(!0),children:m.status==="pending"?"Cancel pending offer":"Disable code"})]}),C&&(0,le.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,le.jsxs)("p",{className:"af-text-sm",children:[m.status==="pending"?"Cancel this pending offer? Any code already created will be disabled. The original code will keep its current state. ":`Disable ${m.code} for new purchases? `,"Discounts already applied to subscriptions will continue."]}),(0,le.jsx)(R,{disabled:l,onClick:()=>void A(),children:m.status==="pending"?"Confirm cancellation":"Confirm disable"})," ",(0,le.jsx)(R,{variant:"ghost",disabled:l,onClick:()=>E(!1),children:"Cancel"})]})]}):(0,le.jsxs)(le.Fragment,{children:[s.map(N=>(0,le.jsxs)("button",{type:"button",disabled:l,onClick:()=>void T(N.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,le.jsxs)("div",{className:"af-flex af-flex-wrap af-justify-between af-gap-2",children:[(0,le.jsx)("span",{className:"af-font-semibold af-break-all",children:N.code}),(0,le.jsx)("span",{className:"af-text-sm",children:N.status})]}),(0,le.jsxs)("div",{className:"af-text-sm",children:[ho(N)," \xB7"," ",N.times_redeemed==null?"Usage unavailable":`${N.times_redeemed} redemptions`]})]},N.id)),!l&&!f&&s.length===0&&(0,le.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."}),l&&(0,le.jsx)("p",{role:"status",children:"Loading promo codes\u2026"}),r&&(0,le.jsx)(R,{variant:"outline",disabled:l,onClick:()=>void _(r),children:"Load more"})]})]})}function wc({currency:e,replaces:t,onCancel:n,onSave:s}){let[a,r]=ze.useState(""),[o,u]=ze.useState(t?.name??""),[g,l]=ze.useState(t?.amount_off!=null?"fixed":"percent"),[i,d]=ze.useState(t?.percent_off?.toString()??(t?.amount_off!=null&&e?String(nt(t.amount_off,e)):"")),[b,f]=ze.useState(t?.minimum_amount!=null&&e?String(nt(t.minimum_amount,e)):""),[c,m]=ze.useState(()=>{if(!t?.expires_at)return"";let ce=new Date(t.expires_at);return Number.isFinite(ce.getTime())?new Date(ce.getTime()-ce.getTimezoneOffset()*6e4).toISOString().slice(0,19):""}),[p,y]=ze.useState(t?.max_redemptions?.toString()??""),[S,C]=ze.useState(t?.duration??"once"),[E,v]=ze.useState(t?.duration_in_months?.toString()??"3"),[_,T]=ze.useState(null),[A,N]=ze.useState(!1),[k,L]=ze.useState(""),P=ze.useRef(!1),Y=e&&ha(e)?"1":"0.01";async function J(ce){if(ce.preventDefault(),P.current)return;L("");let ge=_;if(!ge){if(!e){L("Payment currency is not available.");return}if(t&&a.trim().toUpperCase()===t.code.toUpperCase()){L("Choose a different code for the replacement.");return}let $=It(i,e),te=b?It(b,e):null;if(g==="fixed"&&(!$||$>999999999999)||b&&(!te||te>999999999999)){L("Enter a positive amount within the supported range.");return}if(c&&new Date(c).getTime()<=Date.now()){L("Choose a future expiry.");return}ge={request_id:crypto.randomUUID(),code:a.trim().toUpperCase(),name:o.trim(),duration:S,...g==="percent"?{percent_off:Number(i)}:{amount_off:$,currency:e},...b?{minimum_amount:te,currency:e}:{},...c?{expires_at:new Date(c).toISOString()}:{},...p?{max_redemptions:Number(p)}:{},...S==="repeating"?{duration_in_months:Number(E)}:{}},T(ge)}P.current=!0,N(!0);try{await s(ge)}catch($){L(Es($)),$ instanceof ht&&$.status>=400&&$.status<500&&$.details?.retryable!==!0&&T(null)}finally{P.current=!1,N(!1)}}let q=(ce,ge,$,te={})=>(0,le.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:[ce,(0,le.jsx)(pe,{"aria-label":ce,value:ge,onChange:U=>$(U.target.value),...te})]}),se="af-h-10 af-rounded-md af-border af-bg-background af-px-3 af-text-sm";return(0,le.jsxs)("form",{onSubmit:J,className:"af-max-w-xl af-space-y-4","aria-label":t?"Replace promo code":"Create promo code",children:[(0,le.jsx)("h3",{className:"af-text-lg af-font-semibold",children:t?`Replace ${t.code}`:"Create promo code"}),t&&(0,le.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,le.jsxs)("fieldset",{disabled:A||!!_,className:"af-grid af-gap-4",children:[q("Code",a,r,{required:!0,maxLength:40,pattern:"[a-zA-Z0-9\\-]+",autoComplete:"off"}),q("Name",o,u,{required:!0,maxLength:40}),(0,le.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Discount type",(0,le.jsxs)("select",{"aria-label":"Discount type",className:se,value:g,onChange:ce=>l(ce.target.value),children:[(0,le.jsx)("option",{value:"percent",children:"Percentage"}),(0,le.jsxs)("option",{value:"fixed",children:["Fixed amount (",e?.toUpperCase(),")"]})]})]}),q("Discount",i,d,{type:"number",required:!0,min:g==="percent"?"0.01":Y,max:g==="percent"?"100":void 0,step:g==="percent"?"0.01":Y}),q("Minimum order amount",b,f,{type:"number",min:Y,step:Y,placeholder:e?.toUpperCase()}),(0,le.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."]}),q("Expires at (local time)",c,m,{type:"datetime-local",step:1}),q("Maximum redemptions",p,y,{type:"number",min:1,max:1e6,step:1}),(0,le.jsxs)("label",{className:"af-grid af-gap-1 af-text-sm",children:["Subscription duration",(0,le.jsxs)("select",{"aria-label":"Subscription duration",className:se,value:S,onChange:ce=>C(ce.target.value),children:[(0,le.jsx)("option",{value:"once",children:"First invoice only"}),(0,le.jsx)("option",{value:"forever",children:"Every invoice"}),(0,le.jsx)("option",{value:"repeating",children:"Number of months"})]})]}),S==="repeating"&&q("Months",E,v,{type:"number",required:!0,min:1,max:36,step:1})]}),k&&(0,le.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:k}),_&&!A&&(0,le.jsxs)("p",{className:"af-text-sm",children:["The outcome is not confirmed. Retry this same request before creating another offer. Request ID:"," ",(0,le.jsx)("span",{className:"af-break-all",children:_.request_id})]}),(0,le.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[(0,le.jsx)(R,{type:"submit",disabled:A,children:A?"Saving\u2026":_?"Retry same request":t?"Create replacement":"Create code"}),(0,le.jsx)(R,{type:"button",variant:"ghost",disabled:A||!!_,onClick:n,children:"Cancel"})]})]})}var rs=re(require("react"),1),La=require("lucide-react");var mr=re(require("react"),1),un=require("lucide-react");var we=require("react/jsx-runtime");function Sc(e){if(e.allow_custom_amount){let t=e.min_amount!==null?K(e.min_amount,e.currency):"?",n=e.max_amount!==null?K(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${n})`}return e.unit_amount===null?"Varies by variant":K(e.unit_amount,e.currency)}function Nc(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Is({productsState:e,onSelectProduct:t,onCreateProduct:n,className:s}){let{products:a,isLoading:r,error:o,deleteProduct:u}=e,[g,l]=mr.useState(null),[i,d]=mr.useState(!1),[b,f]=mr.useState(null),c=async()=>{if(g)try{d(!0),f(null),await u(g.id),l(null)}catch(m){f(m instanceof Error?m.message:"Failed to delete product")}finally{d(!1)}};return r?(0,we.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,we.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):o?(0,we.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,we.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o.message]})}):a.length===0?(0,we.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,we.jsx)(un.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,we.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,we.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,we.jsxs)(R,{variant:"outline",onClick:()=>n?.(),children:[(0,we.jsx)(un.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,we.jsxs)("div",{className:s,children:[(0,we.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,we.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>n?.(),children:[(0,we.jsx)(un.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,we.jsxs)(qe,{children:[(0,we.jsx)(je,{children:(0,we.jsxs)(Re,{children:[(0,we.jsx)(j,{children:"Name"}),(0,we.jsx)(j,{children:"Price"}),(0,we.jsx)(j,{children:"Fulfillment"}),(0,we.jsx)(j,{children:"Status"}),(0,we.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,we.jsx)(Ge,{children:a.map(m=>(0,we.jsxs)(Re,{children:[(0,we.jsx)(G,{className:"af-font-medium",children:m.name}),(0,we.jsx)(G,{children:Sc(m)}),(0,we.jsx)(G,{className:"af-text-muted-foreground",children:Nc(m)}),(0,we.jsx)(G,{children:(0,we.jsx)(ne,{variant:m.active?"success":"secondary",children:m.active?"Active":"Inactive"})}),(0,we.jsx)(G,{className:"af-text-right",children:(0,we.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,we.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>t?.(m),children:[(0,we.jsx)(un.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,we.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>{f(null),l(m)},children:[(0,we.jsx)(un.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},m.id))})]}),(0,we.jsx)(Ta,{open:!!g,onOpenChange:m=>{!m&&!i&&l(null)},children:(0,we.jsxs)(fa,{children:[(0,we.jsxs)(ma,{children:[(0,we.jsx)(ga,{children:"Delete product?"}),(0,we.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.']})]}),b&&(0,we.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,we.jsxs)(pa,{children:[(0,we.jsx)(R,{variant:"outline",onClick:()=>l(null),disabled:i,children:"Cancel"}),(0,we.jsx)(R,{variant:"destructive",onClick:c,disabled:i,children:i?"Deleting...":"Delete"})]})]})})]})}var st=re(require("react"),1),xa=require("lucide-react");var xt=re(require("react"),1),Ia=require("lucide-react");var O=require("react/jsx-runtime");function ti(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function As({productId:e,currency:t,className:n}){let{api:s}=ae(),a=ha(t)?"1":"0.01",[r,o]=xt.useState(null),[u,g]=xt.useState(!0),[l,i]=xt.useState(null),[d,b]=xt.useState(null),[f,c]=xt.useState(!1),m=xt.useRef(!0);xt.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]);let p=xt.useCallback(async()=>{try{let D=await s.getProduct(e);if(!m.current)return;o(D)}catch(D){if(!m.current)return;i(D instanceof Error?D.message:"Failed to load product")}finally{m.current&&g(!1)}},[s,e]);xt.useEffect(()=>{p()},[p]);let y=async D=>{b(null),c(!0);try{await D(),await p()}catch(M){m.current&&b(M instanceof Error?M.message:"Something went wrong")}finally{m.current&&c(!1)}},[S,C]=xt.useState(""),[E,v]=xt.useState(""),[_,T]=xt.useState({}),A=()=>y(async()=>{let D=S.trim(),M=E.split(",").map(F=>F.trim()).filter(Boolean);if(!D)throw new Error("Option name is required");if(M.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:D,values:M}),m.current&&(C(""),v(""))}),N=D=>y(async()=>{let M=(_[D.id]??"").trim();if(!M)throw new Error("Enter a value");await s.updateOption(D.id,{add_values:[M]}),m.current&&T(F=>({...F,[D.id]:""}))}),k=(D,M)=>y(()=>s.updateOption(D.id,{remove_values:[M]})),L=D=>y(()=>s.deleteOption(D.id)),[P,Y]=xt.useState(null),[J,q]=xt.useState(null),[se,ce]=xt.useState(!1),[ge,$]=xt.useState(null),te=r?.options??[],U=r?.variants??[],Pe=()=>{q(null),Y({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(te.map(D=>[D.id,D.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},ue=D=>{q(null);let M=D.inventory?.on_hand??0,F=M<0?"":String(M);Y({variant:D,title:D.title??"",sku:D.sku??"",unitAmount:D.unit_amount!=null?String(nt(D.unit_amount,t)):"",compareAt:D.compare_at_amount!=null?String(nt(D.compare_at_amount,t)):"",active:D.active,optionValues:{},tracked:D.inventory?.tracked??!1,onHand:F,initialOnHand:F,allowBackorder:D.inventory?.allow_backorder??!1})},at=async()=>{if(!P)return;q(null);let D=P.variant?.allow_custom_amount??!1,M=null,F=null;if(!D){if(M=It(P.unitAmount,t),M===null||M<=0){q("Enter a valid price");return}if(P.compareAt.trim()&&(F=It(P.compareAt,t),F===null||F<=M)){q("Compare-at price must be greater than the price");return}}let ye=P.onHand.trim()!==P.initialOnHand.trim(),Ne=parseInt(P.onHand,10);if(P.tracked&&ye&&(!Number.isFinite(Ne)||Ne<0)){q("On-hand quantity must be zero or more");return}try{if(ce(!0),P.variant)await s.updateVariant(P.variant.id,{title:P.title.trim()||null,sku:P.sku.trim()||null,...D?{}:{unit_amount:M,compare_at_amount:F},active:P.active}),await s.setVariantInventory(P.variant.id,{tracked:P.tracked,on_hand:P.tracked&&ye?Ne:void 0,allow_backorder:P.allowBackorder});else{let Ee={};for(let Me of te){let ot=P.optionValues[Me.id];if(!ot){q(`Choose a ${Me.title}`),ce(!1);return}Ee[Me.title]=ot}await s.createVariant(e,{title:P.title.trim()||null,sku:P.sku.trim()||null,unit_amount:M,compare_at_amount:F,active:P.active,option_values:te.length>0?Ee:void 0,inventory:P.tracked?{tracked:!0,on_hand:Ne,allow_backorder:P.allowBackorder}:{tracked:!1,allow_backorder:P.allowBackorder}})}await p(),m.current&&Y(null)}catch(Ee){if(m.current&&q(Ee instanceof Error?Ee.message:"Failed to save variant"),P.variant)try{let Me=await s.getProduct(e);m.current&&o(Me)}catch{}}finally{m.current&&ce(!1)}},Te=()=>y(async()=>{ge&&(await s.deleteVariant(ge.id),m.current&&$(null))}),He=P?.variant?.allow_custom_amount??!1,Ye=P?.variant!=null&&P.variant.option_values.length===0&&te.length>0&&!P.variant.active,Le=P?.variant?.inventory!=null&&P.variant.inventory.on_hand<0?-P.variant.inventory.on_hand:null;function Et(D){let M=D.inventory;if(!M||!M.tracked)return(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let F=M.available??M.on_hand;return F<0?(0,O.jsxs)("span",{children:[-F," backordered"]}):(0,O.jsxs)("span",{children:[F," in stock",M.allow_backorder&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return u?(0,O.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${n||""}`,children:(0,O.jsx)(Ia.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):l?(0,O.jsx)("div",{className:n,children:(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l})}):(0,O.jsxs)("div",{className:`af-space-y-6 ${n||""}`,children:[(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)(ke,{children:"Options"}),(0,O.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."})]}),te.length>0&&(0,O.jsx)("div",{className:"af-space-y-3",children:te.map(D=>(0,O.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)("span",{className:"af-text-sm af-font-medium",children:D.title}),(0,O.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>L(D),disabled:f,children:(0,O.jsx)(Ia.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,O.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:D.values.map(M=>(0,O.jsxs)(ne,{variant:"secondary",className:"af-gap-1",children:[M.value,(0,O.jsx)("button",{type:"button",onClick:()=>k(D,M.value),className:"af-ml-1 hover:af-text-destructive",disabled:f,title:"Remove value",children:(0,O.jsx)(Ia.X,{className:"af-h-3 af-w-3"})})]},M.id))}),(0,O.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,O.jsx)(pe,{value:_[D.id]??"",onChange:M=>T(F=>({...F,[D.id]:M.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),N(D))},disabled:f}),(0,O.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>N(D),disabled:f||!(_[D.id]??"").trim(),children:(0,O.jsx)(Ia.Plus,{className:"af-h-4 af-w-4"})})]})]},D.id))}),(0,O.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,O.jsx)(pe,{id:"new-option-title",value:S,onChange:D=>C(D.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:f})]}),(0,O.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,O.jsx)(ke,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,O.jsx)(pe,{id:"new-option-values",value:E,onChange:D=>v(D.target.value),placeholder:"S, M, L",disabled:f})]}),(0,O.jsxs)(R,{type:"button",variant:"outline",onClick:A,disabled:f||!S.trim()||!E.trim(),children:[(0,O.jsx)(Ia.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-3",children:[(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,O.jsx)(ke,{children:"Variants"}),(0,O.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:Pe,disabled:f||te.length===0,children:[(0,O.jsx)(Ia.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),te.length===0&&(0,O.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),U.length===0?(0,O.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,O.jsxs)(qe,{children:[(0,O.jsx)(je,{children:(0,O.jsxs)(Re,{children:[(0,O.jsx)(j,{children:"Variant"}),(0,O.jsx)(j,{children:"SKU"}),(0,O.jsx)(j,{children:"Price"}),(0,O.jsx)(j,{children:"Stock"}),(0,O.jsx)(j,{children:"Status"}),(0,O.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,O.jsx)(Ge,{children:U.map(D=>(0,O.jsxs)(Re,{children:[(0,O.jsx)(G,{className:"af-font-medium",children:ti(D)}),(0,O.jsx)(G,{className:"af-text-muted-foreground",children:D.sku||"-"}),(0,O.jsx)(G,{children:D.unit_amount!=null?(0,O.jsxs)("span",{children:[D.compare_at_amount!=null&&(0,O.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:K(D.compare_at_amount,D.currency)}),K(D.unit_amount,D.currency)]}):D.allow_custom_amount?(0,O.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,O.jsx)(G,{children:Et(D)}),(0,O.jsx)(G,{children:(0,O.jsx)(ne,{variant:D.active?"success":"secondary",children:D.active?"Active":"Inactive"})}),(0,O.jsx)(G,{className:"af-text-right",children:(0,O.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,O.jsx)(R,{variant:"ghost",size:"sm",onClick:()=>ue(D),disabled:f,children:"Edit"}),(0,O.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>$(D),disabled:f,title:"Delete variant",children:(0,O.jsx)(Ia.Trash2,{className:"af-h-4 af-w-4"})})]})})]},D.id))})]})]}),d&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:d}),(0,O.jsx)(Ta,{open:P!==null,onOpenChange:D=>{!D&&!se&&Y(null)},children:(0,O.jsxs)(fa,{children:[(0,O.jsxs)(ma,{children:[(0,O.jsx)(ga,{children:P?.variant?"Edit variant":"Add variant"}),(0,O.jsx)(va,{children:"Price, markdown, and stock live on the variant."})]}),P&&(0,O.jsxs)("div",{className:"af-space-y-3",children:[P.variant?P.variant.option_values.length>0&&(0,O.jsxs)("div",{className:"af-text-sm",children:[(0,O.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),ti(P.variant)]}):te.map(D=>(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{className:"af-text-xs af-text-muted-foreground",children:D.title}),(0,O.jsxs)(Pa,{value:P.optionValues[D.id]??"",onValueChange:M=>Y(F=>F&&{...F,optionValues:{...F.optionValues,[D.id]:M}}),children:[(0,O.jsx)(ua,{children:(0,O.jsx)(Ca,{placeholder:`Choose ${D.title}`})}),(0,O.jsx)(da,{children:D.values.map(M=>(0,O.jsx)(et,{value:M.value,children:M.value},M.id))})]})]},D.id)),He?(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,O.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,O.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)(ke,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,O.jsx)(pe,{id:"variant-price",type:"number",min:"0",step:a,value:P.unitAmount,onChange:D=>Y(M=>M&&{...M,unitAmount:D.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,O.jsx)(pe,{id:"variant-compare",type:"number",min:"0",step:a,value:P.compareAt,onChange:D=>Y(M=>M&&{...M,compareAt:D.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,O.jsx)(pe,{id:"variant-sku",value:P.sku,onChange:D=>Y(M=>M&&{...M,sku:D.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,O.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:P.tracked,onChange:D=>Y(M=>M&&{...M,tracked:D.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),P.tracked&&(0,O.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,O.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsx)(ke,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,O.jsx)(pe,{id:"variant-onhand",type:"number",min:"0",step:"1",value:P.onHand,onChange:D=>Y(M=>M&&{...M,onHand:D.target.value}),placeholder:Le!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,O.jsx)("input",{type:"checkbox",checked:P.allowBackorder,onChange:D=>Y(M=>M&&{...M,allowBackorder:D.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),Le!=null&&(0,O.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",Le," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,O.jsxs)("div",{className:"af-space-y-1",children:[(0,O.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,O.jsx)("input",{type:"checkbox",checked:P.active,onChange:D=>Y(M=>M&&{...M,active:D.target.checked}),className:"af-h-4 af-w-4",disabled:Ye}),"Active (buyers can purchase this variant)"]}),Ye&&(0,O.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."})]}),J&&(0,O.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:J})]}),(0,O.jsxs)(pa,{children:[(0,O.jsx)(R,{variant:"outline",onClick:()=>Y(null),disabled:se,children:"Cancel"}),(0,O.jsxs)(R,{onClick:at,disabled:se,children:[se?(0,O.jsx)(Ia.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,P?.variant?"Save":"Add variant"]})]})]})}),(0,O.jsx)(Ta,{open:ge!==null,onOpenChange:D=>{!D&&!f&&$(null)},children:(0,O.jsxs)(fa,{children:[(0,O.jsxs)(ma,{children:[(0,O.jsx)(ga,{children:"Delete variant?"}),(0,O.jsx)(va,{children:ge&&`"${ti(ge)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,O.jsxs)(pa,{children:[(0,O.jsx)(R,{variant:"outline",onClick:()=>$(null),disabled:f,children:"Cancel"}),(0,O.jsx)(R,{variant:"destructive",onClick:Te,disabled:f,children:"Delete"})]})]})})]})}var Z=require("react/jsx-runtime");function Rc(e){if(e===0)return"0 B";let t=1024,n=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${n[s]}`}function Ds({productsState:e,product:t,currency:n,onSaved:s,className:a}){let{createProduct:r,updateProduct:o,attachProductFile:u,attachProductFileFromUrl:g}=e,l=!!t,i=t?.currency??n,d=ha(i)?"1":"0.01",b=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[f,c]=st.useState(!1),[m,p]=st.useState(null),y=st.useRef(!0);st.useEffect(()=>(y.current=!0,()=>{y.current=!1}),[]);let[S,C]=st.useState(t?.name??""),[E,v]=st.useState(t?.description??""),[_,T]=st.useState(t?.allow_custom_amount?"custom":"fixed"),[A,N]=st.useState(t?.unit_amount!=null?String(nt(t.unit_amount,i)):""),[k,L]=st.useState(t?.min_amount!=null?String(nt(t.min_amount,i)):""),[P,Y]=st.useState(t?.max_amount!=null?String(nt(t.max_amount,i)):""),[J,q]=st.useState(String(t?.max_quantity??10)),se=st.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(nt(t.unit_amount,i)):"",minAmount:t?.min_amount!=null?String(nt(t.min_amount,i)):"",maxAmount:t?.max_amount!=null?String(nt(t.max_amount,i)):"",maxQuantity:String(t?.max_quantity??10)}).current,[ce,ge]=st.useState(t?.collect_shipping_address??!1),[$,te]=st.useState(t?.active??!0),[U,Pe]=st.useState(t?.images??[]),[ue,at]=st.useState(""),[Te,He]=st.useState(t?.fulfillment??null),[Ye,Le]=st.useState(!1),[Et,D]=st.useState(""),[M,F]=st.useState(null),ye=st.useRef(null),Ne=f||Ye,Ee=()=>{let me=ue.trim();if(me){if(U.includes(me)){p("This image URL is already added");return}Pe(Ie=>[...Ie,me]),at(""),p(null)}},Me=me=>{Pe(Ie=>Ie.filter(lt=>lt!==me))},ot=async()=>{if(p(null),!S.trim()){p("Product name is required");return}let me=null,Ie=null,lt=null,la=!l||_!==se.pricingMode||(_==="fixed"?A!==se.unitAmount:k!==se.minAmount||P!==se.maxAmount),Ot=!l||J!==se.maxQuantity,Jt=b||_==="fixed";if(!(b||!la))if(_==="fixed"){if(me=It(A,i),me===null||me<=0){p("Enter a valid price");return}}else{if(Ie=It(k,i),lt=It(P,i),Ie===null||lt===null){p("Enter valid minimum and maximum amounts");return}if(lt<Ie){p("Maximum amount must be at least the minimum amount");return}}let Mt=parseInt(J,10);if(Jt&&Ot&&(!Number.isFinite(Mt)||Mt<1)){p("Max quantity must be at least 1");return}try{c(!0);let Ke;if(l&&t){let ct={name:S.trim(),description:E.trim()||null,images:U,collect_shipping_address:ce,active:$};!b&&la&&(ct.allow_custom_amount=_==="custom",_==="fixed"?ct.unit_amount=me:(ct.min_amount=Ie,ct.max_amount=lt)),Jt&&Ot&&(ct.max_quantity=Mt),Ke=await o(t.id,ct),se.pricingMode=Ke.allow_custom_amount?"custom":"fixed",se.unitAmount=Ke.unit_amount!=null?String(nt(Ke.unit_amount,i)):"",se.minAmount=Ke.min_amount!=null?String(nt(Ke.min_amount,i)):"",se.maxAmount=Ke.max_amount!=null?String(nt(Ke.max_amount,i)):"",se.maxQuantity=String(Ke.max_quantity)}else{let ct={name:S.trim(),allow_custom_amount:_==="custom",collect_shipping_address:ce,active:$};E.trim()&&(ct.description=E.trim()),U.length>0&&(ct.images=U),_==="fixed"?(ct.unit_amount=me,ct.max_quantity=Mt):(ct.min_amount=Ie,ct.max_amount=lt),Ke=await r(ct)}if(!y.current)return;He(Ke.fulfillment),s?.(Ke)}catch(Ke){if(!y.current)return;p(Ke instanceof Error?Ke.message:"Failed to save product")}finally{y.current&&c(!1)}},$e=async me=>{let Ie=me.target.files?.[0];if(!(!Ie||!t))try{Le(!0),F(null);let lt=await u(t.id,Ie);if(!y.current)return;He(lt.fulfillment),s?.(lt)}catch(lt){if(!y.current)return;F(lt instanceof Error?lt.message:"Failed to upload file")}finally{y.current&&(Le(!1),ye.current&&(ye.current.value=""))}},gt=async()=>{let me=Et.trim();if(!(!me||!t))try{Le(!0),F(null);let Ie=await g(t.id,me);if(!y.current)return;He(Ie.fulfillment),D(""),s?.(Ie)}catch(Ie){if(!y.current)return;F(Ie instanceof Error?Ie.message:"Failed to fetch file")}finally{y.current&&Le(!1)}};return(0,Z.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{htmlFor:"product-name",children:"Name"}),(0,Z.jsx)(pe,{id:"product-name",value:S,onChange:me=>C(me.target.value),placeholder:"My product"})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{htmlFor:"product-description",children:"Description"}),(0,Z.jsx)("textarea",{id:"product-description",value:E,onChange:me=>v(me.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,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Pricing"}),b?(0,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Pa,{value:_,onValueChange:me=>T(me),children:[(0,Z.jsx)(ua,{className:"af-w-[260px]",children:(0,Z.jsx)(Ca,{})}),(0,Z.jsxs)(da,{children:[(0,Z.jsx)(et,{value:"fixed",children:"Fixed price"}),(0,Z.jsx)(et,{value:"custom",children:"Buyer chooses the amount"})]})]}),_==="fixed"?(0,Z.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)(ke,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",i.toUpperCase(),")"]}),(0,Z.jsx)(pe,{id:"product-price",type:"number",min:"0",step:d,value:A,onChange:me=>N(me.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)(ke,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",i.toUpperCase(),")"]}),(0,Z.jsx)(pe,{id:"product-min-amount",type:"number",min:"0",step:d,value:k,onChange:me=>L(me.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsxs)(ke,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",i.toUpperCase(),")"]}),(0,Z.jsx)(pe,{id:"product-max-amount",type:"number",min:"0",step:d,value:P,onChange:me=>Y(me.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,Z.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,Z.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",i.toUpperCase(),"), which follows the country of your payment account."]})]}),(b||_==="fixed")&&(0,Z.jsxs)("div",{className:"af-space-y-1",children:[(0,Z.jsx)(ke,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,Z.jsx)(pe,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:J,onChange:me=>q(me.target.value),className:"af-w-[140px]"})]})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Images"}),(0,Z.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,Z.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[U.map(me=>(0,Z.jsxs)(ne,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,Z.jsx)("span",{className:"af-truncate",children:me}),(0,Z.jsx)("button",{type:"button",onClick:()=>Me(me),className:"af-ml-1 hover:af-text-destructive",disabled:f,children:(0,Z.jsx)(xa.X,{className:"af-h-3 af-w-3"})})]},me)),U.length===0&&(0,Z.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,Z.jsx)(pe,{type:"url",value:ue,onChange:me=>at(me.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),Ee())},disabled:f}),(0,Z.jsx)(R,{type:"button",variant:"outline",onClick:Ee,disabled:!ue.trim()||f,children:(0,Z.jsx)(xa.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Digital File"}),(0,Z.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Attach a file (PDF, ZIP, EPUB, Word, Excel, PowerPoint, CSV, image, audio, or video; max 50 MB) and buyers get a download link after paying."}),l?(0,Z.jsxs)("div",{className:"af-space-y-3",children:[Te?.type==="download"&&(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,Z.jsx)(xa.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Z.jsx)("span",{className:"af-text-sm",children:Te.filename}),Te.size!=null&&(0,Z.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Rc(Te.size),")"]})]}),Te?.type==="redirect"&&Te.url&&(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,Z.jsx)(xa.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,Z.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",Te.url]})]}),(0,Z.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,Z.jsx)("input",{ref:ye,type:"file",onChange:$e,className:"af-hidden",disabled:Ne}),(0,Z.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>ye.current?.click(),disabled:Ne,children:[Ye?(0,Z.jsx)(xa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Z.jsx)(xa.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),Te?.type==="download"?"Replace file":"Upload file"]}),(0,Z.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,Z.jsx)(pe,{type:"url",value:Et,onChange:me=>D(me.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:Ye}),(0,Z.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:gt,disabled:!Et.trim()||Ne,children:"Fetch from URL"})]}),M&&(0,Z.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:M})]}):(0,Z.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsx)(ke,{children:"Settings"}),(0,Z.jsxs)("div",{className:"af-space-y-2",children:[(0,Z.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,Z.jsx)("input",{type:"checkbox",checked:ce,onChange:me=>ge(me.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,Z.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,Z.jsx)("input",{type:"checkbox",checked:$,onChange:me=>te(me.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),l&&t&&(0,Z.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,Z.jsx)(ke,{children:"Options & Variants"}),(0,Z.jsx)(As,{productId:t.id,currency:i})]}),m&&(0,Z.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m}),(0,Z.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,Z.jsxs)(R,{type:"button",onClick:ot,disabled:Ne,children:[f?(0,Z.jsx)(xa.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,l?"Save changes":"Create product"]})})]})}var Pt=re(require("react"),1),Sa=require("lucide-react");var ut=re(require("react"),1);var _c=["pending","paid","failed","expired","refunded","partially_refunded","disputed","voided"];function Ls({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=ut.useState([]),[r,o]=ut.useState(0),[u,g]=ut.useState(!0),[l,i]=ut.useState(null),[d,b]=ut.useState(0),[f,c]=ut.useState(e),[m,p]=ut.useState(void 0),[y,S]=ut.useState(""),[C,E]=ut.useState(""),[v,_]=ut.useState(""),[T,A]=ut.useState(!1),[N,k]=ut.useState(!1),[L,P]=ut.useState(void 0),Y=L?L.join(","):"",J=ut.useMemo(()=>{if(!Y)return;let $=new Set(Y.split(","));return _c.filter(te=>!$.has(te))},[Y]),q=ut.useMemo(()=>{let $={};return m?$.status=m:J?$.excludeStatus=J:T||($.excludeStatus=["pending","expired"]),y.trim()&&($.customerEmail=y.trim()),C.trim()&&($.from=C.trim()),v.trim()&&($.to=v.trim()),N&&($.unfulfilledOnly=!0),$},[m,J,T,y,C,v,N]),se=ut.useRef(0),ce=ut.useCallback(async()=>{let $=++se.current;try{g(!0),i(null);let te={...q,limit:f,offset:d*f},U=await n.getOrders(te);if($!==se.current)return;a(U.orders),o(U.total)}catch(te){if($!==se.current)return;i(te instanceof Error?te:new Error("Failed to fetch orders"))}finally{$===se.current&&g(!1)}},[n,d,f,q,t]);ut.useEffect(()=>{ce()},[ce]);let ge=Math.ceil(r/f);return{orders:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<ge-1,hasPreviousPage:d>0,setPage:b,setPageSize:$=>{c($),b(0)},status:m,setStatus:$=>{p($),b(0)},statusIn:L,setStatusIn:$=>{P($&&$.length>0?$:void 0),b(0)},customerEmail:y,setCustomerEmail:$=>{S($),b(0)},from:C,setFrom:$=>{E($),b(0)},to:v,setTo:$=>{_($),b(0)},showAbandoned:T,setShowAbandoned:$=>{A($),b(0)},unfulfilledOnly:N,setUnfulfilledOnly:$=>{k($),b(0)},clearFilters:()=>{p(void 0),P(void 0),A(!1),k(!1),S(""),E(""),_(""),b(0)},filters:q,refetch:ce}}var bt=re(require("react"),1),Oe=require("lucide-react");var xo=re(require("react"),1),Ya=re(require("@radix-ui/react-popover"),1);var pr=require("react/jsx-runtime"),gr=Ya.Root,vr=Ya.Trigger;var Os=xo.forwardRef(({className:e,align:t="end",sideOffset:n=4,...s},a)=>(0,pr.jsx)(Ya.Portal,{children:(0,pr.jsx)("div",{className:"aifeatures-admin",children:(0,pr.jsx)(Ya.Content,{ref:a,align:t,sideOffset:n,className:ee("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),...s})})}));Os.displayName=Ya.Content.displayName;var Bs=require("react/jsx-runtime"),Pc={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed",voided:"Voided"};function Cc(e){return Pc[e]??e}function wo(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 Ln({status:e,className:t}){return(0,Bs.jsx)(ne,{variant:wo(e),className:t,children:Cc(e)})}function _n({status:e}){return(0,Bs.jsx)(Ln,{status:e})}function es({order:e,className:t}){return e.line_items.some(n=>n.collectShippingAddress===!0)?typeof e.merchant_fulfilled_at=="string"?(0,Bs.jsx)(ne,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Bs.jsx)(ne,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function dn(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var h=require("react/jsx-runtime"),_o="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",On="af-text-xs af-text-muted-foreground";function ai(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 Tc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Po(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 br=24,kc=["paid","partially_refunded"],Ec=["paid","partially_refunded","disputed"],Ic=/^[A-Za-z0-9 _-]*$/,So=100;function ri(e,t,n,s,a){let r=kc.includes(s);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"?r?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${n} of ${br} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${n} of ${br} tries used). Nothing is being retried while the order is ${s.replace(/_/g," ")} \u2014 retries resume by themselves if the order goes back to paid.`}:t==="failed_final"?n<br&&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."}:n<br&&e==="buyer"&&!a?{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 ${n} attempt${n===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 ${s==="refunded"?"because the order was refunded":s==="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 No({title:e,recipient:t,status:n,attempts:s,side:a,orderStatus:r,action:o,delivery:u}){if(u)return(0,h.jsxs)("div",{children:[(0,h.jsx)(Ka,{deliveries:[u]}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]});let g=ri(a,n,s,r,t);return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,h.jsx)(ne,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),o&&(0,h.jsx)("div",{className:"af-mt-2",children:o})]})}function Ro(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let n=Tc(e.address)?e.address:null;if(n){for(let a of["line1","line2"]){let r=n[a];typeof r=="string"&&r&&t.push(r)}let s=["city","state","postal_code"].map(a=>n[a]).filter(a=>typeof a=="string"&&!!a).join(", ");s&&t.push(s),typeof n.country=="string"&&n.country&&t.push(n.country)}return t.length>0?t:Object.entries(e).map(([s,a])=>`${s}: ${Po(a)}`)}function Ac(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function ii({value:e,label:t,children:n,className:s,size:a="icon"}){let[r,o]=bt.useState(!1);if(!Ac())return null;let u=async()=>{try{await navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),1500)}catch{}},g=r?(0,h.jsx)(Oe.Check,{className:"af-h-3 af-w-3"}):(0,h.jsx)(Oe.Copy,{className:"af-h-3 af-w-3"});return a==="icon"?(0,h.jsx)(R,{variant:"ghost",size:"icon",className:ee("af-h-6 af-w-6 af-shrink-0",s),onClick:u,title:t,"aria-label":t,children:g}):(0,h.jsxs)(R,{variant:"outline",size:"sm",className:s,onClick:u,"aria-label":t,children:[r?(0,h.jsx)(Oe.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,h.jsx)(Oe.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),r?"Copied":n]})}function ni({label:e,value:t}){return(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:e}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,h.jsx)(ii,{value:t,label:`Copy ${e}`})]})]})}function Dc({src:e}){let[t,n]=bt.useState(!1);return!e||t?(0,h.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,h.jsx)(Oe.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,h.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>n(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function Xa({title:e,action:t,children:n,className:s}){return(0,h.jsxs)("section",{className:ee("af-rounded-lg af-border af-p-4",s),children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,h.jsx)("h4",{className:_o,children:e}),t]}),(0,h.jsx)("div",{className:"af-mt-3",children:n})]})}function ea({label:e,emphasis:t,divider:n,children:s}){return(0,h.jsxs)("div",{className:ee("af-flex af-items-baseline af-justify-between af-gap-6",n&&"af-mt-2 af-border-t af-pt-2"),children:[(0,h.jsx)("span",{className:t?"af-text-base af-font-semibold":On,children:e}),(0,h.jsx)("span",{className:ee("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:s})]})}function si({onSelect:e,disabled:t,icon:n,children:s}){return(0,h.jsxs)(R,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,h.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:n}),s]})}function Lc(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 ${K(fr(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="purchase_receipt"),s=n?lr(n):ri("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(a=>a.kind==="purchase_receipt")?`Receipt emailed${e.customer_email?` to ${e.customer_email}`:""}`:`Buyer receipt \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.variant==="warning"?"warning":void 0})}if(e.merchant_email_status!=="none"){let n=e.email_deliveries?.find(a=>a.kind==="merchant_sale"),s=n?lr(n):ri("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(a=>a.kind==="merchant_sale")?"Sale notification sent":`Sale alert to you \u2014 ${s.label.toLowerCase()}`,at:null,tone:s.variant==="destructive"?"destructive":s.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 ${K(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 Fs({order:e,onBack:t,onRefund:n,onOrderUpdated:s,allowFulfillment:a=!1,onPrevOrder:r,onNextOrder:o,hasPrevOrder:u=!1,hasNextOrder:g=!1}){let{api:l}=ae(),[i,d]=bt.useState(e),[b,f]=bt.useState(null),[c,m]=bt.useState(null),[p,y]=bt.useState(!1),[S,C]=bt.useState(!1),[E,v]=bt.useState(!1),[_,T]=bt.useState(!1),[A,N]=bt.useState(""),[k,L]=bt.useState(!1),[P,Y]=bt.useState(null),[J,q]=bt.useState(!1),[se,ce]=bt.useState(""),[ge,$]=bt.useState([]),[te,U]=bt.useState(!1),[Pe,ue]=bt.useState(!1),[at,Te]=bt.useState(null);bt.useEffect(()=>{d(e)},[e]);let He=B=>{let Ue=B.id===i.id&&B.email_deliveries===void 0?{...B,email_deliveries:i.email_deliveries}:B;d(Ue),s?.(Ue)},Ye=Object.entries(i.metadata??{}),Le=Math.max(0,fr(i)-i.amount_refunded),Et=(i.status==="paid"||i.status==="partially_refunded")&&Le>0,D=i.exclusive_tax_total!=null,M=B=>typeof B.amountNet=="number"?B.amountNet+(B.exclusiveTax??0):(typeof B.unitAmount=="number"?B.unitAmount:0)*(typeof B.quantity=="number"&&B.quantity>0?B.quantity:1),F=Math.max(0,(i.shipping_total??0)-(i.shipping_refunded??0)),ye=ge.reduce((B,Ue)=>B+M(i.line_items[Ue]??{}),0)+(te?F:0),Ne=i.tax_total??0,Ee=Math.max(0,(i.exclusive_tax_total??0)-i.line_items.reduce((B,Ue)=>B+(Ue.exclusiveTax??0),0)),Me=D?te&&F>0?Ee:0:i.automatic_tax&&i.tax_behavior==="exclusive"&&Ne>0&&i.amount_total+(i.shipping_total??0)>0?Math.min(Math.max(0,Ne-(i.tax_refunded??0)),Math.round(Ne*ye/(i.amount_total+(i.shipping_total??0)))):0,ot=i.source==="subscription"&&(i.credit_applied??0)>0&&i.line_items.length===1?Math.min(ye+Me,Le):ye+Me,$e=ge.length>0||te,gt=$e?ot:It(se,i.currency),me=ha(i.currency)?"1":"0.01",Ie=async()=>{try{y(!0),f(null),m(null),await l.resendOrderReceipt(i.id);let B=await l.getOrder(i.id);He(B),m("Receipt email queued.")}catch(B){f(B instanceof Error?B.message:"Failed to resend receipt")}finally{y(!1)}},lt=async()=>{try{C(!0),f(null),m(null);let B=await l.resetOrderDownloads(i.id);He(B),v(!1),m("Download count reset.")}catch(B){f(B instanceof Error?B.message:"Failed to reset downloads")}finally{C(!1)}},la=i.line_items.some(B=>B.collectShippingAddress===!0&&!B.refunded&&!B.unavailableReason),Ot=typeof i.merchant_fulfilled_at=="string",Jt=Ec.includes(i.status)||i.status==="refunded"&&i.line_items.some(B=>B.collectShippingAddress===!0&&B.amountNet===0&&!B.refunded&&!B.unavailableReason),Mt=A.trim(),Ke=Ic.test(Mt)&&Mt.length<=So,ct=async B=>{try{L(!0),Y(null),m(null);let Ue=await l.setOrderFulfillment(i.id,{fulfilled:B,...B&&Mt?{trackingNumber:Mt}:{}});He(Ue),N(""),m(B?"Marked as shipped.":"Marked as not shipped.")}catch(Ue){Ue instanceof ht&&Ue.status===409?Y(`This order is ${i.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):Y(Ue instanceof Error?Ue.message:"Failed to update the order")}finally{L(!1)}},Ua=()=>{Te(null),ce(String(nt(Le,i.currency))),$([]),U(!1),q(!0)},kn=B=>$(Ue=>Ue.includes(B)?Ue.filter(Xt=>Xt!==B):[...Ue,B]),Yt=async(B,Ue)=>{if(n)try{ue(!0),Te(null),await n(i,B,Ue);let Xt=await l.getOrder(i.id);He(Xt),q(!1),m("Refund issued.")}catch(Xt){Te(Xt instanceof Error?Xt.message:"Refund failed")}finally{ue(!1)}},Gr=async()=>{if($e){if(ot<=0){Te("The lines you picked were charged nothing");return}if(ot>Le){Te(`That selection exceeds the refundable remainder (${K(Le,i.currency)})`);return}await Yt(ot,{...ge.length>0?{line_items:[...ge].sort((Ue,Xt)=>Ue-Xt)}:{},...te?{shipping:!0}:{}});return}let B=It(se,i.currency);if(B===null||B<=0){Te("Enter a valid refund amount");return}if(B>Le){Te(`Amount exceeds the refundable remainder (${K(Le,i.currency)})`);return}await Yt(B,{amount:B})},W=()=>Yt(Le,{full:!0}),Xe=!i.subscription_history_only&&i.fulfillment_type==="download",Ga=!i.subscription_history_only&&a&&la,Wr=Lc(i),X=i.shipping_address?Ro(i.shipping_address).join(`
4
+ `):"",jt=i.shipping_total!=null,Kr=i.exclusive_tax_total??(i.automatic_tax&&i.tax_behavior==="exclusive"?i.tax_total??0:0),Ui=i.exclusive_tax_total!=null?Math.max(0,(i.tax_total??0)-Kr):i.automatic_tax&&i.tax_behavior==="exclusive"?0:i.tax_total??0,Mi=Kr>0,Wl=Ui>0,$i=i.amount_subtotal!=null||jt||Mi||(i.discount_total??0)>0,ms=[];return i.subscription_history_only||ms.push((0,h.jsx)(si,{icon:p?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,h.jsx)(Oe.Mail,{className:"af-h-4 af-w-4"}),disabled:p||i.fulfillment_status!=="fulfilled",onSelect:()=>{T(!1),Ie()},children:"Resend receipt"},"resend")),Xe&&ms.push((0,h.jsx)(si,{icon:(0,h.jsx)(Oe.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:S,onSelect:()=>{T(!1),v(!0)},children:"Reset download count"},"reset")),Et&&ms.push((0,h.jsxs)("div",{children:[(0,h.jsx)(si,{icon:(0,h.jsx)(Oe.Undo2,{className:"af-h-4 af-w-4"}),disabled:!n,onSelect:()=>{T(!1),Ua()},children:"Refund\u2026"}),!n&&(0,h.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,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"af-mb-6",children:[(0,h.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,h.jsx)(Oe.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("h3",{className:"af-text-xl af-font-semibold",children:dn(i)}),(0,h.jsx)(Ln,{status:i.status}),a&&!i.subscription_history_only&&(0,h.jsx)(es,{order:i}),i.is_test&&(0,h.jsx)(ne,{variant:"outline",children:"Test"})]}),(0,h.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",ai(i.created_at)]}),i.is_test&&(0,h.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,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(r||o)&&(0,h.jsxs)("div",{className:"af-flex af-items-center",children:[(0,h.jsx)(R,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:r,disabled:!u,"aria-label":"Previous order",children:(0,h.jsx)(Oe.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,h.jsx)(R,{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,h.jsx)(Oe.ChevronRight,{className:"af-h-4 af-w-4"})})]}),Ga&&(Ot?(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",i.merchant_fulfilled_at?` \xB7 ${ai(i.merchant_fulfilled_at)}`:""]}),Jt&&(0,h.jsxs)(R,{variant:"ghost",size:"sm",onClick:()=>ct(!1),disabled:k,children:[k?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(Oe.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Jt?(0,h.jsxs)("div",{className:"af-flex af-flex-nowrap af-items-center af-gap-2",children:[(0,h.jsx)(pe,{value:A,onChange:B=>N(B.target.value),placeholder:"Tracking number (optional)",maxLength:So,className:"af-w-[190px] af-shrink-0","aria-label":"Tracking number (optional)",disabled:k}),(0,h.jsxs)(R,{variant:"default",className:"af-shrink-0",onClick:()=>ct(!0),disabled:k||!Ke,children:[k?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(Oe.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),ms.length>0&&(0,h.jsxs)(gr,{open:_,onOpenChange:T,children:[(0,h.jsx)(vr,{asChild:!0,children:(0,h.jsx)(R,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,h.jsx)(Oe.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,h.jsx)(Os,{children:(0,h.jsx)("div",{className:"af-space-y-0.5",children:ms})})]})]})]}),Ga&&!Ot&&!Ke&&(0,h.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."}),P&&(0,h.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:P}),c&&(0,h.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:c}),b&&(0,h.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:b})]}),(0,h.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,h.jsxs)("div",{className:"af-space-y-6",children:[i.line_items.length>0&&(0,h.jsx)(Xa,{title:"Items",children:(0,h.jsx)("ul",{className:"af-space-y-3",children:i.line_items.map((B,Ue)=>{let Xt=typeof B.name=="string"&&B.name?B.name:"Item",Vi=typeof B.quantity=="number"&&B.quantity>0?B.quantity:1,Hi=typeof B.unitAmount=="number";return(0,h.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,h.jsx)(Dc,{src:typeof B.imageUrl=="string"&&B.imageUrl?B.imageUrl:void 0}),(0,h.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,h.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Xt,typeof B.variantTitle=="string"&&B.variantTitle&&(0,h.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",B.variantTitle]})]}),(0,h.jsxs)("div",{className:On,children:[Vi," \xD7"," ",Hi?K(B.unitAmount,i.currency):"\u2014"]}),B.unavailableReason==="oversold"&&!B.refunded&&(0,h.jsx)(ne,{variant:"secondary",className:"af-mt-1",children:B.amountNet===0?"Sold out \u2014 unavailable; no payment to refund":"Sold out \u2014 unavailable"}),B.refunded===!0&&(0,h.jsx)(ne,{variant:"secondary",className:"af-mt-1",children:B.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,h.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:typeof B.amountNet=="number"||Hi?K(B.amountNet??B.unitAmount*Vi,i.currency):"\u2014"})]},Ue)})})}),Ye.length>0&&(0,h.jsx)(Xa,{title:"Order details",children:(0,h.jsx)("dl",{className:"af-space-y-2",children:Ye.map(([B,Ue])=>(0,h.jsxs)("div",{children:[(0,h.jsx)("dt",{className:ee(On,"af-capitalize"),children:B.replace(/_/g," ")}),(0,h.jsx)("dd",{className:"af-text-sm af-break-words",children:Po(Ue)})]},B))})}),(0,h.jsx)(Xa,{title:"Totals",children:(0,h.jsxs)("div",{className:"af-w-full",children:[$i&&(0,h.jsx)(ea,{label:"Subtotal",children:K(i.amount_subtotal??i.amount_total+(i.discount_total??0),i.currency)}),(i.discount_total??0)>0&&(0,h.jsxs)(ea,{label:"Discount",children:["\u2212",K(i.discount_total,i.currency)]}),jt&&(0,h.jsx)(ea,{label:"Shipping",children:i.shipping_total===0?"Free":K(i.shipping_total??0,i.currency)}),Mi&&(0,h.jsx)(ea,{label:"Tax",children:K(Kr,i.currency)}),(0,h.jsx)(ea,{label:"Total",emphasis:!0,divider:$i,children:K(Ja(i),i.currency)}),(i.credit_applied??0)>0&&(0,h.jsxs)(ea,{label:"Credit applied",children:["\u2212",K(i.credit_applied,i.currency)]}),i.amount_paid!=null&&(0,h.jsx)(ea,{label:"Amount paid",children:K(i.amount_paid,i.currency)}),Wl&&(0,h.jsx)(ea,{label:"incl. tax",children:K(Ui,i.currency)}),i.base_currency!=null&&i.base_amount_total!=null&&(0,h.jsxs)(ea,{label:"Your price",children:[K(i.base_amount_total,i.base_currency),(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",i.currency.toUpperCase()]})]}),i.amount_refunded>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(ea,{label:"Refunded",children:["\u2212",K(i.amount_refunded,i.currency),(i.shipping_refunded??0)>0&&(0,h.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",K(i.shipping_refunded??0,i.currency)," ","shipping"]})]}),(0,h.jsx)(ea,{label:"Net",children:(0,h.jsx)("span",{className:"af-font-medium",children:K(Math.max(0,fr(i)-i.amount_refunded),i.currency)})})]})]})}),i.application_fee_state&&(0,h.jsxs)(Xa,{title:"Platform fee",children:[i.application_fee_original!=null&&(0,h.jsx)(ea,{label:"Collected",children:K(i.application_fee_original,i.application_fee_currency??i.currency)}),i.application_fee_returned!=null&&(0,h.jsx)(ea,{label:"Returned",children:K(i.application_fee_returned,i.application_fee_currency??i.currency)}),i.application_fee_retained!=null&&(0,h.jsx)(ea,{label:"Retained",children:K(i.application_fee_retained,i.application_fee_currency??i.currency)}),i.application_fee_state!=="complete"&&(0,h.jsx)("p",{className:"af-mt-2 af-text-sm af-text-muted-foreground",role:"status",children:i.application_fee_state==="pending"?"Platform fee adjustment pending":"Platform fee needs review"})]}),(0,h.jsx)(Xa,{title:"Timeline",children:(0,h.jsx)("ol",{className:"af-space-y-3",children:Wr.map(B=>(0,h.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,h.jsx)("span",{"aria-hidden":"true",className:ee("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",B.tone==="destructive"?"af-bg-destructive":B.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,h.jsxs)("div",{className:"af-min-w-0",children:[(0,h.jsx)("div",{className:"af-text-sm af-break-words",children:B.text}),B.at&&(0,h.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ai(B.at)})]})]},B.key))})})]}),(0,h.jsxs)("div",{className:"af-space-y-6",children:[(0,h.jsx)(Xa,{title:"Customer",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:"Email"}),(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,h.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:i.customer_email||(0,h.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),i.customer_email&&(0,h.jsx)(ii,{value:i.customer_email,label:"Copy email"})]})]}),i.customer_name&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:"Name"}),(0,h.jsx)("div",{className:"af-text-sm",children:i.customer_name})]}),i.customer&&(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{className:On,children:"Customer record"}),(0,h.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,h.jsx)("span",{className:"af-break-all af-text-sm",children:i.customer.name||i.customer.email}),(0,h.jsx)(ne,{variant:"secondary",children:"Linked"})]})]})]})}),i.shipping_address&&(0,h.jsx)(Xa,{title:"Ship to",action:(0,h.jsx)(ii,{value:X,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,h.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:Ro(i.shipping_address).map((B,Ue)=>(0,h.jsx)("div",{children:B},Ue))})}),i.subscription_history_only?(0,h.jsx)(Xa,{title:"Subscription history",children:(0,h.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,h.jsxs)(Xa,{title:"Emails",children:[(0,h.jsx)(Ka,{deliveries:i.email_deliveries?.filter(B=>!["purchase_receipt","merchant_sale"].includes(B.kind)),problemsOnly:!0,className:"af-mb-4"}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(0,h.jsx)(No,{side:"buyer",title:"Receipt to buyer",delivery:i.email_deliveries?.find(B=>B.kind==="purchase_receipt"),recipient:i.customer_email,status:i.buyer_email_status,attempts:i.buyer_email_attempts,orderStatus:i.status,action:(0,h.jsxs)(R,{variant:"outline",size:"sm",onClick:Ie,disabled:p||i.fulfillment_status!=="fulfilled",children:[p?(0,h.jsx)(Oe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,h.jsx)(Oe.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,h.jsx)(No,{side:"merchant",title:"Sale alert to you",delivery:i.email_deliveries?.find(B=>B.kind==="merchant_sale"),recipient:null,status:i.merchant_email_status,attempts:i.merchant_email_attempts,orderStatus:i.status})]})]}),Xe&&(0,h.jsx)(Xa,{title:"Download",children:(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,h.jsx)(Oe.Download,{className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{children:["Downloaded ",i.download_count," time",i.download_count===1?"":"s"]})]}),i.download_url&&(0,h.jsx)("a",{href:i.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,h.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,h.jsx)("summary",{className:ee(_o,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,h.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,h.jsx)(ni,{label:"Order ID",value:i.id}),i.stripe_checkout_session_id&&(0,h.jsx)(ni,{label:"Checkout session",value:i.stripe_checkout_session_id}),i.stripe_payment_intent_id&&(0,h.jsx)(ni,{label:"Payment",value:i.stripe_payment_intent_id})]})]})]})]}),(0,h.jsx)(Ta,{open:E,onOpenChange:B=>{!B&&!S&&v(!1)},children:(0,h.jsxs)(fa,{children:[(0,h.jsxs)(ma,{children:[(0,h.jsx)(ga,{children:"Reset download count?"}),(0,h.jsx)(va,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,h.jsxs)(pa,{children:[(0,h.jsx)(R,{variant:"outline",onClick:()=>v(!1),disabled:S,children:"Cancel"}),(0,h.jsx)(R,{onClick:lt,disabled:S,children:S?"Resetting...":"Reset"})]})]})}),(0,h.jsx)(Ta,{open:J,onOpenChange:B=>{!B&&!Pe&&q(!1)},children:(0,h.jsxs)(fa,{children:[(0,h.jsxs)(ma,{children:[(0,h.jsx)(ga,{children:"Refund order"}),(0,h.jsxs)(va,{children:["Refund up to ",K(Le,i.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,h.jsxs)("div",{className:"af-space-y-4",children:[(i.line_items.length>0||F>0)&&(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsx)(ke,{children:"Items"}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[i.line_items.map((B,Ue)=>{let Xt=B.refunded===!0;return(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:ge.includes(Ue),onChange:()=>kn(Ue),disabled:Pe||Xt||!!B.unavailableReason||M(B)<=0,className:"af-h-4 af-w-4"}),(0,h.jsxs)("span",{className:Xt?"af-text-muted-foreground af-line-through":void 0,children:[typeof B.name=="string"&&B.name?B.name:"Item",typeof B.variantTitle=="string"&&B.variantTitle?` \u2014 ${B.variantTitle}`:"",typeof B.quantity=="number"&&B.quantity>1?` \xD7 ${B.quantity}`:""]}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Xt?"Refunded":K(M(B),i.currency)})]},Ue)}),F>0&&(0,h.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,h.jsx)("input",{type:"checkbox",checked:te,onChange:B=>U(B.target.checked),disabled:Pe,className:"af-h-4 af-w-4"}),(0,h.jsx)("span",{children:"Shipping"}),(0,h.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:K(F,i.currency)})]})]})]}),(0,h.jsxs)("div",{className:"af-space-y-2",children:[(0,h.jsxs)(ke,{htmlFor:"refund-amount",children:["Amount (",i.currency.toUpperCase(),")"]}),(0,h.jsx)(pe,{id:"refund-amount",type:"number",min:"0",step:me,value:$e?String(nt(ot,i.currency)):se,onChange:B=>ce(B.target.value),disabled:Pe||$e}),$e&&(0,h.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),at&&(0,h.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:at}),(0,h.jsxs)(pa,{children:[(0,h.jsx)(R,{variant:"outline",onClick:()=>q(!1),disabled:Pe,children:"Cancel"}),(0,h.jsx)(R,{variant:"outline",onClick:W,disabled:Pe,children:"Refund everything"}),(0,h.jsx)(R,{variant:"destructive",onClick:Gr,disabled:Pe,children:Pe?"Refunding...":gt!==null&&gt>0?`Refund ${K(gt,i.currency)}`:"Refund"})]})]})})]})}var yr=re(require("react"),1),hr=require("lucide-react");var rt=require("react/jsx-runtime");function wt({title:e,onBackToWebsite:t,hideBackButton:n=!1,children:s,className:a}){let r=yr.useRef(null);return yr.useEffect(()=>{r.current?.focus()},[]),(0,rt.jsxs)("div",{className:ee("af-bg-background",a),children:[(0,rt.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-gap-3 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,rt.jsx)("h2",{ref:r,tabIndex:-1,"aria-live":"polite",className:"af-min-w-0 af-truncate af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!n&&(0,rt.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:t,className:"af-order-first af-shrink-0",children:[(0,rt.jsx)(hr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,rt.jsx)("div",{className:"af-p-4",children:s})]})}function ie({className:e}){return(0,rt.jsx)("div",{"aria-hidden":"true",className:ee("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function dt({label:e,children:t,detail:n,valueClassName:s}){return(0,rt.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,rt.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,rt.jsx)("div",{className:ee("af-mt-1 af-text-lg af-font-semibold",s),children:t}),n&&(0,rt.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:n})]})}function wa({message:e,onRetry:t}){return(0,rt.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,rt.jsx)("span",{children:e}),(0,rt.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,rt.jsx)(hr.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function za({icon:e,children:t}){return(0,rt.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,rt.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}function ts({icon:e,heading:t,body:n,action:s,className:a,children:r}){return(0,rt.jsxs)("div",{className:ee("af-px-6 af-py-10 af-text-center",a),children:[(0,rt.jsx)(e,{className:"af-mx-auto af-h-8 af-w-8 af-text-muted-foreground","aria-hidden":!0}),(0,rt.jsx)("h3",{className:"af-mt-3 af-text-base af-font-semibold",children:t}),(0,rt.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:n}),s&&(0,rt.jsx)(R,{type:"button",className:"af-mt-4",onClick:s.onClick,children:s.label}),r]})}var I=require("react/jsx-runtime"),Oc={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},Co={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function To(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 ko(e){let t=Array.isArray(e.line_items)?e.line_items:[],n=t[0];if(!n)return"\u2014";let s=typeof n.name=="string"&&n.name?n.name:"Item",a=typeof n.quantity=="number"&&n.quantity>0?n.quantity:1,r=a>1?`${s} \xD7${a}`:s;return t.length>1?`${r} +${t.length-1} more`:r}function xr(e){return e.customer?.name||e.customer_name||null}function Bc({onRefund:e,className:t,refreshKey:n,initialOrderId:s,showFulfillment:a=!1,emptyMessage:r,onDetailOpenChange:o,maxRows:u,onViewAll:g}){let l=typeof u=="number",{api:i}=ae(),d=Ls({refreshKey:n}),{orders:b,total:f,isLoading:c,error:m,page:p,pageSize:y,hasNextPage:S,hasPreviousPage:C,setPage:E,setPageSize:v,customerEmail:_,setCustomerEmail:T,setStatusIn:A,from:N,setFrom:k,to:L,setTo:P,showAbandoned:Y,setShowAbandoned:J,setUnfulfilledOnly:q,filters:se,refetch:ce}=d,ge=Pt.useCallback(()=>i.exportOrdersCsv(se),[i,se]),[$,te]=Pt.useState("list"),[U,Pe]=Pt.useState(null),[ue,at]=Pt.useState(""),[Te,He]=Pt.useState(""),[Ye,Le]=Pt.useState(!l&&a?"needs_shipping":"all"),[Et,D]=Pt.useState(!1),[M,F]=Pt.useState(!!s&&!l),[ye,Ne]=Pt.useState(null);Pt.useEffect(()=>{if(!s||l)return;let X=!1;return F(!0),Ne(null),i.getOrder(s).then(jt=>{X||(Pe(jt),te("detail"))}).catch(()=>{X||Ne("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{X||F(!1)}),()=>{X=!0}},[i,s,l]);let Ee=Pt.useCallback(X=>{Le(X);let jt=Co[X];A(jt.statusIn),q(jt.unfulfilledOnly)},[A,q]);Pt.useEffect(()=>{a&&!l&&q(!0)},[]);let Me=Pt.useRef(!a);Pt.useEffect(()=>{Me.current||c||(Me.current=!0,b.length===0&&Ee("all"))},[c,b.length,Ee]);let ot=$==="detail"&&!!U;Pt.useEffect(()=>{o?.(ot)},[ot,o]);let $e=(N?1:0)+(L?1:0)+(Y?1:0),gt=$e>0||!!_||!!Te,me=!!N&&!!L&&N>L,Ie=!l||!!g,lt=X=>{if(l){g?.();return}Pe(X),te("detail")},la=()=>{te("list"),Pe(null),ce()},Ot=X=>{let jt=X.trim();if(!jt){He(""),_&&T("");return}if(jt.startsWith("#")||/^\d+$/.test(jt)){He(jt),_&&T("");return}He(""),T(jt)},Jt=()=>{at(""),He(""),T(""),k(""),P(""),J(!1),D(!1)},Mt=Te.replace(/^#/,"").toLowerCase(),Ke=Mt?b.filter(X=>String(X.order_number??"")===Mt||X.id.toLowerCase().startsWith(Mt)):b,ct=l?Ke.slice(0,u):Ke,Ua=U?b.findIndex(X=>X.id===U.id):-1,kn=Ua>0,Yt=Ua>=0&&Ua<b.length-1;if(M)return(0,I.jsx)("div",{className:t,children:(0,I.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,I.jsx)(Sa.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if($==="detail"&&U)return(0,I.jsx)("div",{className:t,children:(0,I.jsx)(Fs,{order:U,onBack:la,onRefund:e,onOrderUpdated:X=>Pe(X),allowFulfillment:a,onPrevOrder:kn?()=>Pe(b[Ua-1]):void 0,onNextOrder:Yt?()=>Pe(b[Ua+1]):void 0,hasPrevOrder:kn,hasNextOrder:Yt},U.id)});let W=(0,I.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[ye&&(0,I.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:ye}),(0,I.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,I.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:(a?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(X=>(0,I.jsx)("button",{type:"button","aria-pressed":Ye===X,onClick:()=>Ee(X),className:ee("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",Ye===X?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Oc[X]},X))}),(0,I.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,I.jsx)(Sa.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,I.jsx)(pe,{type:"text",value:ue,onChange:X=>at(X.target.value),onBlur:()=>Ot(ue),onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),Ot(ue))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,I.jsxs)(R,{type:"button",variant:$e>0?"secondary":"ghost",size:"sm",onClick:()=>D(X=>!X),"aria-expanded":Et,children:[(0,I.jsx)(Sa.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",$e>0&&(0,I.jsx)(ne,{variant:"secondary",className:"af-ml-2",children:$e})]}),gt&&(0,I.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:Jt,children:"Clear filters"}),(0,I.jsx)(Bt,{fetchCsv:ge,filename:"orders",disabled:!!Te,className:"af-ml-auto"})]}),(Et||!!N||!!L)&&(0,I.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,I.jsx)(ke,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,I.jsx)(pe,{id:"orders-from",type:"date",value:N,max:L||void 0,onChange:X=>k(X.target.value),className:"af-w-[170px]"}),(0,I.jsx)(ke,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,I.jsx)(pe,{id:"orders-to",type:"date",value:L,min:N||void 0,onChange:X=>P(X.target.value),className:"af-w-[170px]"}),!Co[Ye].statusIn&&(0,I.jsx)(R,{type:"button",variant:Y?"secondary":"ghost",size:"sm",onClick:()=>J(!Y),"aria-pressed":Y,children:Y?"Hide abandoned":"Show abandoned"})]}),me&&(0,I.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(c)return(0,I.jsxs)("div",{className:t,children:[l?null:W,(0,I.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(X=>(0,I.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,I.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,I.jsx)(ie,{className:"af-h-4 af-w-16"}),(0,I.jsx)(ie,{className:"af-h-4 af-w-14"})]}),(0,I.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-40"}),(0,I.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-24"})]},X))}),(0,I.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,I.jsxs)(qe,{children:[(0,I.jsx)(je,{children:(0,I.jsxs)(Re,{children:[(0,I.jsx)(j,{children:"Order"}),(0,I.jsx)(j,{children:"Date"}),(0,I.jsx)(j,{children:"Customer"}),(0,I.jsx)(j,{children:"Items"}),(0,I.jsx)(j,{className:"af-text-right",children:"Total"}),(0,I.jsx)(j,{children:"Status"}),(0,I.jsx)(j,{className:"af-w-8"})]})}),(0,I.jsx)(Ge,{"aria-hidden":"true",children:[0,1,2,3,4].map(X=>(0,I.jsxs)(Re,{children:[(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-14"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-24"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-40"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-4 af-w-32"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,I.jsx)(G,{children:(0,I.jsx)(ie,{className:"af-h-5 af-w-16"})}),(0,I.jsx)(G,{})]},X))})]})}),(0,I.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(m)return(0,I.jsxs)("div",{className:t,children:[l?null:W,(0,I.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,I.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,I.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>ce(),children:"Try again"})]})]});let Xe=Ye!=="all";if(Ke.length===0&&p===0)return gt||Xe?(0,I.jsxs)("div",{className:t,children:[!l&&W,(0,I.jsx)(za,{children:"No orders match these filters."})]}):(0,I.jsx)("div",{className:t,children:(0,I.jsx)(ts,{icon:Sa.Receipt,heading:"No orders yet",body:r??"Orders will appear here when someone buys from your website.",children:!l&&(0,I.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>J(!0),children:"Show abandoned checkouts"})})});let Ga=p*y+1,Wr=Math.min((p+1)*y,f);return(0,I.jsxs)("div",{className:t,children:[l?null:W,(0,I.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ct.map(X=>(0,I.jsxs)("button",{type:"button",onClick:()=>lt(X),disabled:!Ie,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${Ie?" hover:af-bg-muted/50":""}`,children:[(0,I.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,I.jsx)("span",{className:"af-font-medium",children:dn(X)}),(0,I.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:K(Ja(X),X.currency)})]}),(0,I.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,I.jsxs)("div",{className:"af-truncate af-text-sm",children:[X.customer_email||(0,I.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),xr(X)&&(0,I.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",xr(X)]})]}),(0,I.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ko(X)}),X.amount_refunded>0&&(0,I.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",K(X.amount_refunded,X.currency)," refunded"]})]}),(0,I.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,I.jsx)(Ln,{status:X.status}),(0,I.jsx)(hs,{deliveries:X.email_deliveries}),X.is_test&&(0,I.jsx)(ne,{variant:"outline",children:"Test"}),a&&(0,I.jsx)(es,{order:X}),(0,I.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:To(X.created_at)})]})]},X.id))}),(0,I.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,I.jsxs)(qe,{children:[(0,I.jsx)(je,{children:(0,I.jsxs)(Re,{children:[(0,I.jsx)(j,{children:"Order"}),(0,I.jsx)(j,{children:"Date"}),(0,I.jsx)(j,{children:"Customer"}),(0,I.jsx)(j,{children:"Items"}),(0,I.jsx)(j,{className:"af-text-right",children:"Total"}),(0,I.jsx)(j,{children:"Status"}),(0,I.jsx)(j,{className:"af-w-8"})]})}),(0,I.jsx)(Ge,{children:ct.map(X=>(0,I.jsxs)(Re,{onClick:Ie?()=>lt(X):void 0,className:Ie?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,I.jsxs)(G,{className:"af-whitespace-nowrap af-font-medium",children:[(0,I.jsx)("button",{type:"button",onClick:jt=>{jt.stopPropagation(),lt(X)},disabled:!Ie,"aria-label":`Open order ${dn(X)}`,className:`af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${Ie?" hover:af-underline":""}`,children:dn(X)}),X.is_test&&(0,I.jsx)(ne,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,I.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:To(X.created_at)}),(0,I.jsxs)(G,{className:"af-max-w-[220px]",children:[(0,I.jsx)("div",{className:"af-truncate",children:X.customer_email||(0,I.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),xr(X)&&(0,I.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:xr(X)})]}),(0,I.jsx)(G,{className:"af-max-w-[220px]",children:(0,I.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:ko(X)})}),(0,I.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,I.jsx)("div",{className:"af-font-medium af-tabular-nums",children:K(Ja(X),X.currency)}),X.amount_refunded>0&&(0,I.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",K(X.amount_refunded,X.currency)," ","refunded"]})]}),(0,I.jsx)(G,{children:(0,I.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,I.jsx)(Ln,{status:X.status}),(0,I.jsx)(hs,{deliveries:X.email_deliveries}),a&&(0,I.jsx)(es,{order:X})]})}),(0,I.jsx)(G,{className:"af-w-8 af-text-right",children:(0,I.jsx)(Sa.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},X.id))})]})}),l?null:(0,I.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,I.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,I.jsx)("span",{children:Mt?`${Ke.length} matching this page`:`Showing ${Ga}-${Wr} of ${f}`}),(0,I.jsxs)(Pa,{value:String(y),onValueChange:X=>v(Number(X)),children:[(0,I.jsx)(ua,{className:"af-w-[70px] af-h-8",children:(0,I.jsx)(Ca,{})}),(0,I.jsxs)(da,{children:[(0,I.jsx)(et,{value:"10",children:"10"}),(0,I.jsx)(et,{value:"25",children:"25"}),(0,I.jsx)(et,{value:"50",children:"50"}),(0,I.jsx)(et,{value:"100",children:"100"})]})]}),(0,I.jsx)("span",{children:"per page"})]}),(0,I.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,I.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>E(p-1),disabled:!C,children:[(0,I.jsx)(Sa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,I.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>E(p+1),disabled:!S,children:["Next",(0,I.jsx)(Sa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}function fn(e){return(0,I.jsx)(Bc,{...e},e.maxRows==null?"full":"compact")}var as=re(require("react"),1),Qa=require("lucide-react");var ta=re(require("react"),1);function Us({initialPageSize:e=25}={}){let{api:t}=ae(),[n,s]=ta.useState([]),[a,r]=ta.useState(0),[o,u]=ta.useState(!0),[g,l]=ta.useState(null),[i,d]=ta.useState(0),[b,f]=ta.useState(e),[c,m]=ta.useState(""),p=ta.useRef(0),y=ta.useCallback(async()=>{let C=++p.current;try{u(!0),l(null);let E={limit:b,offset:i*b};c.trim()&&(E.email=c.trim());let v=await t.getCustomers(E);if(C!==p.current)return;s(v.customers),r(v.total)}catch(E){if(C!==p.current)return;l(E instanceof Error?E:new Error("Failed to fetch customers"))}finally{C===p.current&&u(!1)}},[t,i,b,c]);ta.useEffect(()=>{y()},[y]);let S=Math.ceil(a/b);return{customers:n,total:a,isLoading:o,error:g,page:i,pageSize:b,hasNextPage:i<S-1,hasPreviousPage:i>0,setPage:d,setPageSize:C=>{f(C),d(0)},email:c,setEmail:C=>{m(C),d(0)},refetch:y}}var Bn=re(require("react"),1),wr=require("lucide-react");var be=require("react/jsx-runtime");function Eo(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 Fc(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let n=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return n&&t.push(n),e.country&&t.push(e.country),t}function Ms({customer:e,onBack:t,className:n}){let{api:s}=ae(),[a,r]=Bn.useState(null),[o,u]=Bn.useState([]),[g,l]=Bn.useState(!0),[i,d]=Bn.useState(null);Bn.useEffect(()=>{let c=!1;return l(!0),d(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([m,p])=>{c||(r(m),u(p.orders))}).catch(m=>{c||d(m instanceof Error?m.message:"Failed to load customer")}).finally(()=>{c||l(!1)}),()=>{c=!0}},[s,e.id,e.email]);let b=a?.addresses??[],f=a?.order_count??o.length;return(0,be.jsxs)("div",{className:n,children:[(0,be.jsxs)("div",{className:"af-mb-6",children:[(0,be.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,be.jsx)(wr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,be.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,be.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",Eo(e.created_at)]})]}),g?(0,be.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,be.jsx)(wr.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):i?(0,be.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:i}):(0,be.jsxs)("div",{className:"af-space-y-6",children:[(0,be.jsx)(Ka,{deliveries:a?.email_deliveries}),(0,be.jsxs)("div",{children:[(0,be.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,be.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,be.jsx)("span",{children:e.email})]}),e.name&&(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,be.jsx)("span",{children:e.name})]}),e.phone&&(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,be.jsx)("span",{children:e.phone})]}),(0,be.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,be.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,be.jsx)("span",{children:f})]})]})]}),b.length>0&&(0,be.jsxs)("div",{children:[(0,be.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,be.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:b.map(c=>(0,be.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[c.is_default&&(0,be.jsx)(ne,{variant:"secondary",className:"af-mb-1",children:"Default"}),Fc(c).map((m,p)=>(0,be.jsx)("div",{children:m},p))]},c.id))})]}),(0,be.jsxs)("div",{children:[(0,be.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),o.length===0?(0,be.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,be.jsxs)(qe,{children:[(0,be.jsx)(je,{children:(0,be.jsxs)(Re,{children:[(0,be.jsx)(j,{children:"Date"}),(0,be.jsx)(j,{children:"Amount"}),(0,be.jsx)(j,{children:"Status"})]})}),(0,be.jsx)(Ge,{children:o.map(c=>(0,be.jsxs)(Re,{children:[(0,be.jsx)(G,{className:"af-text-muted-foreground",children:Eo(c.created_at)}),(0,be.jsx)(G,{children:K(Ja(c),c.currency)}),(0,be.jsx)(G,{children:(0,be.jsx)(_n,{status:c.status})})]},c.id))})]})]})]})]})}var fe=require("react/jsx-runtime");function Uc(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 $s({className:e}){let{customers:t,total:n,isLoading:s,error:a,page:r,pageSize:o,hasNextPage:u,hasPreviousPage:g,setPage:l,setPageSize:i,email:d,setEmail:b,refetch:f}=Us(),{api:c}=ae(),m=as.useCallback(()=>c.exportCustomersCsv(),[c]),[p,y]=as.useState("list"),[S,C]=as.useState(null),[E,v]=as.useState(""),_=L=>{C(L),y("detail")},T=()=>{y("list"),C(null),f()};if(p==="detail"&&S)return(0,fe.jsx)("div",{className:e,children:(0,fe.jsx)(Ms,{customer:S,onBack:T})});let A=(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,fe.jsx)(pe,{type:"email",value:E,onChange:L=>v(L.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),b(E.trim()))}}),(0,fe.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>b(E.trim()),children:[(0,fe.jsx)(Qa.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),d&&(0,fe.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{v(""),b("")},children:"Clear"}),(0,fe.jsx)(Bt,{fetchCsv:m,filename:"customers",className:"af-ml-auto"})]});if(s)return(0,fe.jsxs)("div",{className:e,children:[A,(0,fe.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,fe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(a)return(0,fe.jsxs)("div",{className:e,children:[A,(0,fe.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,fe.jsxs)("div",{className:"af-text-destructive",children:["Error: ",a.message]})})]});if(t.length===0&&r===0)return(0,fe.jsxs)("div",{className:e,children:[d&&A,(0,fe.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,fe.jsx)(Qa.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,fe.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:d?"No customers match that email.":(0,fe.jsxs)(fe.Fragment,{children:["No customers yet.",(0,fe.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let N=r*o+1,k=Math.min((r+1)*o,n);return(0,fe.jsxs)("div",{className:e,children:[A,(0,fe.jsxs)(qe,{children:[(0,fe.jsx)(je,{children:(0,fe.jsxs)(Re,{children:[(0,fe.jsx)(j,{children:"Email"}),(0,fe.jsx)(j,{children:"Name"}),(0,fe.jsx)(j,{children:"Phone"}),(0,fe.jsx)(j,{children:"Customer since"}),(0,fe.jsx)(j,{className:"af-text-right",children:"Actions"})]})}),(0,fe.jsx)(Ge,{children:t.map(L=>(0,fe.jsxs)(Re,{children:[(0,fe.jsx)(G,{className:"af-font-medium",children:L.email}),(0,fe.jsx)(G,{children:L.name||(0,fe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,fe.jsx)(G,{children:L.phone||(0,fe.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,fe.jsx)(G,{className:"af-text-muted-foreground",children:Uc(L.created_at)}),(0,fe.jsx)(G,{className:"af-text-right",children:(0,fe.jsx)(R,{variant:"ghost",size:"icon",onClick:()=>_(L),title:"View customer",children:(0,fe.jsx)(Qa.Eye,{className:"af-h-4 af-w-4"})})})]},L.id))})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,fe.jsxs)("span",{children:["Showing ",N,"-",k," of ",n]}),(0,fe.jsxs)(Pa,{value:String(o),onValueChange:L=>i(Number(L)),children:[(0,fe.jsx)(ua,{className:"af-w-[70px] af-h-8",children:(0,fe.jsx)(Ca,{})}),(0,fe.jsxs)(da,{children:[(0,fe.jsx)(et,{value:"10",children:"10"}),(0,fe.jsx)(et,{value:"25",children:"25"}),(0,fe.jsx)(et,{value:"50",children:"50"}),(0,fe.jsx)(et,{value:"100",children:"100"})]})]}),(0,fe.jsx)("span",{children:"per page"})]}),(0,fe.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,fe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>l(r-1),disabled:!g,children:[(0,fe.jsx)(Qa.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,fe.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>l(r+1),disabled:!u,children:["Next",(0,fe.jsx)(Qa.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var De=re(require("react"),1),Nt=require("lucide-react");var St=re(require("react"),1);function Fn({initialPageSize:e=25,refreshKey:t,includeAggregates:n=!1}={}){let{api:s}=ae(),[a,r]=St.useState([]),[o,u]=St.useState(0),[g,l]=St.useState(null),[i,d]=St.useState(!0),[b,f]=St.useState(null),[c,m]=St.useState(0),[p,y]=St.useState(e),[S,C]=St.useState(void 0),[E,v]=St.useState(""),[_,T]=St.useState(""),[A,N]=St.useState(""),[k,L]=St.useState(""),[P,Y]=St.useState(""),J=S?S.join(","):"",q=St.useRef(0),se=St.useCallback(async()=>{let ge=++q.current;d(!0),f(null);try{let $={labels:J?J.split(","):void 0,customerEmail:E||void 0,q:_||void 0,from:A||void 0,to:k||void 0,retainerId:P||void 0,includeAggregates:n,limit:p,offset:c*p},te=await s.getInvoices($);if(ge!==q.current)return;if(c>0&&c*p>=te.total){m(Math.max(0,Math.ceil(te.total/p)-1));return}r(te.invoices),u(te.total),n&&l(te.aggregates??null)}catch($){if(ge!==q.current)return;f($ instanceof Error?$:new Error("Failed to fetch invoices"))}finally{ge===q.current&&d(!1)}},[s,J,E,_,A,k,P,c,p,n]);St.useEffect(()=>{se()},[se,t]);let ce=ge=>$=>{m(0),ge($)};return{invoices:a,total:o,aggregates:g,isLoading:i,error:b,page:c,pageSize:p,hasNextPage:(c+1)*p<o,hasPreviousPage:c>0,setPage:m,setPageSize:ce(y),labels:S,setLabels:ce(C),customerEmail:E,setCustomerEmail:ce(v),q:_,setQ:ce(T),from:A,setFrom:ce(N),to:k,setTo:ce(L),retainerId:P,setRetainerId:ce(Y),clearFilters:()=>{m(0),C(void 0),v(""),T(""),N(""),L(""),Y("")},refetch:se}}var x=require("react/jsx-runtime"),Mc={creating:"Creating",failed:"Failed",awaiting_payment:"Awaiting payment",overdue:"Overdue",payment_processing:"Payment processing",awaiting_authentication:"Awaiting authentication",paid:"Paid",paid_outside_stripe:"Paid outside Stripe",paid_by_credit:"Paid by credit",partially_refunded:"Partially refunded",refunded:"Refunded",disputed:"Disputed",voided:"Voided",uncollectible:"Marked uncollectible"};function ui(e){return e.label==="overdue"?`${e.days_overdue??0} days overdue`:Mc[e.label]??e.label}function $c(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 ci={queued:"Sending",sending:"Sending",sent:"Sent",delivered:"Delivered",bounced:"Bounced \u2014 check the address",complained:"Marked as spam",failed:"Not sent",unknown:"Delivery unknown"},Vc={invoice_sent:"Invoice",reminder:"Reminder",void:"Cancellation notice",receipt:"Receipt"};function ss({invoice:e,className:t}){return(0,x.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[(0,x.jsx)(ne,{variant:$c(e.label),className:t,children:ui(e)}),e.collection_method==="charge_automatically"&&(0,x.jsx)(ne,{variant:"secondary",children:"Managed in Stripe"})]})}function Rr({delivery:e,className:t}){if(!e)return null;let n=e.state==="bounced"||e.state==="complained"||e.state==="failed"?"destructive":e.state==="unknown"?"warning":"outline";return(0,x.jsx)(ne,{variant:n,className:t,children:ci[e.state]??e.state})}function ns(e){return e.invoice_number??`#${e.id.slice(0,8)}`}function Da(e){if(!e)return"\u2014";let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t);return Number.isNaN(n.getTime())?e:n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}var Io={open:"Open",overdue:"Overdue",paid:"Paid",all:"All"},Sr={open:["awaiting_payment","overdue","payment_processing","awaiting_authentication"],overdue:["overdue"],paid:["paid","paid_outside_stripe","paid_by_credit","partially_refunded","refunded"],all:void 0},oi=100,li=5e3;async function Hc(e,t){let n=[],s=0;for(let a=0;a<li;a+=oi){let r=await e.getInvoices({...t,limit:oi,offset:a});if(s=r.total,n.push(...r.invoices),r.invoices.length<oi||n.length>=s)break}return{invoices:n.slice(0,li),total:s,truncated:s>n.length||s>li}}function Do(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"],n=e.map(s=>[s.id,ns(s),ui(s),s.customer_name??"",s.customer_email??"",s.created_at,s.due_at??"",s.paid_at??"",s.currency.toUpperCase(),K(s.amount_subtotal,s.currency),K(s.tax_total,s.currency),K(s.amount_total,s.currency),s.amount_due===null?"":K(s.amount_due,s.currency),s.amount_paid===null?"":K(s.amount_paid,s.currency),K(s.amount_refunded,s.currency),s.payment_method??"",s.pay_url??"",s.retainer_id??"",s.replaces_order_id??"",s.replaced_by_order_id??"",s.tax_behavior??"",s.discount_total===void 0?"":K(s.discount_total,s.currency),s.collection_method??""]);return[t,...n].map(s=>s.map(fo).join(",")).join(`
5
+ `)}function zc(e){dr(new Blob([Do(e)],{type:"text/csv;charset=utf-8"}),ur("invoices"))}function qc({className:e,refreshKey:t,initialInvoiceId:n,onDetailOpenChange:s,onConnectStripe:a,onUpgradePlan:r,needsPaidPlan:o=!1,retainerFilter:u=null,onClearRetainerFilter:g,maxRows:l,onViewAll:i}){let d=typeof l=="number",{api:b}=ae(),{invoices:f,total:c,isLoading:m,error:p,page:y,pageSize:S,hasNextPage:C,hasPreviousPage:E,setPage:v,labels:_,setLabels:T,customerEmail:A,setCustomerEmail:N,q:k,setQ:L,from:P,setFrom:Y,to:J,setTo:q,retainerId:se,setRetainerId:ce,refetch:ge}=Fn({refreshKey:t}),[$,te]=De.useState(typeof l=="number"?"all":"open"),[U,Pe]=De.useState(""),[ue,at]=De.useState(null),Te=De.useRef(0),He=!d||!!i,Ye=De.useCallback(W=>{if(d){i?.();return}Te.current++,Et(!1),at(W)},[d,i]),[Le,Et]=De.useState(!1),[D,M]=De.useState(0),[F,ye]=De.useState(null),[Ne,Ee]=De.useState(!1),[Me,ot]=De.useState(0);De.useEffect(()=>{at(W=>{if(!W)return W;let Xe=f.find(Ga=>Ga.id===W.id);return Xe&&Xe!==W?Xe:W})},[f]);let[$e,gt]=De.useState(!1),[me,Ie]=De.useState(null),lt=async()=>{if(!$e){gt(!0),Ie(null);try{let{invoices:W,total:Xe,truncated:Ga}=await Hc(b,{labels:_,customerEmail:A,q:k,from:P,to:J,retainerId:se});zc(W),Ie(Ga?`Exported the first ${W.length.toLocaleString()} of ${Xe.toLocaleString()} matching invoices \u2014 narrow the filters for the rest.`:null)}catch{Ie("Couldn't export \u2014 try again.")}finally{gt(!1)}}},la=!A&&!k&&!P&&!J&&!se,[Ot,Jt]=De.useState(null);De.useEffect(()=>{if(m||c>0||!la||$!=="open")return;let W=!1;return b.getInvoices({limit:1}).then(Xe=>{W||Jt(Xe.total>0)}).catch(()=>{W||Jt(!0)}),()=>{W=!0}},[b,m,c,la,$,t]),De.useEffect(()=>{T(d?Sr.all:Sr.open)},[]),De.useEffect(()=>{let W=u?.id??"";W!==se&&(ce(W),W&&(te("all"),T(Sr.all),N(""),L(""),Pe(""),Y(""),q("")))},[u?.id]),De.useEffect(()=>{let W=!1;return Ee(!1),b.getInvoiceSettings().then(Xe=>{W||ye({payments_active:Xe.payments_active,blocked:Xe.blocked})}).catch(()=>{W||Ee(!0)}),()=>{W=!0}},[b,t,Me]),De.useEffect(()=>{if(!n||d)return;let W=!1,Xe=Te.current;return Et(!1),b.getInvoice(n).then(Ga=>{!W&&Xe===Te.current&&at(Ga)}).catch(()=>{!W&&Xe===Te.current&&Et(!0)}),()=>{W=!0}},[b,n,D,d]),De.useEffect(()=>{s?.(ue!==null)},[ue,s]);let Mt=W=>{te(W),T(Sr[W])},Ke=W=>{let Xe=W.trim();if(!Xe){k&&L(""),A&&N("");return}if(Xe.includes("@")){k&&L(""),N(Xe);return}A&&N(""),L(Xe.replace(/^#/,""))},ct=f,Ua=d?ct.slice(0,l):ct,kn=Le&&(0,x.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,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>M(W=>W+1),children:"Retry opening invoice"})]});if(ue)return(0,x.jsxs)("div",{className:e,children:[kn,(0,x.jsx)(_r,{invoice:ue,refreshKey:t,onBack:()=>{Ye(null),ge()}},ue.id)]});let Yt=(0,x.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[Ne&&(0,x.jsxs)("div",{role:"alert",className:"af-rounded-md af-border af-p-3 af-text-sm",children:["Couldn't check invoice setup. ",(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>ot(W=>W+1),children:"Retry setup check"})]}),kn,F?.blocked&&(0,x.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",F.blocked.reason?`: ${F.blocked.reason}`:"",". Reply to the email we sent you, or contact support."]}),u&&(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2 af-text-sm",children:[(0,x.jsxs)(ne,{variant:"secondary",className:"af-max-w-full af-whitespace-normal af-break-words",children:["Invoices for ",u.label]}),g&&(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:g,children:"Clear schedule filter"})]}),(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,x.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(Io).map(W=>(0,x.jsx)("button",{type:"button","aria-pressed":$===W,onClick:()=>Mt(W),className:ee("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",$===W?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Io[W]},W))}),(0,x.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,x.jsx)(Nt.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,x.jsx)(pe,{type:"text",value:U,onChange:W=>Pe(W.target.value),onBlur:()=>Ke(U),onKeyDown:W=>{W.key==="Enter"&&(W.preventDefault(),Ke(U))},placeholder:"Search email, name, or invoice #","aria-label":"Search invoices by email, name, or number",className:"af-pl-8"})]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,x.jsx)(ke,{htmlFor:"invoices-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,x.jsx)(pe,{id:"invoices-from",type:"date",value:P,max:J||void 0,onChange:W=>Y(W.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,x.jsx)(ke,{htmlFor:"invoices-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,x.jsx)(pe,{id:"invoices-to",type:"date",value:J,min:P||void 0,onChange:W=>q(W.target.value),className:"af-invoice-date af-w-[150px]"})]}),(0,x.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>void lt(),disabled:$e||m||!!p||c===0,"aria-busy":$e,children:[(0,x.jsx)(Nt.Download,{className:"af-h-4 af-w-4 af-mr-1"}),$e?"Exporting\u2026":"Export CSV (all matching)"]})]}),me&&(0,x.jsx)("div",{role:"status",className:"af-text-xs af-text-muted-foreground",children:me})]});return m?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)("div",{className:"af-space-y-3","aria-hidden":"true",children:[0,1,2,3].map(W=>(0,x.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,x.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,x.jsx)(ie,{className:"af-h-4 af-w-20"}),(0,x.jsx)(ie,{className:"af-h-4 af-w-16"})]}),(0,x.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-40"})]},W))})]}):p?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm",children:["Couldn't load your invoices."," ",(0,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>void ge(),children:"Retry"})]})]}):c===0&&la&&($==="all"||Ot===!1)&&($==="open"||$==="all")?F?.blocked?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"Invoicing is paused",body:"Contact support for help with invoicing."})]}):o?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"Invoicing is on the Pro plan.",body:"Upgrade to send invoices from the chat.",action:r?{label:"Upgrade",onClick:r}:void 0})]}):F&&!F.payments_active?(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"Check your payment setup to send invoices.",body:"Stripe payments need to be active before you can send an invoice.",action:a?{label:"Payment setup",onClick:a}:void 0})]}):(0,x.jsxs)("div",{className:e,children:[d?null:Yt,(0,x.jsx)(Nr,{heading:"No invoices yet",body:!F||Ne?"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,x.jsxs)("div",{className:e,children:[d?null:Yt,Ua.length===0?(0,x.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,x.jsxs)(x.Fragment,{children:[(0,x.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:Ua.map(W=>(0,x.jsxs)("button",{type:"button",onClick:()=>Ye(W),disabled:!He,className:`af-block af-w-full af-rounded-md af-border af-p-3 af-text-left${He?" hover:af-bg-muted/50":""}`,children:[(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,x.jsx)("span",{className:"af-font-medium",children:ns(W)}),(0,x.jsx)(ss,{invoice:W})]}),(0,x.jsx)("div",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:W.customer_name??W.customer_email??"\u2014"}),W.delivery&&(0,x.jsx)("div",{className:"af-mt-1",children:(0,x.jsx)(Rr,{delivery:W.delivery})}),(0,x.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,x.jsx)("span",{children:W.collection_method==="charge_automatically"?"Automatic collection":W.due_at?`Due ${Da(W.due_at)}`:"Due on receipt"}),(0,x.jsx)("span",{className:"af-font-medium af-tabular-nums",children:K(W.amount_due??W.amount_total,W.currency)})]})]},W.id))}),(0,x.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,x.jsxs)(qe,{children:[(0,x.jsx)(je,{children:(0,x.jsxs)(Re,{children:[(0,x.jsx)(j,{children:"Invoice"}),(0,x.jsx)(j,{children:"Created"}),(0,x.jsx)(j,{children:"Customer"}),(0,x.jsx)(j,{children:"Due"}),(0,x.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,x.jsx)(j,{children:"Status"}),(0,x.jsx)(j,{children:"Delivery"}),(0,x.jsx)(j,{className:"af-w-8"})]})}),(0,x.jsx)(Ge,{children:Ua.map(W=>(0,x.jsxs)(Re,{className:He?"af-cursor-pointer":void 0,onClick:He?()=>Ye(W):void 0,children:[(0,x.jsx)(G,{className:"af-font-medium",children:(0,x.jsx)("button",{type:"button",disabled:!He,className:`af-text-left focus-visible:af-ring-2 focus-visible:af-ring-ring${He?" hover:af-underline":""}`,onClick:Xe=>{Xe.stopPropagation(),Ye(W)},"aria-label":`Open invoice ${ns(W)}`,children:ns(W)})}),(0,x.jsx)(G,{children:Da(W.created_at)}),(0,x.jsxs)(G,{children:[(0,x.jsx)("div",{children:W.customer_name??"\u2014"}),(0,x.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:W.customer_email})]}),(0,x.jsx)(G,{children:W.collection_method==="charge_automatically"?"Automatic":W.due_at?Da(W.due_at):"On receipt"}),(0,x.jsx)(G,{className:"af-text-right af-tabular-nums",children:K(W.amount_due??W.amount_total,W.currency)}),(0,x.jsx)(G,{children:(0,x.jsx)(ss,{invoice:W})}),(0,x.jsx)(G,{children:(0,x.jsx)(Rr,{delivery:W.delivery})}),(0,x.jsx)(G,{children:(0,x.jsx)(Nt.ChevronRight,{className:"af-h-4 af-w-4 af-text-muted-foreground"})})]},W.id))})]})}),d?null:(0,x.jsxs)("div",{className:"af-mt-4 af-flex af-items-center af-justify-between af-text-sm af-text-muted-foreground",children:[(0,x.jsxs)("span",{children:[c," invoice",c===1?"":"s"]}),(0,x.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,x.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(y-1),disabled:!E,"aria-label":"Previous page",children:(0,x.jsx)(Nt.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,x.jsxs)("span",{className:"af-tabular-nums",children:[y*S+1,"\u2013",Math.min((y+1)*S,c)]}),(0,x.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>v(y+1),disabled:!C,"aria-label":"Next page",children:(0,x.jsx)(Nt.ChevronRight,{className:"af-h-4 af-w-4"})})]})]})]})]})}function Nr({heading:e,body:t,action:n}){return(0,x.jsx)(ts,{icon:Nt.FileText,heading:e,body:t,action:n})}function pn(e){return(0,x.jsx)(qc,{...e},e.maxRows==null?"full":"compact")}var mn="af-text-xs af-text-muted-foreground";function Ao(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function _r({invoice:e,onBack:t,refreshKey:n,className:s}){let{api:a}=ae(),r=De.useRef(null);De.useEffect(()=>{r.current?.focus()},[e.id]);let[o,u]=De.useState(!1),[g,l]=De.useState(null),[i,d]=De.useState(!1),[b,f]=De.useState(!1),c=De.useRef(0),[m,p]=De.useState(null),[y,S]=De.useState(!1),[C,E]=De.useState(0);De.useEffect(()=>{let P=!1;return S(!1),a.getInvoice(e.id).then(Y=>{P||p({source:e,value:Y})}).catch(()=>{P||S(!0)}),()=>{P=!0}},[a,e,n,C]);let v=m?.source===e?m.value:e,_=v.collection_method==="charge_automatically";De.useEffect(()=>(c.current++,l(null),d(!1),f(!1),u(!1),()=>{c.current++}),[a,v,n]);let T=P=>P==null?"\u2014":K(P,v.currency),A=async()=>{if(!(!v.pay_url||!Ao()))try{await navigator.clipboard.writeText(v.pay_url),u(!0),setTimeout(()=>u(!1),1500)}catch{}},N=async()=>{if(g){l(null);return}let P=++c.current;f(!1),d(!0);try{let Y=await a.getInvoicePreview(v.id);P===c.current&&l(Y)}catch{P===c.current&&f(!0)}finally{P===c.current&&d(!1)}},k=v.bill_to,L=k?[k.company,k.name,k.address?.line1,k.address?.line2,[k.address?.city,k.address?.state,k.address?.postal_code].filter(Boolean).join(", "),k.address?.country,k.tax_id?`${k.tax_id.value}`:null,k.po_number?`PO ${k.po_number}`:null,k.service_period?`Service period: ${k.service_period}`:null].filter(P=>!!P&&P.length>0):[];return(0,x.jsxs)("div",{className:s,children:[(0,x.jsxs)("div",{className:"af-mb-4",children:[(0,x.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,x.jsx)(Nt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to invoices"]}),(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,x.jsxs)("h3",{ref:r,tabIndex:-1,className:"af-text-lg af-font-semibold focus:af-outline-none",children:["Invoice ",ns(v)]}),(0,x.jsx)(ss,{invoice:v}),(0,x.jsx)(Rr,{delivery:v.delivery})]}),(0,x.jsxs)("p",{className:"af-mt-1 af-break-words af-text-sm af-text-muted-foreground",children:[v.customer_name??v.customer_email,v.customer_name&&v.customer_email?` \xB7 ${v.customer_email}`:""]})]}),y&&(0,x.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,x.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>E(P=>P+1),children:"Retry details"})]}),v.label==="failed"&&(0,x.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."}),v.label==="creating"&&(0,x.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,x.jsxs)("div",{className:"af-grid af-grid-cols-1 af-gap-4 lg:af-grid-cols-3",children:[(0,x.jsxs)("div",{className:"af-min-w-0 lg:af-col-span-2 af-space-y-4",children:[(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,x.jsxs)(qe,{children:[(0,x.jsx)(je,{children:(0,x.jsxs)(Re,{children:[(0,x.jsx)(j,{children:"Description"}),(0,x.jsx)(j,{className:"af-text-right",children:"Qty"}),(0,x.jsx)(j,{className:"af-text-right",children:"Amount"})]})}),(0,x.jsx)(Ge,{children:v.line_items.map((P,Y)=>(0,x.jsxs)(Re,{children:[(0,x.jsx)(G,{style:{overflowWrap:"anywhere"},children:P.description}),(0,x.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:P.quantity}),(0,x.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-tabular-nums",children:T(P.amount)})]},Y))})]}),(0,x.jsxs)("dl",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,x.jsx)(Pn,{label:"Subtotal",value:T(v.amount_subtotal)}),(v.discount_total??0)>0&&(0,x.jsx)(Pn,{label:"Discount",value:`-${T(v.discount_total)}`}),v.tax_total>0&&(0,x.jsx)(Pn,{label:v.tax_behavior==="inclusive"?"Tax (included)":"Tax",value:T(v.tax_total)}),(0,x.jsx)(Pn,{label:"Total",value:T(v.amount_total),strong:!0}),v.credit_applied>0&&(0,x.jsx)(Pn,{label:"Credit applied",value:`-${T(v.credit_applied)}`}),v.amount_due!==null&&v.amount_due!==v.amount_total&&(0,x.jsx)(Pn,{label:"Amount due",value:T(v.amount_due),strong:!0}),v.amount_paid!==null&&v.amount_paid>0&&(0,x.jsx)(Pn,{label:"Amount paid",value:T(v.amount_paid)}),v.amount_refunded>0&&(0,x.jsx)(Pn,{label:"Refunded",value:T(v.amount_refunded)})]}),v.credit_notes?.length>0&&(0,x.jsxs)("div",{className:"af-mt-3 af-space-y-1 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Credit notes"}),v.credit_notes.map(P=>(0,x.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-3",children:[(0,x.jsxs)("span",{className:"af-text-muted-foreground",children:[Da(P.created_at)," \xB7 ",P.origin==="dashboard"?"issued in Stripe":"refund",P.stripe_credit_note_id?"":" \xB7 being created"]}),(0,x.jsxs)("span",{className:"af-tabular-nums",children:["-",K(P.amount,P.currency)]})]},P.id))]})]}),(v.note||v.footer)&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[v.note&&(0,x.jsxs)("div",{children:[(0,x.jsx)("div",{className:mn,children:"Note"}),(0,x.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words",children:v.note})]}),v.footer&&(0,x.jsxs)("div",{children:[(0,x.jsx)("div",{className:mn,children:"Footer"}),(0,x.jsx)("div",{className:"af-whitespace-pre-wrap af-break-words af-text-muted-foreground",children:v.footer})]})]}),g&&!_&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4",children:[(0,x.jsxs)("div",{className:ee(mn,"af-break-words"),children:["Email preview \u2014 ",g.subject]}),(0,x.jsx)("p",{className:"af-mt-1 af-text-xs af-text-muted-foreground",children:"Uses current invoice details. Delivery history is shown separately."}),(0,x.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,x.jsxs)("div",{className:"af-min-w-0 af-space-y-4",children:[(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)(Aa,{label:"Created",value:Da(v.created_at)}),(0,x.jsx)(Aa,{label:"Due",value:v.collection_method==="charge_automatically"?"Managed in Stripe":v.due_at?Da(v.due_at):"On receipt"}),v.paid_at&&(0,x.jsx)(Aa,{label:"Paid",value:Da(v.paid_at)}),v.payment_method&&(0,x.jsx)(Aa,{label:"Paid by",value:v.paid_out_of_band?`${v.payment_method} (recorded outside Stripe)`:v.payment_method}),v.payment_state!=="none"&&(0,x.jsx)(Aa,{label:"Payment",value:v.payment_state==="processing"?"Processing":v.payment_state==="requires_action"?"Awaiting authentication":"Last attempt failed"}),v.delivery&&(0,x.jsx)(Aa,{label:"Delivery",value:`${ci[v.delivery.state]} \xB7 ${v.delivery.recipient}`}),v.marked_uncollectible_at&&(0,x.jsx)(Aa,{label:"Written off",value:Da(v.marked_uncollectible_at)}),v.correction_reason&&(0,x.jsx)(Aa,{label:"Correction",value:v.correction_reason}),v.replaced_by_order_id&&(0,x.jsx)(Aa,{label:"Replaced by",value:v.replaced_by_order_id}),v.collection_method==="charge_automatically"?(0,x.jsx)(Aa,{label:"Managed in Stripe",value:"Stripe manages automatic collection for this invoice. View or change its payment settings in Stripe."}):v.retainer_id&&(0,x.jsx)(Aa,{label:"Recurring invoice",value:"Sent on a recurring schedule \u2014 change the schedule, skip the next invoice or pause future invoices from the chat"}),v.replaces_order_id&&(0,x.jsx)(Aa,{label:"Replaces",value:v.replaces_order_id})]}),(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Reminders"}),_?(0,x.jsx)("div",{children:"View automatic payment reminders in Stripe."}):v.reminders.disabled?(0,x.jsx)("div",{children:"Off for this invoice."}):v.reminders.paused_until?(0,x.jsxs)("div",{children:["Paused until ",Da(v.reminders.paused_until),"."]}):v.reminders.next_at?(0,x.jsxs)("div",{children:["Next on ",Da(v.reminders.next_at),"."]}):v.reminders.final_sent_at?(0,x.jsxs)("div",{children:["Final reminder sent ",Da(v.reminders.final_sent_at),"."]}):(0,x.jsx)("div",{children:"None scheduled."}),!_&&(0,x.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["Schedule: ",v.reminders.schedule.length===0?"none":v.reminders.schedule.map(P=>P<0?`${-P}d before`:P===0?"due day":`${P}d after`).join(", ")]})]}),v.communications&&v.communications.length>0&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Email delivery history"}),v.communications.map(P=>(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-items-baseline af-justify-between af-gap-x-3 af-gap-y-1",children:[(0,x.jsxs)("span",{className:"af-min-w-0 af-break-words",children:[Vc[P.kind]??P.kind,P.kind==="reminder"&&P.slot!==null?` #${P.slot}`:"",(0,x.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",P.recipient]})]}),(0,x.jsxs)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:[ci[P.state]??P.state," \xB7 ",Da(P.state_at??P.created_at)]})]},P.id))]}),L.length>0&&(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-text-sm",children:[(0,x.jsx)("div",{className:mn,children:"Bill to"}),L.map((P,Y)=>(0,x.jsx)("div",{className:"af-break-words",children:P},Y))]}),(0,x.jsxs)("section",{className:"af-rounded-md af-border af-p-4 af-space-y-2",children:[v.pay_url&&(0,x.jsxs)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void A(),disabled:!Ao(),children:[(0,x.jsx)(Nt.Copy,{className:"af-h-4 af-w-4 af-mr-1"}),o?"Copied":_?"Copy invoice link":"Copy pay link"]}),v.pdf_url&&(0,x.jsx)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",asChild:!0,children:(0,x.jsxs)("a",{href:v.pdf_url,target:"_blank",rel:"noreferrer",children:[(0,x.jsx)(Nt.ExternalLink,{className:"af-h-4 af-w-4 af-mr-1"}),"Open PDF"]})}),!_&&(0,x.jsxs)(R,{type:"button",variant:"outline",size:"sm",className:"af-w-full",onClick:()=>void N(),disabled:i,children:[i?(0,x.jsx)(Nt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,x.jsx)(Nt.FileText,{className:"af-h-4 af-w-4 af-mr-1"}),g?"Hide email preview":b?"Retry email preview":"Show email preview"]}),b&&!_&&(0,x.jsx)("p",{role:"alert",className:"af-text-xs af-text-destructive",children:"Couldn't load the email preview. Try again."}),v.pay_url&&(0,x.jsx)("div",{className:"af-break-all af-text-xs af-text-muted-foreground",children:v.pay_url}),(0,x.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:_?"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 Aa({label:e,value:t}){return(0,x.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-3",children:[(0,x.jsx)("span",{className:ee(mn,"af-shrink-0"),children:e}),(0,x.jsx)("span",{className:"af-min-w-0 af-break-words af-text-right",children:t})]})}function Pn({label:e,value:t,strong:n}){return(0,x.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-3 af-items-center af-justify-between",children:[(0,x.jsx)("dt",{className:ee(mn,n&&"af-font-medium af-text-foreground"),children:e}),(0,x.jsx)("dd",{className:ee("af-tabular-nums",n&&"af-font-semibold"),children:t})]})}var Oo=require("lucide-react");var Be=require("react/jsx-runtime"),jc={creating:"Setting up",active:"Active",paused:"Paused",canceling:"Ends this period",canceled:"Ended",failed:"Failed"},Lo={merchant:"paused by you",plan:"paused \u2014 invoicing unavailable",suspension:"paused \u2014 payments disabled"};function Gc(e){switch(e){case"active":return"success";case"paused":case"canceling":return"warning";case"failed":return"destructive";case"canceled":return"outline";default:return"secondary"}}function Bo(e){return e.status==="paused"&&e.paused_by.length>0?e.paused_by.map(t=>Lo[t]).join("; "):e.status==="paused"?"Paused in Stripe":e.status==="canceling"&&e.paused_by.length>0?`Ends this period; ${e.paused_by.map(t=>Lo[t]).join("; ")}`:e.status==="active"&&e.skip_next_cycle?"Active \u2014 next invoice skipped":jc[e.status]}function Fo(e){let t=e.interval==="year"?"every year":"every month";return`${K(e.amount,e.currency)} ${t}`}function Wc(e){return e.status==="canceled"?`Ended ${Pr(e.canceled_at)}`:e.status==="canceling"?e.next_cycle_at?`Ends ${Pr(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 ${Pr(e.next_cycle_at)}`:"Next invoice will be skipped":e.next_cycle_at?`Next invoice ${Pr(e.next_cycle_at)}`:"Next invoice not scheduled yet"}function Pr(e){if(!e)return"\u2014";let t=e.includes("T")?e:e.replace(" ","T")+(e.length===19?"Z":""),n=new Date(t);return Number.isNaN(n.getTime())?e.slice(0,10):n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Cr({retainer:e,className:t}){return(0,Be.jsx)(ne,{variant:Gc(e.status),className:ee("af-max-w-full af-whitespace-normal af-break-words",t),children:Bo(e)})}function Un({retainers:e,isLoading:t,error:n,onRetry:s,onShowCycles:a,activeRetainerId:r,total:o,endedTotal:u=0,isLoadingMore:g=!1,onLoadMore:l,includeEnded:i=!1,onIncludeEndedChange:d,exportCsv:b,className:f}){let c=!!d;if(!t&&!n&&e.length===0&&!(c&&(i||u>0)))return null;let m=o!==void 0?Math.max(0,o-e.length):0;return(0,Be.jsxs)("section",{className:ee("af-mb-6",f),"aria-label":"Recurring invoices",children:[(0,Be.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Be.jsx)(Oo.Repeat,{className:"af-h-4 af-w-4 af-text-muted-foreground","aria-hidden":"true"}),(0,Be.jsx)("h3",{className:"af-text-sm af-font-semibold",children:"Recurring invoices"}),(0,Be.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."}),c&&(0,Be.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-ml-auto","aria-pressed":i,onClick:()=>d?.(!i),children:i?"Hide ended recurring invoices":u>0&&e.length===0?`Show ended recurring invoices (${u})`:"Show ended recurring invoices"}),b&&(0,Be.jsx)(Bt,{fetchCsv:b,filename:"retainers",className:c?void 0:"af-ml-auto"})]}),n?(0,Be.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,Be.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:s,children:"Retry"})]}):t?(0,Be.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1].map(p=>(0,Be.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,Be.jsx)(ie,{className:"af-h-4 af-w-48"}),(0,Be.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-32"})]},p))}):e.length===0?(0,Be.jsx)("div",{className:"af-rounded-md af-border af-px-3 af-py-2 af-text-sm af-text-muted-foreground",children:i?"No recurring invoices yet.":"No current recurring invoices. Select Show ended recurring invoices to view past schedules."}):(0,Be.jsx)("ul",{className:"af-grid af-grid-cols-1 af-gap-2 md:af-grid-cols-2",children:e.map(p=>{let y=r===p.id;return(0,Be.jsxs)("li",{className:ee("af-rounded-md af-border af-p-3",y&&"af-border-primary af-bg-muted/40"),children:[(0,Be.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-2",children:[(0,Be.jsxs)("div",{className:"af-min-w-0",children:[(0,Be.jsx)("div",{className:"af-truncate af-font-medium",children:p.customer_name??p.customer_email??"\u2014"}),(0,Be.jsx)("div",{className:"af-truncate af-text-sm af-text-muted-foreground",children:p.description})]}),(0,Be.jsx)(Cr,{retainer:p})]}),p.collection_method==="charge_automatically"?(0,Be.jsxs)("div",{className:"af-mt-2 af-space-y-1",children:[(0,Be.jsx)(ne,{variant:"secondary",children:"Managed in Stripe"}),(0,Be.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,Be.jsx)("div",{className:"af-mt-2 af-text-sm",children:Fo(p)}),(0,Be.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,Be.jsxs)("span",{children:[Wc(p)," \xB7 ",p.cycles.count===0?"no invoices yet":`${p.cycles.paid} paid${p.cycles.open>0?`, ${p.cycles.open} open`:""}`]}),p.cycles.count>0&&(0,Be.jsx)(R,{type:"button",variant:y?"secondary":"ghost",size:"sm",onClick:()=>a(p),"aria-pressed":y,children:y?"Showing invoices":"View invoices"})]}),p.status==="failed"&&p.operation?.last_error&&(0,Be.jsxs)("div",{className:"af-mt-2 af-text-xs af-text-destructive",children:["Couldn't be set up: ",p.operation.last_error,". Ask in the chat to try again."]})]},p.id)})}),!t&&!n&&m>0&&l&&(0,Be.jsx)("div",{className:"af-mt-2",children:(0,Be.jsx)(R,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:g,children:g?"Loading\u2026":`Load more (${m} more)`})})]})}var Uo=re(require("react"),1),Na=require("lucide-react");var _e=require("react/jsx-runtime");function Mn({onConnectStripe:e,onUpgradePlan:t,whenActive:n,className:s}){let{status:a,isLoading:r,error:o,refetch:u}=cn(),[g,l]=Uo.useState(!1),i=async()=>{l(!0);try{await u()}finally{l(!1)}};return r&&!a?(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,_e.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):o||!a?(0,_e.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,_e.jsxs)("div",{className:"af-text-destructive",children:["Error: ",o?.message||"Failed to load payment status"]})}):a.status==="active"?n!==void 0?(0,_e.jsx)("div",{className:s,children:n}):(0,_e.jsx)("div",{className:s,children:(0,_e.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,_e.jsx)(Na.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,_e.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,_e.jsxs)("div",{className:`af-space-y-4 ${s||""}`,children:[a.reason==="needs_stripe"&&(0,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,_e.jsx)(Na.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,_e.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,_e.jsxs)(R,{onClick:e,children:[(0,_e.jsx)(Na.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),a.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,_e.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,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,_e.jsx)(Na.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,_e.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,_e.jsx)(R,{onClick:t,children:"Upgrade plan"}):(0,_e.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,_e.jsxs)("div",{className:"af-space-y-3",children:[(0,_e.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,_e.jsx)(Na.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,_e.jsxs)("div",{children:[(0,_e.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),a.stripe_account_connected?(0,_e.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,_e.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,_e.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&a.stripe_account_connected&&(0,_e.jsxs)(R,{onClick:e,children:[(0,_e.jsx)(Na.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,_e.jsxs)(R,{variant:"outline",onClick:i,disabled:g,children:[g?(0,_e.jsx)(Na.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,_e.jsx)(Na.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var Wt=re(require("react"),1);function di(e,t,n){return e.map(s=>s.id===t?{...s,...n}:s)}function $n({includeStats:e=!1,refreshKey:t}={}){let{api:n}=ae(),[s,a]=Wt.useState([]),[r,o]=Wt.useState(!0),[u,g]=Wt.useState(null),l=Wt.useRef(0),i=Wt.useCallback(async()=>{let p=++l.current;try{o(!0),g(null);let y=await n.getProducts(e?{include:"stats"}:{});if(p!==l.current)return;a(y)}catch(y){if(p!==l.current)return;g(y instanceof Error?y:new Error("Failed to fetch products"))}finally{p===l.current&&o(!1)}},[n,e,t]);Wt.useEffect(()=>{i()},[i]);let d=Wt.useCallback(async p=>{let y=await n.createProduct(p);return a(S=>[y,...S]),y},[n]),b=Wt.useCallback(async(p,y)=>{let S=await n.updateProduct(p,y);return a(C=>di(C,p,S)),S},[n]),f=Wt.useCallback(async p=>{await n.deleteProduct(p),a(y=>y.filter(S=>S.id!==p))},[n]),c=Wt.useCallback(async(p,y)=>{let S=await n.attachProductFile(p,y);return a(C=>di(C,p,S)),S},[n]),m=Wt.useCallback(async(p,y)=>{let S=await n.attachProductFileFromUrl(p,y);return a(C=>di(C,p,S)),S},[n]);return{products:s,isLoading:r,error:u,refetch:i,createProduct:d,updateProduct:b,deleteProduct:f,attachProductFile:c,attachProductFileFromUrl:m}}var Kt=re(require("react"),1);var fi=["creating","active","paused","canceling"],Kc=["canceled","failed"],Zc={statuses:fi},Jc={};function Vn({refreshKey:e,includeEnded:t=!1,limit:n=50}={}){let{api:s}=ae(),[a,r]=Kt.useState([]),[o,u]=Kt.useState(0),[g,l]=Kt.useState(0),[i,d]=Kt.useState(!0),[b,f]=Kt.useState(!1),[c,m]=Kt.useState(null),[p,y]=Kt.useState(t),S=Kt.useRef(0),C=Kt.useCallback(async()=>{let v=++S.current;d(!0),f(!1),m(null);try{let _=await s.getRetainers({statuses:p?void 0:fi,limit:n,offset:0});if(v!==S.current)return;if(r(_.retainers),u(_.total),!p&&_.total===0){let T=await s.getRetainers({statuses:Kc,limit:1,offset:0});if(v!==S.current)return;l(T.total)}else l(0)}catch(_){if(v!==S.current)return;m(_ instanceof Error?_:new Error("Failed to fetch retainers"))}finally{v===S.current&&d(!1)}},[s,p,n]);Kt.useEffect(()=>{C()},[C,e]);let E=Kt.useCallback(async()=>{if(i||b||a.length>=o)return;let v=S.current;f(!0);try{let _=await s.getRetainers({statuses:p?void 0:fi,limit:n,offset:a.length});if(v!==S.current)return;r(T=>{let A=new Set(T.map(N=>N.id));return[...T,..._.retainers.filter(N=>!A.has(N.id))]}),u(_.total)}catch(_){if(v!==S.current)return;m(_ instanceof Error?_:new Error("Failed to fetch retainers"))}finally{v===S.current&&f(!1)}},[s,p,n,i,b,a.length,o]);return{retainers:a,total:o,endedTotal:g,hasMore:a.length<o,isLoading:i,isLoadingMore:b,error:c,includeEnded:p,setIncludeEnded:y,loadMore:E,refetch:C,filters:p?Jc:Zc}}var Se=require("react/jsx-runtime");function mi({className:e,defaultTab:t="products",onConnectStripe:n,onRefund:s,onUpgradePlan:a}){let[r,o]=rs.useState(t),[u,g]=rs.useState("list"),[l,i]=rs.useState(null),d=$n(),{status:b,error:f}=cn(),c=b?.currency,m=C=>{i(C),g("edit")},p=()=>{i(null),g("create")},y=()=>{g("list"),i(null)},S=C=>{i(C),g("edit")};return(0,Se.jsxs)("div",{className:e,children:[(0,Se.jsxs)("div",{className:"af-mb-6",children:[(0,Se.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,Se.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,Se.jsxs)(ir,{value:r,onValueChange:C=>o(C),children:[(0,Se.jsxs)(vs,{className:"af-mb-4 af-h-auto af-flex-wrap",children:[(0,Se.jsxs)($a,{value:"products",className:"af-gap-2",children:[(0,Se.jsx)(La.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,Se.jsxs)($a,{value:"orders",className:"af-gap-2",children:[(0,Se.jsx)(La.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,Se.jsxs)($a,{value:"invoices",className:"af-gap-2",children:[(0,Se.jsx)(La.FileText,{className:"af-h-4 af-w-4"}),"Invoices"]}),(0,Se.jsxs)($a,{value:"customers",className:"af-gap-2",children:[(0,Se.jsx)(La.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,Se.jsx)($a,{value:"promos",children:"Promo codes"}),(0,Se.jsxs)($a,{value:"setup",className:"af-gap-2",children:[(0,Se.jsx)(La.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,Se.jsx)(Va,{value:"products",children:u==="list"?(0,Se.jsx)(Is,{productsState:d,onSelectProduct:m,onCreateProduct:p}):(0,Se.jsxs)("div",{children:[(0,Se.jsxs)("div",{className:"af-mb-6",children:[(0,Se.jsxs)(R,{variant:"ghost",size:"sm",onClick:y,className:"af-mb-2 af--ml-2",children:[(0,Se.jsx)(La.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,Se.jsx)("h3",{className:"af-text-lg af-font-semibold",children:u==="create"?"New Product":l?.name})]}),u==="create"&&!c?(0,Se.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:f?(0,Se.jsxs)("div",{className:"af-text-destructive",children:["Error: ",f.message]}):(0,Se.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,Se.jsx)(Ds,{productsState:d,product:u==="edit"?l:null,currency:c??"usd",onSaved:S},u==="edit"?l?.id??"edit":"new")]})}),(0,Se.jsx)(Va,{value:"orders",children:(0,Se.jsx)(fn,{onRefund:s})}),(0,Se.jsx)(Va,{value:"invoices",children:(0,Se.jsx)(Yc,{onConnectStripe:n,onUpgradePlan:a,needsPaidPlan:b?.reason==="needs_paid_plan"})}),(0,Se.jsx)(Va,{value:"customers",children:(0,Se.jsx)($s,{})}),(0,Se.jsx)(Va,{value:"promos",children:(0,Se.jsx)(Dn,{})}),(0,Se.jsx)(Va,{value:"setup",children:(0,Se.jsx)(Mn,{onConnectStripe:n,onUpgradePlan:a})})]})]})}function Yc({onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n}){let s=Vn(),[a,r]=rs.useState(null),[o,u]=rs.useState(!1);return(0,Se.jsxs)(Se.Fragment,{children:[!o&&(0,Se.jsx)(Un,{retainers:s.retainers,isLoading:s.isLoading,error:s.error,onRetry:()=>void s.refetch(),activeRetainerId:a?.id??null,onShowCycles:g=>r(l=>l?.id===g.id?null:g),total:s.total,endedTotal:s.endedTotal,isLoadingMore:s.isLoadingMore,onLoadMore:()=>void s.loadMore(),includeEnded:s.includeEnded,onIncludeEndedChange:s.setIncludeEnded}),(0,Se.jsx)(pn,{onDetailOpenChange:u,onConnectStripe:e,onUpgradePlan:t,needsPaidPlan:n,retainerFilter:a?{id:a.id,label:`${a.customer_name??a.customer_email??"Recurring invoices"} \u2014 ${a.description}`}:null,onClearRetainerFilter:()=>r(null)})]})}var $o=re(require("react"),1);var en=re(require("react"),1);function Hn({refreshKey:e}={}){let{api:t}=ae(),[n,s]=en.useState(null),[a,r]=en.useState(!0),[o,u]=en.useState(null),g=en.useRef(0),l=en.useCallback(async()=>{let i=++g.current;try{r(!0),u(null);let d=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(i!==g.current)return;s(d)}catch(d){if(i!==g.current)return;u(d instanceof Error?d:new Error("Failed to fetch summary"))}finally{i===g.current&&r(!1)}},[t,e]);return en.useEffect(()=>{l()},[l]),{summary:n,isLoading:a,error:o,refetch:l}}var We=require("react/jsx-runtime");function Mo(e,t){if(e.settled.complete)return{headline:K(e.settled.gross,e.settled.currency),extra:[]};let n=e.totals[0];return n?{headline:K(n.gross,n.currency),extra:e.totals.slice(1).map(s=>`+ ${K(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:K(0,t),extra:[]}}function pi({refreshKey:e,initialOrderId:t,isOwner:n=!1,onRefund:s,onBackToWebsite:a,className:r}){let{summary:o,isLoading:u,error:g,refetch:l}=Hn({refreshKey:e}),[i,d]=$o.useState(!1),b=(0,We.jsx)("div",{className:"af-mb-6",children:g&&!o?(0,We.jsx)(wa,{message:"Couldn't load your revenue summary.",onRetry:()=>l()}):(0,We.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:u||!o?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(dt,{label:"This week",children:(0,We.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,We.jsx)(dt,{label:"Today",children:(0,We.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,We.jsx)(dt,{label:"Needs attention",children:(0,We.jsx)(ie,{className:"af-h-6 af-w-10"})})]}):(0,We.jsx)(We.Fragment,{children:(()=>{let f=Mo(o.revenue.d7,o.currency),c=Mo(o.revenue.today,o.currency);return(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(dt,{label:"This week",detail:f.extra.length>0?(0,We.jsx)("div",{children:f.extra.map(m=>(0,We.jsx)("div",{children:m},m))}):void 0,children:f.headline}),(0,We.jsx)(dt,{label:"Today",detail:c.extra.length>0?(0,We.jsx)("div",{children:c.extra.map(m=>(0,We.jsx)("div",{children:m},m))}):void 0,children:c.headline}),(0,We.jsx)(dt,{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,We.jsxs)(wt,{title:"Orders",onBackToWebsite:a,hideBackButton:i,className:r,children:[b,(0,We.jsx)(fn,{refreshKey:e,initialOrderId:t,onDetailOpenChange:d,showFulfillment:!0,onRefund:n?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Oa=re(require("react"),1),is=require("lucide-react");var tn=re(require("react"),1),Dr=require("lucide-react");var At=require("react/jsx-runtime"),Vo="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Cn="af-text-xs af-text-muted-foreground",Tr="af-text-sm af-font-medium af-tabular-nums",Xc=3;function Qc(e){let t=e.pricing,n=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let g=e.min_amount??t?.min_amount??null,l=e.max_amount??t?.max_amount??null;return g!==null&&l!==null?{text:`Buyer chooses (${K(g,n)} \u2013 ${K(l,n)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let a=t?.min_amount??e.unit_amount,r=t?.max_amount??e.unit_amount;if(a===null||r===null)return{text:"Varies by variant",compareAt:null};let o=a===r?K(a,n):`${K(a,n)} \u2013 ${K(r,n)}`,u=t?.compare_at_amount??null;return{text:o,compareAt:u!==null&&u>r?K(u,n):null}}function kr({product:e,className:t}){let n=Qc(e);return(0,At.jsxs)("div",{className:t,children:[(0,At.jsx)("span",{className:Tr,children:n.text}),n.compareAt&&(0,At.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:n.compareAt})]})}function Er({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,At.jsx)(ne,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,At.jsxs)(ne,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,At.jsx)(ne,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,At.jsxs)(ne,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,At.jsx)(ne,{variant:"warning",children:"Low stock"}):null}function Ir(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function Ar(e){return e.map(t=>K(t.amount,t.currency)).join(" + ")}function Ho(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${K(e.min_amount,e.currency)} \u2013 ${K(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":K(e.unit_amount,e.currency)}function zo({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,At.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let n=t.available??0;return t.allow_backorder?(0,At.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,At.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,n)}),(0,At.jsx)(ne,{variant:"secondary",children:n<0?`${Math.abs(n)} on backorder`:"Backorder"})]}):n<=0?(0,At.jsx)(ne,{variant:"destructive",children:"Out of stock"}):(0,At.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,At.jsx)("span",{className:"af-tabular-nums",children:n}),n<=Xc&&(0,At.jsx)(ne,{variant:"warning",children:"Low"})]})}var Q=require("react/jsx-runtime");function Vs({title:e,children:t,className:n}){return(0,Q.jsxs)("section",{className:ee("af-rounded-lg af-border af-p-4",n),children:[(0,Q.jsx)("h4",{className:Vo,children:e}),(0,Q.jsx)("div",{className:"af-mt-3",children:t})]})}function qo({src:e,className:t}){let[n,s]=tn.useState(!1);return tn.useEffect(()=>s(!1),[e]),!e||n?(0,Q.jsx)("div",{"aria-hidden":"true",className:ee("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,Q.jsx)(Dr.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,Q.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:ee("af-object-cover",t)})}function jo({product:e,showStats:t=!1,onBack:n}){let{api:s}=ae(),[a,r]=tn.useState(null),[o,u]=tn.useState(!0),[g,l]=tn.useState(null),[i,d]=tn.useState(0),[b,f]=tn.useState(0);tn.useEffect(()=>{let v=!1;return u(!0),l(null),s.getProduct(e.id).then(_=>{v||r(_)}).catch(_=>{v||l(_ instanceof Error?_:new Error("Failed to load product"))}).finally(()=>{v||u(!1)}),()=>{v=!0}},[s,e.id,i]);let c=a?{...e,...a}:e,m=c.images.length>0?c.images:e.images,p=m[b]??m[0],y=Ir(c),S=t?c.stats:void 0,C=a?.variants??[],E=C.length>1;return(0,Q.jsxs)("div",{children:[(0,Q.jsxs)("div",{className:"af-mb-6",children:[(0,Q.jsxs)(R,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[(0,Q.jsx)(Dr.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,Q.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,Q.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:c.name}),(0,Q.jsx)(ne,{variant:c.active?"success":"secondary",children:c.active?"Active":"Draft"}),(0,Q.jsx)(Er,{product:c})]}),(0,Q.jsx)(kr,{product:c,className:"af-mt-1"}),!c.active&&(0,Q.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,Q.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,Q.jsxs)("div",{className:"af-space-y-2",children:[(0,Q.jsx)(qo,{src:p,className:"af-h-48 af-w-full af-rounded-md af-border"}),m.length>1&&(0,Q.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:m.map((v,_)=>(0,Q.jsx)("button",{type:"button",onClick:()=>f(_),"aria-label":`Show photo ${_+1} of ${m.length}`,"aria-pressed":_===b,className:ee("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",_===b?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,Q.jsx)(qo,{src:v,className:"af-h-12 af-w-12 af-rounded-md"})},`${v}-${_}`))})]}),(0,Q.jsxs)("div",{className:"af-space-y-6",children:[c.description&&(0,Q.jsx)(Vs,{title:"Description",children:(0,Q.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:c.description})}),o?(0,Q.jsxs)(Vs,{title:"Variants",children:[(0,Q.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(v=>(0,Q.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,Q.jsx)(ie,{className:"af-h-4 af-w-28"}),(0,Q.jsx)(ie,{className:"af-h-4 af-w-20"}),(0,Q.jsx)(ie,{className:"af-h-4 af-w-16"})]},v))}),(0,Q.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):g?(0,Q.jsx)(wa,{message:"Couldn't load this product's variants.",onRetry:()=>d(v=>v+1)}):E?(0,Q.jsx)(Vs,{title:`Variants \xB7 ${C.length}`,children:(0,Q.jsx)("div",{className:"af-overflow-x-auto",children:(0,Q.jsxs)(qe,{children:[(0,Q.jsx)(je,{children:(0,Q.jsxs)(Re,{children:[(0,Q.jsx)(j,{children:"Variant"}),(0,Q.jsx)(j,{children:"SKU"}),(0,Q.jsx)(j,{className:"af-text-right",children:"Price"}),(0,Q.jsx)(j,{children:"Stock"})]})}),(0,Q.jsx)(Ge,{children:C.map(v=>(0,Q.jsxs)(Re,{children:[(0,Q.jsxs)(G,{className:"af-font-medium",children:[v.title||v.option_values.map(_=>_.value).join(" / ")||"\u2014",!v.active&&(0,Q.jsx)(ne,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,Q.jsx)(G,{className:"af-text-muted-foreground",children:v.sku?(0,Q.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:v.sku}):"\u2014"}),(0,Q.jsxs)(G,{className:"af-whitespace-nowrap af-text-right",children:[(0,Q.jsx)("div",{className:Tr,children:Ho(v)}),v.compare_at_amount!==null&&v.unit_amount!==null&&v.compare_at_amount>v.unit_amount&&(0,Q.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:K(v.compare_at_amount,v.currency)})]}),(0,Q.jsx)(G,{className:"af-text-sm",children:(0,Q.jsx)(zo,{variant:v})})]},v.id))})]})})}):null,(0,Q.jsx)(Vs,{title:"Details",children:(0,Q.jsxs)("dl",{className:"af-space-y-2",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Delivery"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:y==="Digital download"?c.fulfillment.filename??"Digital download":y??"Nothing to deliver"})]}),c.fulfillment.type==="redirect"&&c.fulfillment.url&&(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Sends buyers to"}),(0,Q.jsx)("dd",{className:"af-break-all af-text-sm",children:c.fulfillment.url})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Shipping address"}),(0,Q.jsx)("dd",{className:"af-text-sm",children:c.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Most one buyer can order"}),(0,Q.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:c.max_quantity})]})]})}),S&&(0,Q.jsx)(Vs,{title:"Last 30 days",children:(0,Q.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Units sold"}),(0,Q.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.units_sold})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Orders"}),(0,Q.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:S.orders})]}),(0,Q.jsxs)("div",{children:[(0,Q.jsx)("dt",{className:Cn,children:"Gross"}),(0,Q.jsx)("dd",{className:Tr,children:S.gross.length>0?Ar(S.gross):"\u2014"})]})]})}),(0,Q.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var z=require("react/jsx-runtime"),eu={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},tu=["all","active","draft","low_stock","out_of_stock"];function Go(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,n=new Date(t).getTime();return Number.isNaN(n)?0:n}function Wo(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function au(e){return e.inventory?.out_of_stock??!1}function nu(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Wo(e);case"out_of_stock":return au(e);default:return!0}}function su({product:e,showStats:t,onOpen:n}){let s=e.images[0],a=t?e.stats:void 0,r=Ir(e),o=e.variant_count??0;return(0,z.jsxs)("button",{type:"button",onClick:n,"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:[s?(0,z.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,z.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,z.jsx)(is.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,z.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,z.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,z.jsxs)("div",{className:"af-min-w-0",children:[(0,z.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,z.jsx)(kr,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,z.jsx)(ne,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,z.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,z.jsx)(Er,{product:e}),o>1&&(0,z.jsxs)(ne,{variant:"outline",children:[o," variants"]}),r&&(0,z.jsx)(ne,{variant:"outline",children:r})]}),a&&(0,z.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[a.units_sold," sold",a.gross.length>0?` \xB7 ${Ar(a.gross)}`:""," ",(0,z.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function ru(){return(0,z.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,z.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,z.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,z.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,z.jsx)(ie,{className:"af-w-32"}),(0,z.jsx)(ie,{className:"af-w-16"}),(0,z.jsx)(ie,{className:"af-h-5 af-w-24"})]})]},e))})}function gi({refreshKey:e,showStats:t=!1,onBackToWebsite:n,className:s}){let{products:a,isLoading:r,error:o,refetch:u}=$n({includeStats:t,refreshKey:e}),[g,l]=Oa.useState(!1),[i,d]=Oa.useState(null),[b,f]=Oa.useState("all"),{api:c}=ae(),m=Oa.useCallback(()=>c.exportProductsCsv(),[c]),[p,y]=Oa.useState(""),[S,C]=Oa.useState("newest"),E=Oa.useMemo(()=>{if(!t)return null;let J=null;for(let q of a)!q.stats||q.stats.units_sold===0||(!J||q.stats.units_sold>(J.stats?.units_sold??0))&&(J=q);return J},[a,t]),v=Oa.useMemo(()=>a.filter(Wo).length,[a]),_=p.trim().toLowerCase(),T=Oa.useMemo(()=>{let q=[...a.filter(se=>nu(se,b)&&(!_||se.name.toLowerCase().includes(_)))];return S==="name"?q.sort((se,ce)=>se.name.localeCompare(ce.name)):S==="best_selling"?q.sort((se,ce)=>(ce.stats?.units_sold??0)-(se.stats?.units_sold??0)):q.sort((se,ce)=>Go(ce.created_at)-Go(se.created_at)),q},[a,b,_,S]),A=b!=="all"||!!_,N=()=>{f("all"),y("")},k=r||o!==null&&a.length===0,L=(0,z.jsx)("div",{className:"af-mb-6",children:(0,z.jsx)("div",{className:ee("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:k?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Products",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-10"})}),t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Best seller",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-28"})}),(0,z.jsx)(dt,{label:"Low stock",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-10"})})]}):(0,z.jsx)(dt,{label:"Active",children:(0,z.jsx)(ie,{className:"af-h-6 af-w-10"})})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Products",children:a.length}),t?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(dt,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:E?`${E.stats?.units_sold??0} sold, last 30 days`:void 0,children:E?(0,z.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:E.name}):(0,z.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,z.jsx)(dt,{label:"Low stock",children:v})]}):(0,z.jsx)(dt,{label:"Active",children:a.filter(J=>J.active).length})]})})}),P=(0,z.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,z.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,z.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:tu.map(J=>(0,z.jsx)("button",{type:"button","aria-pressed":b===J,onClick:()=>f(J),className:ee("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",b===J?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:eu[J]},J))}),(0,z.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,z.jsx)(is.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,z.jsx)(pe,{type:"text",value:p,onChange:J=>y(J.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,z.jsxs)(Pa,{value:S,onValueChange:J=>C(J),children:[(0,z.jsx)(ua,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,z.jsx)(Ca,{})}),(0,z.jsxs)(da,{children:[(0,z.jsx)(et,{value:"newest",children:"Newest"}),(0,z.jsx)(et,{value:"name",children:"Name A\u2013Z"}),t&&(0,z.jsx)(et,{value:"best_selling",children:"Best selling"})]})]}),A&&(0,z.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:N,children:"Clear filters"}),(0,z.jsx)(Bt,{fetchCsv:m,filename:"products",label:A?"Export all as CSV":void 0,className:"af-ml-auto"})]}),r&&a.length===0?(0,z.jsx)(ie,{className:"af-h-4 af-w-28"}):(0,z.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:A?`${T.length} of ${a.length} products`:`${a.length} ${a.length===1?"product":"products"}${v>0?` \xB7 ${v} low stock`:""}`})]}),Y;return i?Y=(0,z.jsx)(jo,{product:i,showStats:t,onBack:()=>{d(null),u()}},i.id):r&&a.length===0?Y=(0,z.jsxs)(z.Fragment,{children:[P,(0,z.jsx)(ru,{}),(0,z.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):o&&a.length===0?Y=(0,z.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,z.jsx)(wa,{message:"Couldn't load your products.",onRetry:()=>u()})}):a.length===0?Y=(0,z.jsxs)(za,{icon:(0,z.jsx)(is.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,z.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):Y=(0,z.jsxs)(z.Fragment,{children:[P,o&&(0,z.jsx)("div",{className:"af-mb-4",children:(0,z.jsx)(wa,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>u()})}),T.length===0?(0,z.jsxs)(za,{children:["No products match these filters.",(0,z.jsx)("br",{}),(0,z.jsx)(R,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:N,children:"Show all products"})]}):(0,z.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:T.map(J=>(0,z.jsx)(su,{product:J,showStats:t,onOpen:()=>d(J)},J.id))})]}),(0,z.jsx)(wt,{title:"Products",onBackToWebsite:n,hideBackButton:!!i,className:s,children:g?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(R,{variant:"ghost",onClick:()=>l(!1),children:"Back to products"}),(0,z.jsx)(Dn,{})]}):(0,z.jsxs)(z.Fragment,{children:[!i&&(0,z.jsx)("div",{className:"af-mb-4 af-flex af-justify-end",children:(0,z.jsx)(R,{variant:"outline",onClick:()=>l(!0),children:"Promo codes"})}),!i&&L,Y]})})}var na=re(require("react"),1),yt=require("lucide-react");var aa=re(require("react"),1);function Hs({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=aa.useState([]),[r,o]=aa.useState(!0),[u,g]=aa.useState(null),[l,i]=aa.useState(0),[d]=aa.useState(e),[b,f]=aa.useState(""),[c,m]=aa.useState(void 0),p=aa.useRef(0),y=aa.useCallback(async({afterRemoval:S=!1}={})=>{let C=++p.current;try{o(!0),g(null);let E={limit:d,offset:l*d};b.trim()&&(E.q=b.trim()),c&&(E.source=c);let v=await n.getPeople(E);if(C!==p.current)return;if(S&&v.people.length===0&&l>0){i(l-1);return}a(v.people)}catch(E){if(C!==p.current)return;g(E instanceof Error?E:new Error("Failed to fetch people"))}finally{C===p.current&&o(!1)}},[n,l,d,b,c,t]);return aa.useEffect(()=>{y()},[y]),{people:s,isLoading:r,error:u,page:l,pageSize:d,hasNextPage:s.length===d,hasPreviousPage:l>0,setPage:i,q:b,setQ:S=>{f(S),i(0)},source:c,setSource:S=>{m(S),i(0)},refetch:()=>y(),refetchAfterRemoval:()=>y({afterRemoval:!0})}}var an=re(require("react"),1);function zs(e,{refreshKey:t}={}){let{api:n}=ae(),[s,a]=an.useState(null),[r,o]=an.useState(e!==null),[u,g]=an.useState(null),l=an.useRef(0),i=an.useCallback(async()=>{if(e===null){a(null),o(!1),g(null);return}let d=++l.current;try{o(!0),g(null);let b=await n.getPerson(e);if(d!==l.current)return;a(b)}catch(b){if(d!==l.current)return;g(b instanceof Error?b:new Error("Failed to fetch person"))}finally{d===l.current&&o(!1)}},[n,e,t]);return an.useEffect(()=>{i()},[i]),{person:s,isLoading:r,error:u,refetch:i}}var w=require("react/jsx-runtime"),vi="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",iu="af-text-xs af-text-muted-foreground";function os(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 bi(e,t){let n=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(n)}`}function ou(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function lu({value:e,label:t}){let[n,s]=na.useState(!1);return ou()?(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!0),setTimeout(()=>s(!1),1500)}catch{}},"aria-label":t,className:"af-shrink-0",children:[n?(0,w.jsx)(yt.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,w.jsx)(yt.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),n?"Copied":"Copy email"]}):null}function Ko(e){return(0,w.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,w.jsxs)(ne,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,w.jsx)(ne,{variant:"secondary",children:"Contact form"})]})}function Zo(e){return e.name?e.name:e.email?e.email:(0,w.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var cu=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,uu=40;function du(e){let t=Object.entries(e).filter(([a])=>!a.startsWith("_")),s=t.find(([a,r])=>cu.test(a)&&typeof r=="string"&&r.trim())??t.filter(([,a])=>typeof a=="string"&&a.trim().length>=uu).sort((a,r)=>String(r[1]).trim().length-String(a[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([a])=>a!==s[0])}:{message:null,rest:t}}function fu(e){return e.replace(/_/g," ")}function mu(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function pu({data:e}){let{message:t,rest:n}=du(e);return t===null&&n.length===0?(0,w.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,w.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,w.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),n.length>0&&(0,w.jsx)("dl",{className:"af-space-y-1",children:n.map(([s,a])=>(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,w.jsx)("dt",{className:ee(iu,"af-w-28 af-shrink-0 af-capitalize"),children:fu(s)}),(0,w.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:mu(a)})]},s))})]})}function Yo({formName:e,createdAt:t,data:n,onDelete:s}){return(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)(ne,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,w.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,w.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:os(t)}),(0,w.jsx)(Yn,{iconOnly:!0,onDelete:s})]}),(0,w.jsx)(pu,{data:n})]})}function gu(e){return e.charged_total??e.amount_total}function vu({email:e,refreshKey:t,onBack:n,onRemoved:s}){let{api:a}=ae(),{person:r,isLoading:o,error:u,refetch:g}=zs(e,{refreshKey:t}),l=async d=>{await a.deleteSubmission(d),s(),!!r?.customer||(r?.orders.length??0)>0||(r?.submissions.length??0)>1?g():n()},i=bi(e,r?.submissions[0]?.form_name);return(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(R,{variant:"ghost",size:"sm",onClick:n,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(yt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,w.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[o?(0,w.jsx)(ie,{className:"af-h-7 af-w-48"}):(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:r?.name||e}),(0,w.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,w.jsx)(lu,{value:e,label:"Copy email address"})]})]}),(0,w.jsx)(R,{asChild:!0,children:(0,w.jsxs)("a",{href:i,children:[(0,w.jsx)(yt.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),o?(0,w.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(d=>(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsx)(ie,{className:"af-w-40"}),(0,w.jsx)(ie,{className:"af-mt-2 af-w-64"})]},d)),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):u||!r?(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(wa,{message:"Couldn't load this person.",onRetry:()=>g()})}):(0,w.jsxs)("div",{className:"af-space-y-6",children:[r.customer&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:ee(vi,"af-mb-3"),children:"Customer"}),(0,w.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[r.customer.name&&(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,w.jsx)("dd",{children:r.customer.name})]}),r.customer.phone&&(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,w.jsx)("dd",{children:r.customer.phone})]}),(0,w.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,w.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,w.jsx)("dd",{children:os(r.customer.created_at)})]})]})]}),r.orders.length>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:ee(vi,"af-mb-3"),children:"Purchases"}),(0,w.jsx)("div",{className:"af-overflow-x-auto",children:(0,w.jsxs)(qe,{children:[(0,w.jsx)(je,{children:(0,w.jsxs)(Re,{children:[(0,w.jsx)(j,{children:"Order"}),(0,w.jsx)(j,{children:"Date"}),(0,w.jsx)(j,{className:"af-text-right",children:"Total"}),(0,w.jsx)(j,{children:"Status"})]})}),(0,w.jsx)(Ge,{children:r.orders.map(d=>(0,w.jsxs)(Re,{children:[(0,w.jsx)(G,{className:"af-whitespace-nowrap af-font-medium",children:dn(d)}),(0,w.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:os(d.created_at)}),(0,w.jsx)(G,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:K(gu(d),d.currency)}),(0,w.jsx)(G,{children:(0,w.jsx)(_n,{status:d.status})})]},d.id))})]})}),(0,w.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."})]}),r.submissions.length>0&&(0,w.jsxs)("div",{children:[(0,w.jsx)("h4",{className:ee(vi,"af-mb-3"),children:"Messages"}),(0,w.jsx)("div",{className:"af-space-y-3",children:r.submissions.map(d=>(0,w.jsx)(Yo,{formName:d.form_name,createdAt:d.created_at,data:d.data,onDelete:()=>l(d.id)},d.id))})]})]})]})}function bu({submissionId:e,onBack:t,onRemoved:n}){let{api:s}=ae(),[a,r]=na.useState(null),[o,u]=na.useState(!0),[g,l]=na.useState(null),[i,d]=na.useState(0);return na.useEffect(()=>{let b=!1;return u(!0),l(null),s.getSubmission(e).then(f=>{b||r(f)}).catch(f=>{b||l(f instanceof Error?f:new Error("Failed to load submission"))}).finally(()=>{b||u(!1)}),()=>{b=!0}},[s,e,i]),(0,w.jsxs)("div",{children:[(0,w.jsxs)("div",{className:"af-mb-6",children:[(0,w.jsxs)(R,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,w.jsx)(yt.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,w.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),o?(0,w.jsx)(ie,{className:"af-mt-1 af-h-4 af-w-32"}):a&&(0,w.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:os(a.metadata.submitted_at)})]}),o?(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,w.jsx)(ie,{className:"af-w-40"}),(0,w.jsx)(ie,{className:"af-mt-2 af-w-64"}),(0,w.jsx)(ie,{className:"af-mt-2 af-w-52"}),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):g||!a?(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(wa,{message:"Couldn't load this submission.",onRetry:()=>d(b=>b+1)})}):(0,w.jsxs)("div",{className:"af-space-y-3",children:[(0,w.jsx)(Yo,{formName:null,createdAt:a.metadata.submitted_at,data:a.data,onDelete:async()=>{await s.deleteSubmission(e),n(),t()}}),(0,w.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 yu={all:"All",customers:"Customers",leads:"Leads"},hu=["all","customers","leads"],Jo={all:void 0,customers:"customer",leads:"lead"};function xu({refreshKey:e,onBackToWebsite:t,className:n,maxRows:s,onViewAll:a}){let r=typeof s=="number",{people:o,isLoading:u,error:g,page:l,pageSize:i,hasNextPage:d,hasPreviousPage:b,setPage:f,q:c,setQ:m,source:p,setSource:y,refetch:S,refetchAfterRemoval:C}=Hs({refreshKey:e}),[E,v]=na.useState({kind:"list"}),[_,T]=na.useState(""),A=p==="customer"?"customers":p==="lead"?"leads":"all",N=te=>{Jo[te]!==p&&y(Jo[te])},{api:k}=ae(),L=na.useCallback(()=>k.exportPeopleCsv({...c?{q:c}:{},...p?{source:p}:{}}),[k,c,p]),P=!r||!!a,Y=te=>{if(r){a?.();return}te.email?v({kind:"person",email:te.email}):te.submission_id&&v({kind:"submission",submissionId:te.submission_id})},J=na.useRef(!1),q=()=>{J.current=!0},se=()=>{v({kind:"list"}),J.current?(J.current=!1,C()):S()},ce=te=>{let U=te.trim();U!==c&&m(U)},ge=r?o.slice(0,s):o,$;if(E.kind==="person")$=(0,w.jsx)(vu,{email:E.email,refreshKey:e,onBack:se,onRemoved:q});else if(E.kind==="submission")$=(0,w.jsx)(bu,{submissionId:E.submissionId,onBack:se,onRemoved:q});else{let te=(0,w.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,w.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:hu.map(U=>(0,w.jsx)("button",{type:"button","aria-pressed":A===U,onClick:()=>N(U),className:ee("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",A===U?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:yu[U]},U))}),(0,w.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,w.jsx)(yt.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,w.jsx)(pe,{type:"text",value:_,onChange:U=>T(U.target.value),onBlur:()=>ce(_),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),ce(_))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),c&&(0,w.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>{T(""),m("")},children:"Clear search"}),(0,w.jsx)(Bt,{fetchCsv:L,filename:"people",className:"af-ml-auto"})]});if(u)$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,w.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,w.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,w.jsx)(ie,{className:"af-h-4 af-w-32"}),(0,w.jsx)(ie,{className:"af-h-4 af-w-16"})]}),(0,w.jsx)(ie,{className:"af-mt-2 af-h-5 af-w-28"}),(0,w.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-56"})]},U))}),(0,w.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,w.jsxs)(qe,{children:[(0,w.jsx)(je,{children:(0,w.jsxs)(Re,{children:[(0,w.jsx)(j,{children:"Person"}),(0,w.jsx)(j,{children:"Came from"}),(0,w.jsx)(j,{children:"Latest message"}),(0,w.jsx)(j,{children:"Last activity"}),(0,w.jsx)(j,{className:"af-w-8"}),(0,w.jsx)(j,{className:"af-w-8"})]})}),(0,w.jsx)(Ge,{"aria-hidden":"true",children:[0,1,2,3,4].map(U=>(0,w.jsxs)(Re,{children:[(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-4 af-w-40"})}),(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-5 af-w-24"})}),(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-4 af-w-56"})}),(0,w.jsx)(G,{children:(0,w.jsx)(ie,{className:"af-h-4 af-w-24"})}),(0,w.jsx)(G,{}),(0,w.jsx)(G,{})]},U))})]})}),(0,w.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(g)$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,w.jsx)(wa,{message:"Couldn't load your leads.",onRetry:()=>S()})})]});else if(ge.length===0&&l===0){let U=!!c||A!=="all";$=(0,w.jsxs)("div",{children:[U&&te,U?(0,w.jsx)(za,{children:c?"Nobody matches that search.":A==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,w.jsx)(ts,{icon:yt.Users,heading:"No leads yet",body:"Form submissions and customers will show up here."})]})}else if(o.length===0)$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)(za,{children:"No more results."}),(0,w.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(l-1),children:[(0,w.jsx)(yt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let U=l*i+1,Pe=l*i+o.length;$=(0,w.jsxs)("div",{children:[r?null:te,(0,w.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ge.map((ue,at)=>(0,w.jsxs)("div",{onClick:P?()=>Y(ue):void 0,className:`af-rounded-md af-border af-p-3${P?" af-cursor-pointer hover:af-bg-muted/50":""}`,children:[(0,w.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,w.jsxs)("div",{className:"af-min-w-0",children:[(0,w.jsx)("button",{type:"button",onClick:Te=>{Te.stopPropagation(),Y(ue)},disabled:!P,"aria-label":`Open ${ue.name||ue.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${P?" hover:af-underline":""}`,children:Zo(ue)}),ue.name&&ue.email&&(0,w.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:ue.email})]}),(0,w.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,w.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:os(ue.last_activity_at)}),ue.email&&(0,w.jsx)(R,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,w.jsx)("a",{href:bi(ue.email),onClick:Te=>Te.stopPropagation(),"aria-label":`Email ${ue.email}`,children:(0,w.jsx)(yt.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,w.jsx)("div",{className:"af-mt-2",children:Ko(ue)}),ue.latest_message_excerpt&&(0,w.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:ue.latest_message_excerpt})]},ue.email??ue.submission_id??at))}),(0,w.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,w.jsxs)(qe,{children:[(0,w.jsx)(je,{children:(0,w.jsxs)(Re,{children:[(0,w.jsx)(j,{children:"Person"}),(0,w.jsx)(j,{children:"Came from"}),(0,w.jsx)(j,{children:"Latest message"}),(0,w.jsx)(j,{children:"Last activity"}),(0,w.jsx)(j,{className:"af-w-8",children:(0,w.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,w.jsx)(j,{className:"af-w-8"})]})}),(0,w.jsx)(Ge,{children:ge.map((ue,at)=>(0,w.jsxs)(Re,{onClick:P?()=>Y(ue):void 0,className:P?"af-cursor-pointer focus-within:af-bg-muted/50":void 0,children:[(0,w.jsxs)(G,{className:"af-max-w-[260px] af-font-medium",children:[(0,w.jsx)("button",{type:"button",onClick:Te=>{Te.stopPropagation(),Y(ue)},disabled:!P,"aria-label":`Open ${ue.name||ue.email||"this form submission"}`,className:`af-block af-max-w-full af-truncate af-rounded-sm af-text-left focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring${P?" hover:af-underline":""}`,children:Zo(ue)}),ue.name&&ue.email&&(0,w.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:ue.email})]}),(0,w.jsx)(G,{children:Ko(ue)}),(0,w.jsx)(G,{className:"af-max-w-[320px]",children:ue.latest_message_excerpt?(0,w.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:ue.latest_message_excerpt}):(0,w.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,w.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:os(ue.last_activity_at)}),(0,w.jsx)(G,{className:"af-w-8",children:ue.email&&(0,w.jsx)(R,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,w.jsx)("a",{href:bi(ue.email),onClick:Te=>Te.stopPropagation(),"aria-label":`Email ${ue.email}`,children:(0,w.jsx)(yt.Mail,{className:"af-h-4 af-w-4"})})})}),(0,w.jsx)(G,{className:"af-w-8 af-text-right",children:(0,w.jsx)(yt.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},ue.email??ue.submission_id??at))})]})}),!r&&(0,w.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,w.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${U}-${Pe}`}),(0,w.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(l-1),disabled:!b,children:[(0,w.jsx)(yt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,w.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>f(l+1),disabled:!d,children:["Next",(0,w.jsx)(yt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return r?(0,w.jsx)("div",{className:n,children:$}):(0,w.jsx)(wt,{title:"Leads",onBackToWebsite:t,hideBackButton:E.kind!=="list",className:n,children:$})}function qs(e){return(0,w.jsx)(xu,{...e},e.maxRows==null?"full":"compact")}var al=re(require("react"),1),zn=require("lucide-react");var sa=re(require("react"),1);function js({initialPageSize:e=25,refreshKey:t}={}){let{api:n}=ae(),[s,a]=sa.useState([]),[r,o]=sa.useState(0),[u,g]=sa.useState(!0),[l,i]=sa.useState(null),[d,b]=sa.useState(0),[f,c]=sa.useState(e),[m,p]=sa.useState(void 0),y=sa.useRef(0),S=sa.useCallback(async()=>{let E=++y.current;try{g(!0),i(null);let v={limit:f,offset:d*f};m&&(v.status=m);let _=await n.getSubscriptions(v);if(E!==y.current)return;a(_.subscriptions),o(_.total)}catch(v){if(E!==y.current)return;i(v instanceof Error?v:new Error("Failed to fetch subscriptions"))}finally{E===y.current&&g(!1)}},[n,d,f,m,t]);sa.useEffect(()=>{S()},[S]);let C=Math.ceil(r/f);return{subscriptions:s,total:r,isLoading:u,error:l,page:d,pageSize:f,hasNextPage:d<C-1,hasPreviousPage:d>0,setPage:b,setPageSize:E=>{c(E),b(0)},status:m,setStatus:E=>{p(E),b(0)},refetch:S}}var V=require("react/jsx-runtime");function Xo(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 Qo({sub:e}){return e.status==="canceled"?(0,V.jsx)(ne,{variant:"outline",children:"Canceled"}):e.status==="past_due"?(0,V.jsx)(ne,{variant:"destructive",children:"Past due"}):e.status==="active"?e.cancel_at_period_end?(0,V.jsx)(ne,{variant:"warning",children:"Scheduled to cancel"}):(0,V.jsx)(ne,{variant:"success",children:"Active"}):(0,V.jsx)(ne,{variant:"outline",title:e.status,children:"Managed in Stripe"})}function wu(e,t){let n=K(t,e.currency);return e.plan_interval_count===1?`${n} / ${e.plan_interval}`:`${n} every ${e.plan_interval_count} ${e.plan_interval}s`}function el({sub:e}){let t=e.current_amount!==e.plan_amount;return(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-font-medium af-tabular-nums",children:wu(e,e.current_amount)}),t&&(0,V.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["signed up at ",K(e.plan_amount,e.currency)]})]})}function tl(e){return e.status==="canceled"?"\u2014":e.cancel_at_period_end?e.current_period_end?`Ends ${Xo(e.current_period_end)}`:"Ends at period end":e.current_period_end?Xo(e.current_period_end):"\u2014"}function yi({refreshKey:e,onBackToWebsite:t,className:n}){let{subscriptions:s,total:a,isLoading:r,error:o,page:u,pageSize:g,hasNextPage:l,hasPreviousPage:i,setPage:d,status:b,refetch:f}=js({refreshKey:e}),{api:c}=ae(),m=al.useCallback(()=>c.exportSubscriptionsCsv(b?{status:b}:{}),[c,b]),p;if(r)p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(y=>(0,V.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,V.jsx)(ie,{className:"af-h-4 af-w-40"}),(0,V.jsx)(ie,{className:"af-h-4 af-w-20"})]}),(0,V.jsx)(ie,{className:"af-mt-2 af-h-3 af-w-32"}),(0,V.jsx)(ie,{className:"af-mt-2 af-h-5 af-w-24"})]},y))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(qe,{children:[(0,V.jsx)(je,{children:(0,V.jsxs)(Re,{children:[(0,V.jsx)(j,{children:"Subscriber"}),(0,V.jsx)(j,{children:"Plan"}),(0,V.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,V.jsx)(j,{children:"Renews"}),(0,V.jsx)(j,{children:"Status"})]})}),(0,V.jsx)(Ge,{"aria-hidden":"true",children:[0,1,2,3,4].map(y=>(0,V.jsxs)(Re,{children:[(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-4 af-w-44"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-4 af-w-32"})}),(0,V.jsx)(G,{className:"af-text-right",children:(0,V.jsx)(ie,{className:"af-ml-auto af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-4 af-w-24"})}),(0,V.jsx)(G,{children:(0,V.jsx)(ie,{className:"af-h-5 af-w-20"})})]},y))})]})}),(0,V.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading subscriptions"})]});else if(o)p=(0,V.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,V.jsx)(wa,{message:"Couldn't load your subscriptions.",onRetry:()=>f()})});else if(s.length===0&&u===0)p=(0,V.jsx)(za,{icon:(0,V.jsx)(zn.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(s.length===0)p=(0,V.jsxs)("div",{children:[(0,V.jsx)(za,{children:"No more results."}),(0,V.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,V.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>d(u-1),children:[(0,V.jsx)(zn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let y=u*g+1,S=u*g+s.length;p=(0,V.jsxs)("div",{children:[(0,V.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,V.jsx)(Bt,{fetchCsv:m,filename:"subscriptions"})}),(0,V.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:s.map(C=>(0,V.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,V.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,V.jsxs)("div",{className:"af-min-w-0",children:[(0,V.jsx)("div",{className:"af-truncate af-text-sm af-font-medium",children:C.customer_email||(0,V.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),(0,V.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:C.plan_title||"Untitled plan"})]}),(0,V.jsx)("div",{className:"af-shrink-0 af-text-right",children:(0,V.jsx)(el,{sub:C})})]}),(0,V.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Qo,{sub:C}),C.is_test&&(0,V.jsx)(ne,{variant:"outline",children:"Test"}),(0,V.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:tl(C)})]}),(0,V.jsx)(Ka,{deliveries:C.email_deliveries,problemsOnly:!0,className:"af-mt-2"})]},C.id))}),(0,V.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,V.jsxs)(qe,{children:[(0,V.jsx)(je,{children:(0,V.jsxs)(Re,{children:[(0,V.jsx)(j,{children:"Subscriber"}),(0,V.jsx)(j,{children:"Plan"}),(0,V.jsx)(j,{className:"af-text-right",children:"Amount"}),(0,V.jsx)(j,{children:"Renews"}),(0,V.jsx)(j,{children:"Status"})]})}),(0,V.jsx)(Ge,{children:s.map(C=>(0,V.jsxs)(Re,{children:[(0,V.jsx)(G,{className:"af-max-w-[240px]",children:(0,V.jsx)("div",{className:"af-truncate af-font-medium",children:C.customer_email||(0,V.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"No email"})})}),(0,V.jsx)(G,{className:"af-max-w-[220px]",children:(0,V.jsx)("div",{className:"af-truncate",children:C.plan_title||(0,V.jsx)("span",{className:"af-text-muted-foreground",children:"Untitled plan"})})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-right",children:(0,V.jsx)(el,{sub:C})}),(0,V.jsx)(G,{className:"af-whitespace-nowrap af-text-muted-foreground",children:tl(C)}),(0,V.jsxs)(G,{children:[(0,V.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,V.jsx)(Qo,{sub:C}),C.is_test&&(0,V.jsx)(ne,{variant:"outline",children:"Test"})]}),(0,V.jsx)(Ka,{deliveries:C.email_deliveries,problemsOnly:!0,className:"af-mt-2 af-min-w-56 af-max-w-sm af-whitespace-normal"})]})]},C.id))})]})}),(0,V.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,V.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:`Showing ${y}-${S} of ${a}`}),(0,V.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,V.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>d(u-1),disabled:!i,children:[(0,V.jsx)(zn.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,V.jsxs)(R,{variant:"outline",size:"sm",onClick:()=>d(u+1),disabled:!l,children:["Next",(0,V.jsx)(zn.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}return(0,V.jsx)(wt,{title:"Subscriptions",onBackToWebsite:t,className:n,children:p})}var sn=re(require("react"),1),bl=require("lucide-react");var zt=re(require("react"),1);var Lr=re(require("react"),1),qn=typeof window>"u"?Lr.useEffect:Lr.useLayoutEffect;var Or=class extends Error{constructor(){super(...arguments);this.name="SavedButNotRefreshedError"}},Su=(e,t)=>e instanceof Error?e:new Error(t);function Nu(e){let t={};return e.due_days!==void 0&&(t.invoice_due_days=e.due_days),e.reminder_schedule!==void 0&&(t.invoice_reminder_schedule=e.reminder_schedule),e.footer!==void 0&&(t.invoice_footer=e.footer),t}function nl(e,t){return{api:e,siteId:t,seq:0,applied:0,queue:Promise.resolve(),writing:!1,idle:Promise.resolve(),markIdle:()=>{}}}function gn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n}){let{api:s}=ae(),[a,r]=zt.useState(null),[o,u]=zt.useState(!0),[g,l]=zt.useState(null),i=zt.useRef(null),[d,b]=zt.useState(()=>nl(s,e)),f=d.api!==s||d.siteId!==e,c=d;f&&(c=nl(s,e),b(c),r(null),u(!0),l(null));let m=zt.useRef(c);qn(()=>{m.current!==c&&(m.current=c,i.current=null)},[c]);let p=(N,k)=>m.current===N&&k>N.applied,y=(N,k,L)=>p(N,k)?(N.applied=k,i.current=L,r(L),u(!1),!0):!1,S=async N=>{for(;N.writing;)await N.idle;let k=++N.seq;try{let L=await N.api.getSite(N.siteId);return y(N,k,L)&&l(null),{seq:k,error:null}}catch(L){return{seq:k,error:Su(L,"Failed to load store settings")}}},C=(N,k)=>{let L=async()=>{if(m.current!==N)throw new Error("Not saved: the store switched to another site first.");N.writing=!0,N.idle=new Promise(Y=>{N.markIdle=Y});try{return await k(++N.seq)}finally{N.writing=!1,N.markIdle()}},P=N.queue.then(L,L);return N.queue=P.catch(()=>{}),P},E=zt.useCallback(async()=>{let N=await S(c);N.error&&p(c,N.seq)&&(l(N.error),u(!1))},[c]);zt.useEffect(()=>{E()},[E,t]);let v=zt.useCallback(N=>C(c,async k=>{let L=await c.api.updateSite(c.siteId,N),{currency_restatement:P,...Y}=L;return y(c,k,Y)&&l(J=>J instanceof Or?J:null),L}),[c]),_=zt.useRef(n);qn(()=>{_.current=n});let T=zt.useCallback(async(N,k)=>{await C(c,()=>N());let L=await S(c);return L.error&&p(c,L.seq)&&i.current&&(y(c,L.seq,{...i.current,...k}),l(new Or(`Saved, but couldn't refresh settings: ${L.error.message}`))),m.current===c?i.current:null},[c]),A=zt.useCallback(N=>{let k=_.current;return T(()=>k(N),Nu(N))},[T]);return{site:f?null:a,isLoading:f||o,error:f?null:g,refetch:E,updateSite:v,saveInvoiceSettings:n?A:null}}var Ct=re(require("react"),1),wi=require("lucide-react");var it=require("react/jsx-runtime");function Br(e,t="Could not save. Try again."){return e instanceof Error&&e.message?e.message:t}var qa="af-grid af-gap-1 af-text-sm",sl="af-h-9 af-rounded-md af-border af-border-input af-bg-background af-px-3 af-text-sm disabled:af-cursor-not-allowed disabled:af-opacity-50",rl="af-min-h-[72px] 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 disabled:af-cursor-not-allowed disabled:af-opacity-50";function ra({children:e}){return(0,it.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:e})}function Gs({children:e}){return(0,it.jsx)("p",{role:"alert",className:"af-text-sm af-text-destructive",children:e})}var nn=Ct.forwardRef(function({id:t,title:n,description:s,children:a},r){let o=`af-store-${t}-title`;return(0,it.jsxs)("section",{ref:r,id:`af-store-${t}`,"data-store-section":t,tabIndex:-1,"aria-labelledby":o,className:"af-space-y-3 af-border-t af-pt-6 first:af-border-t-0 first:af-pt-0 focus:af-outline-none",children:[(0,it.jsxs)("div",{className:"af-space-y-1",children:[(0,it.jsx)("h3",{id:o,className:"af-text-sm af-font-semibold",children:n}),s&&(0,it.jsx)(ra,{children:s})]}),a]})});function Si({label:e,description:t,checked:n,onSave:s,disabled:a=!1,disabledReason:r}){let[o,u]=Ct.useState(null),[g,l]=Ct.useState(null),i=o??n,d=async b=>{u(b),l(null);try{await s(b)}catch(f){l(Br(f))}finally{u(null)}};return(0,it.jsxs)("div",{className:"af-space-y-1",children:[(0,it.jsxs)("label",{className:"af-flex af-items-start af-gap-2 af-text-sm",children:[(0,it.jsx)("input",{type:"checkbox",role:"switch","aria-label":e,"aria-checked":i,checked:i,disabled:a||o!==null,onChange:b=>void d(b.target.checked),className:"af-mt-0.5 af-h-4 af-w-4"}),(0,it.jsxs)("span",{className:"af-space-y-0.5",children:[(0,it.jsxs)("span",{className:"af-flex af-items-center af-gap-2 af-font-medium",children:[e,o!==null&&(0,it.jsx)(wi.Loader2,{className:"af-h-3 af-w-3 af-animate-spin af-text-muted-foreground"})]}),t&&(0,it.jsx)(ra,{children:t})]})]}),(a&&r||g)&&(0,it.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[a&&r&&(0,it.jsx)(ra,{children:r}),g&&(0,it.jsx)(Gs,{children:g})]})]})}var xi=(e,t)=>JSON.stringify(e)===JSON.stringify(t),hi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ru(e,t,n,s=[]){if(!hi(e)||!hi(t)||!hi(n))return{draft:xi(e,t)?n:e,dropped:[]};let a=[],r={...n};for(let o of Object.keys(n))xi(e[o],t[o])||(s.includes(o)?a.push(o):r[o]=e[o]);return{draft:r,dropped:a}}function ls(e,t){let n=JSON.stringify(e),[s,a]=Ct.useState(e),[r,o]=Ct.useState([]),u=Ct.useRef(e),g=Ct.useRef(e),l=Ct.useRef(s);qn(()=>{g.current=e,l.current=s});let i=Ct.useRef(t?.when);Ct.useEffect(()=>{let b=Object.is(i.current,t?.when)?[]:t?.fields??[];if(i.current=t?.when,xi(u.current,g.current)&&b.length===0)return;let f=Ru(l.current,u.current,g.current,b);u.current=g.current,a(f.draft),f.dropped.length&&o(f.dropped)},[n,t?.when]);let d=Ct.useCallback(b=>{a(b??g.current),o([])},[]);return{draft:s,setDraft:a,dirty:JSON.stringify(s)!==n,reset:d,dropped:r}}function cs({dirty:e,saving:t,error:n,onSave:s,onDiscard:a}){return e?(0,it.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,it.jsxs)(R,{type:"button",size:"sm",disabled:t,onClick:s,children:[t&&(0,it.jsx)(wi.Loader2,{className:"af-animate-spin"}),"Save"]}),(0,it.jsx)(R,{type:"button",size:"sm",variant:"ghost",disabled:t,onClick:a,children:"Discard"}),n&&(0,it.jsx)("p",{role:"alert",className:ee("af-text-sm af-text-destructive"),children:n})]}):null}function us(){let[e,t]=Ct.useState(!1),[n,s]=Ct.useState(null),a=Ct.useCallback(async r=>{t(!0),s(null);try{await r()}catch(o){s(Br(o))}finally{t(!1)}},[]);return{saving:e,error:n,setError:s,run:a}}function il({what:e}){return(0,it.jsxs)(ra,{children:["Only the site owner can change ",e,"."]})}var Ba=re(require("react"),1),jn=require("lucide-react");var H=require("react/jsx-runtime"),Ri=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ul({site:e,updateSite:t}){return(0,H.jsx)("div",{className:"af-space-y-4",children:(0,H.jsx)(Si,{label:"Collect phone number at checkout",description:"Adds a required phone field to your Stripe checkout. Useful for SMS or order follow-up. Collecting a number isn't consent to marketing texts.",checked:e.collect_phone_at_checkout,onSave:n=>t({collect_phone_at_checkout:n})})})}function ol(e){return{countries:(e.shipping_countries??[]).join(", "),rates:(e.shipping_rates??[]).map(t=>({label:t.label,amount:String(nt(t.amount,e.currency))})),threshold:e.free_shipping_over==null?"":String(nt(e.free_shipping_over,e.currency))}}function dl({site:e,updateSite:t,refetch:n,providerSlot:s,currencyChanging:a=!1}){let{draft:r,setDraft:o,dirty:u,reset:g,dropped:l}=ls(ol(e),{when:e.currency,fields:["rates","threshold"]}),{saving:i,error:d,setError:b,run:f}=us(),c=e.currency.toUpperCase(),m=()=>f(async()=>{let y={},S=[...new Set(r.countries.split(/[\s,]+/).map(N=>N.trim().toUpperCase()).filter(Boolean))],C=S.find(N=>!/^[A-Z]{2}$/.test(N));if(C)throw new Error(`"${C}" isn't a two-letter country code (e.g. US, CA).`);let E=S.length?S:null;Ri(E,e.shipping_countries)||(y.shipping_countries=E);let v=[];for(let N of r.rates){let k=N.label.trim(),L=It(N.amount,e.currency);if(!k)throw new Error("Every rate needs a name.");if(N.amount.trim()===""||L===null)throw new Error(`Enter a price for "${k}" (0 for free).`);v.push({label:k,amount:L})}let _=v.length?v:null;Ri(_,e.shipping_rates)||(y.shipping_rates=_);let T=null;if(r.threshold.trim()!==""&&(T=It(r.threshold,e.currency),T===null||T===0))throw new Error("Enter a free-shipping amount above 0, or leave it empty.");if(T!==e.free_shipping_over&&(y.free_shipping_over=T),Object.keys(y).length===0){g();return}("shipping_rates"in y||"free_shipping_over"in y)&&(y.expected_currency=e.currency);let A;try{A=await t(y)}catch(N){throw N instanceof ht&&N.details?.code==="currency_changed"&&await n?.(),N}g(ol(A))}),p=(y,S)=>o({...r,rates:r.rates.map((C,E)=>E===y?{...C,...S}:C)});return(0,H.jsxs)("fieldset",{disabled:i||a,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:qa,children:["Countries you ship to",(0,H.jsx)(pe,{"aria-label":"Countries you ship to",value:r.countries,placeholder:"Anywhere",onChange:y=>o({...r,countries:y.target.value})}),(0,H.jsx)(ra,{children:"Two-letter codes, comma-separated (US, CA). Leave empty to ship anywhere."})]}),(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Flat shipping rates (",c,")"]}),r.rates.length===0&&(0,H.jsx)(ra,{children:"No shipping charge. Add a rate to charge for shipping."}),r.rates.map((y,S)=>(0,H.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,H.jsx)(pe,{"aria-label":`Rate ${S+1} name`,value:y.label,placeholder:"Standard",onChange:C=>p(S,{label:C.target.value})}),(0,H.jsx)(pe,{"aria-label":`Rate ${S+1} price`,type:"number",min:"0",step:"any",value:y.amount,placeholder:"0",className:"af-w-32",onChange:C=>p(S,{amount:C.target.value})}),(0,H.jsx)(R,{type:"button",variant:"ghost",size:"icon","aria-label":`Remove rate ${S+1}`,onClick:()=>o({...r,rates:r.rates.filter((C,E)=>E!==S)}),children:(0,H.jsx)(jn.X,{})})]},S)),(0,H.jsxs)(R,{type:"button",variant:"outline",size:"sm",onClick:()=>o({...r,rates:[...r.rates,{label:"",amount:""}]}),children:[(0,H.jsx)(jn.Plus,{})," Add rate"]}),(0,H.jsx)(ra,{children:"Buyers pick one at checkout. The first is preselected."})]}),(0,H.jsxs)("label",{className:qa,children:["Free shipping over (",c,")",(0,H.jsx)(pe,{"aria-label":"Free shipping over",type:"number",min:"0",step:"any",value:r.threshold,placeholder:"No threshold",className:"af-w-40",onChange:y=>o({...r,threshold:y.target.value})}),(0,H.jsx)(ra,{children:"Orders at or above this get the cheapest rate free."})]}),l.length>0&&(0,H.jsxs)("p",{role:"status",className:"af-text-sm af-text-muted-foreground",children:["The store currency changed to ",c,", so shipping rates and the free-shipping amount were reset to the restated values. Re-enter any changes to them."]}),(0,H.jsx)(cs,{dirty:u,saving:i,error:d,onSave:()=>void m(),onDiscard:()=>{b(null),g()}}),s]})}var Ni="exclusive",_u=[{href:"https://docs.stripe.com/tax/set-up",label:"Set up Stripe Tax"},{href:"https://docs.stripe.com/tax/registering",label:"Add tax registrations"},{href:"https://docs.stripe.com/tax/zero-tax",label:"Why tax can be zero"},{href:"https://stripe.com/tax/pricing",label:"Stripe Tax pricing"}];function Pu({href:e,children:t}){return(0,H.jsxs)("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"af-inline-flex af-items-center af-gap-1 af-font-medium af-underline af-underline-offset-2 hover:af-text-foreground",children:[t,(0,H.jsx)(jn.ExternalLink,{"aria-hidden":!0,className:"af-h-3 af-w-3"})]})}function fl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(e.tax_behavior??Ni),{saving:o,error:u,setError:g,run:l}=us(),[i,d]=Ba.useState(!1),b=e.stripe_tax_enabled,f=b||i,c=()=>l(async()=>{let y=n;if(y===e.tax_behavior){r();return}let S={tax_behavior:y};y!=="inclusive"&&e.tax_rate_bps!=null&&(S.tax_rate_bps=null);let C=await t(S);r(C.tax_behavior??Ni)}),m=()=>l(async()=>{let y={stripe_tax_enabled:!0,tax_behavior:n};n!=="inclusive"&&e.tax_rate_bps!=null&&(y.tax_rate_bps=null);let S=await t(y);r(S.tax_behavior??Ni),d(!1)}),p=(a||i)&&n!=="inclusive"&&e.tax_rate_bps!=null;return(0,H.jsxs)("div",{className:"af-space-y-5",children:[(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded-md af-bg-muted af-p-3 af-text-sm af-text-muted-foreground",children:[(0,H.jsx)("p",{children:"Tax at checkout is calculated by Stripe Tax, which you set up in your Stripe Dashboard (Settings \u2192 Tax): your business address, a default product tax code, and the places you're registered to collect tax."}),(0,H.jsx)("p",{children:"Stripe only collects tax where you've added a registration; anywhere else the tax comes out as zero. Stripe Tax has its own fees, and what it covers (such as filing) depends on your Stripe Tax plan."}),(0,H.jsx)("ul",{className:"af-flex af-flex-wrap af-gap-x-4 af-gap-y-1",children:_u.map(y=>(0,H.jsx)("li",{children:(0,H.jsx)(Pu,{href:y.href,children:y.label})},y.href))})]}),(0,H.jsx)(Si,{label:"Stripe automatic tax",description:b?"On: Stripe adds or includes tax for each buyer's address where you're registered. If orders show no tax, check your registrations in Stripe.":"Off: buyers pay your listed prices, and no tax is added or collected at checkout. Turn on once Stripe Tax is set up.",checked:f,onSave:async y=>{if(i){d(!1),g(null),r();return}if(y&&!e.tax_behavior){d(!0);return}return t({stripe_tax_enabled:y})}}),f&&(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4 af-pl-6",children:[(0,H.jsxs)("label",{className:qa,children:["Do your prices already include tax?",(0,H.jsxs)("select",{"aria-label":"Your prices",className:sl,value:n,onChange:y=>s(y.target.value),children:[(0,H.jsx)("option",{value:"exclusive",children:"No, add tax on top at checkout (common in the US and Canada)"}),(0,H.jsx)("option",{value:"inclusive",children:"Yes, prices include tax (common for VAT and GST)"})]}),(0,H.jsx)(ra,{children:"Stripe Tax takes tax out of your prices or adds it on top."}),p&&(0,H.jsxs)(ra,{children:["Saving clears the ",e.tax_rate_bps/100,"% tax rate shown on receipts and invoices, which only applies when prices include tax."]})]}),i?(0,H.jsxs)("div",{className:"af-space-y-2",children:[(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:o,onClick:()=>void m(),children:"Turn on"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"outline",disabled:o,onClick:()=>{d(!1),g(null),r()},children:"Cancel"})]}),u&&(0,H.jsx)(Gs,{children:u})]}):(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void c(),onDiscard:()=>{g(null),r()}})]})]})}function ll(e){return{rate:e.tax_rate_bps==null?"":String(e.tax_rate_bps/100),taxId:e.tax_id??"",label:e.tax_label??""}}function ml({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(ll(e)),{saving:o,error:u,setError:g,run:l}=us(),i=!(e.stripe_tax_enabled&&e.tax_behavior==="exclusive"),d=()=>l(async()=>{let b={},f=null;if(i&&n.rate.trim()!==""){let y=Number(n.rate);if(!Number.isFinite(y)||y<=0)throw new Error("Enter a tax rate above 0%, or leave it empty.");f=Math.round(y*100)}i&&f!==e.tax_rate_bps&&(b.tax_rate_bps=f),f!=null&&e.tax_behavior!=="inclusive"&&(b.tax_behavior="inclusive");let c=n.taxId.trim()||null;c!==e.tax_id&&(b.tax_id=c);let m=n.label.trim()||null;if(m!==e.tax_label&&(b.tax_label=m),Object.keys(b).length===0){r();return}let p=await t(b);r(ll(p))});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:qa,children:["Tax rate (%)",(0,H.jsx)(pe,{"aria-label":"Tax rate",type:"number",min:"0",step:"any",className:"af-w-32",disabled:!i,value:i?n.rate:"",onChange:b=>s({...n,rate:b.target.value})}),(0,H.jsx)(ra,{children:i?"The tax already included in your prices, shown on receipts and invoices. It never changes what buyers pay.":"Stripe automatic tax adds tax on top of your prices at checkout, so receipts show the tax Stripe calculated."})]}),(0,H.jsxs)("div",{className:"af-grid af-gap-4 sm:af-grid-cols-2",children:[(0,H.jsxs)("label",{className:qa,children:["Tax ID",(0,H.jsx)(pe,{"aria-label":"Tax ID",value:n.taxId,maxLength:64,placeholder:"DE123456789",onChange:b=>s({...n,taxId:b.target.value})})]}),(0,H.jsxs)("label",{className:qa,children:["Tax label",(0,H.jsx)(pe,{"aria-label":"Tax label",value:n.label,maxLength:24,placeholder:"Tax",onChange:b=>s({...n,label:b.target.value})})]})]}),(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void d(),onDiscard:()=>{g(null),r()}})]})}function pl({site:e,updateSite:t,onChangeStart:n}){let[s,a]=Ba.useState(e.currency.toUpperCase()),[r,o]=Ba.useState(!1),[u,g]=Ba.useState(!1),[l,i]=Ba.useState(null),d=e.currency.toUpperCase(),b=Ba.useRef(d);Ba.useEffect(()=>{b.current!==d&&(a(y=>y===b.current?d:y),b.current=d)},[d]);let f=s.trim().toUpperCase(),c=f!==d,m=/^[A-Z]{3}$/.test(f),p=async()=>{g(!0);let y=n?.(),S=!1;i(null);try{let C=await t({currency:f.toLowerCase()});S=!0;let E=C.currency_restatement;E&&!E.applied?i(E.reason?`Not changed: ${E.reason}.`:"The currency was not changed."):(a(C.currency.toUpperCase()),b.current=C.currency.toUpperCase()),o(!1)}catch(C){i(Br(C))}finally{g(!1),y?.(S)}};return(0,H.jsxs)("div",{className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-items-end af-gap-2",children:[(0,H.jsxs)("label",{className:qa,children:["Store currency",(0,H.jsx)(pe,{"aria-label":"Store currency",value:s,maxLength:3,className:"af-w-24 af-uppercase",disabled:u||r,onChange:y=>{a(y.target.value),i(null)}})]}),c&&!r&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:!m,onClick:()=>o(!0),children:"Change currency"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"ghost",onClick:()=>{a(d),i(null)},children:"Discard"})]})]}),(0,H.jsx)(ra,{children:"Three-letter code, e.g. USD, EUR, GBP."}),r&&(0,H.jsxs)("div",{className:"af-space-y-2 af-rounded af-border af-p-3",children:[(0,H.jsxs)("p",{className:"af-text-sm",children:["Change the store currency from ",d," to ",f,"? Every price, shipping rate and free-shipping amount keeps its number and switches to ",f,":"," ",K(2e3,d)," becomes ",K(2e3,f),". Nothing is converted, so check your prices afterwards. Stores that already have orders can't change currency."]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(R,{type:"button",size:"sm",disabled:u,onClick:()=>void p(),children:"Confirm change"}),(0,H.jsx)(R,{type:"button",size:"sm",variant:"ghost",disabled:u,onClick:()=>o(!1),children:"Cancel"})]})]}),l&&(0,H.jsx)(Gs,{children:l})]})}function cl(e){return{dueDays:String(e.invoice_due_days),reminders:e.invoice_reminder_schedule.join(", "),footer:e.invoice_footer??""}}function Cu(e){return e.length===0?"Off":e.map(t=>t===0?"on the due date":t<0?`${-t} day${t===-1?"":"s"} before`:`${t} day${t===1?"":"s"} after`).join(", ")}function gl({site:e,save:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(cl(e)),{saving:o,error:u,setError:g,run:l}=us();if(!t)return(0,H.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,H.jsxs)("p",{children:["Due ",e.invoice_due_days," days after sending"]}),(0,H.jsxs)("p",{children:["Reminders: ",Cu(e.invoice_reminder_schedule)]}),(0,H.jsxs)("p",{children:["Footer: ",e.invoice_footer||"None"]}),(0,H.jsx)(il,{what:"invoice defaults"})]});let i=()=>l(async()=>{let d={},b=Number(n.dueDays);if(n.dueDays.trim()===""||!Number.isInteger(b)||b<0||b>90)throw new Error("Due days must be a whole number from 0 to 90.");b!==e.invoice_due_days&&(d.due_days=b);let c=n.reminders.split(/[\s,]+/).filter(Boolean).map(Number);if(c.some(S=>!Number.isInteger(S)))throw new Error("Reminders are whole days from the due date, e.g. -3, 0, 7.");let m=[...new Set(c)].sort((S,C)=>S-C);Ri(m,e.invoice_reminder_schedule)||(d.reminder_schedule=m);let p=n.footer.trim()||null;if(p!==e.invoice_footer&&(d.footer=p),Object.keys(d).length===0){r();return}let y=await t(d);r(y?cl(y):void 0)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-4",children:[(0,H.jsxs)("label",{className:qa,children:["Days until due",(0,H.jsx)(pe,{"aria-label":"Days until due",type:"number",min:"0",max:"90",step:"1",className:"af-w-24",value:n.dueDays,onChange:d=>s({...n,dueDays:d.target.value})})]}),(0,H.jsxs)("label",{className:qa,children:["Reminder schedule",(0,H.jsx)(pe,{"aria-label":"Reminder schedule",value:n.reminders,placeholder:"Off",onChange:d=>s({...n,reminders:d.target.value})}),(0,H.jsx)(ra,{children:"Days from the due date, comma-separated. Negative is before. Up to 4. Leave empty for no reminders."})]}),(0,H.jsxs)("label",{className:qa,children:["Invoice footer",(0,H.jsx)("textarea",{"aria-label":"Invoice footer",className:rl,maxLength:300,value:n.footer,onChange:d=>s({...n,footer:d.target.value})})]}),(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void i(),onDiscard:()=>{g(null),r()}})]})}function vl({site:e,updateSite:t}){let{draft:n,setDraft:s,dirty:a,reset:r}=ls(e.default_email_recipients),{saving:o,error:u,setError:g,run:l}=us(),[i,d]=Ba.useState(""),[b,f]=Ba.useState(null),c=()=>{let p=i.trim().toLowerCase();if(p){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p)){f("Enter a valid email address.");return}if(n.some(y=>y.toLowerCase()===p)){f("Already added.");return}s([...n,p]),d(""),f(null)}},m=()=>l(async()=>{let p=await t({default_email_recipients:n});r(p.default_email_recipients)});return(0,H.jsxs)("fieldset",{disabled:o,className:"af-space-y-3",children:[(0,H.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2",children:[n.map(p=>(0,H.jsxs)(ne,{variant:"secondary",className:"af-gap-1",children:[p,(0,H.jsx)("button",{type:"button","aria-label":`Remove ${p}`,className:"af-ml-1 hover:af-text-destructive",onClick:()=>s(n.filter(y=>y!==p)),children:(0,H.jsx)(jn.X,{className:"af-h-3 af-w-3"})})]},p)),n.length===0&&(0,H.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:"None. Orders go to the site owner's email."})]}),(0,H.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,H.jsx)(pe,{"aria-label":"Add notification email",type:"email",value:i,placeholder:"Add email address",onChange:p=>{d(p.target.value),f(null)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),c())}}),(0,H.jsx)(R,{type:"button",variant:"outline",disabled:!i.trim(),onClick:c,children:"Add"})]}),b&&(0,H.jsx)(Gs,{children:b}),(0,H.jsx)(cs,{dirty:a,saving:o,error:u,onSave:()=>void m(),onDiscard:()=>{g(null),r()}})]})}var Ft=require("react/jsx-runtime");function _i({siteId:e,refreshKey:t,section:n,shippingProviderSlot:s,onConnectStripe:a,onUpgradePlan:r,className:o}){let{site:u,isLoading:g,error:l,refetch:i,updateSite:d}=gn({siteId:e,refreshKey:t}),b=sn.useRef(i),f=sn.useRef(e);qn(()=>{b.current=i,f.current=e});let c=sn.useRef({}),[m,p]=sn.useState([]),y=m.some(_=>_.siteId===e),S=sn.useCallback(()=>{let _={siteId:e},T=b.current;return p(A=>[...A,_]),A=>{let N=()=>p(L=>L.filter(P=>P!==_));!(f.current===_.siteId)||A&&b.current===T?N():b.current().finally(N)}},[e]),C=_=>T=>{c.current[_]=T},E=u!==null&&u.payments_active;if(sn.useEffect(()=>{if(!E||!n)return;let _=c.current[n];_&&(_.scrollIntoView?.({behavior:"smooth",block:"start"}),_.focus({preventScroll:!0}))},[E,n]),g)return(0,Ft.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ft.jsx)(bl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading store settings\u2026"]});if(!u)return(0,Ft.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l?.message??"Could not load store settings."});if(!u.payments_active)return(0,Ft.jsx)(Mn,{className:o,onConnectStripe:a,onUpgradePlan:r,whenActive:(0,Ft.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Your store can't take payments right now, so store settings are unavailable."})});let v={site:u,updateSite:d,refetch:i};return(0,Ft.jsxs)("div",{className:`af-space-y-6 ${o??""}`,children:[l&&(0,Ft.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:l.message}),(0,Ft.jsx)(nn,{ref:C("checkout"),id:"checkout",title:"Checkout",children:(0,Ft.jsx)(ul,{...v})}),(0,Ft.jsx)(nn,{ref:C("shipping"),id:"shipping",title:"Shipping",children:(0,Ft.jsx)(dl,{...v,providerSlot:s,currencyChanging:y})}),(0,Ft.jsx)(nn,{ref:C("tax"),id:"tax",title:"Tax",children:(0,Ft.jsx)(fl,{...v})}),(0,Ft.jsx)(nn,{ref:C("currency"),id:"currency",title:"Currency",description:"The currency every price in your store is in.",children:(0,Ft.jsx)(pl,{...v,onChangeStart:S})})]},e)}var yl=require("lucide-react");var ja=require("react/jsx-runtime");function Ws({siteId:e,refreshKey:t,onSaveInvoiceSettings:n,className:s}){let{site:a,isLoading:r,error:o,updateSite:u,refetch:g,saveInvoiceSettings:l}=gn({siteId:e,refreshKey:t,onSaveInvoiceSettings:n});return r?(0,ja.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,ja.jsx)(yl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading invoice settings\u2026"]}):a?(0,ja.jsxs)("div",{className:`af-space-y-6 ${s??""}`,children:[o&&(0,ja.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o.message}),(0,ja.jsx)(nn,{id:"invoice-defaults",title:"Invoice defaults",description:"Defaults for new invoices. Invoices already sent keep their own.",children:(0,ja.jsx)(gl,{site:a,save:l})}),(0,ja.jsx)(nn,{id:"declared-tax",title:"Tax on receipts and invoices",description:"Printed on receipts and invoices. Checkout never adds it to what buyers pay.",children:(0,ja.jsx)(ml,{site:a,updateSite:u,refetch:g})})]},e):(0,ja.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:o?.message??"Could not load invoice settings."})}var hl=require("lucide-react");var vn=require("react/jsx-runtime");function Pi({siteId:e,refreshKey:t,className:n}){let{site:s,isLoading:a,error:r,updateSite:o,refetch:u}=gn({siteId:e,refreshKey:t});return a?(0,vn.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,vn.jsx)(hl.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"})," Loading notification settings\u2026"]}):s?(0,vn.jsxs)("div",{className:`af-space-y-3 ${n??""}`,children:[r&&(0,vn.jsx)("div",{role:"status",className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r.message}),(0,vn.jsx)(nn,{id:"notifications",title:"Notification emails",description:"New orders are emailed to these addresses. Forms without their own recipients use them too.",children:(0,vn.jsx)(vl,{site:s,updateSite:o,refetch:u})})]},e):(0,vn.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:r?.message??"Could not load notification settings."})}var ds=re(require("react"),1);var Je=require("react/jsx-runtime");function Ci({refreshKey:e,initialInvoiceId:t,onBackToWebsite:n,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,siteId:o,onSaveInvoiceSettings:u,className:g}){let{aggregates:l,isLoading:i,error:d,refetch:b}=Fn({refreshKey:e,initialPageSize:1,includeAggregates:!0}),f=Vn({refreshKey:e}),{api:c}=ae(),m=f.filters,p=ds.useCallback(()=>c.exportRetainersCsv(m),[c,m]),[y,S]=ds.useState(!1),[C,E]=ds.useState(null),[v,_]=ds.useState(!1),T=(0,Je.jsx)("div",{className:"af-mb-6 af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:d||!i&&!l?(0,Je.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,Je.jsx)(R,{type:"button",variant:"link",size:"sm",onClick:()=>void b(),children:"Retry totals"})]}):i||!l?(0,Je.jsxs)(Je.Fragment,{children:[(0,Je.jsx)(dt,{label:"Outstanding",children:(0,Je.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,Je.jsx)(dt,{label:"Overdue",children:(0,Je.jsx)(ie,{className:"af-h-6 af-w-24"})}),(0,Je.jsx)(dt,{label:"Paid this month",children:(0,Je.jsx)(ie,{className:"af-h-6 af-w-24"})})]}):(0,Je.jsxs)(Je.Fragment,{children:[(0,Je.jsx)(dt,{label:"Outstanding",detail:`${l.outstanding.count} open`,children:K(l.outstanding.amount,l.currency)}),(0,Je.jsx)(dt,{label:"Overdue",detail:l.overdue.count===0?"Nothing overdue":`${l.overdue.count} overdue`,valueClassName:l.overdue.count>0?"af-text-lg af-font-semibold af-text-destructive":void 0,children:K(l.overdue.amount,l.currency)}),(0,Je.jsx)(dt,{label:"Paid this month",detail:`${l.paid_this_month.count} paid`,children:K(l.paid_this_month.amount,l.currency)})]})});return(0,Je.jsxs)(wt,{title:"Invoices",onBackToWebsite:n,hideBackButton:y,className:g,children:[T,o&&!y&&(0,Je.jsxs)("div",{className:"af-mb-6",children:[(0,Je.jsx)(R,{type:"button",variant:"outline",size:"sm","aria-expanded":v,"aria-controls":"af-invoice-settings",onClick:()=>_(A=>!A),children:"Invoice settings"}),v&&(0,Je.jsx)("div",{id:"af-invoice-settings",className:"af-mt-4 af-rounded-md af-border af-p-4",children:(0,Je.jsx)(Ws,{siteId:o,refreshKey:e,onSaveInvoiceSettings:u})})]}),!y&&(0,Je.jsx)(Un,{retainers:f.retainers,isLoading:f.isLoading,error:f.error,onRetry:()=>void f.refetch(),activeRetainerId:C?.id??null,onShowCycles:A=>E(N=>N?.id===A.id?null:A),total:f.total,endedTotal:f.endedTotal,isLoadingMore:f.isLoadingMore,onLoadMore:()=>void f.loadMore(),includeEnded:f.includeEnded,onIncludeEndedChange:f.setIncludeEnded,exportCsv:p}),(0,Je.jsx)(pn,{refreshKey:e,initialInvoiceId:t,onDetailOpenChange:S,onConnectStripe:s,onUpgradePlan:a,needsPaidPlan:r,retainerFilter:C?{id:C.id,label:`${C.customer_name??C.customer_email??"Recurring invoices"} \u2014 ${C.description}`}:null,onClearRetainerFilter:()=>E(null)})]})}var Tt=re(require("react"),1);var Tu=2e3,Ut=()=>({data:null,error:null,isLoading:!0});function Gn(e,{refreshKey:t,breakdowns:n=[],filters:s=[]}={}){let{api:a}=ae(),[r,o]=Tt.useState(Ut),[u,g]=Tt.useState(Ut),[l,i]=Tt.useState(Ut),[d,b]=Tt.useState(Ut),[f,c]=Tt.useState(Ut),m=$=>Object.fromEntries($.map(te=>[te,Ut()])),[p,y]=Tt.useState(()=>m(n)),S=Tt.useRef(0),C=Tt.useRef(0),E=Tt.useRef("idle"),v=n.join(","),_=hn()??"",T=JSON.stringify(s),A=`${e}:${v}:${T}:${_}`,[N,k]=Tt.useState({api:a,fetchIdentity:A});(N.api!==a||N.fetchIdentity!==A)&&(k({api:a,fetchIdentity:A}),S.current+=1,o(Ut),g(Ut),i(Ut),b(Ut),y(m(v?v.split(","):[])));let L=`${e}:${String(t??"")}:${_}`,[P,Y]=Tt.useState({api:a,conversionsIdentity:L});(P.api!==a||P.conversionsIdentity!==L)&&(Y({api:a,conversionsIdentity:L}),C.current+=1,E.current="idle",c(Ut));let J=Tt.useCallback(async $=>{let te=++S.current,U=v?v.split(","):[];o(Ut),g(Ut),i(Ut),b(Ut),y(Object.fromEntries(U.map(D=>[D,Ut()])));let Pe=E.current!=="pending"&&($?.force===!0||E.current==="idle"),ue=(D,M)=>M.then(F=>{te===S.current&&D({data:F,error:null,isLoading:!1})},F=>{te===S.current&&D({data:null,error:F instanceof Error?F:new Error("Failed to fetch report"),isLoading:!1})}),at=a.getAnalyticsStatus(),Te=ue(o,at),He=Symbol("status-timeout"),Ye,Le=await Promise.race([at.then(D=>D,()=>null),new Promise(D=>{Ye=setTimeout(()=>D(He),Tu)})]);if(clearTimeout(Ye),te!==S.current)return;if(Le===He&&o({data:null,error:new Error("Status is taking longer than expected"),isLoading:!1}),Le!==null&&Le!==He&&(Le.collecting!==!0||Le.first_seen===null&&!Le.first_seen_unavailable||Le.first_seen!==null&&Le.first_seen_in_reports===!1)){let D={data:null,error:null,isLoading:!1};g(D),i(D),b(D),y(Object.fromEntries(U.map(M=>[M,{...D}]))),Pe&&(c(D),E.current="done"),await Te;return}await Promise.all([Le===He?Promise.resolve():Te,ue(g,a.getAnalyticsSummary(e,s)),ue(i,a.getAnalyticsTimeseries(e,s)),ue(b,a.getAnalyticsChannels(e,s)),Pe?(()=>{E.current="pending";let D=++C.current;return c(Ut),a.getAnalyticsConversions(e).then(M=>{D===C.current&&(c({data:M,error:null,isLoading:!1}),E.current="done")},M=>{D===C.current&&(c({data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}),E.current="done")})})():Promise.resolve(),...U.map(D=>a.getAnalyticsBreakdown(D,e,s).then(M=>{te===S.current&&y(F=>({...F,[D]:{data:M,error:null,isLoading:!1}}))},M=>{te===S.current&&y(F=>({...F,[D]:{data:null,error:M instanceof Error?M:new Error("Failed to fetch report"),isLoading:!1}}))}))])},[a,e,v,T,L,_]),q=Tt.useCallback(async()=>{let $=S.current;try{let te=await a.getAnalyticsStatus();if($!==S.current)return;o({data:te,error:null,isLoading:!1})}catch(te){if($!==S.current)return;o(U=>({data:U.data,error:te instanceof Error?te:new Error("Failed to fetch status"),isLoading:!1}))}},[a]),se=Tt.useCallback(()=>J({force:!0}),[J]);Tt.useEffect(()=>{J()},[J,t]);let ce=r.isLoading||u.isLoading||l.isLoading||d.isLoading||f.isLoading||Object.values(p).some($=>$.isLoading),ge=[l,u,d,f,...Object.values(p)].map($=>$.data?.status==="ok"?$.data.timezone:void 0).find($=>$!==void 0);return{status:r,summary:u,timeseries:l,channels:d,conversions:f,breakdowns:p,reportedZone:ge,isLoading:ce,refetch:se,refetchStatus:q}}var kt=re(require("react"),1);var Fr=3e4,Ur=3;function Ks(e={}){let t="collecting"in e,{collecting:n,statusFailed:s=!1,identity:a}=e,{api:r}=ae(),[o,u]=kt.useState(null),[g,l]=kt.useState(null),[i,d]=kt.useState(!1),[b,f]=kt.useState(null),[c,m]=kt.useState(!1),[p,y]=kt.useState(!0),[S,C]=kt.useState(0),E=kt.useRef(0),v=kt.useRef(0),_=kt.useRef(void 0);n!==void 0&&(_.current=n);let T=t?_.current===!0||_.current===void 0&&s:!0,[A,N]=kt.useState({api:r,identity:a}),k=a!==void 0&&a!==A.identity;(A.api!==r||k)&&(_.current=void 0,N({api:r,identity:a}),v.current+=1,E.current=0,u(null),l(null),d(!1),f(null),m(!1),y(!0),C(0));let L=kt.useRef(()=>{}),P=kt.useRef(null),Y=kt.useCallback(async()=>{if(P.current!==null&&P.current===v.current)return;let J=++v.current;P.current=J;try{let q=await r.getAnalyticsRealtime();if(J!==v.current)return;if(q.status==="unreachable"){m(!0),d(!0),y(!1),C(se=>se+1);return}E.current=0,m(!1),u(q.data.current_visitors),l(q.as_of),d(!1),f(null),y(!1),C(se=>se+1)}catch(q){if(J!==v.current)return;E.current+=1,y(!1),C(se=>se+1),d(!0),E.current>=Ur&&f(q instanceof Error?q:new Error("Realtime unavailable"))}finally{P.current===J&&(P.current=null)}},[r]);return L.current=()=>void Y(),kt.useEffect(()=>{let J,q=()=>{J===void 0&&(J=setInterval(()=>L.current(),Fr))},se=()=>{J!==void 0&&(clearInterval(J),J=void 0)},ce=()=>{typeof document<"u"&&document.hidden?se():(L.current(),q())};return T?((typeof document>"u"||!document.hidden)&&(L.current(),q()),document?.addEventListener("visibilitychange",ce),()=>{se(),document?.removeEventListener("visibilitychange",ce),v.current+=1}):()=>{document?.removeEventListener("visibilitychange",ce)}},[A.api,A.identity,T]),{currentVisitors:o,asOf:g,isStale:i,error:b,isUnreachable:c,isInitialLoad:p,polls:S}}var mt=re(require("react"),1);var xl=re(require("react"),1);var Wn=require("react/jsx-runtime");function ku(){try{let e=Intl.supportedValuesOf?.("timeZone");if(e&&e.length>0)return e.includes("UTC")?e:["UTC",...e]}catch{}return["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Madrid","Africa/Johannesburg","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Tokyo","Australia/Sydney"]}function Ti({value:e,chosen:t,onChange:n}){let s=ps(),a=t===null&&s!==null&&e===s,r=xl.useMemo(()=>{let o=ku();return o.includes(e)?o:[e,...o]},[e]);return(0,Wn.jsxs)("label",{className:"af-flex af-items-center af-gap-1.5 af-text-xs af-text-muted-foreground",children:[(0,Wn.jsx)("span",{className:"af-sr-only",children:"Reporting timezone"}),(0,Wn.jsxs)("select",{value:a?"":e,onChange:o=>n(o.target.value===""?null:o.target.value),className:"af-rounded-md af-bg-transparent af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground focus:af-outline-none focus-visible:af-ring-1 focus-visible:af-ring-ring",title:`Days are counted in ${e.replace(/_/g," ")}`,children:[(0,Wn.jsx)("option",{value:"",children:s?`${s.replace(/_/g," ")} (this device)`:`${e.replace(/_/g," ")} (site default)`}),r.map(o=>(0,Wn.jsx)("option",{value:o,children:o.replace(/_/g," ")},o))]})]})}var Mr=(e,{published:t}={})=>{let n=t===!1,s=e!=null&&(!e.collecting||n&&e.first_seen===null&&!e.first_seen_unavailable),a=!s&&e?.collecting===!0&&e.first_seen===null&&!e.first_seen_unavailable,r=e?.collecting===!0&&e.first_seen!==null&&e.first_seen_in_reports===!1,o=a||r;return{notCollecting:s,awaitingFirstVisit:a,firstVisitTooRecent:r,holdingForFirstData:o,nothingToReport:s||o}};var Zs=re(require("react"),1),Eu=3e4;function $r({status:e,holdingForFirstData:t,refetchStatus:n,refetch:s}){Zs.useEffect(()=>{if(!t)return;let r,o=()=>{r===void 0&&(r=setInterval(()=>void n(),Eu))},u=()=>{r!==void 0&&(clearInterval(r),r=void 0)},g=()=>{typeof document<"u"&&document.hidden?u():(n(),o())};return(typeof document>"u"||!document.hidden)&&o(),document?.addEventListener("visibilitychange",g),()=>{u(),document?.removeEventListener("visibilitychange",g)}},[t,n]);let a=Zs.useRef(void 0);Zs.useEffect(()=>{if(!e){a.current=void 0;return}let r=a.current;a.current=t,r===!0&&!t&&s()},[e,t,s])}var Kn=re(require("react"),1);var Iu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Zt(e){let t=Math.abs(e);if(t<1e3)return String(e);let n=[[1e9,"B"],[1e6,"M"],[1e3,"k"]];for(let[s,a]of n)if(t>=s){let r=e/s,o=Math.abs(r)<10?Math.round(r*10)/10:Math.round(r);return Math.abs(o)>=1e3&&s!==1e9?Zt(o*s):`${o}${a}`}return String(e)}function fs(e){return`${(e*100).toFixed(1)}%`}function Js(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function Sl(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`:Js(t)}function Nl(e){let t=e*100;return Number.isInteger(t)?`${t}%`:`${t.toFixed(1)}%`}function Rl(e,t){if(!(!Number.isFinite(e)||e<=0))for(let n of t){let s=Math.ceil(e/n);if(s<=5)return Array.from({length:s+1},(a,r)=>Number((r*n).toPrecision(12)))}}function Ys(e){return e==null?"(none)":e.trim()===""?"(not set)":e}function _l(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 ki(e){let t=Number(e.slice(5,7)),n=Number(e.slice(8,10));return`${Iu[t-1]} ${n}`}function wl(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}function Au(e){return new Date(Date.parse(`${e}T00:00:00Z`)+864e5).toISOString().slice(0,10)}function Pl(e,t,n="UTC"){let s=new Map(t.map(o=>[o.date,o])),a=[],r=wl(e.to,n);for(let o=wl(e.from,n);o<r;o=Au(o))a.push(s.get(o)??{date:o,visitors:0,visits:0,pageviews:0,views_per_visit:0,bounce_rate:0,visit_duration_seconds:0});return a}function Cl(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=new Date(`${e}T00:00:00Z`);if(Number.isNaN(s.getTime()))return e;let a=String(s.getUTCDate()).padStart(2,"0");return`${t[s.getUTCDay()]}, ${a} ${n[s.getUTCMonth()]}`}var Ra=require("react/jsx-runtime");function Tl({what:e="This report",onRetry:t,collecting:n}){return(0,Ra.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,Ra.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"We can\u2019t reach analytics right now"}),(0,Ra.jsx)("p",{className:"af-max-w-xs af-text-xs af-leading-relaxed af-text-muted-foreground",children:n===!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,Ra.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 Vr({what:e="No data"}){return(0,Ra.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 bn({sourced:e,error:t,isLoading:n,what:s,onRetry:a,collecting:r,children:o}){return n?(0,Ra.jsx)("div",{role:"status","aria-label":`Loading ${s}`,className:"af-h-24 af-animate-pulse af-rounded-md af-bg-muted"}):t?(0,Ra.jsx)(Tl,{what:s,onRetry:a,collecting:r}):!e||e.status==="unreachable"?(0,Ra.jsx)(Tl,{what:s,onRetry:a,collecting:r}):(0,Ra.jsx)(Ra.Fragment,{children:o(e.data)})}var tt=require("react/jsx-runtime");function Ei({rows:e,dimension:t,metric:n,metricLabel:s,secondary:a,emptyCopy:r="No data for this period",onFilter:o,canFilter:u,maxRows:g=9}){let[l,i]=Kn.useState(!1);if(e.length===0)return(0,tt.jsx)(Vr,{what:r});let d=e.reduce((c,m)=>Math.max(c,Number(m[n]??0)),0)||1,b=Math.max(0,e.length-g),f=l?e:e.slice(0,g);return(0,tt.jsxs)(tt.Fragment,{children:[(0,tt.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,tt.jsx)("thead",{children:(0,tt.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,tt.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:t==="pathname"?"Page":"Name"}),(0,tt.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:s})]})}),(0,tt.jsx)("tbody",{children:f.map((c,m)=>{let p=Number(c[n]??0),y=c[t]??null,S=Ys(y),C=a?c[a]:null,E=y!==null&&(u?u(y,C):!0);return(0,tt.jsxs)("tr",{className:"af-border-t af-border-border",children:[(0,tt.jsxs)("td",{className:"af-relative af-py-1.5 af-pr-2",children:[(0,tt.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,p/d*100)}%`}}),y!==null&&o&&E?(0,tt.jsx)("button",{type:"button",onClick:()=>o(y,C),title:`Filter by ${S}`,"aria-label":`Filter by ${S}`,className:"af-relative af-break-words af-text-left af-text-foreground hover:af-underline",children:S}):(0,tt.jsx)("span",{className:"af-relative af-break-words af-text-foreground",children:S}),C?(0,tt.jsx)("span",{className:"af-relative af-ml-1 af-text-xs af-text-muted-foreground",children:C}):null]}),(0,tt.jsx)("td",{className:"af-py-1.5 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p)})]},`${S}-${C??""}-${m}`)})})]}),b>0?(0,tt.jsx)("button",{type:"button",onClick:()=>i(c=>!c),className:"af-mt-1 af-w-full af-rounded-md af-py-1.5 af-text-xs af-text-muted-foreground hover:af-bg-muted hover:af-text-foreground",children:l?"Show fewer":`Show all ${e.length}`}):null]})}function Xs({title:e,tabs:t,defaultTabId:n,headerRight:s}){let[a,r]=Kn.useState(n),o=t.find(f=>f.id===a)??t[0],u=Kn.useId(),g=f=>`${u}-tab-${f}`,l=f=>`${u}-panel-${f}`,i=Kn.useRef(null),d=(f,c)=>{f.preventDefault();let m=(c+t.length)%t.length;r(t[m].id),i.current?.querySelectorAll('[role="tab"]')?.[m]?.focus()};return(0,tt.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,tt.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,tt.jsx)("div",{ref:i,role:"tablist","aria-label":e,onKeyDown:f=>{let c=t.findIndex(m=>m.id===a);f.key==="ArrowRight"&&d(f,c+1),f.key==="ArrowLeft"&&d(f,c-1),f.key==="Home"&&d(f,0),f.key==="End"&&d(f,t.length-1)},className:"af-flex af-flex-wrap af-gap-1",children:t.map(f=>(0,tt.jsx)("button",{id:g(f.id),role:"tab",type:"button","aria-selected":f.id===a,"aria-controls":l(f.id),tabIndex:f.id===a?0:-1,onClick:()=>r(f.id),className:f.id===a?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:f.label},f.id))}),s]}),o?(0,tt.jsx)("div",{id:l(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 ia=re(require("react"),1),Tn=re(require("@radix-ui/react-popover"),1);var Zn=3,Jn=100;var Fe=require("react/jsx-runtime"),Qs={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"},Du=Object.keys(Qs);function kl(e){let t=Qs[e.dimension],n=e.operator==="is_not"?"is not":"is",s=e.values.map(a=>Ys(a)).join(" or ");return`${t} ${n} ${s}`}function Ii(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));if(n>=0){let s=[...new Set([...e[n].values,...t.values])];return s.length>100||s.length===e[n].values.length?e:e.map((a,r)=>r===n?{...a,values:s}:a)}return t.values.length>100||e.length>=3?e:[...e,t]}function Lu(e,t){let n={};for(let[s,a]of Object.entries(t)){let r=e.get(s)??new Set;for(let o of a)r.add(o);e.set(s,r),n[s]=[...r]}return n}function El(e,t){let n=e.findIndex(s=>s.dimension===t.dimension&&(s.operator??"is")===(t.operator??"is"));return n>=0?e.map((s,a)=>a===n?t:s):t.values.length>100||e.length>=3?e:[...e,t]}function Ou(e){return{dimension:e,operator:"is",search:"",picked:[]}}function Il(e,t,n,s={}){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 a=Lu(e.byDimension,n);for(let[r,o]of Object.entries(s)){let u=e.foldsByLabel.get(r)??new Set;for(let g of o)u.add(g);e.foldsByLabel.set(r,u)}return{suggestions:a,folds:new Map([...e.foldsByLabel].map(([r,o])=>[r,[...o]]))}}function Al(e){let{filters:t,onChange:n}=e,s=t.length>=3;return ia.useEffect(()=>{if(t.length===0)return;let a=r=>{let o=r.target;o&&(o.tagName==="INPUT"||o.closest('[role="dialog"]'))||r.key==="Escape"&&n([])};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[t.length,n]),(0,Fe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[t.map((a,r)=>(0,Fe.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,Fe.jsx)("span",{className:"af-text-foreground",children:kl(a)}),(0,Fe.jsx)("button",{type:"button","aria-label":`Remove filter ${kl(a)}`,onClick:()=>n(t.filter((o,u)=>u!==r)),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"})]},`${a.dimension}-${a.operator??"is"}`)),(0,Fe.jsx)(Bu,{...e,disabled:s}),t.length>0?(0,Fe.jsx)("button",{type:"button",onClick:()=>n([]),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 Bu({filters:e,onChange:t,suggestions:n,resetKey:s,disabled:a,expandValues:r}){let[o,u]=ia.useState(!1),g=ia.useRef(null),[l,i]=ia.useState(null);ia.useEffect(()=>{i(g.current?.closest(".aifeatures-admin")??null)},[]);let[d,b]=ia.useState(null),[f,c]=ia.useState("is"),[m,p]=ia.useState(""),[y,S]=ia.useState([]);ia.useEffect(()=>{o||(b(null),c("is"),p(""),S([]))},[o]);let C=ia.useRef(s);C.current!==s&&(C.current=s,o&&u(!1),d!==null&&b(null),y.length>0&&S([]),m!==""&&p(""),f!=="is"&&c("is"));let E=k=>{let L=Ou(k);b(L.dimension),S(L.picked),p(L.search),c(L.operator)},_=(d?n[d]??[]:[]).filter(k=>k.toLowerCase().includes(m.trim().toLowerCase())),T=d===null||y.length===0?null:Ii(e,{dimension:d,operator:f,values:r?r(d,y):y}),A=T!==null&&T!==e,N=()=>{let k=T;!k||k===e||(t(k),u(!1))};return(0,Fe.jsxs)(Tn.Root,{open:o,onOpenChange:u,children:[(0,Fe.jsx)(Tn.Trigger,{asChild:!0,children:(0,Fe.jsx)("button",{ref:g,type:"button",disabled:!1,title:a?`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,Fe.jsx)(Tn.Portal,{container:l,children:(0,Fe.jsx)(Tn.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:d===null?(0,Fe.jsxs)("div",{children:[(0,Fe.jsx)("p",{className:"af-mb-2 af-text-xs af-font-medium af-text-foreground",children:"Filter by"}),(0,Fe.jsx)("div",{className:"af-max-h-96 af-overflow-y-auto",children:Du.filter(k=>n[k]!==void 0).map(k=>{let L=n[k]?.length??0,P=!e.some(Y=>Y.dimension===k)&&e.length>=3;return(0,Fe.jsxs)("button",{type:"button",onClick:()=>E(k),disabled:L===0||P,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,Fe.jsx)("span",{children:Qs[k]}),(0,Fe.jsx)("span",{className:"af-text-muted-foreground",children:L===0?"no data":P?"no room":L})]},k)})})]}):(0,Fe.jsxs)("div",{children:[(0,Fe.jsxs)("div",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Fe.jsx)("button",{type:"button",onClick:()=>E(null),className:"af-text-xs af-text-muted-foreground hover:af-text-foreground",children:"\u2039 Back"}),(0,Fe.jsx)("span",{className:"af-text-xs af-font-medium af-text-foreground",children:Qs[d]}),(0,Fe.jsxs)("select",{"aria-label":"Operator",value:f,onChange:k=>c(k.target.value),className:"af-rounded-md af-border af-border-border af-bg-background af-px-1 af-py-0.5 af-text-xs af-text-foreground",children:[(0,Fe.jsx)("option",{value:"is",children:"is"}),(0,Fe.jsx)("option",{value:"is_not",children:"is not"})]})]}),(0,Fe.jsx)("input",{type:"text",value:m,onChange:k=>p(k.target.value),placeholder:"Search\u2026","aria-label":`Search ${Qs[d]}`,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,Fe.jsx)("div",{className:"af-max-h-48 af-overflow-y-auto",children:_.length===0?(0,Fe.jsxs)("p",{className:"af-px-2 af-py-3 af-text-xs af-text-muted-foreground",children:["Nothing matches \u201C",m,"\u201D."]}):_.map(k=>(0,Fe.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,Fe.jsx)("input",{type:"checkbox",checked:y.includes(k),disabled:!y.includes(k)&&y.length>=100,onChange:L=>S(P=>L.target.checked?[...P,k]:P.filter(Y=>Y!==k))}),(0,Fe.jsx)("span",{className:"af-break-all",children:Ys(k)})]},k))}),(0,Fe.jsx)("button",{type:"button",onClick:N,disabled:!A,className:"af-mt-2 af-w-full af-rounded-md af-bg-muted af-px-2 af-py-1.5 af-text-xs af-font-medium af-text-foreground hover:af-bg-muted/70 disabled:af-opacity-50",children:y.length<=1?"Apply filter":y.length>=100?`Apply filter (${y.length} values \u2014 the maximum)`:`Apply filter (${y.length} values)`})]})})})]})}var ft=require("react/jsx-runtime"),Fu=[{key:"visitors",label:"Unique visitors",get:e=>e.visitors,format:Zt,chart:"visitors"},{key:"visits",label:"Total visits",get:e=>e.visits,format:Zt,chart:"visits"},{key:"pageviews",label:"Total pageviews",get:e=>e.pageviews,format:Zt,chart:"pageviews"},{key:"viewsPerVisit",label:"Views per visit",get:e=>e.views_per_visit,format:e=>e.toFixed(2),chart:"views_per_visit"},{key:"bounceRate",label:"Bounce rate",get:e=>e.bounce_rate,format:fs,downIsGood:!0,chart:"bounce_rate"},{key:"visitDuration",label:"Visit duration",get:e=>e.visit_duration_seconds,format:Js,chart:"visit_duration_seconds"}];function Uu({current:e,previous:t,downIsGood:n}){if(t===0)return null;let s=(e-t)/t;if(Math.abs(s)<5e-4)return null;let a=s>0,r=n?!a:a,o=`${a?"+":""}${(s*100).toFixed(1)}%`;return(0,ft.jsx)("span",{className:r?"af-text-xs af-font-medium af-text-emerald-600":"af-text-xs af-font-medium af-text-rose-600",children:o})}function Dl({summary:e,selected:t,onSelect:n}){return(0,ft.jsx)("div",{className:"af-@container",children:(0,ft.jsx)("dl",{className:"af-grid af-grid-cols-2 af-gap-3 @xl:af-grid-cols-3 @4xl:af-grid-cols-6",children:Fu.map(s=>{let a=s.chart===t,r=n!==void 0,o=(0,ft.jsxs)(ft.Fragment,{children:[(0,ft.jsx)("dt",{className:"af-min-h-[2.25rem] af-text-xs af-leading-tight af-text-muted-foreground",children:s.label}),(0,ft.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,ft.jsx)("span",{className:"af-text-xl af-font-semibold af-tabular-nums af-text-foreground",children:s.format(s.get(e.current))}),e.previous?(0,ft.jsx)(Uu,{current:s.get(e.current),previous:s.get(e.previous),downIsGood:s.downIsGood}):null]})]});return r?(0,ft.jsx)("button",{type:"button","aria-pressed":a,onClick:()=>n(s.chart),className:a?"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},s.key):(0,ft.jsx)("div",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:o},s.key)})})})}function Ai({currentVisitors:e,asOf:t,isStale:n,isUnreachable:s,isInitialLoad:a=!1,scopeIsSiteWide:r=!1}){if(a&&!s)return(0,ft.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,ft.jsx)("span",{className:"af-h-2 af-w-2 af-rounded-full af-bg-muted"}),(0,ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors"})]});if(s||e===null)return(0,ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"Live visitors unavailable"});let o=t?_l(t):"freshness unknown",u=r?" across the whole site, not the current filter,":"",g=n?`${e} current visitors${u} ${o} (not updating)`:`${e} current visitors${u} ${o}`;return(0,ft.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,ft.jsx)("span",{"aria-hidden":"true",className:n?"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,ft.jsx)("span",{className:"af-text-sm af-font-medium af-tabular-nums af-text-foreground",children:e}),(0,ft.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:r?"current visitors, site-wide":"current visitors"}),(0,ft.jsx)("span",{className:"af-sr-only",children:g})]})}var Ll=re(require("react"),1),Ol=require("lucide-react");var Ve=require("react/jsx-runtime");function Hr(e,t){return!t||e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function zr({rows:e,denominator:t,windowPrecedesCollection:n=!1,coverageUnknown:s=!1,emptyCopy:a="No conversions in this period",maxRows:r=9,primaryConversion:o}){let[u,g]=Ll.useState(!1),l=e.filter(p=>!p.implicit||p.visitors>0||p.events>0||Hr(p,o)),i=n?(0,Ve.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."}):s?(0,Ve.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;if(l.length===0)return(0,Ve.jsxs)(Ve.Fragment,{children:[(0,Ve.jsx)(Vr,{what:a}),i]});let d=l.slice(0,r),b=o?l.find(p=>Hr(p,o)):void 0,f=b&&!d.includes(b)?l.filter(p=>d.includes(p)||p===b).slice(0,Math.max(0,r-1)).concat(b):d,c=u?e:f,m=Math.max(0,e.length-f.length);return(0,Ve.jsxs)(Ve.Fragment,{children:[(0,Ve.jsxs)("table",{className:"af-w-full af-text-sm",children:[(0,Ve.jsx)("thead",{children:(0,Ve.jsxs)("tr",{className:"af-text-xs af-text-muted-foreground",children:[(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-left af-font-normal",children:"Goal"}),(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Visitors"}),(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Total events"}),(0,Ve.jsx)("th",{scope:"col",className:"af-py-1 af-text-right af-font-normal",children:"Rate"})]})}),(0,Ve.jsx)("tbody",{children:c.map((p,y)=>(0,Ve.jsxs)("tr",{className:"af-border-t af-border-border","aria-current":Hr(p,o)?"true":void 0,children:[(0,Ve.jsx)("td",{className:"af-py-1.5 af-pr-2 af-break-words",children:Hr(p,o)?(0,Ve.jsxs)("span",{className:"af-flex af-items-center af-gap-1.5",children:[(0,Ve.jsx)(Ol.Star,{className:"af-h-3 af-w-3 af-shrink-0 af-fill-current af-text-primary","aria-hidden":"true"}),(0,Ve.jsx)("span",{className:"af-font-medium af-text-foreground",children:p.goal}),(0,Ve.jsx)("span",{className:"af-sr-only",children:"(your main conversion)"})]}):p.goal}),(0,Ve.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p.visitors)}),(0,Ve.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:Zt(p.events)}),(0,Ve.jsx)("td",{className:"af-py-1.5 af-pl-2 af-text-right af-tabular-nums af-text-muted-foreground",children:p.conversion_rate===null?(0,Ve.jsx)("span",{"aria-label":"No rate: no visitors in this period",children:"\u2014"}):fs(p.conversion_rate)})]},`${p.goal}-${y}`))})]}),m>0?(0,Ve.jsx)("button",{type:"button",onClick:()=>g(p=>!p),className:"af-mt-2 af-text-xs af-font-medium af-text-muted-foreground hover:af-text-foreground",children:u?"Show fewer":`Show all ${e.length} goals`}):null,(0,Ve.jsxs)("p",{className:"af-mt-2 af-text-xs af-text-muted-foreground",children:["Rate is the share of all ",Zt(t)," ",t===1?"visitor":"visitors"," this period, so goals overlap and the rates don\u2019t add up to 100%."]}),i]})}var oa=require("recharts");var pt=require("react/jsx-runtime"),qr={visitors:"Unique visitors",visits:"Total visits",pageviews:"Total pageviews",views_per_visit:"Views per visit",bounce_rate:"Bounce rate",visit_duration_seconds:"Visit duration"},Li={visitors:Zt,visits:Zt,pageviews:Zt,views_per_visit:e=>e.toFixed(2),bounce_rate:fs,visit_duration_seconds:Js},Mu=31,$u=new Set(["visitors","visits","pageviews"]),Vu={...Li,bounce_rate:Nl,visit_duration_seconds:Sl},Di=[1,2,5,10,20,25,50,100,200,250,500,1e3,2e3,2500,5e3,1e4,2e4,25e3,5e4,1e5,2e5,25e4,5e5,1e6],Hu=[5,10,15,30,60,120,300,600,900,1800,3600,7200],zu=[.01,.02,.05,.1,.2,.25,.5,1],qu=[.25,.5,1,2,5,10,25,50],ju={visitors:Di,visits:Di,pageviews:Di,views_per_visit:qu,bounce_rate:zu,visit_duration_seconds:Hu};function Gu({active:e,payload:t,label:n,metric:s}){if(!e||!t||t.length===0)return null;let a=t[0].payload;return(0,pt.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,pt.jsx)("p",{className:"af-mb-1 af-text-[10px] af-font-medium af-uppercase af-tracking-wide af-text-muted-foreground",children:qr[s]}),(0,pt.jsxs)("p",{className:"af-flex af-items-center af-gap-3 af-text-sm",children:[(0,pt.jsx)("span",{"aria-hidden":"true",className:"af-h-2 af-w-2 af-shrink-0 af-rounded-full af-bg-primary"}),(0,pt.jsx)("span",{className:"af-text-muted-foreground",children:Cl(String(n))}),(0,pt.jsx)("span",{className:"af-ml-auto af-font-semibold af-tabular-nums",children:Li[s](Number(a[s]??0))})]})]})}function jr({rows:e,window:t,metric:n,timeZone:s="UTC",height:a=260}){let r=Pl(t,e,s),o=Li[n],u=Vu[n],g=Rl(r.reduce((i,d)=>Math.max(i,Number(d[n]??0)),0),ju[n]),l=`${qr[n]} by day: ${r.map(i=>`${ki(i.date)}: ${o(Number(i[n]??0))}`).join("; ")}.`;return(0,pt.jsxs)("figure",{"aria-label":`${qr[n]} over time`,className:"af-m-0",children:[(0,pt.jsx)(oa.ResponsiveContainer,{width:"100%",height:a,children:(0,pt.jsxs)(oa.AreaChart,{data:r,margin:{top:8,right:8,bottom:0,left:0},tabIndex:-1,children:[(0,pt.jsx)("defs",{children:(0,pt.jsxs)("linearGradient",{id:"af-analytics-area",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,pt.jsx)("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),(0,pt.jsx)("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),(0,pt.jsx)(oa.CartesianGrid,{vertical:!1,stroke:"hsl(var(--border))",strokeDasharray:"3 3"}),(0,pt.jsx)(oa.XAxis,{dataKey:"date",tickFormatter:ki,tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickMargin:8,minTickGap:24}),(0,pt.jsx)(oa.YAxis,{allowDecimals:!$u.has(n),width:"auto",fontSize:12,tickLine:!1,axisLine:!1,tickMargin:4,...g?{ticks:g,domain:[0,g[g.length-1]]}:{},tickFormatter:i=>u(i),tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),(0,pt.jsx)(oa.Tooltip,{cursor:{stroke:"hsl(var(--muted-foreground))",strokeWidth:1},content:(0,pt.jsx)(Gu,{metric:n})}),(0,pt.jsx)(oa.Area,{type:"linear",dataKey:n,name:qr[n],stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#af-analytics-area)",dot:r.length<=Mu?{r:2.5,fill:"hsl(var(--primary))",strokeWidth:0}:!1,activeDot:{r:4,stroke:"hsl(var(--card))",strokeWidth:2},isAnimationActive:!1})]})}),(0,pt.jsx)("figcaption",{className:"af-sr-only",children:l})]})}var oe=require("react/jsx-runtime"),Wu="2026-08-13",Ku=[{value:7,label:"Last 7 days"},{value:30,label:"Last 30 days"},{value:90,label:"Last 90 days"}],Zu=["sources","utm/campaign","pages","entry-pages","exit-pages","countries","regions","cities","browsers","operating-systems","devices"];function Bl({filters:e,onFiltersChange:t,refreshKey:n,onBackToWebsite:s,primaryConversion:a,className:r,published:o,lastPublishedAt:u}){let[g,l]=mt.useState(30),[i,d]=mt.useState(()=>Yr()),b=e!==void 0&&t!==void 0,[f,c]=mt.useState(e??[]),{api:m}=ae(),[p,y]=mt.useState(m);p!==m&&(y(m),!b&&f.length>0&&c([]));let S=b?e:f,C=mt.useCallback(F=>{t&&t(F),b||c(F)},[t,b]),E=mt.useCallback((F,ye,Ne)=>{let Ee=Array.isArray(ye)?ye:[ye];if(Ee.length===0)return null;let Me=Ii(S,{dimension:F,operator:"is",values:Ee});if(Ne&&(!Ne.value||(Me=El(Me,{dimension:Ne.dimension,operator:"is",values:[Ne.value]}),!Me.find(gt=>gt.dimension===Ne.dimension&&gt.operator!=="is_not")?.values.includes(Ne.value))))return null;let ot=Me.find($e=>$e.dimension===F&&$e.operator!=="is_not");return Ee.every($e=>ot?.values.includes($e))?JSON.stringify(Me)===JSON.stringify(S)?null:Me:null},[S]),v=mt.useCallback((F,ye,Ne)=>E(F,ye,Ne)!==null,[E]),_=mt.useCallback((F,ye,Ne)=>{let Ee=E(F,ye,Ne);Ee&&C(Ee)},[E,C]),[T,A]=mt.useState("visitors"),N=Gn(g,{refreshKey:n,breakdowns:Zu,filters:S}),k=N.status.data,L=N.reportedZone??k?.timezone,P=L??i??ps()??"UTC",{notCollecting:Y,awaitingFirstVisit:J,firstVisitTooRecent:q,holdingForFirstData:se}=Mr(k,{published:o}),ce=o===!1,ge=Ks({collecting:J||Y?!1:k?.collecting,statusFailed:N.status.error!=null,identity:k?.analytics_id}),$=mt.useRef({api:null,period:null,byDimension:new Map,foldsByLabel:new Map}),te=mt.useMemo(()=>{let F=N.breakdowns.sources?.data,ye={};if(!F||F.status!=="ok")return ye;for(let Ne of F.data){let Ee=Ne.source,Me=Ne.sources;typeof Ee=="string"&&Array.isArray(Me)&&Me.length>0&&(ye[Ee]=Me)}return ye},[N.breakdowns.sources?.data]),U=mt.useMemo(()=>{let F=(Ee,Me)=>{let ot=N.breakdowns[Ee]?.data;return!ot||ot.status!=="ok"?[]:[...new Set(ot.data.map($e=>$e[Me]).filter($e=>typeof $e=="string"&&$e!==""))]};return{channel:N.channels.data?.status==="ok"?[...new Set(N.channels.data.data.map(Ee=>Ee.channel))]:[],source:F("sources","source"),campaign:F("utm/campaign","campaign"),page:F("pages","pathname"),entry_page:F("entry-pages","pathname"),exit_page:F("exit-pages","pathname"),country:F("countries","country"),browser:F("browsers","browser"),os:F("operating-systems","os"),device:F("devices","device")}},[N.breakdowns,N.channels.data]),[Pe,ue]=mt.useState({}),at=JSON.stringify(U),[Te,He]=mt.useState(new Map),Ye=JSON.stringify(te);mt.useEffect(()=>{let{suggestions:F,folds:ye}=Il($.current,{api:m,period:g},JSON.parse(at),JSON.parse(Ye));ue(F),He(ye)},[at,Ye,m,g]);let Le=mt.useCallback((F,ye)=>F!=="source"?ye:[...new Set(ye.flatMap(Ne=>{let Ee=[...Te.get(Ne)??[],...te[Ne]??[]];return Ee.length>0?Ee:[Ne]}))],[Te,te]),Et=mt.useMemo(()=>{let F=N.conversions.error;return F instanceof ht&&F.details?.code==="goals_exceed_report_budget"?F.message:null},[N.conversions.error]),D=mt.useMemo(()=>{let F=[N.summary,N.timeseries,N.channels,...Object.values(N.breakdowns)];for(let ye of F){let Ne=ye?.error;if(Ne instanceof ht&&Ne.details?.code==="filter_unsupported")return Ne.message}return null},[N.summary,N.timeseries,N.channels,N.breakdowns]),M=(F,ye,Ne,Ee,Me,ot,$e,gt,me)=>()=>{let Ie=N.breakdowns[F];return(0,oe.jsx)(bn,{sourced:Ie?.data??null,error:Ie?.error,isLoading:Ie?.isLoading,what:ye,collecting:k?.collecting,onRetry:N.refetch,children:lt=>{let la=Ot=>gt?Le(gt,[Ot]):Ot;return(0,oe.jsx)(Ei,{rows:lt,dimension:Ne,metric:Ee,metricLabel:Me,secondary:ot,emptyCopy:S.length>0?"No data for this filter":$e,canFilter:gt?(Ot,Jt)=>v(gt,la(Ot),me?{dimension:me,value:Jt}:void 0):()=>!1,onFilter:gt?(Ot,Jt)=>_(gt,la(Ot),me?{dimension:me,value:Jt}:void 0):void 0})}})};if($r({status:k,holdingForFirstData:se,refetchStatus:N.refetchStatus,refetch:N.refetch}),Y){let F=!!u&&String(u).slice(0,10)<Wu;return(0,oe.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Analytics isn\u2019t collecting yet"}),(0,oe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:ce?"Publish your site to start collecting visitor data. Nothing is recorded until a published page is visited.":F?"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 J?(0,oe.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Collecting \u2014 no visits recorded yet"}),(0,oe.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."})]})}):q?(0,oe.jsxs)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:[(0,oe.jsx)("div",{className:"af-mb-3 af-flex af-justify-end",children:(0,oe.jsx)(Ti,{value:P,chosen:i,onChange:F=>{Xr(F),d(F)}})}),(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"First visit recorded \u2014 reports start tomorrow"}),(0,oe.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",k?.timezone?` ${k.timezone.replace(/_/g," ")} time`:"",". Live visitors below is up to date now."]}),(0,oe.jsx)("div",{className:"af-mt-4 af-flex af-justify-center",children:(0,oe.jsx)(Ai,{currentVisitors:ge.currentVisitors,asOf:ge.asOf,isStale:ge.isStale,isUnreachable:ge.isUnreachable||ge.error!==null,isInitialLoad:ge.isInitialLoad})})]})]}):(0,oe.jsx)(wt,{title:"Analytics",onBackToWebsite:s,className:r,children:(0,oe.jsxs)("div",{className:"af-@container af-flex af-flex-col af-gap-4",children:[(0,oe.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-justify-between af-gap-2",children:[(0,oe.jsx)("div",{role:"group","aria-label":"Period",className:"af-flex af-gap-1",children:Ku.map(F=>(0,oe.jsx)("button",{type:"button","aria-pressed":F.value===g,onClick:()=>l(F.value),className:F.value===g?"af-rounded-md af-bg-muted af-px-2 af-py-1 af-text-xs af-font-medium af-text-foreground":"af-rounded-md af-px-2 af-py-1 af-text-xs af-text-muted-foreground hover:af-text-foreground",children:F.label},F.value))}),(0,oe.jsx)(Ti,{value:P,chosen:i,onChange:F=>{Xr(F),d(F)}}),(0,oe.jsx)(Ai,{currentVisitors:ge.currentVisitors,asOf:ge.asOf,isStale:ge.isStale,isUnreachable:ge.isUnreachable||ge.error!==null,isInitialLoad:ge.isInitialLoad,scopeIsSiteWide:S.length>0})]}),(0,oe.jsx)(Al,{filters:S,onChange:C,suggestions:Pe,expandValues:Le,resetKey:m}),D?(0,oe.jsxs)("div",{role:"status",className:"af-rounded-lg af-border af-border-dashed af-border-border af-p-8 af-text-center",children:[(0,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"This filter can\u2019t be applied here"}),(0,oe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-md af-text-xs af-leading-relaxed af-text-muted-foreground",children:D}),(0,oe.jsx)("button",{type:"button",onClick:()=>C([]),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,!D&&k?.timezone_defaulted?(0,oe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Your timezone could not be read, so days are counted in UTC. Pick one above to see them in your local days."}):null,D?null:(0,oe.jsxs)(oe.Fragment,{children:[(0,oe.jsx)(bn,{sourced:N.summary.data,error:N.summary.error,isLoading:N.summary.isLoading,what:"The traffic summary",collecting:k?.collecting,onRetry:N.refetch,children:F=>(0,oe.jsxs)(oe.Fragment,{children:[(0,oe.jsx)(Dl,{summary:F,selected:T,onSelect:A}),F.previous_unavailable?(0,oe.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:[F.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,oe.jsx)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card af-p-3",children:(0,oe.jsx)(bn,{sourced:N.timeseries.data,error:N.timeseries.error,isLoading:N.timeseries.isLoading,what:"The visitors chart",collecting:k?.collecting,onRetry:N.refetch,children:F=>{let ye=N.timeseries.data?.status==="ok"?N.timeseries.data.window:{from:"",to:""};return(0,oe.jsx)(jr,{rows:F,window:ye,metric:T,timeZone:L??"UTC"})}})}),(0,oe.jsxs)("div",{className:"af-grid af-gap-4 @3xl:af-grid-cols-2",children:[(0,oe.jsx)(Xs,{title:"Acquisition",defaultTabId:"channels",tabs:[{id:"channels",label:"Channels",render:()=>(0,oe.jsx)(bn,{sourced:N.channels.data,error:N.channels.error,isLoading:N.channels.isLoading,what:"Channels",collecting:k?.collecting,onRetry:N.refetch,children:F=>(0,oe.jsx)(Ei,{rows:F,dimension:"channel",metric:"visits",metricLabel:"Visits",emptyCopy:S.length>0?"No data for this filter":"No data for this period",canFilter:ye=>v("channel",ye),onFilter:ye=>_("channel",ye)})})},{id:"sources",label:"Sources",render:M("sources","Sources","source","visitors","Visitors",void 0,void 0,"source")},{id:"utm",label:"Campaigns",render:M("utm/campaign","Campaigns","campaign","visitors","Visitors",void 0,"No campaign traffic in this period","campaign")}]}),(0,oe.jsx)(Xs,{title:"Pages",defaultTabId:"top",tabs:[{id:"top",label:"Top pages",render:M("pages","Top pages","pathname","visitors","Visitors",void 0,void 0,"page")},{id:"entry",label:"Entry pages",render:M("entry-pages","Entry pages","pathname","entries","Unique entrances",void 0,void 0,"entry_page")},{id:"exit",label:"Exit pages",render:M("exit-pages","Exit pages","pathname","exits","Unique exits",void 0,void 0,"exit_page")}]}),(0,oe.jsx)(Xs,{title:"Locations",defaultTabId:"countries",tabs:[{id:"countries",label:"Countries",render:M("countries","Countries","country","visitors","Visitors",void 0,void 0,"country")},{id:"regions",label:"Regions",render:M("regions","Regions","region","visitors","Visitors","country",void 0,"region","country")},{id:"cities",label:"Cities",render:M("cities","Cities","city","visitors","Visitors","country",void 0,"city","country")}]}),(0,oe.jsx)(Xs,{title:"Technology",defaultTabId:"browsers",tabs:[{id:"browsers",label:"Browsers",render:M("browsers","Browsers","browser","visitors","Visitors",void 0,void 0,"browser")},{id:"os",label:"Operating systems",render:M("operating-systems","Operating systems","os","visitors","Visitors",void 0,void 0,"os")},{id:"devices",label:"Devices",render:M("devices","Devices","device","visitors","Visitors",void 0,void 0,"device")}]})]}),(0,oe.jsxs)("section",{className:"af-rounded-lg af-border af-border-border af-bg-card",children:[(0,oe.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,oe.jsx)("h3",{className:"af-text-sm af-font-medium af-text-foreground",children:"Conversions"})}),(0,oe.jsxs)("div",{className:"af-px-3 af-py-2",children:[S.length>0?(0,oe.jsxs)("p",{className:"af-mb-2 af-text-xs af-text-muted-foreground",children:["Conversions are site-wide and don\u2019t follow the"," ",S.length===1?"filter":"filters"," above."]}):null,Et!==null?(0,oe.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,oe.jsx)("p",{className:"af-text-sm af-font-medium af-text-foreground",children:"Too many goal definitions to report on"}),(0,oe.jsx)("p",{className:"af-mx-auto af-mt-1 af-max-w-sm af-text-xs af-leading-relaxed af-text-muted-foreground",children:Et})]}):(0,oe.jsx)(bn,{sourced:N.conversions.data,error:N.conversions.error,isLoading:N.conversions.isLoading,what:"Conversions",collecting:k?.collecting,onRetry:N.refetch,children:F=>{let ye=N.conversions.data?.status==="ok"?N.conversions.data:null;return(0,oe.jsx)(oe.Fragment,{children:(0,oe.jsx)(zr,{rows:F,primaryConversion:a,denominator:ye?.denominator??0,windowPrecedesCollection:ye?.window_precedes_collection??!1,coverageUnknown:ye?.first_seen_unavailable??!1,emptyCopy:"No conversions in this period"})})}})]})]})]})]})})}var Hl=re(require("react"),1),Dt=require("lucide-react");var Fa=re(require("react"),1),yn=require("lucide-react");var xe=require("react/jsx-runtime"),Fl=90,Ul=100;function Ju(e){return e.kind!=="event"?!1:!(e.goal==="Purchase"&&e.implicit)}function Ml(e){return!!e.label&&e.label!==e.target}function Yu(e,t,n){if(!t)return e===0?"We couldn\u2019t tell whether these conversions recorded what they pointed at.":"We couldn\u2019t tell how much of this conversion these account for.";let{goal_events:s,with_a_value:a}=t;return s===0?e===0?"Nothing specific has converted here yet.":null:a===0?"These conversions happened before we recorded what they pointed at, so there is nothing specific to pick yet.":a<s?n?`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest are further down the list, or happened before we recorded what they pointed at.`:`These cover ${a.toLocaleString()} of ${s.toLocaleString()} conversions \u2014 the rest happened before we recorded what they pointed at.`:null}function er(e,t){return e.goal!==t.goal?!1:t.implicit===void 0||e.implicit===t.implicit}function $l({current:e,onChange:t,onClose:n}){let{api:s}=ae(),[a,r]=Fa.useState(null),[o,u]=Fa.useState(!1),[g,l]=Fa.useState({at:"goals"}),[i,d]=Fa.useState(null),[b,f]=Fa.useState(null),[c,m]=Fa.useState(!1),[p,y]=Fa.useState(null),S=Fa.useRef(0);Fa.useEffect(()=>{let _=!0;return r(null),u(!1),l({at:"goals"}),d(null),f(null),m(!1),y(null),S.current+=1,s.getAnalyticsConversions(Fl).then(T=>{if(_){if(T.status!=="ok"){u(!0);return}r(T.data)}}).catch(()=>{_&&u(!0)}),()=>{_=!1}},[s]);let C=_=>{l({at:"targets",row:_}),d(null),f(null),m(!1),y(null);let T=++S.current;s.getAnalyticsGoalTargets(_.goal,Fl,Ul).then(A=>{if(T===S.current){if(A.status!=="ok"){f("failed");return}d(A.data),m(A.truncated===!0),y(A.coverage??null)}}).catch(A=>{if(T!==S.current)return;let N=A instanceof ht?A.details?.code:void 0;f(N==="goal_has_no_targets"?"no-values":"failed")})},E=_=>{t(_),n()};if(o)return(0,xe.jsx)("div",{className:"af-p-1 af-text-sm af-text-muted-foreground",children:"We couldn\u2019t read this site\u2019s conversions just now."});if(!a)return(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-1 af-text-sm af-text-muted-foreground",children:[(0,xe.jsx)(yn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,xe.jsx)("span",{children:"Loading your conversions\u2026"})]});if(g.at==="targets"){let _=g.row,T=new Map;for(let A of i??[])T.set(A.label,(T.get(A.label)??0)+1);return(0,xe.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[(0,xe.jsx)("header",{className:"af-flex af-items-center af-gap-1",children:(0,xe.jsxs)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>l({at:"goals"}),children:[(0,xe.jsx)(yn.ChevronLeft,{className:"af-h-4 af-w-4"}),(0,xe.jsx)("span",{children:"All conversions"})]})}),(0,xe.jsxs)("button",{type:"button","aria-current":e&&er(_,e)&&!e.target?"true":void 0,className:"af-flex af-items-center af-gap-2 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>E({goal:_.goal,implicit:_.implicit}),children:[e&&er(_,e)&&!e.target&&(0,xe.jsx)(yn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,xe.jsxs)("span",{children:["Any ",_.goal.toLowerCase()]})]}),b==="no-values"&&(0,xe.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"This conversion has no specific targets to choose from."}),b==="failed"&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2 af-px-2 af-py-1.5",children:[(0,xe.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"We couldn\u2019t load the targets for this conversion."}),(0,xe.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:()=>C(_),children:"Try again"})]}),!i&&b===null&&(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,xe.jsx)(yn.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}),(0,xe.jsx)("span",{children:"Loading\u2026"})]}),i&&(0,xe.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:Yu(i.length,p,c)}),c&&(0,xe.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["Showing the top ",Ul,". If what you want isn\u2019t here, pick the conversion itself instead."]}),i?.some(Ml)&&(0,xe.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:"Named forms can\u2019t be pinned on their own yet \u2014 pick the conversion itself and they are all counted."}),i?.map(A=>{let N=!!(e&&er(_,e)&&e.target===A.target),k=T.get(A.label)>1;return Ml(A)?(0,xe.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-3 af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:[(0,xe.jsxs)("span",{className:"af-min-w-0",children:[(0,xe.jsx)("span",{className:"af-block af-truncate",children:A.label}),k&&(0,xe.jsx)("span",{className:"af-block af-truncate af-text-xs",children:A.target})]}),(0,xe.jsx)("span",{className:"af-shrink-0 af-text-xs",children:A.visitors.toLocaleString()})]},A.target):(0,xe.jsxs)("button",{type:"button","aria-current":N?"true":void 0,className:"af-flex af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>E({goal:_.goal,implicit:_.implicit,target:A.target,...A.label&&A.label!==A.target?{label:A.label}:{}}),children:[(0,xe.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[N&&(0,xe.jsx)(yn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,xe.jsxs)("span",{className:"af-min-w-0",children:[(0,xe.jsx)("span",{className:"af-block af-truncate",children:A.label}),k&&(0,xe.jsx)("span",{className:"af-block af-truncate af-text-xs af-text-muted-foreground",children:A.target})]})]}),(0,xe.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:A.visitors.toLocaleString()})]},A.target)})]})}let v=e?.goal&&!a.some(_=>er(_,e));return(0,xe.jsxs)("div",{className:"af-flex af-max-h-[min(20rem,var(--radix-popover-content-available-height,20rem))] af-flex-col af-gap-1 af-overflow-y-auto",children:[v&&(0,xe.jsxs)("p",{className:"af-px-2 af-py-1.5 af-text-xs af-text-muted-foreground",children:["\u201C",e?.goal,"\u201D isn\u2019t a conversion this site reports on any more. Pick another, or clear it."]}),a.length===0&&(0,xe.jsx)("p",{className:"af-px-2 af-py-1.5 af-text-sm af-text-muted-foreground",children:"This site has no conversions to mark yet."}),a.map(_=>{let T=e?er(_,e):!1;return(0,xe.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,xe.jsxs)("button",{type:"button","aria-current":T?"true":void 0,className:"af-flex af-min-w-0 af-flex-1 af-items-center af-justify-between af-gap-3 af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm hover:af-bg-accent",onClick:()=>E({goal:_.goal,implicit:_.implicit}),children:[(0,xe.jsxs)("span",{className:"af-flex af-min-w-0 af-items-center af-gap-2",children:[T&&(0,xe.jsx)(yn.Check,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,xe.jsx)("span",{className:"af-truncate",children:_.goal})]}),(0,xe.jsx)("span",{className:"af-shrink-0 af-text-xs af-text-muted-foreground",children:_.visitors.toLocaleString()})]}),Ju(_)&&(0,xe.jsx)(R,{type:"button",variant:"ghost",size:"sm","aria-label":`Narrow ${_.goal}`,onClick:()=>C(_),children:"Narrow"})]},_.goal)}),e?.goal&&(0,xe.jsx)("button",{type:"button",className:"af-rounded af-px-2 af-py-1.5 af-text-left af-text-sm af-text-muted-foreground hover:af-bg-accent",onClick:()=>E(null),children:"No main conversion"})]})}var _a=require("react/jsx-runtime");function Xu(e){let t=[e];e.startsWith("//")?t.push(`https:${e}`):/^[a-z][a-z0-9+.-]*:/i.test(e)||t.push(`https://${e}`);for(let n of t)try{let{hostname:s}=new URL(n);if(s)return s.toLowerCase().replace(/^www\./,"")}catch{}return null}function Qu(e){if(Oi(e,"whatsapp"))return!0;let t=Xu(e);return t===null?!1:["wa.me","whatsapp.com"].some(n=>t===n||t.endsWith(`.${n}`))}function Oi(e,t){return e.slice(0,t.length+1).toLowerCase()===`${t}:`}var Vl=[{goal:"Contact",target:e=>Oi(e,"tel"),icon:Dt.Phone,line:"This site is set up to get you phone calls."},{goal:"Contact",target:e=>Oi(e,"mailto"),icon:Dt.Mail,line:"This site is set up to get you emails."},{goal:"Contact",icon:Dt.Phone,line:"This site is set up to get you calls and emails."},{goal:"Outbound Link: Click",target:e=>Qu(e),icon:Dt.MessageCircle,line:"This site is set up to get you WhatsApp messages."},{goal:"Outbound Link: Click",icon:Dt.ExternalLink,line:"This site is set up to send visitors on to book with you."},{goal:"Form: Submission",icon:Dt.Mail,line:"This site is set up to get you enquiries."},{goal:"Form: Received",icon:Dt.Mail,line:"This site is set up to get you enquiries."},{goal:"Purchase",icon:Dt.ShoppingBag,line:"This site is set up to sell."},{goal:"File Download",icon:Dt.Download,line:"This site is set up to get your file downloaded."}];function zl(e){let{goal:t,target:n}=e;return e.implicit!==!0?null:(n?Vl.find(a=>a.goal===t&&a.target?.(n)):void 0)??Vl.find(a=>a.goal===t&&!a.target)??null}function ed(e){return zl(e)?.icon??Dt.Target}function ql({primaryConversion:e,onChange:t}){let[n,s]=Hl.useState(!1);if(!!!e?.goal&&!t)return null;let r=e?zl(e):null,o=e?.label?.trim(),u=e?ed(e):Dt.Target,g=e?.goal?o?`Your main conversion is ${o}.`:r?.line??`Your main conversion is ${e.goal}.`:"Set your main conversion",l=(0,_a.jsxs)(_a.Fragment,{children:[(0,_a.jsx)(u,{className:"af-h-4 af-w-4 af-shrink-0"}),(0,_a.jsx)("span",{children:g})]});return t?(0,_a.jsxs)(gr,{open:n,onOpenChange:s,children:[(0,_a.jsx)(vr,{asChild:!0,children:(0,_a.jsx)("button",{type:"button",className:"af-flex af-items-center af-gap-2 af-rounded af-text-left af-text-sm af-text-muted-foreground hover:af-text-foreground focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:l})}),(0,_a.jsx)(Os,{align:"start",className:"af-w-80 af-p-1",children:n&&(0,_a.jsx)($l,{current:e,onChange:t,onClose:()=>s(!1)})})]}):(0,_a.jsx)("p",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:l})}var qt=require("react/jsx-runtime");function jl({refreshKey:e,onViewAll:t,primaryConversion:n}){let s=Gn(7,{refreshKey:e,breakdowns:[]}),a=s.status.data??void 0,{nothingToReport:r,notCollecting:o,holdingForFirstData:u}=Mr(a);return $r({status:a,holdingForFirstData:u,refetchStatus:s.refetchStatus,refetch:s.refetch}),(0,qt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,qt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,qt.jsx)("h3",{className:"af-text-sm af-font-medium",children:"Visitors this week"}),t&&(0,qt.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"View all analytics"})]}),r?(0,qt.jsx)("p",{className:"af-py-6 af-text-center af-text-sm af-text-muted-foreground",children:o?"Nothing is measuring this site yet.":"No visits yet \u2014 this fills in as people arrive."}):(0,qt.jsxs)(qt.Fragment,{children:[(0,qt.jsx)(bn,{sourced:s.timeseries.data,error:s.timeseries.error,isLoading:s.timeseries.isLoading,what:"The visitors chart",collecting:a?.collecting,onRetry:s.refetch,children:g=>{let l=s.timeseries.data?.status==="ok"?s.timeseries.data:null;return(0,qt.jsx)(jr,{rows:g,window:l?.window??{from:"",to:""},metric:"visitors",timeZone:l?.timezone,height:140})}}),(0,qt.jsxs)("div",{className:"af-mt-3",children:[(0,qt.jsx)("h3",{className:"af-mb-2 af-text-sm af-font-medium",children:"What those visits did"}),(0,qt.jsx)(bn,{sourced:s.conversions.data,error:s.conversions.error,isLoading:s.conversions.isLoading,what:"Conversions",collecting:a?.collecting,onRetry:s.refetch,children:g=>{let l=s.conversions.data?.status==="ok"?s.conversions.data:null;return(0,qt.jsx)(zr,{rows:g,primaryConversion:n,denominator:l?.denominator??0,windowPrecedesCollection:l?.window_precedes_collection??!1,coverageUnknown:l?.first_seen_unavailable??!1})}})]})]})]})}var Lt=require("react/jsx-runtime"),Bi=5;function Fi({title:e,viewAllLabel:t,onViewAll:n}){return(0,Lt.jsxs)("header",{className:"af-mb-2 af-flex af-items-center af-justify-between af-gap-2",children:[(0,Lt.jsx)("h3",{className:"af-text-sm af-font-medium",children:e}),n&&(0,Lt.jsx)(R,{type:"button",variant:"ghost",size:"sm",onClick:n,children:t})]})}function Gl({refreshKey:e,onBackToWebsite:t,primaryConversion:n,onChangePrimaryConversion:s,onOpenSurface:a,needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:u}){let g=Hn({refreshKey:e}),l=(g.summary?.products.count??0)>0||(g.summary?.commerce?.storefront_orders??!1),i=l||(g.summary?.commerce?.invoicing??!1);return(0,Lt.jsx)(wt,{title:"Dashboard",onBackToWebsite:t,children:(0,Lt.jsxs)("div",{className:"af-flex af-flex-col af-gap-4",children:[(0,Lt.jsx)(ql,{primaryConversion:n,onChange:s}),(0,Lt.jsx)(jl,{refreshKey:e,onViewAll:a&&(()=>a("analytics")),primaryConversion:n}),(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Fi,{title:"Recent leads",viewAllLabel:"View all leads",onViewAll:a&&(()=>a("leads"))}),(0,Lt.jsx)(qs,{refreshKey:e,maxRows:Bi,onViewAll:a&&(()=>a("leads"))})]}),l&&(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Fi,{title:"Recent orders",viewAllLabel:"View all orders",onViewAll:a&&(()=>a("orders"))}),(0,Lt.jsx)(fn,{refreshKey:e,maxRows:Bi,onViewAll:a&&(()=>a("orders"))})]}),i&&(0,Lt.jsxs)("section",{className:"af-rounded-md af-border af-p-3",children:[(0,Lt.jsx)(Fi,{title:"Recent invoices",viewAllLabel:"View all invoices",onViewAll:a&&(()=>a("invoices"))}),(0,Lt.jsx)(pn,{refreshKey:e,maxRows:Bi,onViewAll:a&&(()=>a("invoices")),needsPaidPlan:r,onUpgradePlan:o,onConnectStripe:u})]})]})})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,AnalyticsView,CustomerDetail,CustomersList,DashboardView,ExportCsvButton,FormSettings,FormSubmissions,FormsDashboard,FormsList,InvoiceDetail,InvoiceLabelBadge,InvoiceSettingsPanel,InvoicesList,InvoicesView,LeadsView,MAX_ANALYTICS_FILTERS,MAX_ANALYTICS_FILTER_VALUES,NotificationRecipientsSettings,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,PromosPanel,REALTIME_FAILURES_BEFORE_ERROR,REALTIME_POLL_MS,RetainerStatusBadge,RetainersPanel,StoreSettings,SubmissionDetail,SubscriptionsView,VariantsEditor,ViewShell,WebhookDeliveries,WebhookSettings,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useAnalytics,useBusinessSummary,useCsvExport,useCustomers,useEventDestinations,useForms,useInvoices,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useRealtimeVisitors,useRetainers,useSiteSettings,useSubmissions,useSubscriptions});