@aifeatures/admin-react 0.2.0 → 0.3.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,1388 +1,4 @@
1
1
  "use client";
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- AifeaturesApiError: () => AifeaturesApiError,
35
- AifeaturesProvider: () => AifeaturesProvider,
36
- FormSettings: () => FormSettings,
37
- FormSubmissions: () => FormSubmissions,
38
- FormsDashboard: () => FormsDashboard,
39
- FormsList: () => FormsList,
40
- SubmissionDetail: () => SubmissionDetail,
41
- createApiClient: () => createApiClient,
42
- useAifeatures: () => useAifeaturesContext,
43
- useAifeaturesContext: () => useAifeaturesContext,
44
- useForms: () => useForms,
45
- useSubmissions: () => useSubmissions
46
- });
47
- module.exports = __toCommonJS(index_exports);
48
-
49
- // src/provider/AifeaturesProvider.tsx
50
- var React = __toESM(require("react"), 1);
51
-
52
- // src/lib/api.ts
53
- var AifeaturesApiError = class extends Error {
54
- constructor(message, status, details) {
55
- super(message);
56
- this.status = status;
57
- this.details = details;
58
- this.name = "AifeaturesApiError";
59
- }
60
- };
61
- function toErrorMessage(error, status) {
62
- if (typeof error === "string" && error) return error;
63
- if (error && typeof error === "object") {
64
- try {
65
- return JSON.stringify(error);
66
- } catch {
67
- }
68
- }
69
- return `Request failed with status ${status}`;
70
- }
71
- function createApiClient(siteToken, apiUrl = "https://aifeatures.dev") {
72
- async function request(path, options = {}) {
73
- const url = `${apiUrl}${path}`;
74
- const response = await fetch(url, {
75
- ...options,
76
- headers: {
77
- "Authorization": `Bearer ${siteToken}`,
78
- "Content-Type": "application/json",
79
- ...options.headers
80
- }
81
- });
82
- if (!response.ok) {
83
- let details;
84
- try {
85
- details = await response.json();
86
- } catch {
87
- }
88
- throw new AifeaturesApiError(
89
- toErrorMessage(details?.error, response.status),
90
- response.status,
91
- details
92
- );
93
- }
94
- if (response.status === 204) {
95
- return void 0;
96
- }
97
- return response.json();
98
- }
99
- return {
100
- // Forms
101
- async getForms() {
102
- const data = await request("/api/v1/forms");
103
- return data.forms;
104
- },
105
- async getForm(formId) {
106
- return request(`/api/v1/forms/${formId}`);
107
- },
108
- async createForm(input) {
109
- return request("/api/v1/forms", {
110
- method: "POST",
111
- body: JSON.stringify(input)
112
- });
113
- },
114
- async updateForm(formId, input) {
115
- return request(`/api/v1/forms/${formId}`, {
116
- method: "PATCH",
117
- body: JSON.stringify(input)
118
- });
119
- },
120
- async deleteForm(formId) {
121
- await request(`/api/v1/forms/${formId}`, {
122
- method: "DELETE"
123
- });
124
- },
125
- // Submissions
126
- async getSubmissions(formId, options = {}) {
127
- const params = new URLSearchParams();
128
- if (options.limit !== void 0) {
129
- params.set("limit", String(options.limit));
130
- }
131
- if (options.offset !== void 0) {
132
- params.set("offset", String(options.offset));
133
- }
134
- const query = params.toString();
135
- const path = `/api/v1/forms/${formId}/submissions${query ? `?${query}` : ""}`;
136
- return request(path);
137
- },
138
- async getSubmission(submissionId) {
139
- return request(`/api/v1/submissions/${submissionId}`);
140
- },
141
- async deleteSubmission(submissionId) {
142
- await request(`/api/v1/submissions/${submissionId}`, {
143
- method: "DELETE"
144
- });
145
- },
146
- // Attachments
147
- async downloadAttachment(submissionId, attachment) {
148
- const ref = typeof attachment === "string" ? { name: attachment } : attachment;
149
- const filename = ref.name;
150
- const token = ref.id ?? ref.name;
151
- const url = `${apiUrl}/api/v1/submissions/${submissionId}/attachments/${encodeURIComponent(token)}`;
152
- const response = await fetch(url, {
153
- headers: {
154
- "Authorization": `Bearer ${siteToken}`
155
- }
156
- });
157
- if (!response.ok) {
158
- let details;
159
- try {
160
- details = await response.json();
161
- } catch {
162
- }
163
- throw new AifeaturesApiError(
164
- toErrorMessage(details?.error, response.status),
165
- response.status,
166
- details
167
- );
168
- }
169
- const blob = await response.blob();
170
- const blobUrl = URL.createObjectURL(blob);
171
- const link = document.createElement("a");
172
- link.href = blobUrl;
173
- link.download = filename;
174
- document.body.appendChild(link);
175
- link.click();
176
- document.body.removeChild(link);
177
- URL.revokeObjectURL(blobUrl);
178
- }
179
- };
180
- }
181
-
182
- // src/provider/AifeaturesProvider.tsx
183
- var import_jsx_runtime = require("react/jsx-runtime");
184
- var AifeaturesContext = React.createContext(
185
- null
186
- );
187
- function validateToken(token) {
188
- if (!token) {
189
- return "No siteToken provided to AifeaturesProvider";
190
- }
191
- if (token.startsWith("sk_")) {
192
- return "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.";
193
- }
194
- if (!token.startsWith("st_")) {
195
- return `Invalid token format: Expected a site token starting with "st_" but got "${token.slice(0, 10)}...". Site tokens are returned when you create a site via the API.`;
196
- }
197
- return null;
198
- }
199
- function AifeaturesProvider({
200
- siteToken,
201
- apiUrl = "https://aifeatures.dev",
202
- dark = false,
203
- className,
204
- children
205
- }) {
206
- const tokenError = React.useMemo(() => validateToken(siteToken), [siteToken]);
207
- const api = React.useMemo(
208
- () => createApiClient(siteToken, apiUrl),
209
- [siteToken, apiUrl]
210
- );
211
- const value = React.useMemo(
212
- () => ({
213
- siteToken,
214
- apiUrl,
215
- api
216
- }),
217
- [siteToken, apiUrl, api]
218
- );
219
- if (tokenError) {
220
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `aifeatures-admin ${dark ? "dark" : ""} ${className || ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4", children: [
221
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h3", { className: "af-text-sm af-font-semibold af-text-destructive af-mb-2", children: "AifeaturesProvider Configuration Error" }),
222
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "af-text-sm af-text-destructive", children: tokenError })
223
- ] }) });
224
- }
225
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AifeaturesContext.Provider, { value, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `aifeatures-admin ${dark ? "dark" : ""} ${className || ""}`, children }) });
226
- }
227
- function useAifeaturesContext() {
228
- const context = React.useContext(AifeaturesContext);
229
- if (!context) {
230
- throw new Error(
231
- "useAifeaturesContext must be used within an AifeaturesProvider"
232
- );
233
- }
234
- return context;
235
- }
236
-
237
- // src/components/FormsDashboard.tsx
238
- var React13 = __toESM(require("react"), 1);
239
- var import_lucide_react6 = require("lucide-react");
240
-
241
- // src/ui/tabs.tsx
242
- var React2 = __toESM(require("react"), 1);
243
- var TabsPrimitive = __toESM(require("@radix-ui/react-tabs"), 1);
244
-
245
- // src/lib/cn.ts
246
- var import_clsx = require("clsx");
247
- var import_tailwind_merge = require("tailwind-merge");
248
- function cn(...inputs) {
249
- return (0, import_tailwind_merge.twMerge)((0, import_clsx.clsx)(inputs));
250
- }
251
-
252
- // src/ui/tabs.tsx
253
- var import_jsx_runtime2 = require("react/jsx-runtime");
254
- var Tabs = TabsPrimitive.Root;
255
- var TabsList = React2.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
256
- TabsPrimitive.List,
257
- {
258
- ref,
259
- className: cn(
260
- "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",
261
- className
262
- ),
263
- ...props
264
- }
265
- ));
266
- TabsList.displayName = TabsPrimitive.List.displayName;
267
- var TabsTrigger = React2.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
268
- TabsPrimitive.Trigger,
269
- {
270
- ref,
271
- className: cn(
272
- "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",
273
- className
274
- ),
275
- ...props
276
- }
277
- ));
278
- TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
279
- var TabsContent = React2.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
280
- TabsPrimitive.Content,
281
- {
282
- ref,
283
- className: cn(
284
- "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",
285
- className
286
- ),
287
- ...props
288
- }
289
- ));
290
- TabsContent.displayName = TabsPrimitive.Content.displayName;
291
-
292
- // src/ui/button.tsx
293
- var React3 = __toESM(require("react"), 1);
294
- var import_react_slot = require("@radix-ui/react-slot");
295
- var import_class_variance_authority = require("class-variance-authority");
296
- var import_jsx_runtime3 = require("react/jsx-runtime");
297
- var buttonVariants = (0, import_class_variance_authority.cva)(
298
- "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",
299
- {
300
- variants: {
301
- variant: {
302
- default: "af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/90",
303
- destructive: "af-bg-destructive af-text-destructive-foreground af-shadow-sm hover:af-bg-destructive/90",
304
- outline: "af-border af-border-input af-bg-background af-shadow-sm hover:af-bg-accent hover:af-text-accent-foreground",
305
- secondary: "af-bg-secondary af-text-secondary-foreground af-shadow-sm hover:af-bg-secondary/80",
306
- ghost: "hover:af-bg-accent hover:af-text-accent-foreground",
307
- link: "af-text-primary af-underline-offset-4 hover:af-underline"
308
- },
309
- size: {
310
- default: "af-h-9 af-px-4 af-py-2",
311
- sm: "af-h-8 af-rounded-md af-px-3 af-text-xs",
312
- lg: "af-h-10 af-rounded-md af-px-8",
313
- icon: "af-h-9 af-w-9"
314
- }
315
- },
316
- defaultVariants: {
317
- variant: "default",
318
- size: "default"
319
- }
320
- }
321
- );
322
- var Button = React3.forwardRef(
323
- ({ className, variant, size, asChild = false, ...props }, ref) => {
324
- const Comp = asChild ? import_react_slot.Slot : "button";
325
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
326
- Comp,
327
- {
328
- className: cn(buttonVariants({ variant, size, className })),
329
- ref,
330
- ...props
331
- }
332
- );
333
- }
334
- );
335
- Button.displayName = "Button";
336
-
337
- // src/components/FormsList.tsx
338
- var import_lucide_react = require("lucide-react");
339
-
340
- // src/ui/table.tsx
341
- var React4 = __toESM(require("react"), 1);
342
- var import_jsx_runtime4 = require("react/jsx-runtime");
343
- var Table = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "af-relative af-w-full af-overflow-auto", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
344
- "table",
345
- {
346
- ref,
347
- className: cn("af-w-full af-caption-bottom af-text-sm", className),
348
- ...props
349
- }
350
- ) }));
351
- Table.displayName = "Table";
352
- var TableHeader = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("thead", { ref, className: cn("[&_tr]:af-border-b", className), ...props }));
353
- TableHeader.displayName = "TableHeader";
354
- var TableBody = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
355
- "tbody",
356
- {
357
- ref,
358
- className: cn("[&_tr:last-child]:af-border-0", className),
359
- ...props
360
- }
361
- ));
362
- TableBody.displayName = "TableBody";
363
- var TableFooter = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
364
- "tfoot",
365
- {
366
- ref,
367
- className: cn(
368
- "af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",
369
- className
370
- ),
371
- ...props
372
- }
373
- ));
374
- TableFooter.displayName = "TableFooter";
375
- var TableRow = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
376
- "tr",
377
- {
378
- ref,
379
- className: cn(
380
- "af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",
381
- className
382
- ),
383
- ...props
384
- }
385
- ));
386
- TableRow.displayName = "TableRow";
387
- var TableHead = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
388
- "th",
389
- {
390
- ref,
391
- className: cn(
392
- "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]",
393
- className
394
- ),
395
- ...props
396
- }
397
- ));
398
- TableHead.displayName = "TableHead";
399
- var TableCell = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
400
- "td",
401
- {
402
- ref,
403
- className: cn(
404
- "af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",
405
- className
406
- ),
407
- ...props
408
- }
409
- ));
410
- TableCell.displayName = "TableCell";
411
- var TableCaption = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
412
- "caption",
413
- {
414
- ref,
415
- className: cn("af-mt-4 af-text-sm af-text-muted-foreground", className),
416
- ...props
417
- }
418
- ));
419
- TableCaption.displayName = "TableCaption";
420
-
421
- // src/hooks/useForms.ts
422
- var React5 = __toESM(require("react"), 1);
423
- function useForms() {
424
- const { api } = useAifeaturesContext();
425
- const [forms, setForms] = React5.useState([]);
426
- const [isLoading, setIsLoading] = React5.useState(true);
427
- const [error, setError] = React5.useState(null);
428
- const fetchForms = React5.useCallback(async () => {
429
- try {
430
- setIsLoading(true);
431
- setError(null);
432
- const data = await api.getForms();
433
- setForms(data);
434
- } catch (err) {
435
- setError(err instanceof Error ? err : new Error("Failed to fetch forms"));
436
- } finally {
437
- setIsLoading(false);
438
- }
439
- }, [api]);
440
- React5.useEffect(() => {
441
- fetchForms();
442
- }, [fetchForms]);
443
- const createForm = React5.useCallback(
444
- async (input) => {
445
- const form = await api.createForm(input);
446
- setForms((prev) => [...prev, form]);
447
- return form;
448
- },
449
- [api]
450
- );
451
- const updateForm = React5.useCallback(
452
- async (formId, input) => {
453
- const form = await api.updateForm(formId, input);
454
- setForms((prev) => prev.map((f) => f.id === formId ? form : f));
455
- return form;
456
- },
457
- [api]
458
- );
459
- const deleteForm = React5.useCallback(
460
- async (formId) => {
461
- await api.deleteForm(formId);
462
- setForms((prev) => prev.filter((f) => f.id !== formId));
463
- },
464
- [api]
465
- );
466
- return {
467
- forms,
468
- isLoading,
469
- error,
470
- refetch: fetchForms,
471
- createForm,
472
- updateForm,
473
- deleteForm
474
- };
475
- }
476
-
477
- // src/components/FormsList.tsx
478
- var import_jsx_runtime5 = require("react/jsx-runtime");
479
- function FormsList({ onSelectForm, className }) {
480
- const { forms, isLoading, error } = useForms();
481
- if (isLoading) {
482
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: `af-flex af-items-center af-justify-center af-py-8 ${className || ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "af-text-muted-foreground", children: "Loading forms..." }) });
483
- }
484
- if (error) {
485
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: `af-flex af-items-center af-justify-center af-py-8 ${className || ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "af-text-destructive", children: [
486
- "Error: ",
487
- error.message
488
- ] }) });
489
- }
490
- if (forms.length === 0) {
491
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: `af-flex af-flex-col af-items-center af-justify-center af-py-12 ${className || ""}`, children: [
492
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react.Inbox, { className: "af-h-12 af-w-12 af-text-muted-foreground af-mb-4" }),
493
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("p", { className: "af-text-muted-foreground af-text-center", children: [
494
- "No forms yet.",
495
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("br", {}),
496
- "Forms will appear here when the AI creates contact forms on your website."
497
- ] })
498
- ] });
499
- }
500
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Table, { children: [
501
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(TableRow, { children: [
502
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableHead, { children: "Name" }),
503
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableHead, { children: "Endpoint" }),
504
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableHead, { className: "af-text-right", children: "Actions" })
505
- ] }) }),
506
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableBody, { children: forms.map((form) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(TableRow, { children: [
507
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableCell, { className: "af-font-medium", children: form.name }),
508
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("code", { className: "af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded", children: form.endpoint_url.replace("https://aifeatures.dev", "") }) }),
509
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TableCell, { className: "af-text-right", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "af-flex af-items-center af-justify-end af-gap-2", children: [
510
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
511
- Button,
512
- {
513
- variant: "ghost",
514
- size: "sm",
515
- onClick: () => onSelectForm?.(form, "submissions"),
516
- children: [
517
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react.Inbox, { className: "af-h-4 af-w-4 af-mr-1" }),
518
- "Submissions"
519
- ]
520
- }
521
- ),
522
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
523
- Button,
524
- {
525
- variant: "ghost",
526
- size: "sm",
527
- onClick: () => onSelectForm?.(form, "settings"),
528
- children: [
529
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react.Settings, { className: "af-h-4 af-w-4 af-mr-1" }),
530
- "Settings"
531
- ]
532
- }
533
- )
534
- ] }) })
535
- ] }, form.id)) })
536
- ] }) });
537
- }
538
-
539
- // src/components/FormSubmissions.tsx
540
- var React9 = __toESM(require("react"), 1);
541
- var import_lucide_react4 = require("lucide-react");
542
-
543
- // src/ui/select.tsx
544
- var React6 = __toESM(require("react"), 1);
545
- var SelectPrimitive = __toESM(require("@radix-ui/react-select"), 1);
546
- var import_lucide_react2 = require("lucide-react");
547
- var import_jsx_runtime6 = require("react/jsx-runtime");
548
- var Select = SelectPrimitive.Root;
549
- var SelectValue = SelectPrimitive.Value;
550
- var SelectTrigger = React6.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
551
- SelectPrimitive.Trigger,
552
- {
553
- ref,
554
- className: cn(
555
- "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",
556
- className
557
- ),
558
- ...props,
559
- children: [
560
- children,
561
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SelectPrimitive.Icon, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_lucide_react2.ChevronDown, { className: "af-h-4 af-w-4 af-opacity-50" }) })
562
- ]
563
- }
564
- ));
565
- SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
566
- var SelectScrollUpButton = React6.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
567
- SelectPrimitive.ScrollUpButton,
568
- {
569
- ref,
570
- className: cn(
571
- "af-flex af-cursor-default af-items-center af-justify-center af-py-1",
572
- className
573
- ),
574
- ...props,
575
- children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_lucide_react2.ChevronUp, { className: "af-h-4 af-w-4" })
576
- }
577
- ));
578
- SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
579
- var SelectScrollDownButton = React6.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
580
- SelectPrimitive.ScrollDownButton,
581
- {
582
- ref,
583
- className: cn(
584
- "af-flex af-cursor-default af-items-center af-justify-center af-py-1",
585
- className
586
- ),
587
- ...props,
588
- children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_lucide_react2.ChevronDown, { className: "af-h-4 af-w-4" })
589
- }
590
- ));
591
- SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
592
- var SelectContent = React6.forwardRef(({ className, children, position = "popper", ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SelectPrimitive.Portal, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
593
- SelectPrimitive.Content,
594
- {
595
- ref,
596
- className: cn(
597
- "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",
598
- position === "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",
599
- className
600
- ),
601
- position,
602
- ...props,
603
- children: [
604
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SelectScrollUpButton, {}),
605
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
606
- SelectPrimitive.Viewport,
607
- {
608
- className: cn(
609
- "af-p-1",
610
- position === "popper" && "af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"
611
- ),
612
- children
613
- }
614
- ),
615
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SelectScrollDownButton, {})
616
- ]
617
- }
618
- ) }));
619
- SelectContent.displayName = SelectPrimitive.Content.displayName;
620
- var SelectLabel = React6.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
621
- SelectPrimitive.Label,
622
- {
623
- ref,
624
- className: cn("af-px-2 af-py-1.5 af-text-sm af-font-semibold", className),
625
- ...props
626
- }
627
- ));
628
- SelectLabel.displayName = SelectPrimitive.Label.displayName;
629
- var SelectItem = React6.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
630
- SelectPrimitive.Item,
631
- {
632
- ref,
633
- className: cn(
634
- "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",
635
- className
636
- ),
637
- ...props,
638
- children: [
639
- /* @__PURE__ */ (0, import_jsx_runtime6.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: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SelectPrimitive.ItemIndicator, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_lucide_react2.Check, { className: "af-h-4 af-w-4" }) }) }),
640
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(SelectPrimitive.ItemText, { children })
641
- ]
642
- }
643
- ));
644
- SelectItem.displayName = SelectPrimitive.Item.displayName;
645
- var SelectSeparator = React6.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
646
- SelectPrimitive.Separator,
647
- {
648
- ref,
649
- className: cn("af--mx-1 af-my-1 af-h-px af-bg-muted", className),
650
- ...props
651
- }
652
- ));
653
- SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
654
-
655
- // src/hooks/useSubmissions.ts
656
- var React7 = __toESM(require("react"), 1);
657
- function useSubmissions({
658
- formId,
659
- initialPageSize = 25
660
- }) {
661
- const { api } = useAifeaturesContext();
662
- const [submissions, setSubmissions] = React7.useState([]);
663
- const [total, setTotal] = React7.useState(0);
664
- const [isLoading, setIsLoading] = React7.useState(true);
665
- const [error, setError] = React7.useState(null);
666
- const [page, setPage] = React7.useState(0);
667
- const [pageSize, setPageSize] = React7.useState(initialPageSize);
668
- const fetchSubmissions = React7.useCallback(async () => {
669
- if (!formId) return;
670
- try {
671
- setIsLoading(true);
672
- setError(null);
673
- const options = {
674
- limit: pageSize,
675
- offset: page * pageSize
676
- };
677
- const data = await api.getSubmissions(
678
- formId,
679
- options
680
- );
681
- setSubmissions(data.submissions);
682
- setTotal(data.total);
683
- } catch (err) {
684
- setError(
685
- err instanceof Error ? err : new Error("Failed to fetch submissions")
686
- );
687
- } finally {
688
- setIsLoading(false);
689
- }
690
- }, [api, formId, page, pageSize]);
691
- React7.useEffect(() => {
692
- fetchSubmissions();
693
- }, [fetchSubmissions]);
694
- const deleteSubmission = React7.useCallback(
695
- async (submissionId) => {
696
- await api.deleteSubmission(submissionId);
697
- setSubmissions((prev) => prev.filter((s) => s.id !== submissionId));
698
- setTotal((prev) => prev - 1);
699
- },
700
- [api]
701
- );
702
- const totalPages = Math.ceil(total / pageSize);
703
- return {
704
- submissions,
705
- total,
706
- isLoading,
707
- error,
708
- page,
709
- pageSize,
710
- hasNextPage: page < totalPages - 1,
711
- hasPreviousPage: page > 0,
712
- setPage,
713
- setPageSize: (size) => {
714
- setPageSize(size);
715
- setPage(0);
716
- },
717
- refetch: fetchSubmissions,
718
- deleteSubmission
719
- };
720
- }
721
-
722
- // src/components/SubmissionDetail.tsx
723
- var React8 = __toESM(require("react"), 1);
724
- var import_lucide_react3 = require("lucide-react");
725
- var import_jsx_runtime7 = require("react/jsx-runtime");
726
- function formatDate(dateString) {
727
- return new Date(dateString).toLocaleString(void 0, {
728
- year: "numeric",
729
- month: "short",
730
- day: "numeric",
731
- hour: "2-digit",
732
- minute: "2-digit"
733
- });
734
- }
735
- function formatBytes(bytes) {
736
- if (bytes === 0) return "0 B";
737
- const k = 1024;
738
- const sizes = ["B", "KB", "MB", "GB"];
739
- const i = Math.floor(Math.log(bytes) / Math.log(k));
740
- return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
741
- }
742
- function SubmissionDetail({
743
- submission,
744
- onBack
745
- }) {
746
- const { api } = useAifeaturesContext();
747
- const [downloadingFile, setDownloadingFile] = React8.useState(null);
748
- const attachmentKey = (attachment) => attachment.id ?? attachment.name;
749
- const handleDownload = async (attachment) => {
750
- setDownloadingFile(attachmentKey(attachment));
751
- try {
752
- await api.downloadAttachment(submission.id, attachment);
753
- } catch (error) {
754
- console.error("Download failed:", error);
755
- } finally {
756
- setDownloadingFile(null);
757
- }
758
- };
759
- const dataEntries = Object.entries(submission.data).filter(
760
- ([key]) => !key.startsWith("_")
761
- );
762
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { children: [
763
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-mb-6", children: [
764
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
765
- Button,
766
- {
767
- variant: "ghost",
768
- size: "sm",
769
- onClick: onBack,
770
- className: "af-mb-2 af--ml-2",
771
- children: [
772
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.ArrowLeft, { className: "af-h-4 af-w-4 af-mr-1" }),
773
- "Back to Submissions"
774
- ]
775
- }
776
- ),
777
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("h3", { className: "af-text-lg af-font-semibold", children: "Submission Details" }),
778
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("p", { className: "af-text-sm af-text-muted-foreground", children: [
779
- "Submitted ",
780
- formatDate(submission.metadata.submitted_at)
781
- ] })
782
- ] }),
783
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-space-y-6", children: [
784
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { children: [
785
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("h4", { className: "af-text-sm af-font-medium af-mb-3", children: "Form Data" }),
786
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-space-y-3", children: [
787
- dataEntries.map(([key, value]) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-grid af-grid-cols-3 af-gap-2", children: [
788
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "af-text-sm af-text-muted-foreground af-capitalize", children: key.replace(/_/g, " ") }),
789
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "af-col-span-2 af-text-sm af-break-words", children: typeof value === "string" && value.includes("\n") ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("pre", { className: "af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs", children: value }) : String(value) })
790
- ] }, key)),
791
- dataEntries.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("p", { className: "af-text-sm af-text-muted-foreground", children: "No data submitted" })
792
- ] })
793
- ] }),
794
- submission.attachments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { children: [
795
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("h4", { className: "af-text-sm af-font-medium af-mb-3", children: "Attachments" }),
796
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "af-space-y-2", children: submission.attachments.map((attachment, index) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
797
- "div",
798
- {
799
- className: "af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",
800
- children: [
801
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-flex af-items-center af-gap-2", children: [
802
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.FileText, { className: "af-h-4 af-w-4 af-text-muted-foreground" }),
803
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("span", { className: "af-text-sm", children: attachment.name }),
804
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("span", { className: "af-text-xs af-text-muted-foreground", children: [
805
- "(",
806
- formatBytes(attachment.size),
807
- ")"
808
- ] })
809
- ] }),
810
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
811
- Button,
812
- {
813
- variant: "ghost",
814
- size: "sm",
815
- onClick: () => handleDownload(attachment),
816
- disabled: downloadingFile === attachmentKey(attachment),
817
- children: [
818
- downloadingFile === attachmentKey(attachment) ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.Loader2, { className: "af-h-4 af-w-4 af-mr-1 af-animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.Download, { className: "af-h-4 af-w-4 af-mr-1" }),
819
- downloadingFile === attachmentKey(attachment) ? "Downloading..." : "Download"
820
- ]
821
- }
822
- )
823
- ]
824
- },
825
- index
826
- )) })
827
- ] }),
828
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { children: [
829
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("h4", { className: "af-text-sm af-font-medium af-mb-3", children: "Metadata" }),
830
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-space-y-2 af-text-sm", children: [
831
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-flex af-items-center af-gap-2 af-text-muted-foreground", children: [
832
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.Clock, { className: "af-h-4 af-w-4" }),
833
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("span", { children: formatDate(submission.metadata.submitted_at) })
834
- ] }),
835
- submission.metadata.ip_address && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-flex af-items-center af-gap-2 af-text-muted-foreground", children: [
836
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.Globe, { className: "af-h-4 af-w-4" }),
837
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("span", { children: [
838
- "IP: ",
839
- submission.metadata.ip_address
840
- ] })
841
- ] }),
842
- submission.metadata.user_agent && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-flex af-items-start af-gap-2 af-text-muted-foreground", children: [
843
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.Monitor, { className: "af-h-4 af-w-4 af-mt-0.5" }),
844
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("span", { className: "af-text-xs af-break-all", children: submission.metadata.user_agent })
845
- ] }),
846
- submission.resend_id && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "af-flex af-items-center af-gap-2 af-text-muted-foreground", children: [
847
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_lucide_react3.Mail, { className: "af-h-4 af-w-4" }),
848
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("span", { children: [
849
- "Email ID: ",
850
- submission.resend_id
851
- ] })
852
- ] })
853
- ] })
854
- ] })
855
- ] })
856
- ] });
857
- }
858
-
859
- // src/components/FormSubmissions.tsx
860
- var import_jsx_runtime8 = require("react/jsx-runtime");
861
- function formatDate2(dateString) {
862
- return new Date(dateString).toLocaleString(void 0, {
863
- month: "short",
864
- day: "numeric",
865
- hour: "2-digit",
866
- minute: "2-digit"
867
- });
868
- }
869
- function getEmailFromData(data) {
870
- const emailFields = ["email", "Email", "EMAIL", "e-mail", "mail"];
871
- for (const field of emailFields) {
872
- if (typeof data[field] === "string") {
873
- return data[field];
874
- }
875
- }
876
- return null;
877
- }
878
- function getPreviewText(data) {
879
- const entries = Object.entries(data).filter(
880
- ([key]) => !key.startsWith("_") && !key.toLowerCase().includes("email")
881
- );
882
- if (entries.length === 0) return "";
883
- const [, value] = entries[0];
884
- const text = String(value);
885
- return text.length > 50 ? text.slice(0, 50) + "..." : text;
886
- }
887
- function FormSubmissions({ formId, className, defaultSubmissionId }) {
888
- const {
889
- submissions,
890
- total,
891
- isLoading,
892
- error,
893
- page,
894
- pageSize,
895
- hasNextPage,
896
- hasPreviousPage,
897
- setPage,
898
- setPageSize
899
- } = useSubmissions({ formId });
900
- const [view, setView] = React9.useState("list");
901
- const [selectedSubmission, setSelectedSubmission] = React9.useState(null);
902
- React9.useEffect(() => {
903
- if (defaultSubmissionId && submissions.length > 0) {
904
- const submission = submissions.find((s) => s.id === defaultSubmissionId);
905
- if (submission) {
906
- setSelectedSubmission(submission);
907
- setView("detail");
908
- }
909
- }
910
- }, [defaultSubmissionId, submissions]);
911
- const handleViewSubmission = (submission) => {
912
- setSelectedSubmission(submission);
913
- setView("detail");
914
- };
915
- const handleBack = () => {
916
- setView("list");
917
- setSelectedSubmission(null);
918
- };
919
- if (view === "detail" && selectedSubmission) {
920
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
921
- SubmissionDetail,
922
- {
923
- submission: selectedSubmission,
924
- onBack: handleBack
925
- }
926
- ) });
927
- }
928
- if (isLoading) {
929
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: `af-flex af-items-center af-justify-center af-py-8 ${className || ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: "af-text-muted-foreground", children: "Loading submissions..." }) });
930
- }
931
- if (error) {
932
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: `af-flex af-items-center af-justify-center af-py-8 ${className || ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "af-text-destructive", children: [
933
- "Error: ",
934
- error.message
935
- ] }) });
936
- }
937
- if (submissions.length === 0 && page === 0) {
938
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: `af-flex af-flex-col af-items-center af-justify-center af-py-12 ${className || ""}`, children: [
939
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_lucide_react4.Inbox, { className: "af-h-12 af-w-12 af-text-muted-foreground af-mb-4" }),
940
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("p", { className: "af-text-muted-foreground af-text-center", children: [
941
- "No submissions yet.",
942
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("br", {}),
943
- "Submissions will appear here when visitors use your form."
944
- ] })
945
- ] });
946
- }
947
- const startIndex = page * pageSize + 1;
948
- const endIndex = Math.min((page + 1) * pageSize, total);
949
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className, children: [
950
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Table, { children: [
951
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(TableRow, { children: [
952
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableHead, { children: "Email" }),
953
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableHead, { children: "Preview" }),
954
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableHead, { children: "Date" }),
955
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableHead, { className: "af-text-right", children: "Actions" })
956
- ] }) }),
957
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableBody, { children: submissions.map((submission) => {
958
- const email = getEmailFromData(submission.data);
959
- const preview = getPreviewText(submission.data);
960
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(TableRow, { children: [
961
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableCell, { className: "af-font-medium", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "af-flex af-items-center af-gap-2", children: [
962
- email || /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "af-text-muted-foreground af-italic", children: "No email" }),
963
- submission.attachments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("span", { className: "af-flex af-items-center af-gap-1 af-text-muted-foreground", title: `${submission.attachments.length} attachment(s)`, children: [
964
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_lucide_react4.Paperclip, { className: "af-h-3 af-w-3" }),
965
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "af-text-xs", children: submission.attachments.length })
966
- ] })
967
- ] }) }),
968
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableCell, { className: "af-text-muted-foreground af-max-w-[200px] af-truncate", children: preview || /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "af-italic", children: "No preview available" }) }),
969
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableCell, { className: "af-text-muted-foreground", children: formatDate2(submission.metadata.submitted_at) }),
970
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TableCell, { className: "af-text-right", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
971
- Button,
972
- {
973
- variant: "ghost",
974
- size: "icon",
975
- onClick: () => handleViewSubmission(submission),
976
- title: "View details",
977
- children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_lucide_react4.Eye, { className: "af-h-4 af-w-4" })
978
- }
979
- ) })
980
- ] }, submission.id);
981
- }) })
982
- ] }),
983
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "af-flex af-items-center af-justify-between af-px-2 af-py-4", children: [
984
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground", children: [
985
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("span", { children: [
986
- "Showing ",
987
- startIndex,
988
- "-",
989
- endIndex,
990
- " of ",
991
- total
992
- ] }),
993
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
994
- Select,
995
- {
996
- value: String(pageSize),
997
- onValueChange: (value) => setPageSize(Number(value)),
998
- children: [
999
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(SelectTrigger, { className: "af-w-[70px] af-h-8", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(SelectValue, {}) }),
1000
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(SelectContent, { children: [
1001
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(SelectItem, { value: "10", children: "10" }),
1002
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(SelectItem, { value: "25", children: "25" }),
1003
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(SelectItem, { value: "50", children: "50" }),
1004
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(SelectItem, { value: "100", children: "100" })
1005
- ] })
1006
- ]
1007
- }
1008
- ),
1009
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { children: "per page" })
1010
- ] }),
1011
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "af-flex af-items-center af-gap-2", children: [
1012
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
1013
- Button,
1014
- {
1015
- variant: "outline",
1016
- size: "sm",
1017
- onClick: () => setPage(page - 1),
1018
- disabled: !hasPreviousPage,
1019
- children: [
1020
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_lucide_react4.ChevronLeft, { className: "af-h-4 af-w-4 af-mr-1" }),
1021
- "Previous"
1022
- ]
1023
- }
1024
- ),
1025
- /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
1026
- Button,
1027
- {
1028
- variant: "outline",
1029
- size: "sm",
1030
- onClick: () => setPage(page + 1),
1031
- disabled: !hasNextPage,
1032
- children: [
1033
- "Next",
1034
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_lucide_react4.ChevronRight, { className: "af-h-4 af-w-4 af-ml-1" })
1035
- ]
1036
- }
1037
- )
1038
- ] })
1039
- ] })
1040
- ] });
1041
- }
1042
-
1043
- // src/components/FormSettings.tsx
1044
- var React12 = __toESM(require("react"), 1);
1045
- var import_lucide_react5 = require("lucide-react");
1046
-
1047
- // src/ui/input.tsx
1048
- var React10 = __toESM(require("react"), 1);
1049
- var import_jsx_runtime9 = require("react/jsx-runtime");
1050
- var Input = React10.forwardRef(
1051
- ({ className, type, ...props }, ref) => {
1052
- return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
1053
- "input",
1054
- {
1055
- type,
1056
- className: cn(
1057
- "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",
1058
- className
1059
- ),
1060
- ref,
1061
- ...props
1062
- }
1063
- );
1064
- }
1065
- );
1066
- Input.displayName = "Input";
1067
-
1068
- // src/ui/label.tsx
1069
- var React11 = __toESM(require("react"), 1);
1070
- var import_class_variance_authority2 = require("class-variance-authority");
1071
- var import_jsx_runtime10 = require("react/jsx-runtime");
1072
- var labelVariants = (0, import_class_variance_authority2.cva)(
1073
- "af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"
1074
- );
1075
- var Label2 = React11.forwardRef(
1076
- ({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("label", { ref, className: cn(labelVariants(), className), ...props })
1077
- );
1078
- Label2.displayName = "Label";
1079
-
1080
- // src/ui/badge.tsx
1081
- var import_class_variance_authority3 = require("class-variance-authority");
1082
- var import_jsx_runtime11 = require("react/jsx-runtime");
1083
- var badgeVariants = (0, import_class_variance_authority3.cva)(
1084
- "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",
1085
- {
1086
- variants: {
1087
- variant: {
1088
- default: "af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",
1089
- secondary: "af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",
1090
- destructive: "af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",
1091
- outline: "af-text-foreground",
1092
- success: "af-border-transparent af-bg-green-100 af-text-green-800",
1093
- warning: "af-border-transparent af-bg-yellow-100 af-text-yellow-800"
1094
- }
1095
- },
1096
- defaultVariants: {
1097
- variant: "default"
1098
- }
1099
- }
1100
- );
1101
- function Badge({ className, variant, ...props }) {
1102
- return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: cn(badgeVariants({ variant }), className), ...props });
1103
- }
1104
-
1105
- // src/components/FormSettings.tsx
1106
- var import_jsx_runtime12 = require("react/jsx-runtime");
1107
- function FormSettings({ form, onSaved, className }) {
1108
- const { updateForm } = useForms();
1109
- const [isSaving, setIsSaving] = React12.useState(false);
1110
- const [lastSaved, setLastSaved] = React12.useState(null);
1111
- const [error, setError] = React12.useState(null);
1112
- const [name, setName] = React12.useState(form.name);
1113
- const [redirectUrl, setRedirectUrl] = React12.useState(form.redirect_url || "");
1114
- const [emailRecipients, setEmailRecipients] = React12.useState(
1115
- form.email_recipients
1116
- );
1117
- const [newEmail, setNewEmail] = React12.useState("");
1118
- React12.useEffect(() => {
1119
- setName(form.name);
1120
- setRedirectUrl(form.redirect_url || "");
1121
- setEmailRecipients(form.email_recipients);
1122
- setError(null);
1123
- }, [form]);
1124
- const save = React12.useCallback(
1125
- async (updates) => {
1126
- try {
1127
- setIsSaving(true);
1128
- setError(null);
1129
- const updatedForm = await updateForm(form.id, updates);
1130
- setLastSaved(/* @__PURE__ */ new Date());
1131
- onSaved?.(updatedForm);
1132
- } catch (err) {
1133
- setError(err instanceof Error ? err.message : "Failed to save");
1134
- } finally {
1135
- setIsSaving(false);
1136
- }
1137
- },
1138
- [form.id, updateForm, onSaved]
1139
- );
1140
- React12.useEffect(() => {
1141
- if (lastSaved) {
1142
- const timer = setTimeout(() => setLastSaved(null), 2e3);
1143
- return () => clearTimeout(timer);
1144
- }
1145
- }, [lastSaved]);
1146
- const handleAddEmail = async () => {
1147
- const email = newEmail.trim().toLowerCase();
1148
- if (!email) return;
1149
- if (!email.includes("@")) {
1150
- setError("Please enter a valid email address");
1151
- return;
1152
- }
1153
- if (emailRecipients.includes(email)) {
1154
- setError("This email is already added");
1155
- return;
1156
- }
1157
- const newRecipients = [...emailRecipients, email];
1158
- setEmailRecipients(newRecipients);
1159
- setNewEmail("");
1160
- setError(null);
1161
- await save({ email_recipients: newRecipients });
1162
- };
1163
- const handleRemoveEmail = async (email) => {
1164
- const newRecipients = emailRecipients.filter((e) => e !== email);
1165
- setEmailRecipients(newRecipients);
1166
- await save({ email_recipients: newRecipients });
1167
- };
1168
- const handleNameBlur = async () => {
1169
- if (name !== form.name) {
1170
- await save({ name });
1171
- }
1172
- };
1173
- const handleRedirectBlur = async () => {
1174
- const newValue = redirectUrl || null;
1175
- if (newValue !== form.redirect_url) {
1176
- await save({ redirect_url: newValue });
1177
- }
1178
- };
1179
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: `af-space-y-6 af-relative ${className || ""}`, children: [
1180
- (isSaving || lastSaved) && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50", children: isSaving ? /* @__PURE__ */ (0, import_jsx_runtime12.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: [
1181
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_lucide_react5.Loader2, { className: "af-h-4 af-w-4 af-animate-spin af-text-muted-foreground" }),
1182
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("span", { className: "af-text-sm", children: "Saving..." })
1183
- ] }) : /* @__PURE__ */ (0, import_jsx_runtime12.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: [
1184
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_lucide_react5.Check, { className: "af-h-4 af-w-4 af-text-green-600" }),
1185
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("span", { className: "af-text-sm af-text-green-800", children: "Changes saved" })
1186
- ] }) }),
1187
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-space-y-2", children: [
1188
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Label2, { htmlFor: "form-name", children: "Form Name" }),
1189
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
1190
- Input,
1191
- {
1192
- id: "form-name",
1193
- value: name,
1194
- onChange: (e) => setName(e.target.value),
1195
- onBlur: handleNameBlur,
1196
- placeholder: "Contact Form"
1197
- }
1198
- ),
1199
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("p", { className: "af-text-xs af-text-muted-foreground", children: "A name to identify this form in your dashboard." })
1200
- ] }),
1201
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-space-y-2", children: [
1202
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Label2, { children: "Email Recipients" }),
1203
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("p", { className: "af-text-xs af-text-muted-foreground af-mb-2", children: "Form submissions will be sent to these email addresses." }),
1204
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-flex af-flex-wrap af-gap-2 af-mb-2", children: [
1205
- emailRecipients.map((email) => /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Badge, { variant: "secondary", className: "af-gap-1", children: [
1206
- email,
1207
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
1208
- "button",
1209
- {
1210
- type: "button",
1211
- onClick: () => handleRemoveEmail(email),
1212
- className: "af-ml-1 hover:af-text-destructive",
1213
- disabled: isSaving,
1214
- children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_lucide_react5.X, { className: "af-h-3 af-w-3" })
1215
- }
1216
- )
1217
- ] }, email)),
1218
- emailRecipients.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("span", { className: "af-text-sm af-text-muted-foreground af-italic", children: "No recipients configured" })
1219
- ] }),
1220
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-flex af-gap-2", children: [
1221
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
1222
- Input,
1223
- {
1224
- type: "email",
1225
- value: newEmail,
1226
- onChange: (e) => setNewEmail(e.target.value),
1227
- placeholder: "Add email address",
1228
- onKeyDown: (e) => {
1229
- if (e.key === "Enter") {
1230
- e.preventDefault();
1231
- handleAddEmail();
1232
- }
1233
- },
1234
- disabled: isSaving
1235
- }
1236
- ),
1237
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
1238
- Button,
1239
- {
1240
- type: "button",
1241
- variant: "outline",
1242
- onClick: handleAddEmail,
1243
- disabled: !newEmail.trim() || isSaving,
1244
- children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_lucide_react5.Plus, { className: "af-h-4 af-w-4" })
1245
- }
1246
- )
1247
- ] })
1248
- ] }),
1249
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-space-y-2", children: [
1250
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Label2, { htmlFor: "redirect-url", children: "Redirect URL" }),
1251
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
1252
- Input,
1253
- {
1254
- id: "redirect-url",
1255
- value: redirectUrl,
1256
- onChange: (e) => setRedirectUrl(e.target.value),
1257
- onBlur: handleRedirectBlur,
1258
- placeholder: "/thank-you"
1259
- }
1260
- ),
1261
- /* @__PURE__ */ (0, import_jsx_runtime12.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." })
1262
- ] }),
1263
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-space-y-2", children: [
1264
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Label2, { children: "Form Endpoint" }),
1265
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "af-flex af-items-center af-gap-2", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("code", { className: "af-flex-1 af-text-xs af-bg-muted af-px-3 af-py-2 af-rounded af-border", children: form.endpoint_url }) }),
1266
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("p", { className: "af-text-xs af-text-muted-foreground", children: "Use this URL as the form action attribute." })
1267
- ] }),
1268
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "af-space-y-2", children: [
1269
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Label2, { children: "Captcha Protection" }),
1270
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "af-flex af-items-center af-gap-2", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Badge, { variant: form.turnstile_sitekey ? "success" : "secondary", children: form.turnstile_sitekey ? "Protected" : "Not Configured" }) }),
1271
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("p", { className: "af-text-xs af-text-muted-foreground", children: "Turnstile CAPTCHA is automatically enabled to prevent spam." })
1272
- ] }),
1273
- error && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded", children: error })
1274
- ] });
1275
- }
1276
-
1277
- // src/components/FormsDashboard.tsx
1278
- var import_jsx_runtime13 = require("react/jsx-runtime");
1279
- function FormsDashboard({ className, submissionId }) {
1280
- const { api } = useAifeaturesContext();
1281
- const [view, setView] = React13.useState("list");
1282
- const [selectedForm, setSelectedForm] = React13.useState(null);
1283
- const [activeTab, setActiveTab] = React13.useState(
1284
- "submissions"
1285
- );
1286
- const [deepLinkSubmissionId, setDeepLinkSubmissionId] = React13.useState(submissionId);
1287
- const [isLoadingDeepLink, setIsLoadingDeepLink] = React13.useState(!!submissionId);
1288
- React13.useEffect(() => {
1289
- if (!submissionId) return;
1290
- async function loadSubmission() {
1291
- try {
1292
- const submission = await api.getSubmission(submissionId);
1293
- const form = await api.getForm(submission.form_id);
1294
- setSelectedForm(form);
1295
- setView("detail");
1296
- setActiveTab("submissions");
1297
- setDeepLinkSubmissionId(submissionId);
1298
- } catch (error) {
1299
- console.error("Failed to load submission for deep link:", error);
1300
- } finally {
1301
- setIsLoadingDeepLink(false);
1302
- }
1303
- }
1304
- loadSubmission();
1305
- }, [submissionId, api]);
1306
- const handleSelectForm = (form, tab) => {
1307
- setSelectedForm(form);
1308
- setView("detail");
1309
- setActiveTab(tab);
1310
- setDeepLinkSubmissionId(void 0);
1311
- };
1312
- const handleBack = () => {
1313
- setView("list");
1314
- setSelectedForm(null);
1315
- setDeepLinkSubmissionId(void 0);
1316
- };
1317
- const handleFormSaved = (updatedForm) => {
1318
- setSelectedForm(updatedForm);
1319
- };
1320
- if (isLoadingDeepLink) {
1321
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: `af-flex af-items-center af-justify-center af-py-8 ${className || ""}`, children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "af-text-muted-foreground", children: "Loading..." }) });
1322
- }
1323
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className, children: [
1324
- view === "list" && /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { children: [
1325
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "af-mb-6", children: [
1326
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("h2", { className: "af-text-lg af-font-semibold", children: "Forms" }),
1327
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("p", { className: "af-text-sm af-text-muted-foreground", children: "Manage your contact forms and view submissions." })
1328
- ] }),
1329
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(FormsList, { onSelectForm: handleSelectForm })
1330
- ] }),
1331
- view === "detail" && selectedForm && /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { children: [
1332
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "af-mb-6", children: [
1333
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
1334
- Button,
1335
- {
1336
- variant: "ghost",
1337
- size: "sm",
1338
- onClick: handleBack,
1339
- className: "af-mb-2 af--ml-2",
1340
- children: [
1341
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_lucide_react6.ArrowLeft, { className: "af-h-4 af-w-4 af-mr-1" }),
1342
- "Back to Forms"
1343
- ]
1344
- }
1345
- ),
1346
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("h2", { className: "af-text-lg af-font-semibold", children: selectedForm.name }),
1347
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("p", { className: "af-text-sm af-text-muted-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("code", { className: "af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded", children: selectedForm.endpoint_url }) })
1348
- ] }),
1349
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
1350
- Tabs,
1351
- {
1352
- value: activeTab,
1353
- onValueChange: (v) => setActiveTab(v),
1354
- children: [
1355
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(TabsList, { className: "af-mb-4", children: [
1356
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(TabsTrigger, { value: "submissions", className: "af-gap-2", children: [
1357
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_lucide_react6.Inbox, { className: "af-h-4 af-w-4" }),
1358
- "Submissions"
1359
- ] }),
1360
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(TabsTrigger, { value: "settings", className: "af-gap-2", children: [
1361
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_lucide_react6.Settings, { className: "af-h-4 af-w-4" }),
1362
- "Settings"
1363
- ] })
1364
- ] }),
1365
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(TabsContent, { value: "submissions", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(FormSubmissions, { formId: selectedForm.id, defaultSubmissionId: deepLinkSubmissionId }) }),
1366
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(TabsContent, { value: "settings", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(FormSettings, { form: selectedForm, onSaved: handleFormSaved }) })
1367
- ]
1368
- }
1369
- )
1370
- ] })
1371
- ] });
1372
- }
1373
- // Annotate the CommonJS export names for ESM import in node:
1374
- 0 && (module.exports = {
1375
- AifeaturesApiError,
1376
- AifeaturesProvider,
1377
- FormSettings,
1378
- FormSubmissions,
1379
- FormsDashboard,
1380
- FormsList,
1381
- SubmissionDetail,
1382
- createApiClient,
1383
- useAifeatures,
1384
- useAifeaturesContext,
1385
- useForms,
1386
- useSubmissions
1387
- });
1388
- //# sourceMappingURL=index.cjs.map
2
+ "use strict";var Dr=Object.create;var Ka=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Ar=Object.getOwnPropertyNames;var Fr=Object.getPrototypeOf,Ur=Object.prototype.hasOwnProperty;var Vr=(e,t)=>{for(var a in t)Ka(e,a,{get:t[a],enumerable:!0})},As=(e,t,a,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ar(t))!Ur.call(e,r)&&r!==a&&Ka(e,r,{get:()=>t[r],enumerable:!(s=Ir(t,r))||s.enumerable});return e};var te=(e,t,a)=>(a=e!=null?Dr(Fr(e)):{},As(t||!e||!e.__esModule?Ka(a,"default",{value:e,enumerable:!0}):a,e)),Hr=e=>As(Ka({},"__esModule",{value:!0}),e);var Mn={};Vr(Mn,{AifeaturesApiError:()=>Ft,AifeaturesProvider:()=>Us,CustomerDetail:()=>Ma,CustomersList:()=>$a,FormSettings:()=>Ba,FormSubmissions:()=>La,FormsDashboard:()=>gs,FormsList:()=>Ta,LeadsView:()=>_s,OrderDetail:()=>Va,OrderStatusBadge:()=>sa,OrdersList:()=>ua,OrdersView:()=>Rs,PaymentsDashboard:()=>Ss,PaymentsSetup:()=>za,ProductSettings:()=>Aa,ProductsList:()=>Da,ProductsView:()=>Cs,SubmissionDetail:()=>_a,VariantsEditor:()=>Ia,ViewShell:()=>Kt,chargedTotal:()=>gt,createApiClient:()=>Qa,formatPrice:()=>H,isZeroDecimalCurrency:()=>xt,toMajorUnits:()=>Me,toMinorUnits:()=>vt,useAifeatures:()=>ae,useAifeaturesContext:()=>ae,useBusinessSummary:()=>ja,useCustomers:()=>Ha,useForms:()=>oa,useOrders:()=>Fa,usePaymentsStatus:()=>pa,usePeople:()=>Ga,usePerson:()=>Wa,useProducts:()=>ga,useSubmissions:()=>ka});module.exports=Hr(Mn);var Yt=te(require("react"),1);var Ft=class extends Error{constructor(a,s,r){super(a);this.status=s;this.details=r;this.name="AifeaturesApiError"}};function ps(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 Qa(e,t="https://aifeatures.dev"){async function a(s,r={}){let l=`${t}${s}`,d=await fetch(l,{...r,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",...r.headers}});if(!d.ok){let g;try{g=await d.json()}catch{}throw new Ft(ps(g?.error,d.status),d.status,g)}if(d.status!==204)return d.json()}return{async getForms(){return(await a("/api/v1/forms")).forms},async getForm(s){return a(`/api/v1/forms/${s}`)},async createForm(s){return a("/api/v1/forms",{method:"POST",body:JSON.stringify(s)})},async updateForm(s,r){return a(`/api/v1/forms/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteForm(s){await a(`/api/v1/forms/${s}`,{method:"DELETE"})},async getSubmissions(s,r={}){let l=new URLSearchParams;r.limit!==void 0&&l.set("limit",String(r.limit)),r.offset!==void 0&&l.set("offset",String(r.offset));let d=l.toString(),g=`/api/v1/forms/${s}/submissions${d?`?${d}`:""}`;return a(g)},async getSubmission(s){return a(`/api/v1/submissions/${s}`)},async deleteSubmission(s){await a(`/api/v1/submissions/${s}`,{method:"DELETE"})},async downloadAttachment(s,r){let l=typeof r=="string"?{name:r}:r,d=l.name,g=l.id??l.name,u=`${t}/api/v1/submissions/${s}/attachments/${encodeURIComponent(g)}`,m=await fetch(u,{headers:{Authorization:`Bearer ${e}`}});if(!m.ok){let P;try{P=await m.json()}catch{}throw new Ft(ps(P?.error,m.status),m.status,P)}let n=await m.blob(),b=URL.createObjectURL(n),N=document.createElement("a");N.href=b,N.download=d,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(b)},async getPaymentsStatus(){return a("/api/v1/payments/status")},async getProducts(s={}){let r=new URLSearchParams;s.include&&r.set("include",s.include);let l=r.toString();return(await a(`/api/v1/products${l?`?${l}`:""}`)).products},async getProduct(s){return a(`/api/v1/products/${s}`)},async createProduct(s){return a("/api/v1/products",{method:"POST",body:JSON.stringify(s)})},async updateProduct(s,r){return a(`/api/v1/products/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteProduct(s){await a(`/api/v1/products/${s}`,{method:"DELETE"})},async attachProductFile(s,r){let l=new FormData;l.append("file",r);let d=await fetch(`${t}/api/v1/products/${s}/file`,{method:"POST",headers:{Authorization:`Bearer ${e}`},body:l});if(!d.ok){let g;try{g=await d.json()}catch{}throw new Ft(ps(g?.error,d.status),d.status,g)}return d.json()},async attachProductFileFromUrl(s,r){return a(`/api/v1/products/${s}/file`,{method:"POST",body:JSON.stringify({source_url:r})})},async createOption(s,r){return a(`/api/v1/products/${s}/options`,{method:"POST",body:JSON.stringify(r)})},async updateOption(s,r){return a(`/api/v1/options/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteOption(s){await a(`/api/v1/options/${s}`,{method:"DELETE"})},async createVariant(s,r){return a(`/api/v1/products/${s}/variants`,{method:"POST",body:JSON.stringify(r)})},async updateVariant(s,r){return a(`/api/v1/variants/${s}`,{method:"PATCH",body:JSON.stringify(r)})},async deleteVariant(s){await a(`/api/v1/variants/${s}`,{method:"DELETE"})},async setVariantInventory(s,r){return a(`/api/v1/variants/${s}/inventory`,{method:"PUT",body:JSON.stringify(r)})},async adjustVariantInventory(s,r){return a(`/api/v1/variants/${s}/inventory/adjust`,{method:"POST",body:JSON.stringify(r)})},async getCustomers(s={}){let r=new URLSearchParams;s.email&&r.set("email",s.email),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let l=r.toString();return a(`/api/v1/customers${l?`?${l}`:""}`)},async getCustomer(s){return a(`/api/v1/customers/${s}`)},async getOrders(s={}){let r=new URLSearchParams;s.status&&r.set("status",s.status),s.excludeStatus?.length&&r.set("exclude_status",s.excludeStatus.join(",")),s.customerEmail&&r.set("customer_email",s.customerEmail),s.from&&r.set("from",s.from),s.to&&r.set("to",s.to),s.unfulfilledOnly&&r.set("unfulfilled_only","true"),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let l=r.toString();return a(`/api/v1/orders${l?`?${l}`:""}`)},async getOrder(s){return a(`/api/v1/orders/${s}`)},async resendOrderReceipt(s){await a(`/api/v1/orders/${s}/resend-receipt`,{method:"POST"})},async resetOrderDownloads(s){return a(`/api/v1/orders/${s}/reset-downloads`,{method:"POST"})},async setOrderFulfillment(s,r){return a(`/api/v1/orders/${s}/fulfillment`,{method:"POST",body:JSON.stringify({fulfilled:r.fulfilled,...r.trackingNumber!==void 0?{tracking_number:r.trackingNumber}:{}})})},async getBusinessSummary(s){let r=new URLSearchParams;return r.set("tz_offset_minutes",String(s.tzOffsetMinutes)),a(`/api/v1/summary?${r.toString()}`)},async getPeople(s={}){let r=new URLSearchParams;s.since&&r.set("since",s.since),s.q&&r.set("q",s.q),s.limit!==void 0&&r.set("limit",String(s.limit)),s.offset!==void 0&&r.set("offset",String(s.offset));let l=r.toString();return a(`/api/v1/people${l?`?${l}`:""}`)},async getPerson(s){return a(`/api/v1/people/${encodeURIComponent(s)}`)}}}var Zt=require("react/jsx-runtime"),Fs=Yt.createContext(null);function Mr(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 Us({siteToken:e,apiUrl:t="https://aifeatures.dev",dark:a=!1,className:s,children:r}){let l=Yt.useMemo(()=>Mr(e),[e]),d=Yt.useMemo(()=>Qa(e,t),[e,t]),g=Yt.useMemo(()=>({siteToken:e,apiUrl:t,api:d}),[e,t,d]);return l?(0,Zt.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:(0,Zt.jsxs)("div",{className:"af-rounded-md af-border af-border-destructive af-bg-destructive/10 af-p-4",children:[(0,Zt.jsx)("h3",{className:"af-text-sm af-font-semibold af-text-destructive af-mb-2",children:"AifeaturesProvider Configuration Error"}),(0,Zt.jsx)("p",{className:"af-text-sm af-text-destructive",children:l})]})}):(0,Zt.jsx)(Fs.Provider,{value:g,children:(0,Zt.jsx)("div",{className:`aifeatures-admin ${a?"dark":""} ${s||""}`,children:r})})}function ae(){let e=Yt.useContext(Fs);if(!e)throw new Error("useAifeaturesContext must be used within an AifeaturesProvider");return e}var ta=te(require("react"),1),ha=require("lucide-react");var Ja=te(require("react"),1),yt=te(require("@radix-ui/react-tabs"),1);var Vs=require("clsx"),Hs=require("tailwind-merge");function I(...e){return(0,Hs.twMerge)((0,Vs.clsx)(e))}var Ya=require("react/jsx-runtime"),Za=yt.Root,Ra=Ja.forwardRef(({className:e,...t},a)=>(0,Ya.jsx)(yt.List,{ref:a,className:I("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}));Ra.displayName=yt.List.displayName;var Ut=Ja.forwardRef(({className:e,...t},a)=>(0,Ya.jsx)(yt.Trigger,{ref:a,className:I("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}));Ut.displayName=yt.Trigger.displayName;var Vt=Ja.forwardRef(({className:e,...t},a)=>(0,Ya.jsx)(yt.Content,{ref:a,className:I("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}));Vt.displayName=yt.Content.displayName;var Ms=te(require("react"),1),$s=require("@radix-ui/react-slot"),zs=require("class-variance-authority");var js=require("react/jsx-runtime"),$r=(0,zs.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"}}),x=Ms.forwardRef(({className:e,variant:t,size:a,asChild:s=!1,...r},l)=>(0,js.jsx)(s?$s.Slot:"button",{className:I($r({variant:t,size:a,className:e})),ref:l,...r}));x.displayName="Button";var Ca=require("lucide-react");var Ht=te(require("react"),1);var kt=require("react/jsx-runtime"),Re=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("div",{className:"af-relative af-w-full af-overflow-auto",children:(0,kt.jsx)("table",{ref:a,className:I("af-w-full af-caption-bottom af-text-sm",e),...t})}));Re.displayName="Table";var Ce=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("thead",{ref:a,className:I("[&_tr]:af-border-b",e),...t}));Ce.displayName="TableHeader";var Te=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("tbody",{ref:a,className:I("[&_tr:last-child]:af-border-0",e),...t}));Te.displayName="TableBody";var zr=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("tfoot",{ref:a,className:I("af-border-t af-bg-muted/50 af-font-medium [&>tr]:last:af-border-b-0",e),...t}));zr.displayName="TableFooter";var oe=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("tr",{ref:a,className:I("af-border-b af-transition-colors hover:af-bg-muted/50 data-[state=selected]:af-bg-muted",e),...t}));oe.displayName="TableRow";var E=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("th",{ref:a,className:I("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}));E.displayName="TableHead";var D=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("td",{ref:a,className:I("af-p-2 af-align-middle [&:has([role=checkbox])]:af-pr-0 [&>[role=checkbox]]:af-translate-y-[2px]",e),...t}));D.displayName="TableCell";var jr=Ht.forwardRef(({className:e,...t},a)=>(0,kt.jsx)("caption",{ref:a,className:I("af-mt-4 af-text-sm af-text-muted-foreground",e),...t}));jr.displayName="TableCaption";var ht=te(require("react"),1);function oa(){let{api:e}=ae(),[t,a]=ht.useState([]),[s,r]=ht.useState(!0),[l,d]=ht.useState(null),g=ht.useCallback(async()=>{try{r(!0),d(null);let b=await e.getForms();a(b)}catch(b){d(b instanceof Error?b:new Error("Failed to fetch forms"))}finally{r(!1)}},[e]);ht.useEffect(()=>{g()},[g]);let u=ht.useCallback(async b=>{let N=await e.createForm(b);return a(P=>[...P,N]),N},[e]),m=ht.useCallback(async(b,N)=>{let P=await e.updateForm(b,N);return a(h=>h.map(y=>y.id===b?P:y)),P},[e]),n=ht.useCallback(async b=>{await e.deleteForm(b),a(N=>N.filter(P=>P.id!==b))},[e]);return{forms:t,isLoading:s,error:l,refetch:g,createForm:u,updateForm:m,deleteForm:n}}var me=require("react/jsx-runtime");function Ta({onSelectForm:e,className:t}){let{forms:a,isLoading:s,error:r}=oa();return s?(0,me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,me.jsx)("div",{className:"af-text-muted-foreground",children:"Loading forms..."})}):r?(0,me.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,me.jsxs)("div",{className:"af-text-destructive",children:["Error: ",r.message]})}):a.length===0?(0,me.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,me.jsx)(Ca.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,me.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No forms yet.",(0,me.jsx)("br",{}),"Forms will appear here when the AI creates contact forms on your website."]})]}):(0,me.jsx)("div",{className:t,children:(0,me.jsxs)(Re,{children:[(0,me.jsx)(Ce,{children:(0,me.jsxs)(oe,{children:[(0,me.jsx)(E,{children:"Name"}),(0,me.jsx)(E,{children:"Endpoint"}),(0,me.jsx)(E,{className:"af-text-right",children:"Actions"})]})}),(0,me.jsx)(Te,{children:a.map(l=>(0,me.jsxs)(oe,{children:[(0,me.jsx)(D,{className:"af-font-medium",children:l.name}),(0,me.jsx)(D,{children:(0,me.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:l.endpoint_url.replace("https://aifeatures.dev","")})}),(0,me.jsx)(D,{className:"af-text-right",children:(0,me.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,me.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>e?.(l,"submissions"),children:[(0,me.jsx)(Ca.Inbox,{className:"af-h-4 af-w-4 af-mr-1"}),"Submissions"]}),(0,me.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>e?.(l,"settings"),children:[(0,me.jsx)(Ca.Settings,{className:"af-h-4 af-w-4 af-mr-1"}),"Settings"]})]})})]},l.id))})]})})}var Oa=te(require("react"),1),_t=require("lucide-react");var Xt=te(require("react"),1),re=te(require("@radix-ui/react-select"),1),la=require("lucide-react");var Le=require("react/jsx-runtime"),ut=re.Root;var mt=re.Value,at=Xt.forwardRef(({className:e,children:t,...a},s)=>(0,Le.jsxs)(re.Trigger,{ref:s,className:I("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),...a,children:[t,(0,Le.jsx)(re.Icon,{asChild:!0,children:(0,Le.jsx)(la.ChevronDown,{className:"af-h-4 af-w-4 af-opacity-50"})})]}));at.displayName=re.Trigger.displayName;var qs=Xt.forwardRef(({className:e,...t},a)=>(0,Le.jsx)(re.ScrollUpButton,{ref:a,className:I("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,Le.jsx)(la.ChevronUp,{className:"af-h-4 af-w-4"})}));qs.displayName=re.ScrollUpButton.displayName;var Gs=Xt.forwardRef(({className:e,...t},a)=>(0,Le.jsx)(re.ScrollDownButton,{ref:a,className:I("af-flex af-cursor-default af-items-center af-justify-center af-py-1",e),...t,children:(0,Le.jsx)(la.ChevronDown,{className:"af-h-4 af-w-4"})}));Gs.displayName=re.ScrollDownButton.displayName;var st=Xt.forwardRef(({className:e,children:t,position:a="popper",...s},r)=>(0,Le.jsx)(re.Portal,{children:(0,Le.jsxs)(re.Content,{ref:r,className:I("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",a==="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:a,...s,children:[(0,Le.jsx)(qs,{}),(0,Le.jsx)(re.Viewport,{className:I("af-p-1",a==="popper"&&"af-h-[var(--radix-select-trigger-height)] af-w-full af-min-w-[var(--radix-select-trigger-width)]"),children:t}),(0,Le.jsx)(Gs,{})]})}));st.displayName=re.Content.displayName;var qr=Xt.forwardRef(({className:e,...t},a)=>(0,Le.jsx)(re.Label,{ref:a,className:I("af-px-2 af-py-1.5 af-text-sm af-font-semibold",e),...t}));qr.displayName=re.Label.displayName;var he=Xt.forwardRef(({className:e,children:t,...a},s)=>(0,Le.jsxs)(re.Item,{ref:s,className:I("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),...a,children:[(0,Le.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,Le.jsx)(re.ItemIndicator,{children:(0,Le.jsx)(la.Check,{className:"af-h-4 af-w-4"})})}),(0,Le.jsx)(re.ItemText,{children:t})]}));he.displayName=re.Item.displayName;var Gr=Xt.forwardRef(({className:e,...t},a)=>(0,Le.jsx)(re.Separator,{ref:a,className:I("af--mx-1 af-my-1 af-h-px af-bg-muted",e),...t}));Gr.displayName=re.Separator.displayName;var pt=te(require("react"),1);function ka({formId:e,initialPageSize:t=25}){let{api:a}=ae(),[s,r]=pt.useState([]),[l,d]=pt.useState(0),[g,u]=pt.useState(!0),[m,n]=pt.useState(null),[b,N]=pt.useState(0),[P,h]=pt.useState(t),y=pt.useCallback(async()=>{if(e)try{u(!0),n(null);let O={limit:P,offset:b*P},F=await a.getSubmissions(e,O);r(F.submissions),d(F.total)}catch(O){n(O instanceof Error?O:new Error("Failed to fetch submissions"))}finally{u(!1)}},[a,e,b,P]);pt.useEffect(()=>{y()},[y]);let w=pt.useCallback(async O=>{await a.deleteSubmission(O),r(F=>F.filter(Y=>Y.id!==O)),d(F=>F-1)},[a]),T=Math.ceil(l/P);return{submissions:s,total:l,isLoading:g,error:m,page:b,pageSize:P,hasNextPage:b<T-1,hasPreviousPage:b>0,setPage:N,setPageSize:O=>{h(O),N(0)},refetch:y,deleteSubmission:w}}var Ks=te(require("react"),1),Qe=require("lucide-react");var J=require("react/jsx-runtime");function Ws(e){return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Wr(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function _a({submission:e,onBack:t}){let{api:a}=ae(),[s,r]=Ks.useState(null),l=u=>u.id??u.name,d=async u=>{r(l(u));try{await a.downloadAttachment(e.id,u)}catch(m){console.error("Download failed:",m)}finally{r(null)}},g=Object.entries(e.data).filter(([u])=>!u.startsWith("_"));return(0,J.jsxs)("div",{children:[(0,J.jsxs)("div",{className:"af-mb-6",children:[(0,J.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,J.jsx)(Qe.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Submissions"]}),(0,J.jsx)("h3",{className:"af-text-lg af-font-semibold",children:"Submission Details"}),(0,J.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Submitted ",Ws(e.metadata.submitted_at)]})]}),(0,J.jsxs)("div",{className:"af-space-y-6",children:[(0,J.jsxs)("div",{children:[(0,J.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Form Data"}),(0,J.jsxs)("div",{className:"af-space-y-3",children:[g.map(([u,m])=>(0,J.jsxs)("div",{className:"af-grid af-grid-cols-3 af-gap-2",children:[(0,J.jsx)("div",{className:"af-text-sm af-text-muted-foreground af-capitalize",children:u.replace(/_/g," ")}),(0,J.jsx)("div",{className:"af-col-span-2 af-text-sm af-break-words",children:typeof m=="string"&&m.includes(`
3
+ `)?(0,J.jsx)("pre",{className:"af-whitespace-pre-wrap af-font-sans af-bg-muted af-p-2 af-rounded af-text-xs",children:m}):String(m)})]},u)),g.length===0&&(0,J.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"})]})]}),e.attachments.length>0&&(0,J.jsxs)("div",{children:[(0,J.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Attachments"}),(0,J.jsx)("div",{className:"af-space-y-2",children:e.attachments.map((u,m)=>(0,J.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-p-2 af-bg-muted af-rounded",children:[(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,J.jsx)(Qe.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,J.jsx)("span",{className:"af-text-sm",children:u.name}),(0,J.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",Wr(u.size),")"]})]}),(0,J.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>d(u),disabled:s===l(u),children:[s===l(u)?(0,J.jsx)(Qe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,J.jsx)(Qe.Download,{className:"af-h-4 af-w-4 af-mr-1"}),s===l(u)?"Downloading...":"Download"]})]},m))})]}),(0,J.jsxs)("div",{children:[(0,J.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Metadata"}),(0,J.jsxs)("div",{className:"af-space-y-2 af-text-sm",children:[(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,J.jsx)(Qe.Clock,{className:"af-h-4 af-w-4"}),(0,J.jsx)("span",{children:Ws(e.metadata.submitted_at)})]}),e.metadata.ip_address&&(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,J.jsx)(Qe.Globe,{className:"af-h-4 af-w-4"}),(0,J.jsxs)("span",{children:["IP: ",e.metadata.ip_address]})]}),e.metadata.user_agent&&(0,J.jsxs)("div",{className:"af-flex af-items-start af-gap-2 af-text-muted-foreground",children:[(0,J.jsx)(Qe.Monitor,{className:"af-h-4 af-w-4 af-mt-0.5"}),(0,J.jsx)("span",{className:"af-text-xs af-break-all",children:e.metadata.user_agent})]}),e.resend_id&&(0,J.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-muted-foreground",children:[(0,J.jsx)(Qe.Mail,{className:"af-h-4 af-w-4"}),(0,J.jsxs)("span",{children:["Email ID: ",e.resend_id]})]})]})]})]})]})}var j=require("react/jsx-runtime");function Kr(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Qr(e){let t=["email","Email","EMAIL","e-mail","mail"];for(let a of t)if(typeof e[a]=="string")return e[a];return null}function Jr(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")&&!r.toLowerCase().includes("email"));if(t.length===0)return"";let[,a]=t[0],s=String(a);return s.length>50?s.slice(0,50)+"...":s}function La({formId:e,className:t,defaultSubmissionId:a}){let{submissions:s,total:r,isLoading:l,error:d,page:g,pageSize:u,hasNextPage:m,hasPreviousPage:n,setPage:b,setPageSize:N}=ka({formId:e}),[P,h]=Oa.useState("list"),[y,w]=Oa.useState(null);Oa.useEffect(()=>{if(a&&s.length>0){let B=s.find(V=>V.id===a);B&&(w(B),h("detail"))}},[a,s]);let T=B=>{w(B),h("detail")},O=()=>{h("list"),w(null)};if(P==="detail"&&y)return(0,j.jsx)("div",{className:t,children:(0,j.jsx)(_a,{submission:y,onBack:O})});if(l)return(0,j.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,j.jsx)("div",{className:"af-text-muted-foreground",children:"Loading submissions..."})});if(d)return(0,j.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${t||""}`,children:(0,j.jsxs)("div",{className:"af-text-destructive",children:["Error: ",d.message]})});if(s.length===0&&g===0)return(0,j.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${t||""}`,children:[(0,j.jsx)(_t.Inbox,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,j.jsxs)("p",{className:"af-text-muted-foreground af-text-center",children:["No submissions yet.",(0,j.jsx)("br",{}),"Submissions will appear here when visitors use your form."]})]});let F=g*u+1,Y=Math.min((g+1)*u,r);return(0,j.jsxs)("div",{className:t,children:[(0,j.jsxs)(Re,{children:[(0,j.jsx)(Ce,{children:(0,j.jsxs)(oe,{children:[(0,j.jsx)(E,{children:"Email"}),(0,j.jsx)(E,{children:"Preview"}),(0,j.jsx)(E,{children:"Date"}),(0,j.jsx)(E,{className:"af-text-right",children:"Actions"})]})}),(0,j.jsx)(Te,{children:s.map(B=>{let V=Qr(B.data),M=Jr(B.data);return(0,j.jsxs)(oe,{children:[(0,j.jsx)(D,{className:"af-font-medium",children:(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[V||(0,j.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),B.attachments.length>0&&(0,j.jsxs)("span",{className:"af-flex af-items-center af-gap-1 af-text-muted-foreground",title:`${B.attachments.length} attachment(s)`,children:[(0,j.jsx)(_t.Paperclip,{className:"af-h-3 af-w-3"}),(0,j.jsx)("span",{className:"af-text-xs",children:B.attachments.length})]})]})}),(0,j.jsx)(D,{className:"af-text-muted-foreground af-max-w-[200px] af-truncate",children:M||(0,j.jsx)("span",{className:"af-italic",children:"No preview available"})}),(0,j.jsx)(D,{className:"af-text-muted-foreground",children:Kr(B.metadata.submitted_at)}),(0,j.jsx)(D,{className:"af-text-right",children:(0,j.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>T(B),title:"View details",children:(0,j.jsx)(_t.Eye,{className:"af-h-4 af-w-4"})})})]},B.id)})})]}),(0,j.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,j.jsxs)("span",{children:["Showing ",F,"-",Y," of ",r]}),(0,j.jsxs)(ut,{value:String(u),onValueChange:B=>N(Number(B)),children:[(0,j.jsx)(at,{className:"af-w-[70px] af-h-8",children:(0,j.jsx)(mt,{})}),(0,j.jsxs)(st,{children:[(0,j.jsx)(he,{value:"10",children:"10"}),(0,j.jsx)(he,{value:"25",children:"25"}),(0,j.jsx)(he,{value:"50",children:"50"}),(0,j.jsx)(he,{value:"100",children:"100"})]})]}),(0,j.jsx)("span",{children:"per page"})]}),(0,j.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,j.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>b(g-1),disabled:!n,children:[(0,j.jsx)(_t.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,j.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>b(g+1),disabled:!m,children:["Next",(0,j.jsx)(_t.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var rt=te(require("react"),1),ea=require("lucide-react");var Qs=te(require("react"),1);var Js=require("react/jsx-runtime"),le=Qs.forwardRef(({className:e,type:t,...a},s)=>(0,Js.jsx)("input",{type:t,className:I("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,...a}));le.displayName="Input";var Zs=te(require("react"),1),Ys=require("class-variance-authority");var Xs=require("react/jsx-runtime"),Zr=(0,Ys.cva)("af-text-sm af-font-medium af-leading-none peer-disabled:af-cursor-not-allowed peer-disabled:af-opacity-70"),ne=Zs.forwardRef(({className:e,...t},a)=>(0,Xs.jsx)("label",{ref:a,className:I(Zr(),e),...t}));ne.displayName="Label";var er=require("class-variance-authority");var tr=require("react/jsx-runtime"),Yr=(0,er.cva)("af-inline-flex af-items-center af-rounded-md af-border af-px-2.5 af-py-0.5 af-text-xs af-font-semibold af-transition-colors focus:af-outline-none focus:af-ring-2 focus:af-ring-ring focus:af-ring-offset-2",{variants:{variant:{default:"af-border-transparent af-bg-primary af-text-primary-foreground af-shadow hover:af-bg-primary/80",secondary:"af-border-transparent af-bg-secondary af-text-secondary-foreground hover:af-bg-secondary/80",destructive:"af-border-transparent af-bg-destructive af-text-destructive-foreground af-shadow hover:af-bg-destructive/80",outline:"af-text-foreground",success:"af-border-transparent af-bg-green-100 af-text-green-800",warning:"af-border-transparent af-bg-yellow-100 af-text-yellow-800"}},defaultVariants:{variant:"default"}});function W({className:e,variant:t,...a}){return(0,tr.jsx)("div",{className:I(Yr({variant:t}),e),...a})}var ee=require("react/jsx-runtime");function Ba({form:e,onSaved:t,className:a}){let{updateForm:s}=oa(),[r,l]=rt.useState(!1),[d,g]=rt.useState(null),[u,m]=rt.useState(null),[n,b]=rt.useState(e.name),[N,P]=rt.useState(e.redirect_url||""),[h,y]=rt.useState(e.email_recipients),[w,T]=rt.useState("");rt.useEffect(()=>{b(e.name),P(e.redirect_url||""),y(e.email_recipients),m(null)},[e]);let O=rt.useCallback(async M=>{try{l(!0),m(null);let Q=await s(e.id,M);g(new Date),t?.(Q)}catch(Q){m(Q instanceof Error?Q.message:"Failed to save")}finally{l(!1)}},[e.id,s,t]);rt.useEffect(()=>{if(d){let M=setTimeout(()=>g(null),2e3);return()=>clearTimeout(M)}},[d]);let F=async()=>{let M=w.trim().toLowerCase();if(!M)return;if(!M.includes("@")){m("Please enter a valid email address");return}if(h.includes(M)){m("This email is already added");return}let Q=[...h,M];y(Q),T(""),m(null),await O({email_recipients:Q})},Y=async M=>{let Q=h.filter($=>$!==M);y(Q),await O({email_recipients:Q})},B=async()=>{n!==e.name&&await O({name:n})},V=async()=>{let M=N||null;M!==e.redirect_url&&await O({redirect_url:M})};return(0,ee.jsxs)("div",{className:`af-space-y-6 af-relative ${a||""}`,children:[(r||d)&&(0,ee.jsx)("div",{className:"aifeatures-admin af-fixed af-bottom-4 af-right-4 af-z-50",children:r?(0,ee.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,ee.jsx)(ea.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"}),(0,ee.jsx)("span",{className:"af-text-sm",children:"Saving..."})]}):(0,ee.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,ee.jsx)(ea.Check,{className:"af-h-4 af-w-4 af-text-green-600"}),(0,ee.jsx)("span",{className:"af-text-sm af-text-green-800",children:"Changes saved"})]})}),(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)(ne,{htmlFor:"form-name",children:"Form Name"}),(0,ee.jsx)(le,{id:"form-name",value:n,onChange:M=>b(M.target.value),onBlur:B,placeholder:"Contact Form"}),(0,ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"A name to identify this form in your dashboard."})]}),(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)(ne,{children:"Email Recipients"}),(0,ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Form submissions will be sent to these email addresses."}),(0,ee.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[h.map(M=>(0,ee.jsxs)(W,{variant:"secondary",className:"af-gap-1",children:[M,(0,ee.jsx)("button",{type:"button",onClick:()=>Y(M),className:"af-ml-1 hover:af-text-destructive",disabled:r,children:(0,ee.jsx)(ea.X,{className:"af-h-3 af-w-3"})})]},M)),h.length===0&&(0,ee.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No recipients configured"})]}),(0,ee.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,ee.jsx)(le,{type:"email",value:w,onChange:M=>T(M.target.value),placeholder:"Add email address",onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),F())},disabled:r}),(0,ee.jsx)(x,{type:"button",variant:"outline",onClick:F,disabled:!w.trim()||r,children:(0,ee.jsx)(ea.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)(ne,{htmlFor:"redirect-url",children:"Redirect URL"}),(0,ee.jsx)(le,{id:"redirect-url",value:N,onChange:M=>P(M.target.value),onBlur:V,placeholder:"/thank-you"}),(0,ee.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,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)(ne,{children:"Form Endpoint"}),(0,ee.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,ee.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,ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Use this URL as the form action attribute."})]}),(0,ee.jsxs)("div",{className:"af-space-y-2",children:[(0,ee.jsx)(ne,{children:"Captcha Protection"}),(0,ee.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,ee.jsx)(W,{variant:e.turnstile_sitekey?"success":"secondary",children:e.turnstile_sitekey?"Protected":"Not Configured"})}),(0,ee.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Turnstile CAPTCHA is automatically enabled to prevent spam."})]}),u&&(0,ee.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:u})]})}var pe=require("react/jsx-runtime");function gs({className:e,submissionId:t}){let{api:a}=ae(),[s,r]=ta.useState("list"),[l,d]=ta.useState(null),[g,u]=ta.useState("submissions"),[m,n]=ta.useState(t),[b,N]=ta.useState(!!t);ta.useEffect(()=>{if(!t)return;async function w(){try{let T=await a.getSubmission(t),O=await a.getForm(T.form_id);d(O),r("detail"),u("submissions"),n(t)}catch(T){console.error("Failed to load submission for deep link:",T)}finally{N(!1)}}w()},[t,a]);let P=(w,T)=>{d(w),r("detail"),u(T),n(void 0)},h=()=>{r("list"),d(null),n(void 0)},y=w=>{d(w)};return b?(0,pe.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${e||""}`,children:(0,pe.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,pe.jsxs)("div",{className:e,children:[s==="list"&&(0,pe.jsxs)("div",{children:[(0,pe.jsxs)("div",{className:"af-mb-6",children:[(0,pe.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Forms"}),(0,pe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your contact forms and view submissions."})]}),(0,pe.jsx)(Ta,{onSelectForm:P})]}),s==="detail"&&l&&(0,pe.jsxs)("div",{children:[(0,pe.jsxs)("div",{className:"af-mb-6",children:[(0,pe.jsxs)(x,{variant:"ghost",size:"sm",onClick:h,className:"af-mb-2 af--ml-2",children:[(0,pe.jsx)(ha.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Forms"]}),(0,pe.jsx)("h2",{className:"af-text-lg af-font-semibold",children:l.name}),(0,pe.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:(0,pe.jsx)("code",{className:"af-text-xs af-bg-muted af-px-1.5 af-py-0.5 af-rounded",children:l.endpoint_url})})]}),(0,pe.jsxs)(Za,{value:g,onValueChange:w=>u(w),children:[(0,pe.jsxs)(Ra,{className:"af-mb-4",children:[(0,pe.jsxs)(Ut,{value:"submissions",className:"af-gap-2",children:[(0,pe.jsx)(ha.Inbox,{className:"af-h-4 af-w-4"}),"Submissions"]}),(0,pe.jsxs)(Ut,{value:"settings",className:"af-gap-2",children:[(0,pe.jsx)(ha.Settings,{className:"af-h-4 af-w-4"}),"Settings"]})]}),(0,pe.jsx)(Vt,{value:"submissions",children:(0,pe.jsx)(La,{formId:l.id,defaultSubmissionId:m})}),(0,pe.jsx)(Vt,{value:"settings",children:(0,pe.jsx)(Ba,{form:l,onSaved:y})})]})]})]})}var os=te(require("react"),1),Et=require("lucide-react");var Xa=te(require("react"),1),Gt=require("lucide-react");var Ea=te(require("react"),1),Fe=te(require("@radix-ui/react-dialog"),1),ar=require("lucide-react");var et=require("react/jsx-runtime"),aa=Fe.Root;var Xr=Fe.Portal;var sr=Ea.forwardRef(({className:e,...t},a)=>(0,et.jsx)(Fe.Overlay,{ref:a,className:I("aifeatures-dialog-overlay af-fixed af-inset-0 af-z-50 af-bg-black/80",e),...t}));sr.displayName=Fe.Overlay.displayName;var Mt=Ea.forwardRef(({className:e,children:t,...a},s)=>(0,et.jsx)(Xr,{children:(0,et.jsxs)("div",{className:"aifeatures-admin",children:[(0,et.jsx)(sr,{}),(0,et.jsxs)(Fe.Content,{ref:s,className:I("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),...a,children:[t,(0,et.jsxs)(Fe.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,et.jsx)(ar.X,{className:"af-h-4 af-w-4"}),(0,et.jsx)("span",{className:"af-sr-only",children:"Close"})]})]})]})}));Mt.displayName=Fe.Content.displayName;var $t=({className:e,...t})=>(0,et.jsx)("div",{className:I("af-flex af-flex-col af-space-y-1.5 af-text-center sm:af-text-left",e),...t});$t.displayName="DialogHeader";var zt=({className:e,...t})=>(0,et.jsx)("div",{className:I("af-flex af-flex-col-reverse sm:af-flex-row sm:af-justify-end sm:af-space-x-2",e),...t});zt.displayName="DialogFooter";var jt=Ea.forwardRef(({className:e,...t},a)=>(0,et.jsx)(Fe.Title,{ref:a,className:I("af-text-lg af-font-semibold af-leading-none af-tracking-tight",e),...t}));jt.displayName=Fe.Title.displayName;var qt=Ea.forwardRef(({className:e,...t},a)=>(0,et.jsx)(Fe.Description,{ref:a,className:I("af-text-sm af-text-muted-foreground",e),...t}));qt.displayName=Fe.Description.displayName;var en=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function xt(e){return en.has(e.toLowerCase())}function H(e,t,a){let s=xt(t)?e:e/100;try{return new Intl.NumberFormat(a,{style:"currency",currency:t.toUpperCase()}).format(s)}catch{return`${s} ${t.toUpperCase()}`}}function gt(e){let t=e.automatic_tax&&e.tax_behavior==="exclusive"?e.tax_total??0:0;return e.amount_total+(e.shipping_total??0)+t}function vt(e,t){let a=typeof e=="string"?parseFloat(e):e;if(!Number.isFinite(a)||a<0)return null;let s=xt(t)?a:a*100;return Math.round(s)}function Me(e,t){return xt(t)?e:e/100}var G=require("react/jsx-runtime");function tn(e){if(e.allow_custom_amount){let t=e.min_amount!==null?H(e.min_amount,e.currency):"?",a=e.max_amount!==null?H(e.max_amount,e.currency):"?";return`Buyer chooses (${t} - ${a})`}return e.unit_amount===null?"Varies by variant":H(e.unit_amount,e.currency)}function an(e){switch(e.fulfillment.type){case"download":return e.fulfillment.filename||"Digital download";case"redirect":return"Redirect";default:return"-"}}function Da({productsState:e,onSelectProduct:t,onCreateProduct:a,className:s}){let{products:r,isLoading:l,error:d,deleteProduct:g}=e,[u,m]=Xa.useState(null),[n,b]=Xa.useState(!1),[N,P]=Xa.useState(null),h=async()=>{if(u)try{b(!0),P(null),await g(u.id),m(null)}catch(y){P(y instanceof Error?y.message:"Failed to delete product")}finally{b(!1)}};return l?(0,G.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,G.jsx)("div",{className:"af-text-muted-foreground",children:"Loading products..."})}):d?(0,G.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${s||""}`,children:(0,G.jsxs)("div",{className:"af-text-destructive",children:["Error: ",d.message]})}):r.length===0?(0,G.jsxs)("div",{className:`af-flex af-flex-col af-items-center af-justify-center af-py-12 ${s||""}`,children:[(0,G.jsx)(Gt.Package,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,G.jsxs)("p",{className:"af-text-muted-foreground af-text-center af-mb-4",children:["No products yet.",(0,G.jsx)("br",{}),"Products will appear here when the AI adds them to your website, or you can create one yourself."]}),(0,G.jsxs)(x,{variant:"outline",onClick:()=>a?.(),children:[(0,G.jsx)(Gt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})]}):(0,G.jsxs)("div",{className:s,children:[(0,G.jsx)("div",{className:"af-flex af-justify-end af-mb-4",children:(0,G.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>a?.(),children:[(0,G.jsx)(Gt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"New Product"]})}),(0,G.jsxs)(Re,{children:[(0,G.jsx)(Ce,{children:(0,G.jsxs)(oe,{children:[(0,G.jsx)(E,{children:"Name"}),(0,G.jsx)(E,{children:"Price"}),(0,G.jsx)(E,{children:"Fulfillment"}),(0,G.jsx)(E,{children:"Status"}),(0,G.jsx)(E,{className:"af-text-right",children:"Actions"})]})}),(0,G.jsx)(Te,{children:r.map(y=>(0,G.jsxs)(oe,{children:[(0,G.jsx)(D,{className:"af-font-medium",children:y.name}),(0,G.jsx)(D,{children:tn(y)}),(0,G.jsx)(D,{className:"af-text-muted-foreground",children:an(y)}),(0,G.jsx)(D,{children:(0,G.jsx)(W,{variant:y.active?"success":"secondary",children:y.active?"Active":"Inactive"})}),(0,G.jsx)(D,{className:"af-text-right",children:(0,G.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-2",children:[(0,G.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>t?.(y),children:[(0,G.jsx)(Gt.Pencil,{className:"af-h-4 af-w-4 af-mr-1"}),"Edit"]}),(0,G.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>{P(null),m(y)},children:[(0,G.jsx)(Gt.Trash2,{className:"af-h-4 af-w-4 af-mr-1"}),"Delete"]})]})})]},y.id))})]}),(0,G.jsx)(aa,{open:!!u,onOpenChange:y=>{!y&&!n&&m(null)},children:(0,G.jsxs)(Mt,{children:[(0,G.jsxs)($t,{children:[(0,G.jsx)(jt,{children:"Delete product?"}),(0,G.jsxs)(qt,{children:['"',u?.name,'" will be removed from your site and can no longer be purchased. Past orders and buyer downloads are not affected.']})]}),N&&(0,G.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:N}),(0,G.jsxs)(zt,{children:[(0,G.jsx)(x,{variant:"outline",onClick:()=>m(null),disabled:n,children:"Cancel"}),(0,G.jsx)(x,{variant:"destructive",onClick:h,disabled:n,children:n?"Deleting...":"Delete"})]})]})})]})}var Ne=te(require("react"),1),nt=require("lucide-react");var Ie=te(require("react"),1),bt=require("lucide-react");var c=require("react/jsx-runtime");function vs(e){return e.option_values.length>0?e.option_values.map(t=>t.value).join(" / "):e.title||"Default"}function Ia({productId:e,currency:t,className:a}){let{api:s}=ae(),r=xt(t)?"1":"0.01",[l,d]=Ie.useState(null),[g,u]=Ie.useState(!0),[m,n]=Ie.useState(null),[b,N]=Ie.useState(null),[P,h]=Ie.useState(!1),y=Ie.useRef(!0);Ie.useEffect(()=>(y.current=!0,()=>{y.current=!1}),[]);let w=Ie.useCallback(async()=>{try{let v=await s.getProduct(e);if(!y.current)return;d(v)}catch(v){if(!y.current)return;n(v instanceof Error?v.message:"Failed to load product")}finally{y.current&&u(!1)}},[s,e]);Ie.useEffect(()=>{w()},[w]);let T=async v=>{N(null),h(!0);try{await v(),await w()}catch(_){y.current&&N(_ instanceof Error?_.message:"Something went wrong")}finally{y.current&&h(!1)}},[O,F]=Ie.useState(""),[Y,B]=Ie.useState(""),[V,M]=Ie.useState({}),Q=()=>T(async()=>{let v=O.trim(),_=Y.split(",").map(ie=>ie.trim()).filter(Boolean);if(!v)throw new Error("Option name is required");if(_.length===0)throw new Error("Add at least one value");await s.createOption(e,{title:v,values:_}),y.current&&(F(""),B(""))}),$=v=>T(async()=>{let _=(V[v.id]??"").trim();if(!_)throw new Error("Enter a value");await s.updateOption(v.id,{add_values:[_]}),y.current&&M(ie=>({...ie,[v.id]:""}))}),A=(v,_)=>T(()=>s.updateOption(v.id,{remove_values:[_]})),ve=v=>T(()=>s.deleteOption(v.id)),[p,se]=Ie.useState(null),[we,xe]=Ie.useState(null),[ce,Ae]=Ie.useState(!1),[X,ue]=Ie.useState(null),Pe=l?.options??[],je=l?.variants??[],Ve=()=>{xe(null),se({variant:null,title:"",sku:"",unitAmount:"",compareAt:"",active:!0,optionValues:Object.fromEntries(Pe.map(v=>[v.id,v.values[0]?.value??""])),tracked:!1,onHand:"0",initialOnHand:"0",allowBackorder:!1})},Pt=v=>{xe(null);let _=v.inventory?.on_hand??0,ie=_<0?"":String(_);se({variant:v,title:v.title??"",sku:v.sku??"",unitAmount:v.unit_amount!=null?String(Me(v.unit_amount,t)):"",compareAt:v.compare_at_amount!=null?String(Me(v.compare_at_amount,t)):"",active:v.active,optionValues:{},tracked:v.inventory?.tracked??!1,onHand:ie,initialOnHand:ie,allowBackorder:v.inventory?.allow_backorder??!1})},St=async()=>{if(!p)return;xe(null);let v=p.variant?.allow_custom_amount??!1,_=null,ie=null;if(!v){if(_=vt(p.unitAmount,t),_===null||_<=0){xe("Enter a valid price");return}if(p.compareAt.trim()&&(ie=vt(p.compareAt,t),ie===null||ie<=_)){xe("Compare-at price must be greater than the price");return}}let Ge=p.onHand.trim()!==p.initialOnHand.trim(),We=parseInt(p.onHand,10);if(p.tracked&&Ge&&(!Number.isFinite(We)||We<0)){xe("On-hand quantity must be zero or more");return}try{if(Ae(!0),p.variant)await s.updateVariant(p.variant.id,{title:p.title.trim()||null,sku:p.sku.trim()||null,...v?{}:{unit_amount:_,compare_at_amount:ie},active:p.active}),await s.setVariantInventory(p.variant.id,{tracked:p.tracked,on_hand:p.tracked&&Ge?We:void 0,allow_backorder:p.allowBackorder});else{let Ke={};for(let qe of Pe){let Ct=p.optionValues[qe.id];if(!Ct){xe(`Choose a ${qe.title}`),Ae(!1);return}Ke[qe.title]=Ct}await s.createVariant(e,{title:p.title.trim()||null,sku:p.sku.trim()||null,unit_amount:_,compare_at_amount:ie,active:p.active,option_values:Pe.length>0?Ke:void 0,inventory:p.tracked?{tracked:!0,on_hand:We,allow_backorder:p.allowBackorder}:{tracked:!1,allow_backorder:p.allowBackorder}})}await w(),y.current&&se(null)}catch(Ke){if(y.current&&xe(Ke instanceof Error?Ke.message:"Failed to save variant"),p.variant)try{let qe=await s.getProduct(e);y.current&&d(qe)}catch{}}finally{y.current&&Ae(!1)}},_e=()=>T(async()=>{X&&(await s.deleteVariant(X.id),y.current&&ue(null))}),ft=p?.variant?.allow_custom_amount??!1,dt=p?.variant!=null&&p.variant.option_values.length===0&&Pe.length>0&&!p.variant.active,De=p?.variant?.inventory!=null&&p.variant.inventory.on_hand<0?-p.variant.inventory.on_hand:null;function Rt(v){let _=v.inventory;if(!_||!_.tracked)return(0,c.jsx)("span",{className:"af-text-muted-foreground",children:"Unlimited"});let ie=_.available??_.on_hand;return ie<0?(0,c.jsxs)("span",{children:[-ie," backordered"]}):(0,c.jsxs)("span",{children:[ie," in stock",_.allow_backorder&&(0,c.jsx)("span",{className:"af-text-muted-foreground af-text-xs af-ml-1",children:"(backorder)"})]})}return g?(0,c.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-6 ${a||""}`,children:(0,c.jsx)(bt.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):m?(0,c.jsx)("div",{className:a,children:(0,c.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:m})}):(0,c.jsxs)("div",{className:`af-space-y-6 ${a||""}`,children:[(0,c.jsxs)("div",{className:"af-space-y-3",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(ne,{children:"Options"}),(0,c.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."})]}),Pe.length>0&&(0,c.jsx)("div",{className:"af-space-y-3",children:Pe.map(v=>(0,c.jsxs)("div",{className:"af-border af-rounded af-p-3 af-space-y-2",children:[(0,c.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,c.jsx)("span",{className:"af-text-sm af-font-medium",children:v.title}),(0,c.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>ve(v),disabled:P,children:(0,c.jsx)(bt.Trash2,{className:"af-h-4 af-w-4"})})]}),(0,c.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:v.values.map(_=>(0,c.jsxs)(W,{variant:"secondary",className:"af-gap-1",children:[_.value,(0,c.jsx)("button",{type:"button",onClick:()=>A(v,_.value),className:"af-ml-1 hover:af-text-destructive",disabled:P,title:"Remove value",children:(0,c.jsx)(bt.X,{className:"af-h-3 af-w-3"})})]},_.id))}),(0,c.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,c.jsx)(le,{value:V[v.id]??"",onChange:_=>M(ie=>({...ie,[v.id]:_.target.value})),placeholder:"Add a value",className:"af-h-8",onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),$(v))},disabled:P}),(0,c.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>$(v),disabled:P||!(V[v.id]??"").trim(),children:(0,c.jsx)(bt.Plus,{className:"af-h-4 af-w-4"})})]})]},v.id))}),(0,c.jsxs)("div",{className:"af-flex af-flex-wrap af-items-end af-gap-2",children:[(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsx)(ne,{htmlFor:"new-option-title",className:"af-text-xs af-text-muted-foreground",children:"Option name"}),(0,c.jsx)(le,{id:"new-option-title",value:O,onChange:v=>F(v.target.value),placeholder:"Size",className:"af-w-[140px]",disabled:P})]}),(0,c.jsxs)("div",{className:"af-space-y-1 af-flex-1 af-min-w-[180px]",children:[(0,c.jsx)(ne,{htmlFor:"new-option-values",className:"af-text-xs af-text-muted-foreground",children:"Values (comma-separated)"}),(0,c.jsx)(le,{id:"new-option-values",value:Y,onChange:v=>B(v.target.value),placeholder:"S, M, L",disabled:P})]}),(0,c.jsxs)(x,{type:"button",variant:"outline",onClick:Q,disabled:P||!O.trim()||!Y.trim(),children:[(0,c.jsx)(bt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add option"]})]})]}),(0,c.jsxs)("div",{className:"af-space-y-3",children:[(0,c.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,c.jsx)(ne,{children:"Variants"}),(0,c.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:Ve,disabled:P||Pe.length===0,children:[(0,c.jsx)(bt.Plus,{className:"af-h-4 af-w-4 af-mr-1"}),"Add variant"]})]}),Pe.length===0&&(0,c.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Add an option (e.g. Size) above before adding variants."}),je.length===0?(0,c.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No variants yet."}):(0,c.jsxs)(Re,{children:[(0,c.jsx)(Ce,{children:(0,c.jsxs)(oe,{children:[(0,c.jsx)(E,{children:"Variant"}),(0,c.jsx)(E,{children:"SKU"}),(0,c.jsx)(E,{children:"Price"}),(0,c.jsx)(E,{children:"Stock"}),(0,c.jsx)(E,{children:"Status"}),(0,c.jsx)(E,{className:"af-text-right",children:"Actions"})]})}),(0,c.jsx)(Te,{children:je.map(v=>(0,c.jsxs)(oe,{children:[(0,c.jsx)(D,{className:"af-font-medium",children:vs(v)}),(0,c.jsx)(D,{className:"af-text-muted-foreground",children:v.sku||"-"}),(0,c.jsx)(D,{children:v.unit_amount!=null?(0,c.jsxs)("span",{children:[v.compare_at_amount!=null&&(0,c.jsx)("span",{className:"af-text-muted-foreground af-line-through af-mr-1",children:H(v.compare_at_amount,v.currency)}),H(v.unit_amount,v.currency)]}):v.allow_custom_amount?(0,c.jsx)("span",{className:"af-text-muted-foreground",children:"Buyer chooses"}):"-"}),(0,c.jsx)(D,{children:Rt(v)}),(0,c.jsx)(D,{children:(0,c.jsx)(W,{variant:v.active?"success":"secondary",children:v.active?"Active":"Inactive"})}),(0,c.jsx)(D,{className:"af-text-right",children:(0,c.jsxs)("div",{className:"af-flex af-items-center af-justify-end af-gap-1",children:[(0,c.jsx)(x,{variant:"ghost",size:"sm",onClick:()=>Pt(v),disabled:P,children:"Edit"}),(0,c.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>ue(v),disabled:P,title:"Delete variant",children:(0,c.jsx)(bt.Trash2,{className:"af-h-4 af-w-4"})})]})})]},v.id))})]})]}),b&&(0,c.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:b}),(0,c.jsx)(aa,{open:p!==null,onOpenChange:v=>{!v&&!ce&&se(null)},children:(0,c.jsxs)(Mt,{children:[(0,c.jsxs)($t,{children:[(0,c.jsx)(jt,{children:p?.variant?"Edit variant":"Add variant"}),(0,c.jsx)(qt,{children:"Price, markdown, and stock live on the variant."})]}),p&&(0,c.jsxs)("div",{className:"af-space-y-3",children:[p.variant?p.variant.option_values.length>0&&(0,c.jsxs)("div",{className:"af-text-sm",children:[(0,c.jsx)("span",{className:"af-text-muted-foreground af-mr-2",children:"Options"}),vs(p.variant)]}):Pe.map(v=>(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsx)(ne,{className:"af-text-xs af-text-muted-foreground",children:v.title}),(0,c.jsxs)(ut,{value:p.optionValues[v.id]??"",onValueChange:_=>se(ie=>ie&&{...ie,optionValues:{...ie.optionValues,[v.id]:_}}),children:[(0,c.jsx)(at,{children:(0,c.jsx)(mt,{placeholder:`Choose ${v.title}`})}),(0,c.jsx)(st,{children:v.values.map(_=>(0,c.jsx)(he,{value:_.value,children:_.value},_.id))})]})]},v.id)),ft?(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsx)(ne,{className:"af-text-xs af-text-muted-foreground",children:"Price"}),(0,c.jsx)("p",{className:"af-text-sm",children:"Buyer chooses the amount \u2014 this variant has no fixed price."})]}):(0,c.jsxs)("div",{className:"af-flex af-gap-3",children:[(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsxs)(ne,{htmlFor:"variant-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",t.toUpperCase(),")"]}),(0,c.jsx)(le,{id:"variant-price",type:"number",min:"0",step:r,value:p.unitAmount,onChange:v=>se(_=>_&&{..._,unitAmount:v.target.value}),placeholder:"25.00",className:"af-w-[130px]"})]}),(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsx)(ne,{htmlFor:"variant-compare",className:"af-text-xs af-text-muted-foreground",children:"Compare-at (optional)"}),(0,c.jsx)(le,{id:"variant-compare",type:"number",min:"0",step:r,value:p.compareAt,onChange:v=>se(_=>_&&{..._,compareAt:v.target.value}),placeholder:"40.00",className:"af-w-[130px]"})]})]}),(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsx)(ne,{htmlFor:"variant-sku",className:"af-text-xs af-text-muted-foreground",children:"SKU (optional)"}),(0,c.jsx)(le,{id:"variant-sku",value:p.sku,onChange:v=>se(_=>_&&{..._,sku:v.target.value}),placeholder:"TEE-L-BLACK",className:"af-w-[200px]"})]}),(0,c.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-3",children:[(0,c.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,c.jsx)("input",{type:"checkbox",checked:p.tracked,onChange:v=>se(_=>_&&{..._,tracked:v.target.checked}),className:"af-h-4 af-w-4"}),"Track inventory"]}),p.tracked&&(0,c.jsxs)("div",{className:"af-space-y-1 af-pl-6",children:[(0,c.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsx)(ne,{htmlFor:"variant-onhand",className:"af-text-xs af-text-muted-foreground",children:"On hand"}),(0,c.jsx)(le,{id:"variant-onhand",type:"number",min:"0",step:"1",value:p.onHand,onChange:v=>se(_=>_&&{..._,onHand:v.target.value}),placeholder:De!=null?"0":void 0,className:"af-w-[100px]"})]}),(0,c.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm af-mb-2",children:[(0,c.jsx)("input",{type:"checkbox",checked:p.allowBackorder,onChange:v=>se(_=>_&&{..._,allowBackorder:v.target.checked}),className:"af-h-4 af-w-4"}),"Allow backorder"]})]}),De!=null&&(0,c.jsxs)("p",{className:"af-text-xs af-text-muted-foreground af-max-w-[300px]",children:["Currently ",De," backordered. Leave the field empty to keep the backorder count, or enter a quantity (0 or more) to reset stock and clear it."]})]})]}),(0,c.jsxs)("div",{className:"af-space-y-1",children:[(0,c.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,c.jsx)("input",{type:"checkbox",checked:p.active,onChange:v=>se(_=>_&&{..._,active:v.target.checked}),className:"af-h-4 af-w-4",disabled:dt}),"Active (buyers can purchase this variant)"]}),dt&&(0,c.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."})]}),we&&(0,c.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:we})]}),(0,c.jsxs)(zt,{children:[(0,c.jsx)(x,{variant:"outline",onClick:()=>se(null),disabled:ce,children:"Cancel"}),(0,c.jsxs)(x,{onClick:St,disabled:ce,children:[ce?(0,c.jsx)(bt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,p?.variant?"Save":"Add variant"]})]})]})}),(0,c.jsx)(aa,{open:X!==null,onOpenChange:v=>{!v&&!P&&ue(null)},children:(0,c.jsxs)(Mt,{children:[(0,c.jsxs)($t,{children:[(0,c.jsx)(jt,{children:"Delete variant?"}),(0,c.jsx)(qt,{children:X&&`"${vs(X)}" will no longer be purchasable. Past orders are unaffected.`})]}),(0,c.jsxs)(zt,{children:[(0,c.jsx)(x,{variant:"outline",onClick:()=>ue(null),disabled:P,children:"Cancel"}),(0,c.jsx)(x,{variant:"destructive",onClick:_e,disabled:P,children:"Delete"})]})]})})]})}var C=require("react/jsx-runtime");function sn(e){if(e===0)return"0 B";let t=1024,a=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/Math.pow(t,s)).toFixed(1))} ${a[s]}`}function Aa({productsState:e,product:t,currency:a,onSaved:s,className:r}){let{createProduct:l,updateProduct:d,attachProductFile:g,attachProductFileFromUrl:u}=e,m=!!t,n=t?.currency??a,b=xt(n)?"1":"0.01",N=t!=null&&t.unit_amount===null&&!t.allow_custom_amount,[P,h]=Ne.useState(!1),[y,w]=Ne.useState(null),T=Ne.useRef(!0);Ne.useEffect(()=>(T.current=!0,()=>{T.current=!1}),[]);let[O,F]=Ne.useState(t?.name??""),[Y,B]=Ne.useState(t?.description??""),[V,M]=Ne.useState(t?.allow_custom_amount?"custom":"fixed"),[Q,$]=Ne.useState(t?.unit_amount!=null?String(Me(t.unit_amount,n)):""),[A,ve]=Ne.useState(t?.min_amount!=null?String(Me(t.min_amount,n)):""),[p,se]=Ne.useState(t?.max_amount!=null?String(Me(t.max_amount,n)):""),[we,xe]=Ne.useState(String(t?.max_quantity??10)),ce=Ne.useRef({pricingMode:t?.allow_custom_amount?"custom":"fixed",unitAmount:t?.unit_amount!=null?String(Me(t.unit_amount,n)):"",minAmount:t?.min_amount!=null?String(Me(t.min_amount,n)):"",maxAmount:t?.max_amount!=null?String(Me(t.max_amount,n)):"",maxQuantity:String(t?.max_quantity??10)}).current,[Ae,X]=Ne.useState(t?.collect_shipping_address??!1),[ue,Pe]=Ne.useState(t?.active??!0),[je,Ve]=Ne.useState(t?.images??[]),[Pt,St]=Ne.useState(""),[_e,ft]=Ne.useState(t?.fulfillment??null),[dt,De]=Ne.useState(!1),[Rt,v]=Ne.useState(""),[_,ie]=Ne.useState(null),Ge=Ne.useRef(null),We=P||dt,Ke=()=>{let z=Pt.trim();if(z){if(je.includes(z)){w("This image URL is already added");return}Ve(ye=>[...ye,z]),St(""),w(null)}},qe=z=>{Ve(ye=>ye.filter(Se=>Se!==z))},Ct=async()=>{if(w(null),!O.trim()){w("Product name is required");return}let z=null,ye=null,Se=null,Jt=!m||V!==ce.pricingMode||(V==="fixed"?Q!==ce.unitAmount:A!==ce.minAmount||p!==ce.maxAmount),Tt=!m||we!==ce.maxQuantity,ya=N||V==="fixed";if(!(N||!Jt))if(V==="fixed"){if(z=vt(Q,n),z===null||z<=0){w("Enter a valid price");return}}else{if(ye=vt(A,n),Se=vt(p,n),ye===null||Se===null){w("Enter valid minimum and maximum amounts");return}if(Se<ye){w("Maximum amount must be at least the minimum amount");return}}let ct=parseInt(we,10);if(ya&&Tt&&(!Number.isFinite(ct)||ct<1)){w("Max quantity must be at least 1");return}try{h(!0);let Oe;if(m&&t){let He={name:O.trim(),description:Y.trim()||null,images:je,collect_shipping_address:Ae,active:ue};!N&&Jt&&(He.allow_custom_amount=V==="custom",V==="fixed"?He.unit_amount=z:(He.min_amount=ye,He.max_amount=Se)),ya&&Tt&&(He.max_quantity=ct),Oe=await d(t.id,He),ce.pricingMode=Oe.allow_custom_amount?"custom":"fixed",ce.unitAmount=Oe.unit_amount!=null?String(Me(Oe.unit_amount,n)):"",ce.minAmount=Oe.min_amount!=null?String(Me(Oe.min_amount,n)):"",ce.maxAmount=Oe.max_amount!=null?String(Me(Oe.max_amount,n)):"",ce.maxQuantity=String(Oe.max_quantity)}else{let He={name:O.trim(),allow_custom_amount:V==="custom",collect_shipping_address:Ae,active:ue};Y.trim()&&(He.description=Y.trim()),je.length>0&&(He.images=je),V==="fixed"?(He.unit_amount=z,He.max_quantity=ct):(He.min_amount=ye,He.max_amount=Se),Oe=await l(He)}if(!T.current)return;ft(Oe.fulfillment),s?.(Oe)}catch(Oe){if(!T.current)return;w(Oe instanceof Error?Oe.message:"Failed to save product")}finally{T.current&&h(!1)}},va=async z=>{let ye=z.target.files?.[0];if(!(!ye||!t))try{De(!0),ie(null);let Se=await g(t.id,ye);if(!T.current)return;ft(Se.fulfillment),s?.(Se)}catch(Se){if(!T.current)return;ie(Se instanceof Error?Se.message:"Failed to upload file")}finally{T.current&&(De(!1),Ge.current&&(Ge.current.value=""))}},ba=async()=>{let z=Rt.trim();if(!(!z||!t))try{De(!0),ie(null);let ye=await u(t.id,z);if(!T.current)return;ft(ye.fulfillment),v(""),s?.(ye)}catch(ye){if(!T.current)return;ie(ye instanceof Error?ye.message:"Failed to fetch file")}finally{T.current&&De(!1)}};return(0,C.jsxs)("div",{className:`af-space-y-6 ${r||""}`,children:[(0,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsx)(ne,{htmlFor:"product-name",children:"Name"}),(0,C.jsx)(le,{id:"product-name",value:O,onChange:z=>F(z.target.value),placeholder:"My product"})]}),(0,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsx)(ne,{htmlFor:"product-description",children:"Description"}),(0,C.jsx)("textarea",{id:"product-description",value:Y,onChange:z=>B(z.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,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsx)(ne,{children:"Pricing"}),N?(0,C.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,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(ut,{value:V,onValueChange:z=>M(z),children:[(0,C.jsx)(at,{className:"af-w-[260px]",children:(0,C.jsx)(mt,{})}),(0,C.jsxs)(st,{children:[(0,C.jsx)(he,{value:"fixed",children:"Fixed price"}),(0,C.jsx)(he,{value:"custom",children:"Buyer chooses the amount"})]})]}),V==="fixed"?(0,C.jsx)("div",{className:"af-flex af-items-end af-gap-3",children:(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsxs)(ne,{htmlFor:"product-price",className:"af-text-xs af-text-muted-foreground",children:["Price (",n.toUpperCase(),")"]}),(0,C.jsx)(le,{id:"product-price",type:"number",min:"0",step:b,value:Q,onChange:z=>$(z.target.value),placeholder:"29.00",className:"af-w-[140px]"})]})}):(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsxs)("div",{className:"af-flex af-items-end af-gap-3",children:[(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsxs)(ne,{htmlFor:"product-min-amount",className:"af-text-xs af-text-muted-foreground",children:["Minimum (",n.toUpperCase(),")"]}),(0,C.jsx)(le,{id:"product-min-amount",type:"number",min:"0",step:b,value:A,onChange:z=>ve(z.target.value),placeholder:"1.00",className:"af-w-[140px]"})]}),(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsxs)(ne,{htmlFor:"product-max-amount",className:"af-text-xs af-text-muted-foreground",children:["Maximum (",n.toUpperCase(),")"]}),(0,C.jsx)(le,{id:"product-max-amount",type:"number",min:"0",step:b,value:p,onChange:z=>se(z.target.value),placeholder:"500.00",className:"af-w-[140px]"})]})]}),(0,C.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,C.jsxs)("p",{className:"af-text-xs af-text-muted-foreground",children:["Prices are in your site currency (",n.toUpperCase(),"), which follows the country of your payment account."]})]}),(N||V==="fixed")&&(0,C.jsxs)("div",{className:"af-space-y-1",children:[(0,C.jsx)(ne,{htmlFor:"product-max-quantity",className:"af-text-xs af-text-muted-foreground",children:"Max quantity per order"}),(0,C.jsx)(le,{id:"product-max-quantity",type:"number",min:"1",step:"1",value:we,onChange:z=>xe(z.target.value),className:"af-w-[140px]"})]})]}),(0,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsx)(ne,{children:"Images"}),(0,C.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mb-2",children:"Image URLs shown on the Stripe checkout page."}),(0,C.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-2 af-mb-2",children:[je.map(z=>(0,C.jsxs)(W,{variant:"secondary",className:"af-gap-1 af-max-w-[320px]",children:[(0,C.jsx)("span",{className:"af-truncate",children:z}),(0,C.jsx)("button",{type:"button",onClick:()=>qe(z),className:"af-ml-1 hover:af-text-destructive",disabled:P,children:(0,C.jsx)(nt.X,{className:"af-h-3 af-w-3"})})]},z)),je.length===0&&(0,C.jsx)("span",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No images"})]}),(0,C.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,C.jsx)(le,{type:"url",value:Pt,onChange:z=>St(z.target.value),placeholder:"https://example.com/image.jpg",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),Ke())},disabled:P}),(0,C.jsx)(x,{type:"button",variant:"outline",onClick:Ke,disabled:!Pt.trim()||P,children:(0,C.jsx)(nt.Plus,{className:"af-h-4 af-w-4"})})]})]}),(0,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsx)(ne,{children:"Digital File"}),(0,C.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."}),m?(0,C.jsxs)("div",{className:"af-space-y-3",children:[_e?.type==="download"&&(0,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,C.jsx)(nt.FileText,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,C.jsx)("span",{className:"af-text-sm",children:_e.filename}),_e.size!=null&&(0,C.jsxs)("span",{className:"af-text-xs af-text-muted-foreground",children:["(",sn(_e.size),")"]})]}),_e?.type==="redirect"&&_e.url&&(0,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-p-2 af-bg-muted af-rounded",children:[(0,C.jsx)(nt.Link2,{className:"af-h-4 af-w-4 af-text-muted-foreground"}),(0,C.jsxs)("span",{className:"af-text-sm af-truncate",children:["Buyers are sent to ",_e.url]})]}),(0,C.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,C.jsx)("input",{ref:Ge,type:"file",onChange:va,className:"af-hidden",disabled:We}),(0,C.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>Ge.current?.click(),disabled:We,children:[dt?(0,C.jsx)(nt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,C.jsx)(nt.Upload,{className:"af-h-4 af-w-4 af-mr-1"}),_e?.type==="download"?"Replace file":"Upload file"]}),(0,C.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:"or"}),(0,C.jsx)(le,{type:"url",value:Rt,onChange:z=>v(z.target.value),placeholder:"https://example.com/file.pdf",className:"af-flex-1",disabled:dt}),(0,C.jsx)(x,{type:"button",variant:"outline",size:"sm",onClick:ba,disabled:!Rt.trim()||We,children:"Fetch from URL"})]}),_&&(0,C.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:_})]}):(0,C.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"Save the product first, then attach a file."})]}),(0,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsx)(ne,{children:"Settings"}),(0,C.jsxs)("div",{className:"af-space-y-2",children:[(0,C.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,C.jsx)("input",{type:"checkbox",checked:Ae,onChange:z=>X(z.target.checked),className:"af-h-4 af-w-4"}),"Collect a shipping address at checkout"]}),(0,C.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,C.jsx)("input",{type:"checkbox",checked:ue,onChange:z=>Pe(z.target.checked),className:"af-h-4 af-w-4"}),"Active (buyers can purchase this product)"]})]})]}),m&&t&&(0,C.jsxs)("div",{className:"af-space-y-2 af-border-t af-pt-6",children:[(0,C.jsx)(ne,{children:"Options & Variants"}),(0,C.jsx)(Ia,{productId:t.id,currency:n})]}),y&&(0,C.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:y}),(0,C.jsx)("div",{className:"af-flex af-items-center af-gap-2",children:(0,C.jsxs)(x,{type:"button",onClick:Ct,disabled:We,children:[P?(0,C.jsx)(nt.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):null,m?"Save changes":"Create product"]})})]})}var $e=te(require("react"),1),it=require("lucide-react");var ke=te(require("react"),1);var rn=["pending","paid","failed","expired","refunded","partially_refunded","disputed"];function Fa({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=ae(),[s,r]=ke.useState([]),[l,d]=ke.useState(0),[g,u]=ke.useState(!0),[m,n]=ke.useState(null),[b,N]=ke.useState(0),[P,h]=ke.useState(e),[y,w]=ke.useState(void 0),[T,O]=ke.useState(""),[F,Y]=ke.useState(""),[B,V]=ke.useState(""),[M,Q]=ke.useState(!1),[$,A]=ke.useState(!1),[ve,p]=ke.useState(void 0),se=ve?ve.join(","):"",we=ke.useMemo(()=>{if(!se)return;let X=new Set(se.split(","));return rn.filter(ue=>!X.has(ue))},[se]),xe=ke.useRef(0),ce=ke.useCallback(async()=>{let X=++xe.current;try{u(!0),n(null);let ue={limit:P,offset:b*P};y?ue.status=y:we?ue.excludeStatus=we:M||(ue.excludeStatus=["pending","expired"]),T.trim()&&(ue.customerEmail=T.trim()),F.trim()&&(ue.from=F.trim()),B.trim()&&(ue.to=B.trim()),$&&(ue.unfulfilledOnly=!0);let Pe=await a.getOrders(ue);if(X!==xe.current)return;r(Pe.orders),d(Pe.total)}catch(ue){if(X!==xe.current)return;n(ue instanceof Error?ue:new Error("Failed to fetch orders"))}finally{X===xe.current&&u(!1)}},[a,b,P,y,we,M,$,T,F,B,t]);ke.useEffect(()=>{ce()},[ce]);let Ae=Math.ceil(l/P);return{orders:s,total:l,isLoading:g,error:m,page:b,pageSize:P,hasNextPage:b<Ae-1,hasPreviousPage:b>0,setPage:N,setPageSize:X=>{h(X),N(0)},status:y,setStatus:X=>{w(X),N(0)},statusIn:ve,setStatusIn:X=>{p(X&&X.length>0?X:void 0),N(0)},customerEmail:T,setCustomerEmail:X=>{O(X),N(0)},from:F,setFrom:X=>{Y(X),N(0)},to:B,setTo:X=>{V(X),N(0)},showAbandoned:M,setShowAbandoned:X=>{Q(X),N(0)},unfulfilledOnly:$,setUnfulfilledOnly:X=>{A(X),N(0)},clearFilters:()=>{w(void 0),p(void 0),Q(!1),A(!1),O(""),Y(""),V(""),N(0)},refetch:ce}}var Be=te(require("react"),1),fe=require("lucide-react");var rr=te(require("react"),1),Ot=te(require("@radix-ui/react-popover"),1);var es=require("react/jsx-runtime"),nr=Ot.Root,ir=Ot.Trigger;var bs=rr.forwardRef(({className:e,align:t="end",sideOffset:a=4,...s},r)=>(0,es.jsx)(Ot.Portal,{children:(0,es.jsx)("div",{className:"aifeatures-admin",children:(0,es.jsx)(Ot.Content,{ref:r,align:t,sideOffset:a,className:I("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})})}));bs.displayName=Ot.Content.displayName;var Ua=require("react/jsx-runtime"),nn={pending:"Pending",paid:"Paid",failed:"Failed",expired:"Expired",refunded:"Refunded",partially_refunded:"Partially refunded",disputed:"Disputed"};function on(e){return nn[e]??e}function or(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 fa({status:e,className:t}){return(0,Ua.jsx)(W,{variant:or(e),className:t,children:on(e)})}function sa({status:e}){return(0,Ua.jsx)(fa,{status:e})}function xa({order:e,className:t}){return e.shipping_address?typeof e.merchant_fulfilled_at=="string"?(0,Ua.jsx)(W,{variant:"outline",className:t,children:"Shipped"}):e.merchant_fulfilled_at===null&&(e.status==="paid"||e.status==="partially_refunded"||e.status==="disputed")?(0,Ua.jsx)(W,{variant:"warning",className:t,children:"Needs shipping"}):null:null}function Wt(e){return typeof e.order_number=="number"?`#${e.order_number}`:`#${e.id.slice(0,8)}`}var o=require("react/jsx-runtime"),cr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",da="af-text-xs af-text-muted-foreground";function ys(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`;return new Date(t).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ur(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 ts=24,fn=["paid","partially_refunded"],dn=["paid","partially_refunded","disputed"],cn=/^[A-Za-z0-9 _-]*$/,lr=100;function Ns(e,t,a,s,r){let l=fn.includes(s);return t==="sent"?{label:"Sent",variant:"success",detail:null}:t==="sending"?{label:"Sending",variant:"secondary",detail:"Going out right now."}:t==="failed"?l?{label:"Retrying",variant:"warning",detail:`This did not go out yet. We have used ${a} of ${ts} tries and keep retrying automatically.`}:{label:"Retries paused",variant:"warning",detail:`This did not go out (${a} of ${ts} 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"?a<ts&&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."}:a<ts&&e==="buyer"&&!r?{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 ${a} attempt${a===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 fr({title:e,recipient:t,status:a,attempts:s,side:r,orderStatus:l,action:d}){let g=Ns(r,a,s,l,t);return(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,o.jsxs)("div",{className:"af-min-w-0",children:[(0,o.jsx)("div",{className:"af-text-sm",children:e}),t&&(0,o.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-break-all",children:t})]}),(0,o.jsx)(W,{variant:g.variant,className:"af-shrink-0",children:g.label})]}),g.detail&&(0,o.jsx)("p",{className:"af-text-xs af-text-muted-foreground af-mt-1",children:g.detail}),d&&(0,o.jsx)("div",{className:"af-mt-2",children:d})]})}function dr(e){let t=[];typeof e.name=="string"&&e.name&&t.push(e.name);let a=ln(e.address)?e.address:null;if(a){for(let r of["line1","line2"]){let l=a[r];typeof l=="string"&&l&&t.push(l)}let s=["city","state","postal_code"].map(r=>a[r]).filter(r=>typeof r=="string"&&!!r).join(", ");s&&t.push(s),typeof a.country=="string"&&a.country&&t.push(a.country)}return t.length>0?t:Object.entries(e).map(([s,r])=>`${s}: ${ur(r)}`)}function un(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function ws({value:e,label:t,children:a,className:s,size:r="icon"}){let[l,d]=Be.useState(!1);if(!un())return null;let g=async()=>{try{await navigator.clipboard.writeText(e),d(!0),setTimeout(()=>d(!1),1500)}catch{}},u=l?(0,o.jsx)(fe.Check,{className:"af-h-3 af-w-3"}):(0,o.jsx)(fe.Copy,{className:"af-h-3 af-w-3"});return r==="icon"?(0,o.jsx)(x,{variant:"ghost",size:"icon",className:I("af-h-6 af-w-6 af-shrink-0",s),onClick:g,title:t,"aria-label":t,children:u}):(0,o.jsxs)(x,{variant:"outline",size:"sm",className:s,onClick:g,"aria-label":t,children:[l?(0,o.jsx)(fe.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,o.jsx)(fe.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),l?"Copied":a]})}function hs({label:e,value:t}){return(0,o.jsxs)("div",{children:[(0,o.jsx)("div",{className:da,children:e}),(0,o.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,o.jsx)("code",{className:"af-text-xs af-font-mono af-break-all",children:t}),(0,o.jsx)(ws,{value:t,label:`Copy ${e}`})]})]})}function mn({src:e}){let[t,a]=Be.useState(!1);return!e||t?(0,o.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,o.jsx)(fe.Package,{className:"af-h-4 af-w-4 af-text-muted-foreground"})}):(0,o.jsx)("img",{src:e,alt:"","aria-hidden":"true",onError:()=>a(!0),className:"af-h-10 af-w-10 af-shrink-0 af-rounded-md af-border af-object-cover"})}function ra({title:e,action:t,children:a,className:s}){return(0,o.jsxs)("section",{className:I("af-rounded-lg af-border af-p-4",s),children:[(0,o.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-2",children:[(0,o.jsx)("h4",{className:cr,children:e}),t]}),(0,o.jsx)("div",{className:"af-mt-3",children:a})]})}function na({label:e,emphasis:t,children:a}){return(0,o.jsxs)("div",{className:I("af-flex af-items-baseline af-justify-between af-gap-6",t&&"af-mt-2 af-border-t af-pt-2"),children:[(0,o.jsx)("span",{className:t?"af-text-base af-font-semibold":da,children:e}),(0,o.jsx)("span",{className:I("af-text-right af-tabular-nums",t?"af-text-base af-font-semibold":"af-text-sm"),children:a})]})}function xs({onSelect:e,disabled:t,icon:a,children:s}){return(0,o.jsxs)(x,{variant:"ghost",size:"sm",className:"af-w-full af-justify-start af-font-normal",onClick:e,disabled:t,children:[(0,o.jsx)("span",{className:"af-mr-2 af-flex af-h-4 af-w-4 af-items-center af-justify-center",children:a}),s]})}function pn(e){let t=[];if(t.push({key:"placed",text:"Order placed",at:e.created_at}),e.paid_at&&t.push({key:"paid",text:`Payment received \u2014 ${H(gt(e),e.currency)}`,at:e.paid_at}),e.buyer_email_status!=="none"){let a=Ns("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"?`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 a=Ns("merchant",e.merchant_email_status,e.merchant_email_attempts,e.status,null);t.push({key:"merchant-email",text:e.merchant_email_status==="sent"?"You were notified of this sale":`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 ${H(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 Va({order:e,onBack:t,onRefund:a,onOrderUpdated:s,allowFulfillment:r=!1,onPrevOrder:l,onNextOrder:d,hasPrevOrder:g=!1,hasNextOrder:u=!1}){let{api:m}=ae(),[n,b]=Be.useState(e),[N,P]=Be.useState(null),[h,y]=Be.useState(null),[w,T]=Be.useState(!1),[O,F]=Be.useState(!1),[Y,B]=Be.useState(!1),[V,M]=Be.useState(!1),[Q,$]=Be.useState(""),[A,ve]=Be.useState(!1),[p,se]=Be.useState(null),[we,xe]=Be.useState(!1),[ce,Ae]=Be.useState(""),[X,ue]=Be.useState([]),[Pe,je]=Be.useState(!1),[Ve,Pt]=Be.useState(!1),[St,_e]=Be.useState(null);Be.useEffect(()=>{b(e)},[e]);let ft=S=>{b(S),s?.(S)},dt=Object.entries(n.metadata??{}),De=gt(n)-n.amount_refunded,Rt=(n.status==="paid"||n.status==="partially_refunded")&&De>0,v=S=>(typeof S.unitAmount=="number"?S.unitAmount:0)*(typeof S.quantity=="number"&&S.quantity>0?S.quantity:1),_=Math.max(0,(n.shipping_total??0)-(n.shipping_refunded??0)),ie=X.reduce((S,be)=>S+v(n.line_items[be]??{}),0)+(Pe?_:0),Ge=n.tax_total??0,We=n.automatic_tax&&n.tax_behavior==="exclusive"&&Ge>0&&n.amount_total+(n.shipping_total??0)>0?Math.min(Math.max(0,Ge-(n.tax_refunded??0)),Math.round(Ge*ie/(n.amount_total+(n.shipping_total??0)))):0,Ke=ie+We,qe=X.length>0||Pe,Ct=qe?Ke:vt(ce,n.currency),va=xt(n.currency)?"1":"0.01",ba=async()=>{try{T(!0),P(null),y(null),await m.resendOrderReceipt(n.id);let S=await m.getOrder(n.id);ft(S),y("Receipt email queued.")}catch(S){P(S instanceof Error?S.message:"Failed to resend receipt")}finally{T(!1)}},z=async()=>{try{F(!0),P(null),y(null);let S=await m.resetOrderDownloads(n.id);ft(S),B(!1),y("Download count reset.")}catch(S){P(S instanceof Error?S.message:"Failed to reset downloads")}finally{F(!1)}},ye=!!n.shipping_address,Se=typeof n.merchant_fulfilled_at=="string",Jt=dn.includes(n.status),Tt=Q.trim(),ya=cn.test(Tt)&&Tt.length<=lr,ct=async S=>{try{ve(!0),se(null),y(null);let be=await m.setOrderFulfillment(n.id,{fulfilled:S,...S&&Tt?{trackingNumber:Tt}:{}});ft(be),$(""),y(S?"Marked as shipped.":"Marked as not shipped.")}catch(be){be instanceof Ft&&be.status===409?se(`This order is ${n.status.replace(/_/g," ")}, so it can't be marked here. Refresh to see its current state.`):se(be instanceof Error?be.message:"Failed to update the order")}finally{ve(!1)}},Oe=()=>{_e(null),Ae(String(Me(De,n.currency))),ue([]),je(!1),xe(!0)},He=S=>ue(be=>be.includes(S)?be.filter(Xe=>Xe!==S):[...be,S]),Pa=async(S,be)=>{if(a)try{Pt(!0),_e(null),await a(n,S,be);let Xe=await m.getOrder(n.id);ft(Xe),xe(!1),y("Refund issued.")}catch(Xe){_e(Xe instanceof Error?Xe.message:"Refund failed")}finally{Pt(!1)}},L=async()=>{if(qe){if(Ke<=0){_e("The lines you picked were charged nothing");return}if(Ke>De){_e(`That selection exceeds the refundable remainder (${H(De,n.currency)})`);return}await Pa(Ke,{...X.length>0?{line_items:[...X].sort((be,Xe)=>be-Xe)}:{},...Pe?{shipping:!0}:{}});return}let S=vt(ce,n.currency);if(S===null||S<=0){_e("Enter a valid refund amount");return}if(S>De){_e(`Amount exceeds the refundable remainder (${H(De,n.currency)})`);return}await Pa(S,{amount:S})},Ye=()=>Pa(De,{full:!0}),Os=n.fulfillment_type==="download",Ls=r&&ye,Or=pn(n),Lr=n.shipping_address?dr(n.shipping_address).join(`
4
+ `):"",Bs=n.shipping_total!=null,Es=!!n.automatic_tax&&n.tax_behavior==="exclusive"&&(n.tax_total??0)>0,Br=!(n.automatic_tax&&n.tax_behavior==="exclusive")&&(n.tax_total??0)>0,Er=Bs||Es,Sa=[];return Sa.push((0,o.jsx)(xs,{icon:w?(0,o.jsx)(fe.Loader2,{className:"af-h-4 af-w-4 af-animate-spin"}):(0,o.jsx)(fe.Mail,{className:"af-h-4 af-w-4"}),disabled:w||n.fulfillment_status!=="fulfilled",onSelect:()=>{M(!1),ba()},children:"Resend receipt"},"resend")),Os&&Sa.push((0,o.jsx)(xs,{icon:(0,o.jsx)(fe.RotateCcw,{className:"af-h-4 af-w-4"}),disabled:O,onSelect:()=>{M(!1),B(!0)},children:"Reset download count"},"reset")),Rt&&Sa.push((0,o.jsxs)("div",{children:[(0,o.jsx)(xs,{icon:(0,o.jsx)(fe.Undo2,{className:"af-h-4 af-w-4"}),disabled:!a,onSelect:()=>{M(!1),Oe()},children:"Refund\u2026"}),!a&&(0,o.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,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:"af-mb-6",children:[(0,o.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,o.jsx)(fe.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Orders"]}),(0,o.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,o.jsxs)("div",{className:"af-min-w-0",children:[(0,o.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,o.jsx)("h3",{className:"af-text-xl af-font-semibold",children:Wt(n)}),(0,o.jsx)(fa,{status:n.status}),r&&(0,o.jsx)(xa,{order:n}),n.is_test&&(0,o.jsx)(W,{variant:"outline",children:"Test"})]}),(0,o.jsxs)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:["Placed ",ys(n.created_at)]}),n.is_test&&(0,o.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,o.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(l||d)&&(0,o.jsxs)("div",{className:"af-flex af-items-center",children:[(0,o.jsx)(x,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-r-none",onClick:l,disabled:!g,"aria-label":"Previous order",children:(0,o.jsx)(fe.ChevronLeft,{className:"af-h-4 af-w-4"})}),(0,o.jsx)(x,{variant:"outline",size:"icon",className:"af-h-9 af-w-9 af-rounded-l-none af--ml-px",onClick:d,disabled:!u,"aria-label":"Next order",children:(0,o.jsx)(fe.ChevronRight,{className:"af-h-4 af-w-4"})})]}),Ls&&(Se?(0,o.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,o.jsxs)("span",{className:"af-text-sm af-text-muted-foreground",children:["Shipped \u2713",n.merchant_fulfilled_at?` \xB7 ${ys(n.merchant_fulfilled_at)}`:""]}),Jt&&(0,o.jsxs)(x,{variant:"ghost",size:"sm",onClick:()=>ct(!1),disabled:A,children:[A?(0,o.jsx)(fe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,o.jsx)(fe.Undo2,{className:"af-h-4 af-w-4 af-mr-1"}),"Undo"]})]}):Jt?(0,o.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,o.jsx)(le,{value:Q,onChange:S=>$(S.target.value),placeholder:"Tracking number (optional)",maxLength:lr,className:"af-w-[200px]","aria-label":"Tracking number (optional)",disabled:A}),(0,o.jsxs)(x,{variant:"default",onClick:()=>ct(!0),disabled:A||!ya,children:[A?(0,o.jsx)(fe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,o.jsx)(fe.Truck,{className:"af-h-4 af-w-4 af-mr-1"}),"Mark as shipped"]})]}):null),Sa.length>0&&(0,o.jsxs)(nr,{open:V,onOpenChange:M,children:[(0,o.jsx)(ir,{asChild:!0,children:(0,o.jsx)(x,{variant:"outline",size:"icon","aria-label":"More actions",children:(0,o.jsx)(fe.MoreHorizontal,{className:"af-h-4 af-w-4"})})}),(0,o.jsx)(bs,{children:(0,o.jsx)("div",{className:"af-space-y-0.5",children:Sa})})]})]})]}),Ls&&!Se&&!ya&&(0,o.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,o.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}),h&&(0,o.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:h}),N&&(0,o.jsx)("div",{className:"af-mt-2 af-rounded af-bg-destructive/10 af-px-3 af-py-2 af-text-sm af-text-destructive",children:N})]}),(0,o.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[1fr_320px]",children:[(0,o.jsxs)("div",{className:"af-space-y-6",children:[n.line_items.length>0&&(0,o.jsx)(ra,{title:"Items",children:(0,o.jsx)("ul",{className:"af-space-y-3",children:n.line_items.map((S,be)=>{let Xe=typeof S.name=="string"&&S.name?S.name:"Item",Ds=typeof S.quantity=="number"&&S.quantity>0?S.quantity:1,Is=typeof S.unitAmount=="number";return(0,o.jsxs)("li",{className:"af-flex af-items-start af-gap-3",children:[(0,o.jsx)(mn,{src:typeof S.imageUrl=="string"&&S.imageUrl?S.imageUrl:void 0}),(0,o.jsxs)("div",{className:"af-min-w-0 af-flex-1",children:[(0,o.jsxs)("div",{className:"af-text-sm af-font-medium",children:[Xe,typeof S.variantTitle=="string"&&S.variantTitle&&(0,o.jsxs)("span",{className:"af-font-normal af-text-muted-foreground",children:[" \u2014 ",S.variantTitle]})]}),(0,o.jsxs)("div",{className:da,children:[Ds," \xD7"," ",Is?H(S.unitAmount,n.currency):"\u2014"]}),S.refunded===!0&&(0,o.jsx)(W,{variant:"secondary",className:"af-mt-1",children:S.refundReason==="oversold"?"Sold out \u2014 refunded":"Refunded"})]}),(0,o.jsx)("div",{className:"af-shrink-0 af-text-sm af-tabular-nums",children:Is?H(S.unitAmount*Ds,n.currency):"\u2014"})]},be)})})}),dt.length>0&&(0,o.jsx)(ra,{title:"Order details",children:(0,o.jsx)("dl",{className:"af-space-y-2",children:dt.map(([S,be])=>(0,o.jsxs)("div",{children:[(0,o.jsx)("dt",{className:I(da,"af-capitalize"),children:S.replace(/_/g," ")}),(0,o.jsx)("dd",{className:"af-text-sm af-break-words",children:ur(be)})]},S))})}),(0,o.jsx)(ra,{title:"Payment",children:(0,o.jsxs)("div",{className:"af-ml-auto af-w-full sm:af-max-w-xs",children:[Er&&(0,o.jsx)(na,{label:"Subtotal",children:H(n.amount_total,n.currency)}),Bs&&(0,o.jsx)(na,{label:"Shipping",children:n.shipping_total===0?"Free":H(n.shipping_total??0,n.currency)}),Es&&(0,o.jsx)(na,{label:"Tax",children:H(n.tax_total??0,n.currency)}),(0,o.jsx)(na,{label:"Total",emphasis:!0,children:H(gt(n),n.currency)}),Br&&(0,o.jsx)(na,{label:"incl. tax",children:H(n.tax_total??0,n.currency)}),n.base_currency!=null&&n.base_amount_total!=null&&(0,o.jsxs)(na,{label:"Your price",children:[H(n.base_amount_total,n.base_currency),(0,o.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["buyer paid in ",n.currency.toUpperCase()]})]}),n.amount_refunded>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(na,{label:"Refunded",children:["\u2212",H(n.amount_refunded,n.currency),(n.shipping_refunded??0)>0&&(0,o.jsxs)("span",{className:"af-block af-text-xs af-text-muted-foreground",children:["incl."," ",H(n.shipping_refunded??0,n.currency)," ","shipping"]})]}),(0,o.jsx)(na,{label:"Net",children:(0,o.jsx)("span",{className:"af-font-medium",children:H(Math.max(0,gt(n)-n.amount_refunded),n.currency)})})]})]})}),(0,o.jsx)(ra,{title:"Timeline",children:(0,o.jsx)("ol",{className:"af-space-y-3",children:Or.map(S=>(0,o.jsxs)("li",{className:"af-flex af-gap-3",children:[(0,o.jsx)("span",{"aria-hidden":"true",className:I("af-mt-1.5 af-h-2 af-w-2 af-shrink-0 af-rounded-full",S.tone==="destructive"?"af-bg-destructive":S.tone==="warning"?"af-bg-yellow-500":"af-bg-muted-foreground/40")}),(0,o.jsxs)("div",{className:"af-min-w-0",children:[(0,o.jsx)("div",{className:"af-text-sm af-break-words",children:S.text}),S.at&&(0,o.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:ys(S.at)})]})]},S.key))})})]}),(0,o.jsxs)("div",{className:"af-space-y-6",children:[(0,o.jsx)(ra,{title:"Customer",children:(0,o.jsxs)("div",{className:"af-space-y-2",children:[(0,o.jsxs)("div",{children:[(0,o.jsx)("div",{className:da,children:"Email"}),(0,o.jsxs)("div",{className:"af-flex af-items-center af-gap-1",children:[(0,o.jsx)("span",{className:"af-min-w-0 af-break-all af-text-sm",children:n.customer_email||(0,o.jsx)("span",{className:"af-italic af-text-muted-foreground",children:"Unknown"})}),n.customer_email&&(0,o.jsx)(ws,{value:n.customer_email,label:"Copy email"})]})]}),n.customer_name&&(0,o.jsxs)("div",{children:[(0,o.jsx)("div",{className:da,children:"Name"}),(0,o.jsx)("div",{className:"af-text-sm",children:n.customer_name})]}),n.customer&&(0,o.jsxs)("div",{children:[(0,o.jsx)("div",{className:da,children:"Customer record"}),(0,o.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,o.jsx)("span",{className:"af-break-all af-text-sm",children:n.customer.name||n.customer.email}),(0,o.jsx)(W,{variant:"secondary",children:"Linked"})]})]})]})}),n.shipping_address&&(0,o.jsx)(ra,{title:"Ship to",action:(0,o.jsx)(ws,{value:Lr,label:"Copy address",size:"sm",children:"Copy address"}),children:(0,o.jsx)("address",{className:"af-space-y-0.5 af-text-sm af-not-italic",children:dr(n.shipping_address).map((S,be)=>(0,o.jsx)("div",{children:S},be))})}),(0,o.jsx)(ra,{title:"Emails",children:(0,o.jsxs)("div",{className:"af-space-y-4",children:[(0,o.jsx)(fr,{side:"buyer",title:"Receipt to buyer",recipient:n.customer_email,status:n.buyer_email_status,attempts:n.buyer_email_attempts,orderStatus:n.status,action:(0,o.jsxs)(x,{variant:"outline",size:"sm",onClick:ba,disabled:w||n.fulfillment_status!=="fulfilled",children:[w?(0,o.jsx)(fe.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,o.jsx)(fe.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Resend"]})}),(0,o.jsx)(fr,{side:"merchant",title:"Sale alert to you",recipient:null,status:n.merchant_email_status,attempts:n.merchant_email_attempts,orderStatus:n.status})]})}),Os&&(0,o.jsx)(ra,{title:"Download",children:(0,o.jsxs)("div",{className:"af-space-y-2",children:[(0,o.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,o.jsx)(fe.Download,{className:"af-h-4 af-w-4"}),(0,o.jsxs)("span",{children:["Downloaded ",n.download_count," time",n.download_count===1?"":"s"]})]}),n.download_url&&(0,o.jsx)("a",{href:n.download_url,target:"_blank",rel:"noreferrer",className:"af-inline-block af-text-sm af-underline af-underline-offset-2",children:"Buyer download link"})]})}),(0,o.jsxs)("details",{className:"af-rounded-lg af-border af-p-4",children:[(0,o.jsx)("summary",{className:I(cr,"af-cursor-pointer af-select-none"),children:"Technical details"}),(0,o.jsxs)("div",{className:"af-mt-3 af-space-y-2",children:[(0,o.jsx)(hs,{label:"Order ID",value:n.id}),n.stripe_checkout_session_id&&(0,o.jsx)(hs,{label:"Checkout session",value:n.stripe_checkout_session_id}),n.stripe_payment_intent_id&&(0,o.jsx)(hs,{label:"Payment",value:n.stripe_payment_intent_id})]})]})]})]}),(0,o.jsx)(aa,{open:Y,onOpenChange:S=>{!S&&!O&&B(!1)},children:(0,o.jsxs)(Mt,{children:[(0,o.jsxs)($t,{children:[(0,o.jsx)(jt,{children:"Reset download count?"}),(0,o.jsx)(qt,{children:"The buyer's download link stops working after it reaches the download limit. Resetting the count lets them download again."})]}),(0,o.jsxs)(zt,{children:[(0,o.jsx)(x,{variant:"outline",onClick:()=>B(!1),disabled:O,children:"Cancel"}),(0,o.jsx)(x,{onClick:z,disabled:O,children:O?"Resetting...":"Reset"})]})]})}),(0,o.jsx)(aa,{open:we,onOpenChange:S=>{!S&&!Ve&&xe(!1)},children:(0,o.jsxs)(Mt,{children:[(0,o.jsxs)($t,{children:[(0,o.jsx)(jt,{children:"Refund order"}),(0,o.jsxs)(qt,{children:["Refund up to ",H(De,n.currency)," to the buyer's original payment method. Stripe's processing fee is not returned."]})]}),(0,o.jsxs)("div",{className:"af-space-y-4",children:[(n.line_items.length>0||_>0)&&(0,o.jsxs)("div",{className:"af-space-y-2",children:[(0,o.jsx)(ne,{children:"Items"}),(0,o.jsxs)("div",{className:"af-space-y-2",children:[n.line_items.map((S,be)=>{let Xe=S.refunded===!0;return(0,o.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,o.jsx)("input",{type:"checkbox",checked:X.includes(be),onChange:()=>He(be),disabled:Ve||Xe,className:"af-h-4 af-w-4"}),(0,o.jsxs)("span",{className:Xe?"af-text-muted-foreground af-line-through":void 0,children:[typeof S.name=="string"&&S.name?S.name:"Item",typeof S.variantTitle=="string"&&S.variantTitle?` \u2014 ${S.variantTitle}`:"",typeof S.quantity=="number"&&S.quantity>1?` \xD7 ${S.quantity}`:""]}),(0,o.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:Xe?"Refunded":H(v(S),n.currency)})]},be)}),_>0&&(0,o.jsxs)("label",{className:"af-flex af-items-center af-gap-2 af-text-sm",children:[(0,o.jsx)("input",{type:"checkbox",checked:Pe,onChange:S=>je(S.target.checked),disabled:Ve,className:"af-h-4 af-w-4"}),(0,o.jsx)("span",{children:"Shipping"}),(0,o.jsx)("span",{className:"af-ml-auto af-text-muted-foreground",children:H(_,n.currency)})]})]})]}),(0,o.jsxs)("div",{className:"af-space-y-2",children:[(0,o.jsxs)(ne,{htmlFor:"refund-amount",children:["Amount (",n.currency.toUpperCase(),")"]}),(0,o.jsx)(le,{id:"refund-amount",type:"number",min:"0",step:va,value:qe?String(Me(Ke,n.currency)):ce,onChange:S=>Ae(S.target.value),disabled:Ve||qe}),qe&&(0,o.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Priced from the order. Clear the ticks above to refund a different amount."})]})]}),St&&(0,o.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:St}),(0,o.jsxs)(zt,{children:[(0,o.jsx)(x,{variant:"outline",onClick:()=>xe(!1),disabled:Ve,children:"Cancel"}),(0,o.jsx)(x,{variant:"outline",onClick:Ye,disabled:Ve,children:"Refund everything"}),(0,o.jsx)(x,{variant:"destructive",onClick:L,disabled:Ve,children:Ve?"Refunding...":Ct!==null&&Ct>0?`Refund ${H(Ct,n.currency)}`:"Refund"})]})]})})]})}var as=te(require("react"),1),ss=require("lucide-react");var Ue=require("react/jsx-runtime");function Kt({title:e,onBackToWebsite:t,hideBackButton:a=!1,children:s,className:r}){let l=as.useRef(null);return as.useEffect(()=>{l.current?.focus()},[]),(0,Ue.jsxs)("div",{className:I("af-bg-background",r),children:[(0,Ue.jsxs)("div",{className:"af-sticky af-top-0 af-z-10 lg:af-static af-flex af-items-center af-justify-between af-gap-2 af-border-b af-bg-background af-px-4 af-py-2",children:[(0,Ue.jsx)("h2",{ref:l,tabIndex:-1,"aria-live":"polite",className:"af-text-lg af-font-semibold focus:af-outline-none",children:e}),t&&!a&&(0,Ue.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:t,children:[(0,Ue.jsx)(ss.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to website"]})]}),(0,Ue.jsx)("div",{className:"af-p-4",children:s})]})}function K({className:e}){return(0,Ue.jsx)("div",{"aria-hidden":"true",className:I("af-h-4 af-w-16 af-animate-pulse af-rounded af-bg-muted",e)})}function Je({label:e,children:t,detail:a,valueClassName:s}){return(0,Ue.jsxs)("div",{className:"af-rounded-md af-border af-px-3 af-py-2",children:[(0,Ue.jsx)("div",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,Ue.jsx)("div",{className:I("af-mt-1 af-text-lg af-font-semibold",s),children:t}),a&&(0,Ue.jsx)("div",{className:"af-mt-0.5 af-text-xs af-text-muted-foreground",children:a})]})}function Nt({message:e,onRetry:t}){return(0,Ue.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,Ue.jsx)("span",{children:e}),(0,Ue.jsxs)(x,{type:"button",variant:"ghost",size:"sm",onClick:t,children:[(0,Ue.jsx)(ss.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Try again"]})]})}function ca({icon:e,children:t}){return(0,Ue.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[e,(0,Ue.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:t})]})}var f=require("react/jsx-runtime"),gn={needs_shipping:"Needs shipping",all:"All",paid:"Paid",refunds:"Refunds & disputes"},mr={needs_shipping:{unfulfilledOnly:!0},all:{unfulfilledOnly:!1},paid:{statusIn:["paid","partially_refunded"],unfulfilledOnly:!1},refunds:{statusIn:["refunded","partially_refunded","disputed"],unfulfilledOnly:!1}};function pr(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 gr(e){let t=Array.isArray(e.line_items)?e.line_items:[],a=t[0];if(!a)return"\u2014";let s=typeof a.name=="string"&&a.name?a.name:"Item",r=typeof a.quantity=="number"&&a.quantity>0?a.quantity:1,l=r>1?`${s} \xD7${r}`:s;return t.length>1?`${l} +${t.length-1} more`:l}function rs(e){return e.customer?.name||e.customer_name||null}function ua({onRefund:e,className:t,refreshKey:a,initialOrderId:s,showFulfillment:r=!1,emptyMessage:l,onDetailOpenChange:d}){let{api:g}=ae(),u=Fa({refreshKey:a}),{orders:m,total:n,isLoading:b,error:N,page:P,pageSize:h,hasNextPage:y,hasPreviousPage:w,setPage:T,setPageSize:O,customerEmail:F,setCustomerEmail:Y,setStatusIn:B,from:V,setFrom:M,to:Q,setTo:$,showAbandoned:A,setShowAbandoned:ve,setUnfulfilledOnly:p,refetch:se}=u,[we,xe]=$e.useState("list"),[ce,Ae]=$e.useState(null),[X,ue]=$e.useState(""),[Pe,je]=$e.useState(""),[Ve,Pt]=$e.useState(r?"needs_shipping":"all"),[St,_e]=$e.useState(!1),[ft,dt]=$e.useState(!!s),[De,Rt]=$e.useState(null);$e.useEffect(()=>{if(!s)return;let L=!1;return dt(!0),Rt(null),g.getOrder(s).then(Ye=>{L||(Ae(Ye),xe("detail"))}).catch(()=>{L||Rt("Couldn't open that order \u2014 showing all orders.")}).finally(()=>{L||dt(!1)}),()=>{L=!0}},[g,s]);let v=$e.useCallback(L=>{Pt(L);let Ye=mr[L];B(Ye.statusIn),p(Ye.unfulfilledOnly)},[B,p]);$e.useEffect(()=>{r&&p(!0)},[]);let _=$e.useRef(!r);$e.useEffect(()=>{_.current||b||(_.current=!0,m.length===0&&v("all"))},[b,m.length,v]);let ie=we==="detail"&&!!ce;$e.useEffect(()=>{d?.(ie)},[ie,d]);let Ge=(V?1:0)+(Q?1:0)+(A?1:0),We=Ge>0||!!F||!!Pe,Ke=!!V&&!!Q&&V>Q,qe=L=>{Ae(L),xe("detail")},Ct=()=>{xe("list"),Ae(null),se()},va=L=>{let Ye=L.trim();if(!Ye){je(""),F&&Y("");return}if(Ye.startsWith("#")||/^\d+$/.test(Ye)){je(Ye),F&&Y("");return}je(""),Y(Ye)},ba=()=>{ue(""),je(""),Y(""),M(""),$(""),ve(!1),_e(!1)},z=Pe.replace(/^#/,"").toLowerCase(),ye=z?m.filter(L=>String(L.order_number??"")===z||L.id.toLowerCase().startsWith(z)):m,Se=ce?m.findIndex(L=>L.id===ce.id):-1,Jt=Se>0,Tt=Se>=0&&Se<m.length-1;if(ft)return(0,f.jsx)("div",{className:t,children:(0,f.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,f.jsx)(it.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})})});if(we==="detail"&&ce)return(0,f.jsx)("div",{className:t,children:(0,f.jsx)(Va,{order:ce,onBack:Ct,onRefund:e,onOrderUpdated:L=>Ae(L),allowFulfillment:r,onPrevOrder:Jt?()=>Ae(m[Se-1]):void 0,onNextOrder:Tt?()=>Ae(m[Se+1]):void 0,hasPrevOrder:Jt,hasNextOrder:Tt},ce.id)});let ct=(0,f.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[De&&(0,f.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:De}),(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,f.jsx)("div",{role:"group","aria-label":"Order views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:(r?["needs_shipping","all","paid","refunds"]:["all","paid","refunds"]).map(L=>(0,f.jsx)("button",{type:"button","aria-pressed":Ve===L,onClick:()=>v(L),className:I("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",Ve===L?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:gn[L]},L))}),(0,f.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,f.jsx)(it.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,f.jsx)(le,{type:"text",value:X,onChange:L=>ue(L.target.value),onBlur:()=>va(X),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),va(X))},placeholder:"Search email, name, or order #","aria-label":"Search orders by email, name, or order number",className:"af-pl-8"})]}),(0,f.jsxs)(x,{type:"button",variant:Ge>0?"secondary":"ghost",size:"sm",onClick:()=>_e(L=>!L),"aria-expanded":St,children:[(0,f.jsx)(it.SlidersHorizontal,{className:"af-h-4 af-w-4 af-mr-1"}),"Filters",Ge>0&&(0,f.jsx)(W,{variant:"secondary",className:"af-ml-2",children:Ge})]}),We&&(0,f.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:ba,children:"Clear filters"})]}),(St||!!V||!!Q)&&(0,f.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,f.jsx)(ne,{htmlFor:"orders-from",className:"af-text-xs af-text-muted-foreground",children:"From"}),(0,f.jsx)(le,{id:"orders-from",type:"date",value:V,max:Q||void 0,onChange:L=>M(L.target.value),className:"af-w-[170px]"}),(0,f.jsx)(ne,{htmlFor:"orders-to",className:"af-text-xs af-text-muted-foreground",children:"To"}),(0,f.jsx)(le,{id:"orders-to",type:"date",value:Q,min:V||void 0,onChange:L=>$(L.target.value),className:"af-w-[170px]"}),!mr[Ve].statusIn&&(0,f.jsx)(x,{type:"button",variant:A?"secondary":"ghost",size:"sm",onClick:()=>ve(!A),"aria-pressed":A,children:A?"Hide abandoned":"Show abandoned"})]}),Ke&&(0,f.jsx)("p",{className:"af-text-xs af-text-destructive",children:"The end date is before the start date, so nothing can match."})]});if(b)return(0,f.jsxs)("div",{className:t,children:[ct,(0,f.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(L=>(0,f.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,f.jsxs)("div",{className:"af-flex af-items-center af-justify-between",children:[(0,f.jsx)(K,{className:"af-h-4 af-w-16"}),(0,f.jsx)(K,{className:"af-h-4 af-w-14"})]}),(0,f.jsx)(K,{className:"af-mt-2 af-h-3 af-w-40"}),(0,f.jsx)(K,{className:"af-mt-2 af-h-3 af-w-24"})]},L))}),(0,f.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,f.jsxs)(Re,{children:[(0,f.jsx)(Ce,{children:(0,f.jsxs)(oe,{children:[(0,f.jsx)(E,{children:"Order"}),(0,f.jsx)(E,{children:"Date"}),(0,f.jsx)(E,{children:"Customer"}),(0,f.jsx)(E,{children:"Items"}),(0,f.jsx)(E,{className:"af-text-right",children:"Total"}),(0,f.jsx)(E,{children:"Status"}),(0,f.jsx)(E,{className:"af-w-8"})]})}),(0,f.jsx)(Te,{"aria-hidden":"true",children:[0,1,2,3,4].map(L=>(0,f.jsxs)(oe,{children:[(0,f.jsx)(D,{children:(0,f.jsx)(K,{className:"af-h-4 af-w-14"})}),(0,f.jsx)(D,{children:(0,f.jsx)(K,{className:"af-h-4 af-w-24"})}),(0,f.jsx)(D,{children:(0,f.jsx)(K,{className:"af-h-4 af-w-40"})}),(0,f.jsx)(D,{children:(0,f.jsx)(K,{className:"af-h-4 af-w-32"})}),(0,f.jsx)(D,{children:(0,f.jsx)(K,{className:"af-ml-auto af-h-4 af-w-16"})}),(0,f.jsx)(D,{children:(0,f.jsx)(K,{className:"af-h-5 af-w-16"})}),(0,f.jsx)(D,{})]},L))})]})}),(0,f.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading orders"})]});if(N)return(0,f.jsxs)("div",{className:t,children:[ct,(0,f.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-gap-2 af-py-8",children:[(0,f.jsx)("div",{className:"af-text-sm af-text-muted-foreground",children:"Couldn't load orders."}),(0,f.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>se(),children:"Try again"})]})]});let Oe=Ve!=="all";if(ye.length===0&&P===0)return(0,f.jsxs)("div",{className:t,children:[(We||Oe)&&ct,(0,f.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,f.jsx)(it.Receipt,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,f.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:We||Oe?"No orders match these filters.":l??(0,f.jsxs)(f.Fragment,{children:["No orders yet.",(0,f.jsx)("br",{}),"Orders will appear here when someone buys from your website."]})}),!We&&!Oe&&(0,f.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:()=>ve(!0),children:"Show abandoned checkouts"})]})]});let He=P*h+1,Pa=Math.min((P+1)*h,n);return(0,f.jsxs)("div",{className:t,children:[ct,(0,f.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:ye.map(L=>(0,f.jsxs)("button",{type:"button",onClick:()=>qe(L),className:"af-block af-w-full af-rounded-md af-border af-p-3 af-text-left hover:af-bg-muted/50",children:[(0,f.jsxs)("div",{className:"af-flex af-items-baseline af-justify-between af-gap-2",children:[(0,f.jsx)("span",{className:"af-font-medium",children:Wt(L)}),(0,f.jsx)("span",{className:"af-shrink-0 af-font-medium af-tabular-nums",children:H(gt(L),L.currency)})]}),(0,f.jsxs)("div",{className:"af-mt-1 af-min-w-0",children:[(0,f.jsxs)("div",{className:"af-truncate af-text-sm",children:[L.customer_email||(0,f.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"}),rs(L)&&(0,f.jsxs)("span",{className:"af-text-muted-foreground",children:[" \xB7 ",rs(L)]})]}),(0,f.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:gr(L)}),L.amount_refunded>0&&(0,f.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(L.amount_refunded,L.currency)," refunded"]})]}),(0,f.jsxs)("div",{className:"af-mt-2 af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,f.jsx)(fa,{status:L.status}),L.is_test&&(0,f.jsx)(W,{variant:"outline",children:"Test"}),r&&(0,f.jsx)(xa,{order:L}),(0,f.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:pr(L.created_at)})]})]},L.id))}),(0,f.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,f.jsxs)(Re,{children:[(0,f.jsx)(Ce,{children:(0,f.jsxs)(oe,{children:[(0,f.jsx)(E,{children:"Order"}),(0,f.jsx)(E,{children:"Date"}),(0,f.jsx)(E,{children:"Customer"}),(0,f.jsx)(E,{children:"Items"}),(0,f.jsx)(E,{className:"af-text-right",children:"Total"}),(0,f.jsx)(E,{children:"Status"}),(0,f.jsx)(E,{className:"af-w-8"})]})}),(0,f.jsx)(Te,{children:ye.map(L=>(0,f.jsxs)(oe,{onClick:()=>qe(L),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,f.jsxs)(D,{className:"af-whitespace-nowrap af-font-medium",children:[(0,f.jsx)("button",{type:"button",onClick:Ye=>{Ye.stopPropagation(),qe(L)},"aria-label":`Open order ${Wt(L)}`,className:"af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:Wt(L)}),L.is_test&&(0,f.jsx)(W,{variant:"outline",className:"af-ml-2",children:"Test"})]}),(0,f.jsx)(D,{className:"af-whitespace-nowrap af-text-muted-foreground",children:pr(L.created_at)}),(0,f.jsxs)(D,{className:"af-max-w-[220px]",children:[(0,f.jsx)("div",{className:"af-truncate",children:L.customer_email||(0,f.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"No email"})}),rs(L)&&(0,f.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:rs(L)})]}),(0,f.jsx)(D,{className:"af-max-w-[220px]",children:(0,f.jsx)("div",{className:"af-truncate af-text-muted-foreground",children:gr(L)})}),(0,f.jsxs)(D,{className:"af-whitespace-nowrap af-text-right",children:[(0,f.jsx)("div",{className:"af-font-medium af-tabular-nums",children:H(gt(L),L.currency)}),L.amount_refunded>0&&(0,f.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:["\u2212",H(L.amount_refunded,L.currency)," ","refunded"]})]}),(0,f.jsx)(D,{children:(0,f.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,f.jsx)(fa,{status:L.status}),r&&(0,f.jsx)(xa,{order:L})]})}),(0,f.jsx)(D,{className:"af-w-8 af-text-right",children:(0,f.jsx)(it.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},L.id))})]})}),(0,f.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,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,f.jsx)("span",{children:z?`${ye.length} matching this page`:`Showing ${He}-${Pa} of ${n}`}),(0,f.jsxs)(ut,{value:String(h),onValueChange:L=>O(Number(L)),children:[(0,f.jsx)(at,{className:"af-w-[70px] af-h-8",children:(0,f.jsx)(mt,{})}),(0,f.jsxs)(st,{children:[(0,f.jsx)(he,{value:"10",children:"10"}),(0,f.jsx)(he,{value:"25",children:"25"}),(0,f.jsx)(he,{value:"50",children:"50"}),(0,f.jsx)(he,{value:"100",children:"100"})]})]}),(0,f.jsx)("span",{children:"per page"})]}),(0,f.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,f.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>T(P-1),disabled:!w,children:[(0,f.jsx)(it.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,f.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>T(P+1),disabled:!y,children:["Next",(0,f.jsx)(it.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var is=te(require("react"),1),Lt=require("lucide-react");var tt=te(require("react"),1);function Ha({initialPageSize:e=25}={}){let{api:t}=ae(),[a,s]=tt.useState([]),[r,l]=tt.useState(0),[d,g]=tt.useState(!0),[u,m]=tt.useState(null),[n,b]=tt.useState(0),[N,P]=tt.useState(e),[h,y]=tt.useState(""),w=tt.useRef(0),T=tt.useCallback(async()=>{let F=++w.current;try{g(!0),m(null);let Y={limit:N,offset:n*N};h.trim()&&(Y.email=h.trim());let B=await t.getCustomers(Y);if(F!==w.current)return;s(B.customers),l(B.total)}catch(Y){if(F!==w.current)return;m(Y instanceof Error?Y:new Error("Failed to fetch customers"))}finally{F===w.current&&g(!1)}},[t,n,N,h]);tt.useEffect(()=>{T()},[T]);let O=Math.ceil(r/N);return{customers:a,total:r,isLoading:d,error:u,page:n,pageSize:N,hasNextPage:n<O-1,hasPreviousPage:n>0,setPage:b,setPageSize:F=>{P(F),b(0)},email:h,setEmail:F=>{y(F),b(0)},refetch:T}}var ma=te(require("react"),1),ns=require("lucide-react");var q=require("react/jsx-runtime");function vr(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 vn(e){let t=[];e.name&&t.push(e.name),t.push(e.line1),e.line2&&t.push(e.line2);let a=[e.city,e.state,e.postal_code].filter(Boolean).join(", ");return a&&t.push(a),e.country&&t.push(e.country),t}function Ma({customer:e,onBack:t,className:a}){let{api:s}=ae(),[r,l]=ma.useState(null),[d,g]=ma.useState([]),[u,m]=ma.useState(!0),[n,b]=ma.useState(null);ma.useEffect(()=>{let h=!1;return m(!0),b(null),Promise.all([s.getCustomer(e.id),s.getOrders({customerEmail:e.email,excludeStatus:["pending","expired"],limit:100})]).then(([y,w])=>{h||(l(y),g(w.orders))}).catch(y=>{h||b(y instanceof Error?y.message:"Failed to load customer")}).finally(()=>{h||m(!1)}),()=>{h=!0}},[s,e.id,e.email]);let N=r?.addresses??[],P=r?.order_count??d.length;return(0,q.jsxs)("div",{className:a,children:[(0,q.jsxs)("div",{className:"af-mb-6",children:[(0,q.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,q.jsx)(ns.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Customers"]}),(0,q.jsx)("h3",{className:"af-text-lg af-font-semibold",children:e.name||e.email}),(0,q.jsxs)("p",{className:"af-text-sm af-text-muted-foreground",children:["Customer since ",vr(e.created_at)]})]}),u?(0,q.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,q.jsx)(ns.Loader2,{className:"af-h-4 af-w-4 af-animate-spin af-text-muted-foreground"})}):n?(0,q.jsx)("div",{className:"af-text-sm af-text-destructive af-bg-destructive/10 af-px-3 af-py-2 af-rounded",children:n}):(0,q.jsxs)("div",{className:"af-space-y-6",children:[(0,q.jsxs)("div",{children:[(0,q.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Contact"}),(0,q.jsxs)("div",{className:"af-space-y-1 af-text-sm",children:[(0,q.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,q.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Email"}),(0,q.jsx)("span",{children:e.email})]}),e.name&&(0,q.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,q.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Name"}),(0,q.jsx)("span",{children:e.name})]}),e.phone&&(0,q.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,q.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Phone"}),(0,q.jsx)("span",{children:e.phone})]}),(0,q.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,q.jsx)("span",{className:"af-text-muted-foreground af-w-32",children:"Orders"}),(0,q.jsx)("span",{children:P})]})]})]}),N.length>0&&(0,q.jsxs)("div",{children:[(0,q.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Addresses"}),(0,q.jsx)("div",{className:"af-flex af-flex-wrap af-gap-3",children:N.map(h=>(0,q.jsxs)("div",{className:"af-text-sm af-bg-muted af-rounded af-p-3 af-space-y-0.5",children:[h.is_default&&(0,q.jsx)(W,{variant:"secondary",className:"af-mb-1",children:"Default"}),vn(h).map((y,w)=>(0,q.jsx)("div",{children:y},w))]},h.id))})]}),(0,q.jsxs)("div",{children:[(0,q.jsx)("h4",{className:"af-text-sm af-font-medium af-mb-3",children:"Orders"}),d.length===0?(0,q.jsx)("p",{className:"af-text-sm af-text-muted-foreground af-italic",children:"No orders."}):(0,q.jsxs)(Re,{children:[(0,q.jsx)(Ce,{children:(0,q.jsxs)(oe,{children:[(0,q.jsx)(E,{children:"Date"}),(0,q.jsx)(E,{children:"Amount"}),(0,q.jsx)(E,{children:"Status"})]})}),(0,q.jsx)(Te,{children:d.map(h=>(0,q.jsxs)(oe,{children:[(0,q.jsx)(D,{className:"af-text-muted-foreground",children:vr(h.created_at)}),(0,q.jsx)(D,{children:H(gt(h),h.currency)}),(0,q.jsx)(D,{children:(0,q.jsx)(sa,{status:h.status})})]},h.id))})]})]})]})]})}var U=require("react/jsx-runtime");function bn(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 $a({className:e}){let{customers:t,total:a,isLoading:s,error:r,page:l,pageSize:d,hasNextPage:g,hasPreviousPage:u,setPage:m,setPageSize:n,email:b,setEmail:N,refetch:P}=Ha(),[h,y]=is.useState("list"),[w,T]=is.useState(null),[O,F]=is.useState(""),Y=$=>{T($),y("detail")},B=()=>{y("list"),T(null),P()};if(h==="detail"&&w)return(0,U.jsx)("div",{className:e,children:(0,U.jsx)(Ma,{customer:w,onBack:B})});let V=(0,U.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-mb-4",children:[(0,U.jsx)(le,{type:"email",value:O,onChange:$=>F($.target.value),placeholder:"Search by email",className:"af-w-[260px]",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),N(O.trim()))}}),(0,U.jsxs)(x,{type:"button",variant:"outline",size:"sm",onClick:()=>N(O.trim()),children:[(0,U.jsx)(Lt.Search,{className:"af-h-4 af-w-4 af-mr-1"}),"Search"]}),b&&(0,U.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>{F(""),N("")},children:"Clear"})]});if(s)return(0,U.jsxs)("div",{className:e,children:[V,(0,U.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,U.jsx)("div",{className:"af-text-muted-foreground",children:"Loading customers..."})})]});if(r)return(0,U.jsxs)("div",{className:e,children:[V,(0,U.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:(0,U.jsxs)("div",{className:"af-text-destructive",children:["Error: ",r.message]})})]});if(t.length===0&&l===0)return(0,U.jsxs)("div",{className:e,children:[b&&V,(0,U.jsxs)("div",{className:"af-flex af-flex-col af-items-center af-justify-center af-py-12",children:[(0,U.jsx)(Lt.Users,{className:"af-h-12 af-w-12 af-text-muted-foreground af-mb-4"}),(0,U.jsx)("p",{className:"af-text-muted-foreground af-text-center",children:b?"No customers match that email.":(0,U.jsxs)(U.Fragment,{children:["No customers yet.",(0,U.jsx)("br",{}),"Customers appear here after their first purchase."]})})]})]});let M=l*d+1,Q=Math.min((l+1)*d,a);return(0,U.jsxs)("div",{className:e,children:[V,(0,U.jsxs)(Re,{children:[(0,U.jsx)(Ce,{children:(0,U.jsxs)(oe,{children:[(0,U.jsx)(E,{children:"Email"}),(0,U.jsx)(E,{children:"Name"}),(0,U.jsx)(E,{children:"Customer since"}),(0,U.jsx)(E,{className:"af-text-right",children:"Actions"})]})}),(0,U.jsx)(Te,{children:t.map($=>(0,U.jsxs)(oe,{children:[(0,U.jsx)(D,{className:"af-font-medium",children:$.email}),(0,U.jsx)(D,{children:$.name||(0,U.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"-"})}),(0,U.jsx)(D,{className:"af-text-muted-foreground",children:bn($.created_at)}),(0,U.jsx)(D,{className:"af-text-right",children:(0,U.jsx)(x,{variant:"ghost",size:"icon",onClick:()=>Y($),title:"View customer",children:(0,U.jsx)(Lt.Eye,{className:"af-h-4 af-w-4"})})})]},$.id))})]}),(0,U.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-px-2 af-py-4",children:[(0,U.jsxs)("div",{className:"af-flex af-items-center af-gap-2 af-text-sm af-text-muted-foreground",children:[(0,U.jsxs)("span",{children:["Showing ",M,"-",Q," of ",a]}),(0,U.jsxs)(ut,{value:String(d),onValueChange:$=>n(Number($)),children:[(0,U.jsx)(at,{className:"af-w-[70px] af-h-8",children:(0,U.jsx)(mt,{})}),(0,U.jsxs)(st,{children:[(0,U.jsx)(he,{value:"10",children:"10"}),(0,U.jsx)(he,{value:"25",children:"25"}),(0,U.jsx)(he,{value:"50",children:"50"}),(0,U.jsx)(he,{value:"100",children:"100"})]})]}),(0,U.jsx)("span",{children:"per page"})]}),(0,U.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,U.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(l-1),disabled:!u,children:[(0,U.jsx)(Lt.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,U.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>m(l+1),disabled:!g,children:["Next",(0,U.jsx)(Lt.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}var br=te(require("react"),1),ot=require("lucide-react");var Bt=te(require("react"),1);function pa(){let{api:e}=ae(),[t,a]=Bt.useState(null),[s,r]=Bt.useState(!0),[l,d]=Bt.useState(null),g=Bt.useRef(0),u=Bt.useCallback(async()=>{let m=++g.current;try{r(!0),d(null);let n=await e.getPaymentsStatus();if(m!==g.current)return;a(n)}catch(n){if(m!==g.current)return;d(n instanceof Error?n:new Error("Failed to fetch payments status"))}finally{m===g.current&&r(!1)}},[e]);return Bt.useEffect(()=>{u()},[u]),{status:t,isLoading:s,error:l,refetch:u}}var Z=require("react/jsx-runtime");function za({onConnectStripe:e,onUpgradePlan:t,className:a}){let{status:s,isLoading:r,error:l,refetch:d}=pa(),[g,u]=br.useState(!1),m=async()=>{u(!0);try{await d()}finally{u(!1)}};return r&&!s?(0,Z.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,Z.jsx)("div",{className:"af-text-muted-foreground",children:"Loading payment status..."})}):l||!s?(0,Z.jsx)("div",{className:`af-flex af-items-center af-justify-center af-py-8 ${a||""}`,children:(0,Z.jsxs)("div",{className:"af-text-destructive",children:["Error: ",l?.message||"Failed to load payment status"]})}):s.status==="active"?(0,Z.jsx)("div",{className:a,children:(0,Z.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,Z.jsx)(ot.CheckCircle2,{className:"af-h-5 af-w-5 af-text-green-600 af-mt-0.5"}),(0,Z.jsxs)("div",{children:[(0,Z.jsx)("p",{className:"af-text-sm af-font-medium af-text-green-800",children:"Payments are active"}),(0,Z.jsxs)("p",{className:"af-text-sm af-text-green-800",children:["Your Stripe account is connected and your site can accept payments in ",s.currency.toUpperCase(),". Payouts go directly to your Stripe account."]})]})]})}):(0,Z.jsxs)("div",{className:`af-space-y-4 ${a||""}`,children:[s.reason==="needs_stripe"&&(0,Z.jsxs)("div",{className:"af-space-y-3",children:[(0,Z.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Z.jsx)(ot.CreditCard,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Z.jsxs)("div",{children:[(0,Z.jsx)("p",{className:"af-text-sm af-font-medium",children:"Set up payments to start selling"}),(0,Z.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,Z.jsxs)(x,{onClick:e,children:[(0,Z.jsx)(ot.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),s.stripe_account_connected?"Finish setting up":"Set up payments"]}):(0,Z.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Set up payments from your site dashboard to start selling."})]}),s.reason==="needs_paid_plan"&&(0,Z.jsxs)("div",{className:"af-space-y-3",children:[(0,Z.jsxs)("div",{className:"af-flex af-items-start af-gap-3 af-bg-muted af-rounded-lg af-p-4",children:[(0,Z.jsx)(ot.AlertTriangle,{className:"af-h-5 af-w-5 af-text-muted-foreground af-mt-0.5"}),(0,Z.jsxs)("div",{children:[(0,Z.jsx)("p",{className:"af-text-sm af-font-medium",children:"Selling requires a paid plan"}),(0,Z.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,Z.jsx)(x,{onClick:t,children:"Upgrade plan"}):(0,Z.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Upgrade your plan from your site dashboard to start selling."})]}),s.reason==="account_disabled"&&(0,Z.jsxs)("div",{className:"af-space-y-3",children:[(0,Z.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,Z.jsx)(ot.AlertTriangle,{className:"af-h-5 af-w-5 af-text-yellow-600 af-mt-0.5"}),(0,Z.jsxs)("div",{children:[(0,Z.jsx)("p",{className:"af-text-sm af-font-medium af-text-yellow-800",children:"Payments are paused"}),s.stripe_account_connected?(0,Z.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,Z.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,Z.jsxs)("div",{className:"af-flex af-gap-2",children:[e&&s.stripe_account_connected&&(0,Z.jsxs)(x,{onClick:e,children:[(0,Z.jsx)(ot.CreditCard,{className:"af-h-4 af-w-4 af-mr-1"}),"Finish setting up"]}),(0,Z.jsxs)(x,{variant:"outline",onClick:m,disabled:g,children:[g?(0,Z.jsx)(ot.Loader2,{className:"af-h-4 af-w-4 af-mr-1 af-animate-spin"}):(0,Z.jsx)(ot.RefreshCw,{className:"af-h-4 af-w-4 af-mr-1"}),"Refresh status"]})]})]})]})}var Ze=te(require("react"),1);function Ps(e,t,a){return e.map(s=>s.id===t?{...s,...a}:s)}function ga({includeStats:e=!1,refreshKey:t}={}){let{api:a}=ae(),[s,r]=Ze.useState([]),[l,d]=Ze.useState(!0),[g,u]=Ze.useState(null),m=Ze.useRef(0),n=Ze.useCallback(async()=>{let w=++m.current;try{d(!0),u(null);let T=await a.getProducts(e?{include:"stats"}:{});if(w!==m.current)return;r(T)}catch(T){if(w!==m.current)return;u(T instanceof Error?T:new Error("Failed to fetch products"))}finally{w===m.current&&d(!1)}},[a,e,t]);Ze.useEffect(()=>{n()},[n]);let b=Ze.useCallback(async w=>{let T=await a.createProduct(w);return r(O=>[T,...O]),T},[a]),N=Ze.useCallback(async(w,T)=>{let O=await a.updateProduct(w,T);return r(F=>Ps(F,w,O)),O},[a]),P=Ze.useCallback(async w=>{await a.deleteProduct(w),r(T=>T.filter(O=>O.id!==w))},[a]),h=Ze.useCallback(async(w,T)=>{let O=await a.attachProductFile(w,T);return r(F=>Ps(F,w,O)),O},[a]),y=Ze.useCallback(async(w,T)=>{let O=await a.attachProductFileFromUrl(w,T);return r(F=>Ps(F,w,O)),O},[a]);return{products:s,isLoading:l,error:g,refetch:n,createProduct:b,updateProduct:N,deleteProduct:P,attachProductFile:h,attachProductFileFromUrl:y}}var de=require("react/jsx-runtime");function Ss({className:e,defaultTab:t="products",onConnectStripe:a,onRefund:s,onUpgradePlan:r}){let[l,d]=os.useState(t),[g,u]=os.useState("list"),[m,n]=os.useState(null),b=ga(),{status:N,error:P}=pa(),h=N?.currency,y=F=>{n(F),u("edit")},w=()=>{n(null),u("create")},T=()=>{u("list"),n(null)},O=F=>{n(F),u("edit")};return(0,de.jsxs)("div",{className:e,children:[(0,de.jsxs)("div",{className:"af-mb-6",children:[(0,de.jsx)("h2",{className:"af-text-lg af-font-semibold",children:"Payments"}),(0,de.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"Manage your products, orders, and payment setup."})]}),(0,de.jsxs)(Za,{value:l,onValueChange:F=>d(F),children:[(0,de.jsxs)(Ra,{className:"af-mb-4",children:[(0,de.jsxs)(Ut,{value:"products",className:"af-gap-2",children:[(0,de.jsx)(Et.Package,{className:"af-h-4 af-w-4"}),"Products"]}),(0,de.jsxs)(Ut,{value:"orders",className:"af-gap-2",children:[(0,de.jsx)(Et.Receipt,{className:"af-h-4 af-w-4"}),"Orders"]}),(0,de.jsxs)(Ut,{value:"customers",className:"af-gap-2",children:[(0,de.jsx)(Et.Users,{className:"af-h-4 af-w-4"}),"Customers"]}),(0,de.jsxs)(Ut,{value:"setup",className:"af-gap-2",children:[(0,de.jsx)(Et.Settings,{className:"af-h-4 af-w-4"}),"Setup"]})]}),(0,de.jsx)(Vt,{value:"products",children:g==="list"?(0,de.jsx)(Da,{productsState:b,onSelectProduct:y,onCreateProduct:w}):(0,de.jsxs)("div",{children:[(0,de.jsxs)("div",{className:"af-mb-6",children:[(0,de.jsxs)(x,{variant:"ghost",size:"sm",onClick:T,className:"af-mb-2 af--ml-2",children:[(0,de.jsx)(Et.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Back to Products"]}),(0,de.jsx)("h3",{className:"af-text-lg af-font-semibold",children:g==="create"?"New Product":m?.name})]}),g==="create"&&!h?(0,de.jsx)("div",{className:"af-flex af-items-center af-justify-center af-py-8",children:P?(0,de.jsxs)("div",{className:"af-text-destructive",children:["Error: ",P.message]}):(0,de.jsx)("div",{className:"af-text-muted-foreground",children:"Loading..."})}):(0,de.jsx)(Aa,{productsState:b,product:g==="edit"?m:null,currency:h??"usd",onSaved:O},g==="edit"?m?.id??"edit":"new")]})}),(0,de.jsx)(Vt,{value:"orders",children:(0,de.jsx)(ua,{onRefund:s})}),(0,de.jsx)(Vt,{value:"customers",children:(0,de.jsx)($a,{})}),(0,de.jsx)(Vt,{value:"setup",children:(0,de.jsx)(za,{onConnectStripe:a,onUpgradePlan:r})})]})]})}var hr=te(require("react"),1);var Dt=te(require("react"),1);function ja({refreshKey:e}={}){let{api:t}=ae(),[a,s]=Dt.useState(null),[r,l]=Dt.useState(!0),[d,g]=Dt.useState(null),u=Dt.useRef(0),m=Dt.useCallback(async()=>{let n=++u.current;try{l(!0),g(null);let b=await t.getBusinessSummary({tzOffsetMinutes:-new Date().getTimezoneOffset()});if(n!==u.current)return;s(b)}catch(b){if(n!==u.current)return;g(b instanceof Error?b:new Error("Failed to fetch summary"))}finally{n===u.current&&l(!1)}},[t,e]);return Dt.useEffect(()=>{m()},[m]),{summary:a,isLoading:r,error:d,refetch:m}}var ge=require("react/jsx-runtime");function yr(e,t){if(e.settled.complete)return{headline:H(e.settled.gross,e.settled.currency),extra:[]};let a=e.totals[0];return a?{headline:H(a.gross,a.currency),extra:e.totals.slice(1).map(s=>`+ ${H(s.gross,s.currency)} in ${s.currency.toUpperCase()}`)}:{headline:H(0,t),extra:[]}}function Rs({refreshKey:e,initialOrderId:t,isOwner:a=!1,onRefund:s,onBackToWebsite:r,className:l}){let{summary:d,isLoading:g,error:u,refetch:m}=ja({refreshKey:e}),[n,b]=hr.useState(!1),N=(0,ge.jsx)("div",{className:"af-mb-6",children:u&&!d?(0,ge.jsx)(Nt,{message:"Couldn't load your revenue summary.",onRetry:()=>m()}):(0,ge.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-3 sm:af-grid-cols-3",children:g||!d?(0,ge.jsxs)(ge.Fragment,{children:[(0,ge.jsx)(Je,{label:"This week",children:(0,ge.jsx)(K,{className:"af-h-6 af-w-24"})}),(0,ge.jsx)(Je,{label:"Today",children:(0,ge.jsx)(K,{className:"af-h-6 af-w-24"})}),(0,ge.jsx)(Je,{label:"Needs attention",children:(0,ge.jsx)(K,{className:"af-h-6 af-w-10"})})]}):(0,ge.jsx)(ge.Fragment,{children:(()=>{let P=yr(d.revenue.d7,d.currency),h=yr(d.revenue.today,d.currency);return(0,ge.jsxs)(ge.Fragment,{children:[(0,ge.jsx)(Je,{label:"This week",detail:P.extra.length>0?(0,ge.jsx)("div",{children:P.extra.map(y=>(0,ge.jsx)("div",{children:y},y))}):void 0,children:P.headline}),(0,ge.jsx)(Je,{label:"Today",detail:h.extra.length>0?(0,ge.jsx)("div",{children:h.extra.map(y=>(0,ge.jsx)("div",{children:y},y))}):void 0,children:h.headline}),(0,ge.jsx)(Je,{label:"Needs attention",valueClassName:d.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:d.needs_attention.count===0?"All clear":d.needs_attention.items[0]?.title??void 0,children:d.needs_attention.count})]})})()})})});return(0,ge.jsxs)(Kt,{title:"Orders",onBackToWebsite:r,hideBackButton:n,className:l,children:[N,(0,ge.jsx)(ua,{refreshKey:e,initialOrderId:t,onDetailOpenChange:b,showFulfillment:!0,onRefund:a?s:void 0,emptyMessage:"Orders will appear here \u2014 your store is live."})]})}var Qt=te(require("react"),1),Na=require("lucide-react");var It=te(require("react"),1),ms=require("lucide-react");var ze=require("react/jsx-runtime"),xr="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",ia="af-text-xs af-text-muted-foreground",ls="af-text-sm af-font-medium af-tabular-nums",yn=3;function hn(e){let t=e.pricing,a=t?.currency??e.currency;if(t?.custom_amount??e.allow_custom_amount){let u=e.min_amount??t?.min_amount??null,m=e.max_amount??t?.max_amount??null;return u!==null&&m!==null?{text:`Buyer chooses (${H(u,a)} \u2013 ${H(m,a)})`,compareAt:null}:{text:"Buyer chooses",compareAt:null}}let r=t?.min_amount??e.unit_amount,l=t?.max_amount??e.unit_amount;if(r===null||l===null)return{text:"Varies by variant",compareAt:null};let d=r===l?H(r,a):`${H(r,a)} \u2013 ${H(l,a)}`,g=t?.compare_at_amount??null;return{text:d,compareAt:g!==null&&g>l?H(g,a):null}}function fs({product:e,className:t}){let a=hn(e);return(0,ze.jsxs)("div",{className:t,children:[(0,ze.jsx)("span",{className:ls,children:a.text}),a.compareAt&&(0,ze.jsx)("span",{className:"af-ml-2 af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:a.compareAt})]})}function ds({product:e}){let t=e.inventory;return t?t.tracked?t.out_of_stock?(0,ze.jsx)(W,{variant:"destructive",children:"Out of stock"}):t.low_stock?(0,ze.jsxs)(W,{variant:"warning",children:["Low stock \xB7 ",t.available]}):t.allow_backorder?(0,ze.jsx)(W,{variant:"secondary",children:"Backorder"}):t.available===null?null:(0,ze.jsxs)(W,{variant:"secondary",children:["In stock \xB7 ",t.available]}):null:e.stats?.low_stock?(0,ze.jsx)(W,{variant:"warning",children:"Low stock"}):null}function cs(e){switch(e.fulfillment.type){case"download":return"Digital download";case"redirect":return"Redirect";default:return e.collect_shipping_address?"Ships":null}}function us(e){return e.map(t=>H(t.amount,t.currency)).join(" + ")}function Nr(e){return e.allow_custom_amount?e.min_amount!==null&&e.max_amount!==null?`Buyer chooses (${H(e.min_amount,e.currency)} \u2013 ${H(e.max_amount,e.currency)})`:"Buyer chooses":e.unit_amount===null?"\u2014":H(e.unit_amount,e.currency)}function wr({variant:e}){let t=e.inventory;if(!t||!t.tracked)return(0,ze.jsx)("span",{className:"af-text-muted-foreground",children:"Not tracked"});let a=t.available??0;return t.allow_backorder?(0,ze.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ze.jsx)("span",{className:"af-tabular-nums",children:Math.max(0,a)}),(0,ze.jsx)(W,{variant:"secondary",children:a<0?`${Math.abs(a)} on backorder`:"Backorder"})]}):a<=0?(0,ze.jsx)(W,{variant:"destructive",children:"Out of stock"}):(0,ze.jsxs)("span",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,ze.jsx)("span",{className:"af-tabular-nums",children:a}),a<=yn&&(0,ze.jsx)(W,{variant:"warning",children:"Low"})]})}var k=require("react/jsx-runtime");function qa({title:e,children:t,className:a}){return(0,k.jsxs)("section",{className:I("af-rounded-lg af-border af-p-4",a),children:[(0,k.jsx)("h4",{className:xr,children:e}),(0,k.jsx)("div",{className:"af-mt-3",children:t})]})}function Pr({src:e,className:t}){let[a,s]=It.useState(!1);return It.useEffect(()=>s(!1),[e]),!e||a?(0,k.jsx)("div",{"aria-hidden":"true",className:I("af-flex af-items-center af-justify-center af-bg-muted",t),children:(0,k.jsx)(ms.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}):(0,k.jsx)("img",{src:e,alt:"",loading:"lazy",onError:()=>s(!0),className:I("af-object-cover",t)})}function Sr({product:e,showStats:t=!1,onBack:a}){let{api:s}=ae(),[r,l]=It.useState(null),[d,g]=It.useState(!0),[u,m]=It.useState(null),[n,b]=It.useState(0),[N,P]=It.useState(0);It.useEffect(()=>{let B=!1;return g(!0),m(null),s.getProduct(e.id).then(V=>{B||l(V)}).catch(V=>{B||m(V instanceof Error?V:new Error("Failed to load product"))}).finally(()=>{B||g(!1)}),()=>{B=!0}},[s,e.id,n]);let h=r?{...e,...r}:e,y=h.images.length>0?h.images:e.images,w=y[N]??y[0],T=cs(h),O=t?h.stats:void 0,F=r?.variants??[],Y=F.length>1;return(0,k.jsxs)("div",{children:[(0,k.jsxs)("div",{className:"af-mb-6",children:[(0,k.jsxs)(x,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,k.jsx)(ms.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Products"]}),(0,k.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,k.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-words",children:h.name}),(0,k.jsx)(W,{variant:h.active?"success":"secondary",children:h.active?"Active":"Draft"}),(0,k.jsx)(ds,{product:h})]}),(0,k.jsx)(fs,{product:h,className:"af-mt-1"}),!h.active&&(0,k.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,k.jsxs)("div",{className:"af-grid af-gap-6 lg:af-grid-cols-[280px_1fr]",children:[(0,k.jsxs)("div",{className:"af-space-y-2",children:[(0,k.jsx)(Pr,{src:w,className:"af-h-48 af-w-full af-rounded-md af-border"}),y.length>1&&(0,k.jsx)("div",{className:"af-flex af-flex-wrap af-gap-2",children:y.map((B,V)=>(0,k.jsx)("button",{type:"button",onClick:()=>P(V),"aria-label":`Show photo ${V+1} of ${y.length}`,"aria-pressed":V===N,className:I("af-rounded-md af-border focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",V===N?"af-ring-2 af-ring-ring":"af-opacity-80 hover:af-opacity-100"),children:(0,k.jsx)(Pr,{src:B,className:"af-h-12 af-w-12 af-rounded-md"})},`${B}-${V}`))})]}),(0,k.jsxs)("div",{className:"af-space-y-6",children:[h.description&&(0,k.jsx)(qa,{title:"Description",children:(0,k.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:h.description})}),d?(0,k.jsxs)(qa,{title:"Variants",children:[(0,k.jsx)("div",{className:"af-space-y-2","aria-hidden":"true",children:[0,1,2].map(B=>(0,k.jsxs)("div",{className:"af-flex af-items-center af-justify-between af-gap-4",children:[(0,k.jsx)(K,{className:"af-h-4 af-w-28"}),(0,k.jsx)(K,{className:"af-h-4 af-w-20"}),(0,k.jsx)(K,{className:"af-h-4 af-w-16"})]},B))}),(0,k.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading product details"})]}):u?(0,k.jsx)(Nt,{message:"Couldn't load this product's variants.",onRetry:()=>b(B=>B+1)}):Y?(0,k.jsx)(qa,{title:`Variants \xB7 ${F.length}`,children:(0,k.jsx)("div",{className:"af-overflow-x-auto",children:(0,k.jsxs)(Re,{children:[(0,k.jsx)(Ce,{children:(0,k.jsxs)(oe,{children:[(0,k.jsx)(E,{children:"Variant"}),(0,k.jsx)(E,{children:"SKU"}),(0,k.jsx)(E,{className:"af-text-right",children:"Price"}),(0,k.jsx)(E,{children:"Stock"})]})}),(0,k.jsx)(Te,{children:F.map(B=>(0,k.jsxs)(oe,{children:[(0,k.jsxs)(D,{className:"af-font-medium",children:[B.title||B.option_values.map(V=>V.value).join(" / ")||"\u2014",!B.active&&(0,k.jsx)(W,{variant:"secondary",className:"af-ml-2",children:"Hidden"})]}),(0,k.jsx)(D,{className:"af-text-muted-foreground",children:B.sku?(0,k.jsx)("code",{className:"af-font-mono af-text-xs af-break-all",children:B.sku}):"\u2014"}),(0,k.jsxs)(D,{className:"af-whitespace-nowrap af-text-right",children:[(0,k.jsx)("div",{className:ls,children:Nr(B)}),B.compare_at_amount!==null&&B.unit_amount!==null&&B.compare_at_amount>B.unit_amount&&(0,k.jsx)("div",{className:"af-text-xs af-text-muted-foreground af-line-through af-tabular-nums",children:H(B.compare_at_amount,B.currency)})]}),(0,k.jsx)(D,{className:"af-text-sm",children:(0,k.jsx)(wr,{variant:B})})]},B.id))})]})})}):null,(0,k.jsx)(qa,{title:"Details",children:(0,k.jsxs)("dl",{className:"af-space-y-2",children:[(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Delivery"}),(0,k.jsx)("dd",{className:"af-text-sm",children:T==="Digital download"?h.fulfillment.filename??"Digital download":T??"Nothing to deliver"})]}),h.fulfillment.type==="redirect"&&h.fulfillment.url&&(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Sends buyers to"}),(0,k.jsx)("dd",{className:"af-break-all af-text-sm",children:h.fulfillment.url})]}),(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Shipping address"}),(0,k.jsx)("dd",{className:"af-text-sm",children:h.collect_shipping_address?"Collected at checkout":"Not collected"})]}),(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Most one buyer can order"}),(0,k.jsx)("dd",{className:"af-text-sm af-tabular-nums",children:h.max_quantity})]})]})}),O&&(0,k.jsx)(qa,{title:"Last 30 days",children:(0,k.jsxs)("dl",{className:"af-grid af-grid-cols-3 af-gap-3",children:[(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Units sold"}),(0,k.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:O.units_sold})]}),(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Orders"}),(0,k.jsx)("dd",{className:"af-text-sm af-font-medium af-tabular-nums",children:O.orders})]}),(0,k.jsxs)("div",{children:[(0,k.jsx)("dt",{className:ia,children:"Gross"}),(0,k.jsx)("dd",{className:ls,children:O.gross.length>0?us(O.gross):"\u2014"})]})]})}),(0,k.jsx)("p",{className:"af-text-xs af-text-muted-foreground",children:"Ask the AI to change anything here \u2014 price, stock, photos, wording."})]})]})]})}var R=require("react/jsx-runtime"),xn={all:"All",active:"Active",draft:"Draft",low_stock:"Low stock",out_of_stock:"Out of stock"},Nn=["all","active","draft","low_stock","out_of_stock"];function Rr(e){let t=e.includes("T")?e:`${e.replace(" ","T")}Z`,a=new Date(t).getTime();return Number.isNaN(a)?0:a}function Cr(e){return e.inventory?.low_stock??e.stats?.low_stock??!1}function wn(e){return e.inventory?.out_of_stock??!1}function Pn(e,t){switch(t){case"active":return e.active;case"draft":return!e.active;case"low_stock":return Cr(e);case"out_of_stock":return wn(e);default:return!0}}function Sn({product:e,showStats:t,onOpen:a}){let s=e.images[0],r=t?e.stats:void 0,l=cs(e),d=e.variant_count??0;return(0,R.jsxs)("button",{type:"button",onClick:a,"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,R.jsx)("img",{src:s,alt:"",loading:"lazy",className:"af-h-36 af-w-full af-object-cover"}):(0,R.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,R.jsx)(Na.ImageOff,{className:"af-h-8 af-w-8 af-text-muted-foreground"})}),(0,R.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,R.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,R.jsxs)("div",{className:"af-min-w-0",children:[(0,R.jsx)("div",{className:"af-truncate af-text-sm af-font-medium af-text-foreground",children:e.name}),(0,R.jsx)(fs,{product:e,className:"af-mt-0.5"})]}),!e.active&&(0,R.jsx)(W,{variant:"secondary",className:"af-shrink-0",children:"Draft"})]}),(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-1",children:[(0,R.jsx)(ds,{product:e}),d>1&&(0,R.jsxs)(W,{variant:"outline",children:[d," variants"]}),l&&(0,R.jsx)(W,{variant:"outline",children:l})]}),r&&(0,R.jsxs)("div",{className:"af-text-xs af-text-muted-foreground",children:[r.units_sold," sold",r.gross.length>0?` \xB7 ${us(r.gross)}`:""," ",(0,R.jsx)("span",{className:"af-text-muted-foreground/70",children:"last 30 days"})]})]})]})}function Rn(){return(0,R.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,R.jsxs)("div",{"aria-hidden":"true",className:"af-overflow-hidden af-rounded-md af-border",children:[(0,R.jsx)("div",{className:"af-h-36 af-w-full af-animate-pulse af-bg-muted"}),(0,R.jsxs)("div",{className:"af-space-y-2 af-p-3",children:[(0,R.jsx)(K,{className:"af-w-32"}),(0,R.jsx)(K,{className:"af-w-16"}),(0,R.jsx)(K,{className:"af-h-5 af-w-24"})]})]},e))})}function Cs({refreshKey:e,showStats:t=!1,onBackToWebsite:a,className:s}){let{products:r,isLoading:l,error:d,refetch:g}=ga({includeStats:t,refreshKey:e}),[u,m]=Qt.useState(null),[n,b]=Qt.useState("all"),[N,P]=Qt.useState(""),[h,y]=Qt.useState("newest"),w=Qt.useMemo(()=>{if(!t)return null;let A=null;for(let ve of r)!ve.stats||ve.stats.units_sold===0||(!A||ve.stats.units_sold>(A.stats?.units_sold??0))&&(A=ve);return A},[r,t]),T=Qt.useMemo(()=>r.filter(Cr).length,[r]),O=N.trim().toLowerCase(),F=Qt.useMemo(()=>{let ve=[...r.filter(p=>Pn(p,n)&&(!O||p.name.toLowerCase().includes(O)))];return h==="name"?ve.sort((p,se)=>p.name.localeCompare(se.name)):h==="best_selling"?ve.sort((p,se)=>(se.stats?.units_sold??0)-(p.stats?.units_sold??0)):ve.sort((p,se)=>Rr(se.created_at)-Rr(p.created_at)),ve},[r,n,O,h]),Y=n!=="all"||!!O,B=()=>{b("all"),P("")},V=l||d!==null&&r.length===0,M=(0,R.jsx)("div",{className:"af-mb-6",children:(0,R.jsx)("div",{className:I("af-grid af-grid-cols-1 af-gap-3",t?"sm:af-grid-cols-3":"sm:af-grid-cols-2"),children:V?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Je,{label:"Products",children:(0,R.jsx)(K,{className:"af-h-6 af-w-10"})}),t?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Je,{label:"Best seller",children:(0,R.jsx)(K,{className:"af-h-6 af-w-28"})}),(0,R.jsx)(Je,{label:"Low stock",children:(0,R.jsx)(K,{className:"af-h-6 af-w-10"})})]}):(0,R.jsx)(Je,{label:"Active",children:(0,R.jsx)(K,{className:"af-h-6 af-w-10"})})]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Je,{label:"Products",children:r.length}),t?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Je,{label:"Best seller",valueClassName:"af-text-sm af-font-medium",detail:w?`${w.stats?.units_sold??0} sold, last 30 days`:void 0,children:w?(0,R.jsx)("span",{className:"af-block af-truncate af-text-sm af-font-medium",children:w.name}):(0,R.jsx)("span",{className:"af-block af-text-sm af-font-medium af-text-muted-foreground",children:"No sales yet"})}),(0,R.jsx)(Je,{label:"Low stock",children:T})]}):(0,R.jsx)(Je,{label:"Active",children:r.filter(A=>A.active).length})]})})}),Q=(0,R.jsxs)("div",{className:"af-mb-4 af-space-y-3",children:[(0,R.jsxs)("div",{className:"af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,R.jsx)("div",{role:"group","aria-label":"Product views",className:"af-inline-flex af-items-center af-gap-1 af-rounded-lg af-bg-muted af-p-1",children:Nn.map(A=>(0,R.jsx)("button",{type:"button","aria-pressed":n===A,onClick:()=>b(A),className:I("af-whitespace-nowrap af-rounded-md af-px-3 af-py-1 af-text-sm af-font-medium af-transition-colors focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",n===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:xn[A]},A))}),(0,R.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,R.jsx)(Na.Search,{className:"af-pointer-events-none af-absolute af-left-2.5 af-top-1/2 af-h-4 af-w-4 af--translate-y-1/2 af-text-muted-foreground"}),(0,R.jsx)(le,{type:"text",value:N,onChange:A=>P(A.target.value),placeholder:"Search products","aria-label":"Search products by name",className:"af-pl-8"})]}),(0,R.jsxs)(ut,{value:h,onValueChange:A=>y(A),children:[(0,R.jsx)(at,{className:"af-h-9 af-w-[150px]","aria-label":"Sort products",children:(0,R.jsx)(mt,{})}),(0,R.jsxs)(st,{children:[(0,R.jsx)(he,{value:"newest",children:"Newest"}),(0,R.jsx)(he,{value:"name",children:"Name A\u2013Z"}),t&&(0,R.jsx)(he,{value:"best_selling",children:"Best selling"})]})]}),Y&&(0,R.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:B,children:"Clear filters"})]}),l&&r.length===0?(0,R.jsx)(K,{className:"af-h-4 af-w-28"}):(0,R.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:Y?`${F.length} of ${r.length} products`:`${r.length} ${r.length===1?"product":"products"}${T>0?` \xB7 ${T} low stock`:""}`})]}),$;return u?$=(0,R.jsx)(Sr,{product:u,showStats:t,onBack:()=>{m(null),g()}},u.id):l&&r.length===0?$=(0,R.jsxs)(R.Fragment,{children:[Q,(0,R.jsx)(Rn,{}),(0,R.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading products"})]}):d&&r.length===0?$=(0,R.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,R.jsx)(Nt,{message:"Couldn't load your products.",onRetry:()=>g()})}):r.length===0?$=(0,R.jsxs)(ca,{icon:(0,R.jsx)(Na.Package,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:["No products yet.",(0,R.jsx)("br",{}),"Ask the AI to add one \u2014 try \u201Cadd a $25 t-shirt in S, M and L\u201D."]}):$=(0,R.jsxs)(R.Fragment,{children:[Q,d&&(0,R.jsx)("div",{className:"af-mb-4",children:(0,R.jsx)(Nt,{message:"Couldn't refresh your products \u2014 showing the last version loaded.",onRetry:()=>g()})}),F.length===0?(0,R.jsxs)(ca,{children:["No products match these filters.",(0,R.jsx)("br",{}),(0,R.jsx)(x,{type:"button",variant:"ghost",size:"sm",className:"af-mt-2",onClick:B,children:"Show all products"})]}):(0,R.jsx)("div",{className:"af-grid af-grid-cols-1 af-gap-4 sm:af-grid-cols-2 lg:af-grid-cols-3",children:F.map(A=>(0,R.jsx)(Sn,{product:A,showStats:t,onOpen:()=>m(A)},A.id))})]}),(0,R.jsxs)(Kt,{title:"Products",onBackToWebsite:a,hideBackButton:!!u,className:s,children:[!u&&M,$]})}var wt=te(require("react"),1),Ee=require("lucide-react");var lt=te(require("react"),1);function Ga({initialPageSize:e=25,refreshKey:t}={}){let{api:a}=ae(),[s,r]=lt.useState([]),[l,d]=lt.useState(!0),[g,u]=lt.useState(null),[m,n]=lt.useState(0),[b]=lt.useState(e),[N,P]=lt.useState(""),h=lt.useRef(0),y=lt.useCallback(async()=>{let w=++h.current;try{d(!0),u(null);let T={limit:b,offset:m*b};N.trim()&&(T.q=N.trim());let O=await a.getPeople(T);if(w!==h.current)return;r(O.people)}catch(T){if(w!==h.current)return;u(T instanceof Error?T:new Error("Failed to fetch people"))}finally{w===h.current&&d(!1)}},[a,m,b,N,t]);return lt.useEffect(()=>{y()},[y]),{people:s,isLoading:l,error:g,page:m,pageSize:b,hasNextPage:s.length===b,hasPreviousPage:m>0,setPage:n,q:N,setQ:w=>{P(w),n(0)},refetch:y}}var At=te(require("react"),1);function Wa(e,{refreshKey:t}={}){let{api:a}=ae(),[s,r]=At.useState(null),[l,d]=At.useState(e!==null),[g,u]=At.useState(null),m=At.useRef(0),n=At.useCallback(async()=>{if(e===null){r(null),d(!1),u(null);return}let b=++m.current;try{d(!0),u(null);let N=await a.getPerson(e);if(b!==m.current)return;r(N)}catch(N){if(b!==m.current)return;u(N instanceof Error?N:new Error("Failed to fetch person"))}finally{b===m.current&&d(!1)}},[a,e,t]);return At.useEffect(()=>{n()},[n]),{person:s,isLoading:l,error:g,refetch:n}}var i=require("react/jsx-runtime"),Ts="af-text-[11px] af-font-semibold af-uppercase af-tracking-wide af-text-muted-foreground",Cn="af-text-xs af-text-muted-foreground";function wa(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 ks(e,t){let a=t?`Re: ${t}`:"Re: your message";return`mailto:${encodeURIComponent(e)}?subject=${encodeURIComponent(a)}`}function Tn(){return typeof navigator<"u"&&!!navigator.clipboard?.writeText}function kn({value:e,label:t}){let[a,s]=wt.useState(!1);return Tn()?(0,i.jsxs)(x,{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:[a?(0,i.jsx)(Ee.Check,{className:"af-h-3.5 af-w-3.5 af-mr-1"}):(0,i.jsx)(Ee.ClipboardCopy,{className:"af-h-3.5 af-w-3.5 af-mr-1"}),a?"Copied":"Copy email"]}):null}function Tr(e){return(0,i.jsxs)("span",{className:"af-inline-flex af-flex-wrap af-gap-1",children:[e.sources.includes("customer")&&(0,i.jsxs)(W,{variant:"success",children:["Customer \xB7 ",e.order_count," ",e.order_count===1?"order":"orders"]}),e.sources.includes("lead")&&(0,i.jsx)(W,{variant:"secondary",children:"Contact form"})]})}function kr(e){return e.name?e.name:e.email?e.email:(0,i.jsx)("span",{className:"af-text-muted-foreground af-italic",children:"Form submission"})}var _n=/^(message|messages|comment|comments|enquiry|inquiry|question|questions|details|notes|note|body)$/i,On=40;function Ln(e){let t=Object.entries(e).filter(([r])=>!r.startsWith("_")),s=t.find(([r,l])=>_n.test(r)&&typeof l=="string"&&l.trim())??t.filter(([,r])=>typeof r=="string"&&r.trim().length>=On).sort((r,l)=>String(l[1]).trim().length-String(r[1]).trim().length)[0];return s?{message:String(s[1]),rest:t.filter(([r])=>r!==s[0])}:{message:null,rest:t}}function Bn(e){return e.replace(/_/g," ")}function En(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Dn({data:e}){let{message:t,rest:a}=Ln(e);return t===null&&a.length===0?(0,i.jsx)("p",{className:"af-text-sm af-text-muted-foreground",children:"No data submitted"}):(0,i.jsxs)("div",{className:"af-space-y-3",children:[t!==null&&(0,i.jsx)("p",{className:"af-whitespace-pre-wrap af-break-words af-text-sm",children:t}),a.length>0&&(0,i.jsx)("dl",{className:"af-space-y-1",children:a.map(([s,r])=>(0,i.jsxs)("div",{className:"af-flex af-flex-wrap af-gap-x-2",children:[(0,i.jsx)("dt",{className:I(Cn,"af-w-28 af-shrink-0 af-capitalize"),children:Bn(s)}),(0,i.jsx)("dd",{className:"af-min-w-0 af-break-words af-text-sm",children:En(r)})]},s))})]})}function _r({formName:e,createdAt:t,data:a}){return(0,i.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,i.jsxs)("div",{className:"af-mb-2 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,i.jsx)(W,{variant:"outline",children:"Form submission (unverified)"}),e&&(0,i.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:e}),(0,i.jsx)("span",{className:"af-ml-auto af-text-xs af-text-muted-foreground",children:wa(t)})]}),(0,i.jsx)(Dn,{data:a})]})}function In(e){return e.charged_total??e.amount_total}function An({email:e,refreshKey:t,onBack:a}){let{person:s,isLoading:r,error:l,refetch:d}=Wa(e,{refreshKey:t}),g=ks(e,s?.submissions[0]?.form_name);return(0,i.jsxs)("div",{children:[(0,i.jsxs)("div",{className:"af-mb-6",children:[(0,i.jsxs)(x,{variant:"ghost",size:"sm",onClick:a,className:"af-mb-2 af--ml-2",children:[(0,i.jsx)(Ee.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,i.jsxs)("div",{className:"af-flex af-flex-wrap af-items-start af-justify-between af-gap-3",children:[(0,i.jsxs)("div",{className:"af-min-w-0",children:[r?(0,i.jsx)(K,{className:"af-h-7 af-w-48"}):(0,i.jsx)("h3",{className:"af-text-xl af-font-semibold af-break-all",children:s?.name||e}),(0,i.jsxs)("div",{className:"af-mt-1 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,i.jsx)("span",{className:"af-break-all af-text-sm af-text-muted-foreground",children:e}),(0,i.jsx)(kn,{value:e,label:"Copy email address"})]})]}),(0,i.jsx)(x,{asChild:!0,children:(0,i.jsxs)("a",{href:g,children:[(0,i.jsx)(Ee.Mail,{className:"af-h-4 af-w-4 af-mr-1"}),"Reply"]})})]})]}),r?(0,i.jsxs)("div",{className:"af-space-y-3","aria-hidden":"true",children:[[0,1,2].map(u=>(0,i.jsxs)("div",{className:"af-rounded-md af-border af-p-3",children:[(0,i.jsx)(K,{className:"af-w-40"}),(0,i.jsx)(K,{className:"af-mt-2 af-w-64"})]},u)),(0,i.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this person"})]}):l||!s?(0,i.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,i.jsx)(Nt,{message:"Couldn't load this person.",onRetry:()=>d()})}):(0,i.jsxs)("div",{className:"af-space-y-6",children:[s.customer&&(0,i.jsxs)("div",{children:[(0,i.jsx)("h4",{className:I(Ts,"af-mb-3"),children:"Customer"}),(0,i.jsxs)("dl",{className:"af-space-y-1 af-text-sm",children:[s.customer.name&&(0,i.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,i.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Name"}),(0,i.jsx)("dd",{children:s.customer.name})]}),s.customer.phone&&(0,i.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,i.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Phone"}),(0,i.jsx)("dd",{children:s.customer.phone})]}),(0,i.jsxs)("div",{className:"af-flex af-gap-2",children:[(0,i.jsx)("dt",{className:"af-w-32 af-shrink-0 af-text-muted-foreground",children:"Customer since"}),(0,i.jsx)("dd",{children:wa(s.customer.created_at)})]})]})]}),s.orders.length>0&&(0,i.jsxs)("div",{children:[(0,i.jsx)("h4",{className:I(Ts,"af-mb-3"),children:"Purchases"}),(0,i.jsx)("div",{className:"af-overflow-x-auto",children:(0,i.jsxs)(Re,{children:[(0,i.jsx)(Ce,{children:(0,i.jsxs)(oe,{children:[(0,i.jsx)(E,{children:"Order"}),(0,i.jsx)(E,{children:"Date"}),(0,i.jsx)(E,{className:"af-text-right",children:"Total"}),(0,i.jsx)(E,{children:"Status"})]})}),(0,i.jsx)(Te,{children:s.orders.map(u=>(0,i.jsxs)(oe,{children:[(0,i.jsx)(D,{className:"af-whitespace-nowrap af-font-medium",children:Wt(u)}),(0,i.jsx)(D,{className:"af-whitespace-nowrap af-text-muted-foreground",children:wa(u.created_at)}),(0,i.jsx)(D,{className:"af-whitespace-nowrap af-text-right af-font-medium af-tabular-nums",children:H(In(u),u.currency)}),(0,i.jsx)(D,{children:(0,i.jsx)(sa,{status:u.status})})]},u.id))})]})}),(0,i.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."})]}),s.submissions.length>0&&(0,i.jsxs)("div",{children:[(0,i.jsx)("h4",{className:I(Ts,"af-mb-3"),children:"Messages"}),(0,i.jsx)("div",{className:"af-space-y-3",children:s.submissions.map(u=>(0,i.jsx)(_r,{formName:u.form_name,createdAt:u.created_at,data:u.data},u.id))})]})]})]})}function Fn({submissionId:e,onBack:t}){let{api:a}=ae(),[s,r]=wt.useState(null),[l,d]=wt.useState(!0),[g,u]=wt.useState(null),[m,n]=wt.useState(0);return wt.useEffect(()=>{let b=!1;return d(!0),u(null),a.getSubmission(e).then(N=>{b||r(N)}).catch(N=>{b||u(N instanceof Error?N:new Error("Failed to load submission"))}).finally(()=>{b||d(!1)}),()=>{b=!0}},[a,e,m]),(0,i.jsxs)("div",{children:[(0,i.jsxs)("div",{className:"af-mb-6",children:[(0,i.jsxs)(x,{variant:"ghost",size:"sm",onClick:t,className:"af-mb-2 af--ml-2",children:[(0,i.jsx)(Ee.ArrowLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"People"]}),(0,i.jsx)("h3",{className:"af-text-xl af-font-semibold",children:"Form submission"}),l?(0,i.jsx)(K,{className:"af-mt-1 af-h-4 af-w-32"}):s&&(0,i.jsx)("p",{className:"af-mt-1 af-text-sm af-text-muted-foreground",children:wa(s.metadata.submitted_at)})]}),l?(0,i.jsxs)("div",{className:"af-rounded-md af-border af-p-3","aria-hidden":"true",children:[(0,i.jsx)(K,{className:"af-w-40"}),(0,i.jsx)(K,{className:"af-mt-2 af-w-64"}),(0,i.jsx)(K,{className:"af-mt-2 af-w-52"}),(0,i.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading this submission"})]}):g||!s?(0,i.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,i.jsx)(Nt,{message:"Couldn't load this submission.",onRetry:()=>n(b=>b+1)})}):(0,i.jsxs)("div",{className:"af-space-y-3",children:[(0,i.jsx)(_r,{formName:null,createdAt:s.metadata.submitted_at,data:s.data}),(0,i.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 Un={all:"All",customers:"Customers",leads:"Leads"},Vn=["all","customers","leads"];function Hn(e,t){return t==="customers"?e.sources.includes("customer"):t==="leads"?e.sources.includes("lead"):!0}function _s({refreshKey:e,onBackToWebsite:t,className:a}){let{people:s,isLoading:r,error:l,page:d,pageSize:g,hasNextPage:u,hasPreviousPage:m,setPage:n,q:b,setQ:N,refetch:P}=Ga({refreshKey:e}),[h,y]=wt.useState({kind:"list"}),[w,T]=wt.useState(""),[O,F]=wt.useState("all"),Y=$=>{$.email?y({kind:"person",email:$.email}):$.submission_id&&y({kind:"submission",submissionId:$.submission_id})},B=()=>{y({kind:"list"}),P()},V=$=>{let A=$.trim();A!==b&&N(A)},M=s.filter($=>Hn($,O)),Q;if(h.kind==="person")Q=(0,i.jsx)(An,{email:h.email,refreshKey:e,onBack:B});else if(h.kind==="submission")Q=(0,i.jsx)(Fn,{submissionId:h.submissionId,onBack:B});else{let $=(0,i.jsxs)("div",{className:"af-mb-4 af-flex af-flex-wrap af-items-center af-gap-2",children:[(0,i.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:Vn.map(A=>(0,i.jsx)("button",{type:"button","aria-pressed":O===A,onClick:()=>F(A),className:I("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",O===A?"af-bg-background af-text-foreground af-shadow":"af-text-muted-foreground hover:af-text-foreground"),children:Un[A]},A))}),(0,i.jsxs)("div",{className:"af-relative af-w-full af-max-w-xs",children:[(0,i.jsx)(Ee.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)(le,{type:"text",value:w,onChange:A=>T(A.target.value),onBlur:()=>V(w),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),V(w))},placeholder:"Search by name or email","aria-label":"Search people by name or email",className:"af-pl-8"})]}),b&&(0,i.jsx)(x,{type:"button",variant:"ghost",size:"sm",onClick:()=>{T(""),N("")},children:"Clear search"})]});if(r)Q=(0,i.jsxs)("div",{children:[$,(0,i.jsx)("div",{className:"af-space-y-3 lg:af-hidden","aria-hidden":"true",children:[0,1,2,3,4].map(A=>(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)(K,{className:"af-h-4 af-w-32"}),(0,i.jsx)(K,{className:"af-h-4 af-w-16"})]}),(0,i.jsx)(K,{className:"af-mt-2 af-h-5 af-w-28"}),(0,i.jsx)(K,{className:"af-mt-2 af-h-3 af-w-56"})]},A))}),(0,i.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,i.jsxs)(Re,{children:[(0,i.jsx)(Ce,{children:(0,i.jsxs)(oe,{children:[(0,i.jsx)(E,{children:"Person"}),(0,i.jsx)(E,{children:"Came from"}),(0,i.jsx)(E,{children:"Latest message"}),(0,i.jsx)(E,{children:"Last activity"}),(0,i.jsx)(E,{className:"af-w-8"}),(0,i.jsx)(E,{className:"af-w-8"})]})}),(0,i.jsx)(Te,{"aria-hidden":"true",children:[0,1,2,3,4].map(A=>(0,i.jsxs)(oe,{children:[(0,i.jsx)(D,{children:(0,i.jsx)(K,{className:"af-h-4 af-w-40"})}),(0,i.jsx)(D,{children:(0,i.jsx)(K,{className:"af-h-5 af-w-24"})}),(0,i.jsx)(D,{children:(0,i.jsx)(K,{className:"af-h-4 af-w-56"})}),(0,i.jsx)(D,{children:(0,i.jsx)(K,{className:"af-h-4 af-w-24"})}),(0,i.jsx)(D,{}),(0,i.jsx)(D,{})]},A))})]})}),(0,i.jsx)("span",{className:"af-sr-only",role:"status",children:"Loading people"})]});else if(l)Q=(0,i.jsxs)("div",{children:[$,(0,i.jsx)("div",{className:"af-flex af-justify-center af-py-8",children:(0,i.jsx)(Nt,{message:"Couldn't load your leads.",onRetry:()=>P()})})]});else if(M.length===0&&d===0){let A=!!b||O!=="all";Q=(0,i.jsxs)("div",{children:[A&&$,A?(0,i.jsx)(ca,{children:b?"Nobody matches that search.":O==="customers"?"Nobody has bought anything yet.":"No form submissions yet."}):(0,i.jsx)(ca,{icon:(0,i.jsx)(Ee.Users,{className:"af-mb-4 af-h-12 af-w-12 af-text-muted-foreground"}),children:"Form submissions and customers will show up here."})]})}else if(s.length===0)Q=(0,i.jsxs)("div",{children:[$,(0,i.jsx)(ca,{children:"No more results."}),(0,i.jsx)("div",{className:"af-flex af-justify-end af-px-2 af-py-4",children:(0,i.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>n(d-1),children:[(0,i.jsx)(Ee.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]})})]});else{let A=d*g+1,ve=d*g+s.length;Q=(0,i.jsxs)("div",{children:[$,(0,i.jsx)("div",{className:"af-space-y-3 lg:af-hidden",children:M.map((p,se)=>(0,i.jsxs)("div",{onClick:()=>Y(p),className:"af-cursor-pointer af-rounded-md af-border af-p-3 hover:af-bg-muted/50",children:[(0,i.jsxs)("div",{className:"af-flex af-items-start af-justify-between af-gap-2",children:[(0,i.jsxs)("div",{className:"af-min-w-0",children:[(0,i.jsx)("button",{type:"button",onClick:we=>{we.stopPropagation(),Y(p)},"aria-label":`Open ${p.name||p.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left af-text-sm af-font-medium hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:kr(p)}),p.name&&p.email&&(0,i.jsx)("div",{className:"af-truncate af-text-xs af-text-muted-foreground",children:p.email})]}),(0,i.jsxs)("div",{className:"af-flex af-shrink-0 af-items-center af-gap-1",children:[(0,i.jsx)("span",{className:"af-text-xs af-text-muted-foreground",children:wa(p.last_activity_at)}),p.email&&(0,i.jsx)(x,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,i.jsx)("a",{href:ks(p.email),onClick:we=>we.stopPropagation(),"aria-label":`Email ${p.email}`,children:(0,i.jsx)(Ee.Mail,{className:"af-h-4 af-w-4"})})})]})]}),(0,i.jsx)("div",{className:"af-mt-2",children:Tr(p)}),p.latest_message_excerpt&&(0,i.jsx)("p",{className:"af-mt-2 af-line-clamp-2 af-break-words af-text-xs af-text-muted-foreground",children:p.latest_message_excerpt})]},p.email??p.submission_id??se))}),(0,i.jsx)("div",{className:"af-hidden af-overflow-x-auto lg:af-block",children:(0,i.jsxs)(Re,{children:[(0,i.jsx)(Ce,{children:(0,i.jsxs)(oe,{children:[(0,i.jsx)(E,{children:"Person"}),(0,i.jsx)(E,{children:"Came from"}),(0,i.jsx)(E,{children:"Latest message"}),(0,i.jsx)(E,{children:"Last activity"}),(0,i.jsx)(E,{className:"af-w-8",children:(0,i.jsx)("span",{className:"af-sr-only",children:"Reply"})}),(0,i.jsx)(E,{className:"af-w-8"})]})}),(0,i.jsx)(Te,{children:M.map((p,se)=>(0,i.jsxs)(oe,{onClick:()=>Y(p),className:"af-cursor-pointer focus-within:af-bg-muted/50",children:[(0,i.jsxs)(D,{className:"af-max-w-[260px] af-font-medium",children:[(0,i.jsx)("button",{type:"button",onClick:we=>{we.stopPropagation(),Y(p)},"aria-label":`Open ${p.name||p.email||"this form submission"}`,className:"af-block af-max-w-full af-truncate af-rounded-sm af-text-left hover:af-underline focus-visible:af-outline-none focus-visible:af-ring-2 focus-visible:af-ring-ring",children:kr(p)}),p.name&&p.email&&(0,i.jsx)("div",{className:"af-truncate af-text-xs af-font-normal af-text-muted-foreground",children:p.email})]}),(0,i.jsx)(D,{children:Tr(p)}),(0,i.jsx)(D,{className:"af-max-w-[320px]",children:p.latest_message_excerpt?(0,i.jsx)("span",{className:"af-line-clamp-1 af-break-words af-text-sm af-text-muted-foreground",children:p.latest_message_excerpt}):(0,i.jsx)("span",{className:"af-text-muted-foreground",children:"\u2014"})}),(0,i.jsx)(D,{className:"af-whitespace-nowrap af-text-muted-foreground",children:wa(p.last_activity_at)}),(0,i.jsx)(D,{className:"af-w-8",children:p.email&&(0,i.jsx)(x,{asChild:!0,variant:"ghost",size:"icon",className:"af-h-8 af-w-8",children:(0,i.jsx)("a",{href:ks(p.email),onClick:we=>we.stopPropagation(),"aria-label":`Email ${p.email}`,children:(0,i.jsx)(Ee.Mail,{className:"af-h-4 af-w-4"})})})}),(0,i.jsx)(D,{className:"af-w-8 af-text-right",children:(0,i.jsx)(Ee.ChevronRight,{"aria-hidden":"true",className:"af-h-4 af-w-4 af-text-muted-foreground/50"})})]},p.email??p.submission_id??se))})]})}),(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.jsx)("span",{className:"af-text-sm af-text-muted-foreground",children:O==="all"?`Showing ${A}-${ve}`:`${M.length} of ${s.length} on this page`}),(0,i.jsxs)("div",{className:"af-flex af-items-center af-gap-2",children:[(0,i.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>n(d-1),disabled:!m,children:[(0,i.jsx)(Ee.ChevronLeft,{className:"af-h-4 af-w-4 af-mr-1"}),"Previous"]}),(0,i.jsxs)(x,{variant:"outline",size:"sm",onClick:()=>n(d+1),disabled:!u,children:["Next",(0,i.jsx)(Ee.ChevronRight,{className:"af-h-4 af-w-4 af-ml-1"})]})]})]})]})}}return(0,i.jsx)(Kt,{title:"Leads",onBackToWebsite:t,hideBackButton:h.kind!=="list",className:a,children:Q})}0&&(module.exports={AifeaturesApiError,AifeaturesProvider,CustomerDetail,CustomersList,FormSettings,FormSubmissions,FormsDashboard,FormsList,LeadsView,OrderDetail,OrderStatusBadge,OrdersList,OrdersView,PaymentsDashboard,PaymentsSetup,ProductSettings,ProductsList,ProductsView,SubmissionDetail,VariantsEditor,ViewShell,chargedTotal,createApiClient,formatPrice,isZeroDecimalCurrency,toMajorUnits,toMinorUnits,useAifeatures,useAifeaturesContext,useBusinessSummary,useCustomers,useForms,useOrders,usePaymentsStatus,usePeople,usePerson,useProducts,useSubmissions});