@prenta/admin 2.9.3 → 2.10.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.
Files changed (261) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/AdminRoot.d.ts.map +1 -1
  3. package/dist/AdminRoot.js +5 -3
  4. package/dist/AdminRoot.js.map +1 -1
  5. package/dist/__tests__/components/attribution-rows.test.js +1 -1
  6. package/dist/__tests__/components/attribution-rows.test.js.map +1 -1
  7. package/dist/__tests__/components/date-range-picker.test.d.ts +2 -0
  8. package/dist/__tests__/components/date-range-picker.test.d.ts.map +1 -0
  9. package/dist/__tests__/components/date-range-picker.test.js +59 -0
  10. package/dist/__tests__/components/date-range-picker.test.js.map +1 -0
  11. package/dist/__tests__/components/form-build-model.test.d.ts +2 -0
  12. package/dist/__tests__/components/form-build-model.test.d.ts.map +1 -0
  13. package/dist/__tests__/components/form-build-model.test.js +162 -0
  14. package/dist/__tests__/components/form-build-model.test.js.map +1 -0
  15. package/dist/__tests__/components/form-build.test.d.ts +2 -0
  16. package/dist/__tests__/components/form-build.test.d.ts.map +1 -0
  17. package/dist/__tests__/components/form-build.test.js +120 -0
  18. package/dist/__tests__/components/form-build.test.js.map +1 -0
  19. package/dist/__tests__/components/qa-a11y.render.test.js +1 -17
  20. package/dist/__tests__/components/qa-a11y.render.test.js.map +1 -1
  21. package/dist/__tests__/lib/batch-wizard.test.js +2 -0
  22. package/dist/__tests__/lib/batch-wizard.test.js.map +1 -1
  23. package/dist/__tests__/lib/forms-settings-normalize.test.d.ts +2 -0
  24. package/dist/__tests__/lib/forms-settings-normalize.test.d.ts.map +1 -0
  25. package/dist/__tests__/lib/forms-settings-normalize.test.js +16 -0
  26. package/dist/__tests__/lib/forms-settings-normalize.test.js.map +1 -0
  27. package/dist/__tests__/views/dashboard.test.js +105 -30
  28. package/dist/__tests__/views/dashboard.test.js.map +1 -1
  29. package/dist/__tests__/views/form-editor.render.test.js +17 -9
  30. package/dist/__tests__/views/form-editor.render.test.js.map +1 -1
  31. package/dist/__tests__/views/form-entries.render.test.js +23 -9
  32. package/dist/__tests__/views/form-entries.render.test.js.map +1 -1
  33. package/dist/__tests__/views/form-submissions.render.test.js +13 -14
  34. package/dist/__tests__/views/form-submissions.render.test.js.map +1 -1
  35. package/dist/__tests__/views/forms-list.render.test.js +139 -16
  36. package/dist/__tests__/views/forms-list.render.test.js.map +1 -1
  37. package/dist/__tests__/views/forms-settings.fixture.d.ts +3 -0
  38. package/dist/__tests__/views/forms-settings.fixture.d.ts.map +1 -0
  39. package/dist/__tests__/views/forms-settings.fixture.js +31 -0
  40. package/dist/__tests__/views/forms-settings.fixture.js.map +1 -0
  41. package/dist/__tests__/views/forms-settings.render.test.d.ts +2 -0
  42. package/dist/__tests__/views/forms-settings.render.test.d.ts.map +1 -0
  43. package/dist/__tests__/views/forms-settings.render.test.js +120 -0
  44. package/dist/__tests__/views/forms-settings.render.test.js.map +1 -0
  45. package/dist/__tests__/views/inbox-format.test.d.ts +2 -0
  46. package/dist/__tests__/views/inbox-format.test.d.ts.map +1 -0
  47. package/dist/__tests__/views/inbox-format.test.js +47 -0
  48. package/dist/__tests__/views/inbox-format.test.js.map +1 -0
  49. package/dist/__tests__/views/jobs-wizard.render.test.js +17 -3
  50. package/dist/__tests__/views/jobs-wizard.render.test.js.map +1 -1
  51. package/dist/__tests__/views/onboarding-block.render.test.js +9 -7
  52. package/dist/__tests__/views/onboarding-block.render.test.js.map +1 -1
  53. package/dist/components/forms/BlocklistDialog.d.ts +19 -0
  54. package/dist/components/forms/BlocklistDialog.d.ts.map +1 -0
  55. package/dist/components/forms/BlocklistDialog.js +225 -0
  56. package/dist/components/forms/BlocklistDialog.js.map +1 -0
  57. package/dist/components/forms/ExportMenu.d.ts +3 -1
  58. package/dist/components/forms/ExportMenu.d.ts.map +1 -1
  59. package/dist/components/forms/ExportMenu.js +2 -2
  60. package/dist/components/forms/ExportMenu.js.map +1 -1
  61. package/dist/components/forms/FieldOptions.d.ts +11 -0
  62. package/dist/components/forms/FieldOptions.d.ts.map +1 -0
  63. package/dist/components/forms/FieldOptions.js +106 -0
  64. package/dist/components/forms/FieldOptions.js.map +1 -0
  65. package/dist/components/forms/FormBuild.d.ts +11 -0
  66. package/dist/components/forms/FormBuild.d.ts.map +1 -0
  67. package/dist/components/forms/FormBuild.js +299 -0
  68. package/dist/components/forms/FormBuild.js.map +1 -0
  69. package/dist/components/forms/FormsListTable.d.ts +14 -0
  70. package/dist/components/forms/FormsListTable.d.ts.map +1 -0
  71. package/dist/components/forms/FormsListTable.js +84 -0
  72. package/dist/components/forms/FormsListTable.js.map +1 -0
  73. package/dist/components/forms/form-build-model.d.ts +74 -0
  74. package/dist/components/forms/form-build-model.d.ts.map +1 -0
  75. package/dist/components/forms/form-build-model.js +297 -0
  76. package/dist/components/forms/form-build-model.js.map +1 -0
  77. package/dist/components/forms/form-build-ui.d.ts +35 -0
  78. package/dist/components/forms/form-build-ui.d.ts.map +1 -0
  79. package/dist/components/forms/form-build-ui.js +59 -0
  80. package/dist/components/forms/form-build-ui.js.map +1 -0
  81. package/dist/components/forms/primitives.d.ts +3 -22
  82. package/dist/components/forms/primitives.d.ts.map +1 -1
  83. package/dist/components/forms/primitives.js +4 -19
  84. package/dist/components/forms/primitives.js.map +1 -1
  85. package/dist/components/ui/Badge.d.ts +1 -1
  86. package/dist/components/ui/Card.d.ts +1 -1
  87. package/dist/components/ui/DateRangePicker.d.ts +7 -0
  88. package/dist/components/ui/DateRangePicker.d.ts.map +1 -0
  89. package/dist/components/ui/DateRangePicker.js +112 -0
  90. package/dist/components/ui/DateRangePicker.js.map +1 -0
  91. package/dist/components/ui/Input.d.ts +1 -1
  92. package/dist/components/ui/Segmented.d.ts +3 -1
  93. package/dist/components/ui/Segmented.d.ts.map +1 -1
  94. package/dist/components/ui/Segmented.js +3 -3
  95. package/dist/components/ui/Segmented.js.map +1 -1
  96. package/dist/components/ui/StatusBadge.d.ts +3 -2
  97. package/dist/components/ui/StatusBadge.d.ts.map +1 -1
  98. package/dist/components/ui/StatusBadge.js +9 -3
  99. package/dist/components/ui/StatusBadge.js.map +1 -1
  100. package/dist/components/ui/Toggle.d.ts +1 -1
  101. package/dist/components/ui/Toggle.d.ts.map +1 -1
  102. package/dist/components/ui/Toggle.js +3 -0
  103. package/dist/components/ui/Toggle.js.map +1 -1
  104. package/dist/components/ui/UnderlineTabs.d.ts +5 -1
  105. package/dist/components/ui/UnderlineTabs.d.ts.map +1 -1
  106. package/dist/components/ui/UnderlineTabs.js +14 -11
  107. package/dist/components/ui/UnderlineTabs.js.map +1 -1
  108. package/dist/layout/Sidebar.js +3 -1
  109. package/dist/layout/Sidebar.js.map +1 -1
  110. package/dist/lib/batch-wizard.d.ts +1 -1
  111. package/dist/lib/batch-wizard.d.ts.map +1 -1
  112. package/dist/lib/batch-wizard.js +2 -2
  113. package/dist/lib/batch-wizard.js.map +1 -1
  114. package/dist/lib/entry-attribution.d.ts +13 -0
  115. package/dist/lib/entry-attribution.d.ts.map +1 -0
  116. package/dist/lib/entry-attribution.js +81 -0
  117. package/dist/lib/entry-attribution.js.map +1 -0
  118. package/dist/lib/forms-service.d.ts +100 -0
  119. package/dist/lib/forms-service.d.ts.map +1 -1
  120. package/dist/lib/forms-service.js +101 -0
  121. package/dist/lib/forms-service.js.map +1 -1
  122. package/dist/lib/job-drawer.d.ts +1 -0
  123. package/dist/lib/job-drawer.d.ts.map +1 -1
  124. package/dist/lib/job-drawer.js +23 -1
  125. package/dist/lib/job-drawer.js.map +1 -1
  126. package/dist/lib/job-view.d.ts +6 -0
  127. package/dist/lib/job-view.d.ts.map +1 -1
  128. package/dist/lib/job-view.js +7 -0
  129. package/dist/lib/job-view.js.map +1 -1
  130. package/dist/prenta-admin.css +1 -1
  131. package/dist/router/admin-routes.d.ts.map +1 -1
  132. package/dist/router/admin-routes.js +1 -0
  133. package/dist/router/admin-routes.js.map +1 -1
  134. package/dist/views/Dashboard.d.ts.map +1 -1
  135. package/dist/views/Dashboard.js +438 -309
  136. package/dist/views/Dashboard.js.map +1 -1
  137. package/dist/views/FormEditor.d.ts.map +1 -1
  138. package/dist/views/FormEditor.js +68 -13
  139. package/dist/views/FormEditor.js.map +1 -1
  140. package/dist/views/FormEntries.d.ts.map +1 -1
  141. package/dist/views/FormEntries.js +4 -190
  142. package/dist/views/FormEntries.js.map +1 -1
  143. package/dist/views/FormSubmissions.d.ts +1 -1
  144. package/dist/views/FormSubmissions.d.ts.map +1 -1
  145. package/dist/views/FormSubmissions.js +6 -195
  146. package/dist/views/FormSubmissions.js.map +1 -1
  147. package/dist/views/Forms.d.ts +11 -1
  148. package/dist/views/Forms.d.ts.map +1 -1
  149. package/dist/views/Forms.js +141 -93
  150. package/dist/views/Forms.js.map +1 -1
  151. package/dist/views/FormsSettings.d.ts +6 -1
  152. package/dist/views/FormsSettings.d.ts.map +1 -1
  153. package/dist/views/FormsSettings.js +434 -30
  154. package/dist/views/FormsSettings.js.map +1 -1
  155. package/dist/views/Jobs/DrawerReview.d.ts.map +1 -1
  156. package/dist/views/Jobs/DrawerReview.js +8 -7
  157. package/dist/views/Jobs/DrawerReview.js.map +1 -1
  158. package/dist/views/Jobs/NewBatchJob.d.ts.map +1 -1
  159. package/dist/views/Jobs/NewBatchJob.js +2 -1
  160. package/dist/views/Jobs/NewBatchJob.js.map +1 -1
  161. package/dist/views/SpamFolder.js +1 -1
  162. package/dist/views/SpamFolder.js.map +1 -1
  163. package/dist/views/dashboard/Delta.d.ts +7 -0
  164. package/dist/views/dashboard/Delta.d.ts.map +1 -0
  165. package/dist/views/dashboard/Delta.js +21 -0
  166. package/dist/views/dashboard/Delta.js.map +1 -0
  167. package/dist/views/dashboard/KpiCard.d.ts +22 -0
  168. package/dist/views/dashboard/KpiCard.d.ts.map +1 -0
  169. package/dist/views/dashboard/KpiCard.js +15 -0
  170. package/dist/views/dashboard/KpiCard.js.map +1 -0
  171. package/dist/views/dashboard/Sparkline.d.ts +11 -0
  172. package/dist/views/dashboard/Sparkline.d.ts.map +1 -0
  173. package/dist/views/dashboard/Sparkline.js +15 -0
  174. package/dist/views/dashboard/Sparkline.js.map +1 -0
  175. package/dist/views/dashboard/TrendChart.d.ts +8 -0
  176. package/dist/views/dashboard/TrendChart.d.ts.map +1 -0
  177. package/dist/views/dashboard/TrendChart.js +98 -0
  178. package/dist/views/dashboard/TrendChart.js.map +1 -0
  179. package/dist/views/dashboard/dashboard-date.d.ts +33 -0
  180. package/dist/views/dashboard/dashboard-date.d.ts.map +1 -0
  181. package/dist/views/dashboard/dashboard-date.js +136 -0
  182. package/dist/views/dashboard/dashboard-date.js.map +1 -0
  183. package/dist/views/entries/EntriesInbox.d.ts +8 -0
  184. package/dist/views/entries/EntriesInbox.d.ts.map +1 -0
  185. package/dist/views/entries/EntriesInbox.js +516 -0
  186. package/dist/views/entries/EntriesInbox.js.map +1 -0
  187. package/dist/views/entries/inbox-format.d.ts +27 -0
  188. package/dist/views/entries/inbox-format.d.ts.map +1 -0
  189. package/dist/views/entries/inbox-format.js +119 -0
  190. package/dist/views/entries/inbox-format.js.map +1 -0
  191. package/package.json +4 -4
  192. package/src/AdminRoot.tsx +7 -3
  193. package/src/__tests__/components/attribution-rows.test.ts +1 -1
  194. package/src/__tests__/components/date-range-picker.test.tsx +69 -0
  195. package/src/__tests__/components/form-build-model.test.ts +200 -0
  196. package/src/__tests__/components/form-build.test.tsx +157 -0
  197. package/src/__tests__/components/qa-a11y.render.test.tsx +1 -29
  198. package/src/__tests__/lib/batch-wizard.test.ts +2 -0
  199. package/src/__tests__/lib/forms-settings-normalize.test.ts +17 -0
  200. package/src/__tests__/views/dashboard.test.tsx +110 -32
  201. package/src/__tests__/views/form-editor.render.test.tsx +18 -10
  202. package/src/__tests__/views/form-entries.render.test.tsx +27 -9
  203. package/src/__tests__/views/form-submissions.render.test.tsx +15 -14
  204. package/src/__tests__/views/forms-list.render.test.tsx +157 -17
  205. package/src/__tests__/views/forms-settings.fixture.ts +32 -0
  206. package/src/__tests__/views/forms-settings.render.test.tsx +145 -0
  207. package/src/__tests__/views/inbox-format.test.ts +72 -0
  208. package/src/__tests__/views/jobs-wizard.render.test.tsx +18 -3
  209. package/src/__tests__/views/onboarding-block.render.test.tsx +9 -7
  210. package/src/components/forms/BlocklistDialog.tsx +552 -0
  211. package/src/components/forms/ExportMenu.tsx +8 -2
  212. package/src/components/forms/FieldOptions.tsx +629 -0
  213. package/src/components/forms/FormBuild.tsx +900 -0
  214. package/src/components/forms/FormsListTable.tsx +300 -0
  215. package/src/components/forms/form-build-model.ts +365 -0
  216. package/src/components/forms/form-build-ui.tsx +130 -0
  217. package/src/components/forms/primitives.tsx +6 -55
  218. package/src/components/ui/DateRangePicker.tsx +358 -0
  219. package/src/components/ui/Segmented.tsx +9 -2
  220. package/src/components/ui/StatusBadge.tsx +17 -4
  221. package/src/components/ui/Toggle.tsx +3 -0
  222. package/src/components/ui/UnderlineTabs.tsx +20 -9
  223. package/src/layout/Sidebar.tsx +4 -2
  224. package/src/lib/batch-wizard.ts +2 -2
  225. package/src/lib/entry-attribution.ts +94 -0
  226. package/src/lib/forms-service.ts +194 -0
  227. package/src/lib/job-drawer.ts +21 -1
  228. package/src/lib/job-view.ts +7 -0
  229. package/src/router/admin-routes.ts +1 -0
  230. package/src/styles/theme.css +86 -0
  231. package/src/views/Dashboard.tsx +1183 -772
  232. package/src/views/FormEditor.tsx +397 -199
  233. package/src/views/FormEntries.tsx +3 -422
  234. package/src/views/FormSubmissions.tsx +5 -411
  235. package/src/views/Forms.tsx +333 -321
  236. package/src/views/FormsSettings.tsx +1381 -73
  237. package/src/views/Jobs/DrawerReview.tsx +14 -8
  238. package/src/views/Jobs/NewBatchJob.tsx +5 -1
  239. package/src/views/SpamFolder.tsx +2 -2
  240. package/src/views/dashboard/Delta.tsx +44 -0
  241. package/src/views/dashboard/KpiCard.tsx +98 -0
  242. package/src/views/dashboard/Sparkline.tsx +51 -0
  243. package/src/views/dashboard/TrendChart.tsx +246 -0
  244. package/src/views/dashboard/dashboard-date.ts +168 -0
  245. package/src/views/entries/EntriesInbox.tsx +1277 -0
  246. package/src/views/entries/inbox-format.ts +128 -0
  247. package/dist/components/forms/EntriesTable.d.ts +0 -29
  248. package/dist/components/forms/EntriesTable.d.ts.map +0 -1
  249. package/dist/components/forms/EntriesTable.js +0 -29
  250. package/dist/components/forms/EntriesTable.js.map +0 -1
  251. package/dist/components/forms/FormEntryDetailPane.d.ts +0 -23
  252. package/dist/components/forms/FormEntryDetailPane.d.ts.map +0 -1
  253. package/dist/components/forms/FormEntryDetailPane.js +0 -208
  254. package/dist/components/forms/FormEntryDetailPane.js.map +0 -1
  255. package/dist/components/ui/PanelSection.d.ts +0 -16
  256. package/dist/components/ui/PanelSection.d.ts.map +0 -1
  257. package/dist/components/ui/PanelSection.js +0 -15
  258. package/dist/components/ui/PanelSection.js.map +0 -1
  259. package/src/components/forms/EntriesTable.tsx +0 -207
  260. package/src/components/forms/FormEntryDetailPane.tsx +0 -402
  261. package/src/components/ui/PanelSection.tsx +0 -53
@@ -1,54 +1,56 @@
1
1
  'use client'
2
2
 
3
3
  /**
4
- * Dashboard
5
- * ----------
6
- * Single-file, lean dashboard implementation. Two API calls only
7
- * (`/stats` + `/health`, both shared with the rest of the admin), everything
8
- * else derived client-side via `useMemo`. No charting libraries on this view
9
- * (the design uses plain progress bars + colored dots), keeping the bundle
10
- * and TTI cost low.
4
+ * Dashboard — period report (design_handoff_dashboard).
11
5
  *
12
- * Responsive layout (SHELL.md §8, cms-layouts.css):
13
- * ≤ 768px (mobile): stat cards 2-col (an odd last card spans both), main
14
- * grid stacks, quick actions scroll-x
15
- * 769–1024 (tablet): stat cards 2+3, main grid stacks
16
- * 1025–1399: stat cards 2+3, main grid is `1fr 320px`
17
- * ≥ 1400: stat cards in one row
6
+ * The page is driven by `/stats/dashboard`: pick a range and comparison and
7
+ * the KPIs, chart, tables and bars all recompute. Organic sessions and
8
+ * pageviews have no analytics source yet, so the endpoint returns them as
9
+ * null and those surfaces render the kit's "Connect analytics" state.
18
10
  */
19
11
 
20
- import { useEffect, useMemo, useState } from 'react'
21
- import { usePublicSiteUrl } from '../hooks/usePublicSiteUrl.js'
12
+ import { useEffect, useMemo, useState, type ReactNode } from 'react'
22
13
  import {
23
- FileText,
24
- File as FileIcon,
25
- Image as ImageIcon,
26
- ClipboardList,
27
- Search,
28
- Plus,
29
- Upload,
30
- Globe,
31
- ExternalLink,
32
14
  Activity,
15
+ AlertCircle,
33
16
  AlertTriangle,
34
17
  Clock,
35
- Zap,
36
18
  Database,
37
- ChevronRight,
38
- Loader2,
39
- TrendingUp,
40
- TrendingDown,
19
+ Download,
20
+ Eye,
21
+ FileText,
41
22
  Gauge,
42
- AlertCircle,
23
+ Globe,
24
+ Inbox,
25
+ Plus,
26
+ Search,
27
+ Target,
28
+ Zap,
43
29
  type LucideIcon,
44
30
  } from 'lucide-react'
45
31
  import { useApiData } from '../lib/useApiData.js'
46
32
  import { editPathForDoc } from '../lib/collection-routes.js'
47
33
  import { AuthorAvatar } from '../components/ui/AuthorAvatar.js'
48
- import { PanelSection, PANEL_LIST_ROW_CLASS } from '../components/ui/PanelSection.js'
34
+ import { DateRangePicker } from '../components/ui/DateRangePicker.js'
35
+ import { Button } from '../components/ui/Button.js'
49
36
  import { OnboardingBlock, shouldShowOnboarding } from './dashboard/OnboardingBlock.js'
50
37
  import type { OnboardingSignals } from './dashboard/OnboardingBlock.js'
51
38
  import { kpiCardSpan, kpiGridClass } from './dashboard/kpi-grid.js'
39
+ import {
40
+ comparisonFor,
41
+ dateKey,
42
+ inclusiveDays,
43
+ isCompareMode,
44
+ isMetricKey,
45
+ rangeFromUrlValue,
46
+ rangeLabel,
47
+ rangeToUrlValue,
48
+ type DashboardMetricKey,
49
+ type DashboardRange,
50
+ } from './dashboard/dashboard-date.js'
51
+ import { Delta, deltaPercent } from './dashboard/Delta.js'
52
+ import { KpiCard } from './dashboard/KpiCard.js'
53
+ import { TrendChart } from './dashboard/TrendChart.js'
52
54
 
53
55
  interface DashboardStats {
54
56
  totalDocuments: number
@@ -100,6 +102,45 @@ interface ContentHealthData {
100
102
  lastScanAt: string | null
101
103
  }
102
104
 
105
+ interface DashboardPoint {
106
+ date: string
107
+ v: number
108
+ }
109
+
110
+ type DashboardMetric = DashboardMetricKey
111
+
112
+ interface DashboardReport {
113
+ range: { start: string; end: string; days: number }
114
+ compareRange: { start: string; end: string } | null
115
+ analyticsConnected: boolean
116
+ series: Record<DashboardMetric, DashboardPoint[] | null>
117
+ compare: Record<DashboardMetric, DashboardPoint[] | null> | null
118
+ totals: Record<DashboardMetric, { cur: number | null; prev: number | null }>
119
+ topPages: {
120
+ path: string
121
+ title: string
122
+ docId?: string
123
+ collection?: string
124
+ sessions: number
125
+ sessionsPrev: number | null
126
+ entries: number
127
+ entriesPrev: number | null
128
+ }[]
129
+ entriesByForm: { slug: string; name: string; cur: number; prev: number | null }[]
130
+ unreadEntries: number
131
+ }
132
+
133
+ interface ScheduledData {
134
+ items: {
135
+ id: string
136
+ collection: string
137
+ title: string
138
+ scheduledFor: string
139
+ author: string
140
+ }[]
141
+ total: number
142
+ }
143
+
103
144
  interface CollectionMeta {
104
145
  slug: string
105
146
  type?: string
@@ -112,7 +153,14 @@ export interface DashboardProps {
112
153
  onNavigate?: (path: string) => void
113
154
  }
114
155
 
115
- // ─── helpers (kept top-level so they aren't re-created on every render) ──────
156
+ const METRIC_META: Record<DashboardMetric, { label: string; icon: LucideIcon }> = {
157
+ entries: { label: 'Form entries', icon: Inbox },
158
+ sessions: { label: 'Organic sessions', icon: Globe },
159
+ views: { label: 'Pageviews', icon: Eye },
160
+ published: { label: 'Content published', icon: FileText },
161
+ }
162
+
163
+ const number = new Intl.NumberFormat('en-US')
116
164
 
117
165
  function resolveCollections(config: any): CollectionMeta[] {
118
166
  if (!config?.collections) return []
@@ -146,16 +194,10 @@ function relativeTime(dateStr: string): string {
146
194
  function timeOfDayGreeting(): string {
147
195
  const h = new Date().getHours()
148
196
  if (h < 12) return 'Good morning'
149
- if (h < 17) return 'Good afternoon'
197
+ if (h < 18) return 'Good afternoon'
150
198
  return 'Good evening'
151
199
  }
152
200
 
153
- /**
154
- * Return the user's first name for the greeting. Falls back to the
155
- * email local-part, then a generic "there". Strips role-style names
156
- * like "Admin" / "Administrator" / "Editor" — a literal
157
- * `Good morning, Admin` reads as bot-output, not a person.
158
- */
159
201
  function firstNameForGreeting(session: any): string {
160
202
  const raw = (session?.user?.name ?? session?.name ?? '').trim()
161
203
  const email = session?.user?.email ?? session?.email
@@ -171,73 +213,112 @@ function firstNameForGreeting(session: any): string {
171
213
  return 'there'
172
214
  }
173
215
 
174
- function todayDateString(): string {
175
- return new Date().toLocaleDateString('en-US', {
176
- weekday: 'long',
177
- month: 'long',
178
- day: 'numeric',
179
- year: 'numeric',
180
- })
216
+ function statusBadge(status: string): { label: string; cls: string } {
217
+ switch (status) {
218
+ case 'PUBLISHED':
219
+ return { label: 'Published', cls: 'bg-[var(--suc-l)] text-[var(--suc)]' }
220
+ case 'DRAFT':
221
+ return { label: 'Draft', cls: 'bg-[var(--warn-l)] text-[var(--warn)]' }
222
+ case 'SCHEDULED':
223
+ return { label: 'Scheduled', cls: 'bg-[var(--bg)] text-[var(--sub)]' }
224
+ case 'IN_REVIEW':
225
+ return { label: 'In Review', cls: 'bg-[var(--info-l)] text-[var(--info)]' }
226
+ default:
227
+ return { label: status, cls: 'bg-[var(--bg)] text-[var(--sub)]' }
228
+ }
181
229
  }
182
230
 
183
- /**
184
- * Semantic state styling uses theme tokens (`success` / `warning` / `info`
185
- * / `brand`) so the dashboard tracks the design system in both light and
186
- * dark mode. One deliberate exception remains as raw values:
187
- * - Error states keep `text-red-*` / `bg-red-*`. The `--destructive`
188
- * token's dark value is intentionally dark (low contrast as TEXT on a
189
- * dark card), so tokenizing error text here would regress contrast.
190
- * Promoting error to a token is a separate, admin-wide change.
191
- * Author avatar colors moved to the shared `AuthorAvatar` component.
192
- */
193
- function statusBadge(status: string): {
194
- label: string
195
- cls: string
196
- } {
231
+ function activityVerb(status: string): string {
197
232
  switch (status) {
198
233
  case 'PUBLISHED':
199
- return { label: 'Published', cls: 'bg-success/10 text-success' }
234
+ return 'published'
200
235
  case 'DRAFT':
201
- return { label: 'Draft', cls: 'bg-muted text-muted-foreground' }
236
+ return 'saved as draft'
202
237
  case 'SCHEDULED':
203
- return { label: 'Scheduled', cls: 'bg-warn-l text-warning' }
238
+ return 'scheduled'
204
239
  case 'IN_REVIEW':
205
- return { label: 'In Review', cls: 'bg-info/10 text-info' }
240
+ return 'submitted for review'
206
241
  default:
207
- return { label: status, cls: 'bg-muted text-muted-foreground' }
242
+ return 'updated'
208
243
  }
209
244
  }
210
245
 
211
- interface StatCardData {
212
- label: string
213
- value: string
214
- unit?: string
215
- hint?: string
216
- hintUp?: boolean
217
- icon: LucideIcon
218
- iconBg: string
219
- iconColor: string
220
- href?: string
246
+ function userPreferenceKey(session: any): string {
247
+ const id =
248
+ session?.user?.id ?? session?.user?.email ?? session?.userId ?? session?.email ?? 'anon'
249
+ return `prenta.dashboard.${String(id)}`
221
250
  }
222
251
 
223
- // ─── Dashboard ───────────────────────────────────────────────────────────────
252
+ function readPreference(session: any): { range: string; compare: string; metric: string } | null {
253
+ try {
254
+ const raw = window.localStorage.getItem(userPreferenceKey(session))
255
+ if (!raw) return null
256
+ const parsed = JSON.parse(raw) as Record<string, unknown>
257
+ return {
258
+ range: typeof parsed.range === 'string' ? parsed.range : '28d',
259
+ compare: typeof parsed.compare === 'string' ? parsed.compare : 'prev',
260
+ metric: typeof parsed.metric === 'string' ? parsed.metric : 'entries',
261
+ }
262
+ } catch {
263
+ return null
264
+ }
265
+ }
266
+
267
+ function initialDashboardState(session: any): {
268
+ range: DashboardRange
269
+ metric: DashboardMetricKey
270
+ } {
271
+ const today = dateKey(new Date())
272
+ let range = rangeFromUrlValue('28d', today)!
273
+ let metric: DashboardMetricKey = 'entries'
274
+
275
+ if (typeof window !== 'undefined') {
276
+ const params = new URLSearchParams(window.location.search)
277
+ const preference = readPreference(session)
278
+ const urlRange = rangeFromUrlValue(params.get('range'), today)
279
+ const storedRange = preference ? rangeFromUrlValue(preference.range, today) : null
280
+ range = urlRange ?? storedRange ?? range
281
+ const compareValue = params.get('compare') ?? preference?.compare ?? range.compare
282
+ if (isCompareMode(compareValue)) range = { ...range, compare: compareValue }
283
+ const metricValue = params.get('metric') ?? preference?.metric ?? metric
284
+ if (isMetricKey(metricValue)) metric = metricValue
285
+ }
286
+
287
+ return { range, metric }
288
+ }
289
+
290
+ function csvCell(value: string | number | null): string {
291
+ if (value === null) return ''
292
+ const text = String(value)
293
+ return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
294
+ }
224
295
 
225
296
  export function Dashboard({ config, session, onNavigate }: DashboardProps) {
226
297
  const nav = (path: string) => onNavigate?.(path)
227
- // Cache responses for 30s so navigating away and back doesn't re-fire
228
- // all four dashboard requests on every visit. First load is unaffected
229
- // (cold cache) and each request still streams independently; `refetch`
230
- // (the Retry button) bypasses the cache.
231
298
  const DASH_CACHE_MS = 30_000
299
+ const [initial] = useState(() => initialDashboardState(session))
300
+ const [range, setRange] = useState<DashboardRange>(initial.range)
301
+ const [metric, setMetric] = useState<DashboardMetricKey>(initial.metric)
302
+
303
+ const reportEndpoint = `/stats/dashboard?start=${range.start}&end=${range.end}&compare=${range.compare}`
232
304
  const {
233
305
  data: stats,
234
- loading,
235
306
  error,
236
307
  exhausted,
237
308
  refetch,
238
309
  } = useApiData<DashboardStats>('/stats', null, {
239
310
  cacheMs: DASH_CACHE_MS,
240
311
  })
312
+ const { data: report, loading: reportLoading } = useApiData<DashboardReport>(
313
+ reportEndpoint,
314
+ null,
315
+ {
316
+ cacheMs: DASH_CACHE_MS,
317
+ },
318
+ )
319
+ const { data: scheduled } = useApiData<ScheduledData>('/stats/scheduled?limit=5', null, {
320
+ cacheMs: DASH_CACHE_MS,
321
+ })
241
322
  const { data: health } = useApiData<HealthData>('/health', null, { cacheMs: DASH_CACHE_MS })
242
323
  const { data: delivery, loading: deliveryLoading } = useApiData<DeliveryStats>(
243
324
  '/stats/api-delivery',
@@ -250,215 +331,80 @@ export function Dashboard({ config, session, onNavigate }: DashboardProps) {
250
331
  { cacheMs: DASH_CACHE_MS },
251
332
  )
252
333
 
253
- // A slow ticker (60s) so the greeting, calendar date, and "x minutes
254
- // ago" relative times stay correct on a dashboard left open for hours
255
- // — without it, a tab opened at 11:58am would read "Good morning" all
256
- // afternoon and show stale activity timestamps.
257
334
  const [now, setNow] = useState(() => Date.now())
258
335
  useEffect(() => {
259
336
  const id = setInterval(() => setNow(Date.now()), 60_000)
260
337
  return () => clearInterval(id)
261
338
  }, [])
262
339
 
263
- const greeting = useMemo(() => timeOfDayGreeting(), [now])
264
- const dateStr = useMemo(() => todayDateString(), [now])
265
- const userName = useMemo(() => firstNameForGreeting(session), [session])
266
-
267
- const collections = useMemo(() => resolveCollections(config), [config])
268
-
269
- // Hero CTA targets (mirrors the quick-action "New Post" resolution).
270
- const heroNewPostPath = useMemo(() => {
271
- const postTypes = collections.filter((c) => c.type === 'post')
272
- if (postTypes.length === 1) return `/${postTypes[0]!.slug}/new`
273
- return postTypes.length > 1 ? '/posts/new' : '/posts/types/new'
274
- }, [collections])
275
- const { siteUrl: resolvedSiteUrl, loading: siteUrlLoading } = usePublicSiteUrl(
276
- config?.site?.url ?? config?.seo?.siteUrl ?? null,
277
- )
278
- // Hide View Site while /site/public-url is in flight so the hero actions
279
- // don't flash when the resolved URL arrives after first paint.
280
- const siteUrl: string | null = siteUrlLoading || !resolvedSiteUrl ? null : resolvedSiteUrl
281
-
282
- // ── Stat cards ──────────────────────────────────────────────────────────
283
- const statCards: StatCardData[] = useMemo(() => {
284
- const counts = stats?.collectionCounts ?? {}
285
-
286
- // Prefer two real collections (the user's primary content types) over
287
- // hard-coded Posts/Pages so the dashboard adapts to admin-managed types.
288
- const primary: CollectionMeta[] = []
289
- const posts = collections.find((c) => c.slug === 'posts' || c.type === 'post')
290
- const pages = collections.find((c) => c.slug === 'pages' || c.type === 'page')
291
- if (posts) primary.push(posts)
292
- if (pages) primary.push(pages)
293
- if (primary.length < 2) {
294
- for (const c of collections) {
295
- if (primary.length >= 2) break
296
- if (!primary.includes(c)) primary.push(c)
340
+ // Applied range/metric round-trip through the URL and the per-user
341
+ // preference. replaceState keeps these changes out of the history stack.
342
+ useEffect(() => {
343
+ try {
344
+ const params = new URLSearchParams(window.location.search)
345
+ params.set('range', rangeToUrlValue(range))
346
+ params.set('compare', range.compare)
347
+ params.set('metric', metric)
348
+ const nextUrl = `${window.location.pathname}?${params.toString()}`
349
+ // Only write when something changed: Next's router intercepts
350
+ // replaceState as a navigation and remounts the admin panel, so an
351
+ // unconditional write here loops the page.
352
+ if (nextUrl !== `${window.location.pathname}${window.location.search}`) {
353
+ window.history.replaceState(null, '', nextUrl)
297
354
  }
355
+ window.localStorage.setItem(
356
+ userPreferenceKey(session),
357
+ JSON.stringify({ range: rangeToUrlValue(range), compare: range.compare, metric }),
358
+ )
359
+ } catch {
360
+ // Private-mode storage / non-browser test environments.
298
361
  }
362
+ }, [range, metric, session])
299
363
 
300
- const cards: StatCardData[] = []
301
-
302
- if (primary[0]) {
303
- cards.push({
304
- label: collectionLabel(primary[0]),
305
- value: String(counts[primary[0].slug] ?? 0),
306
- icon: primary[0].type === 'page' ? FileIcon : FileText,
307
- iconBg: 'bg-chart-1/15',
308
- iconColor: 'text-chart-1',
309
- href: `/${primary[0].slug}`,
310
- })
311
- } else {
312
- cards.push({
313
- label: 'Documents',
314
- value: String(stats?.totalDocuments ?? 0),
315
- icon: FileText,
316
- iconBg: 'bg-chart-1/15',
317
- iconColor: 'text-chart-1',
318
- })
319
- }
320
-
321
- if (primary[1]) {
322
- cards.push({
323
- label: collectionLabel(primary[1]),
324
- value: String(counts[primary[1].slug] ?? 0),
325
- icon: primary[1].type === 'page' ? FileIcon : FileText,
326
- iconBg: 'bg-chart-2/15',
327
- iconColor: 'text-chart-2',
328
- href: `/${primary[1].slug}`,
329
- })
330
- }
331
-
332
- cards.push({
333
- label: 'Media',
334
- value: String(stats?.totalMedia ?? 0),
335
- hint:
336
- stats && stats.totalMedia > 0
337
- ? `${stats.totalMedia} file${stats.totalMedia === 1 ? '' : 's'}`
338
- : undefined,
339
- icon: ImageIcon,
340
- iconBg: 'bg-chart-3/15',
341
- iconColor: 'text-chart-3',
342
- href: '/media',
343
- })
344
-
345
- // `formCount` in /stats is the *submission* count; the number of
346
- // forms is the count of `collection: forms` documents.
347
- const formsCount = stats?.formCount ?? counts['forms'] ?? 0
348
- const submissions = stats?.formSubmissionCount ?? 0
349
- cards.push({
350
- label: 'Forms',
351
- value: String(formsCount),
352
- hint: submissions > 0 ? `${submissions} response${submissions === 1 ? '' : 's'}` : undefined,
353
- icon: ClipboardList,
354
- iconBg: 'bg-chart-4/15',
355
- iconColor: 'text-chart-4',
356
- href: '/forms',
357
- })
358
-
359
- const seo = stats?.avgSeoScore ?? 0
360
- cards.push({
361
- label: 'SEO Score',
362
- value: seo > 0 ? String(seo) : '—',
363
- unit: seo > 0 ? '/100' : undefined,
364
- hint: seo > 0 ? (seo >= 70 ? 'Good' : seo >= 40 ? 'Fair' : 'Needs work') : 'No content yet',
365
- hintUp: seo >= 70,
366
- icon: Search,
367
- iconBg: 'bg-chart-5/15',
368
- iconColor: 'text-chart-5',
369
- href: '/seo',
370
- })
371
-
372
- return cards
373
- }, [stats, collections])
364
+ const greeting = useMemo(() => timeOfDayGreeting(), [now])
365
+ const userName = useMemo(() => firstNameForGreeting(session), [session])
366
+ const collections = useMemo(() => resolveCollections(config), [config])
374
367
 
375
- // ── Quick actions ───────────────────────────────────────────────────────
376
- // 5-button strip matching the reference dashboard. The "+ New Post" entry
377
- // intentionally duplicates the top-bar primary action: the top bar
378
- // surface is for chrome-level navigation, the quick-action row is the
379
- // dashboard's content-creation toolbar. Order mirrors the natural
380
- // authoring flow (post → page → media → form → integration).
381
368
  const quickActions = useMemo(() => {
382
369
  const postTypes = collections.filter((c) => c.type === 'post')
383
370
  const pages = collections.find((c) => c.slug === 'pages' || c.type === 'page')
384
371
  const pagesSlug = pages?.slug ?? 'pages'
385
- // "New Post": one Post Type → straight to its editor; several →
386
- // the picker; none → the Post Type setup instructions (avoids a
387
- // broken slug-based new URL).
388
372
  const newPostPath =
389
373
  postTypes.length === 1
390
374
  ? `/${postTypes[0]!.slug}/new`
391
375
  : postTypes.length > 1
392
376
  ? '/posts/new'
393
377
  : '/posts/types/new'
394
- const items: { label: string; icon: LucideIcon; onClick: () => void }[] = [
395
- {
396
- label: 'New Post',
397
- icon: Plus,
398
- onClick: () => nav(newPostPath),
399
- },
400
- { label: 'New Page', icon: Plus, onClick: () => nav(`/${pagesSlug}/new`) },
401
- { label: 'Upload Media', icon: Upload, onClick: () => nav('/media') },
402
- { label: 'New Form', icon: Plus, onClick: () => nav('/forms') },
403
- { label: 'View API', icon: Globe, onClick: () => nav('/settings?tab=api-keys') },
378
+ return [
379
+ { label: 'New Post', onClick: () => nav(newPostPath) },
380
+ { label: 'New Page', onClick: () => nav(`/${pagesSlug}/new`) },
381
+ { label: 'Upload Media', onClick: () => nav('/media') },
382
+ { label: 'New Form', onClick: () => nav('/forms') },
383
+ { label: 'Run SEO Audit', onClick: () => nav('/seo?run=1') },
404
384
  ]
405
- return items
406
- }, [collections, onNavigate]) // eslint-disable-line react-hooks/exhaustive-deps
385
+ // eslint-disable-next-line react-hooks/exhaustive-deps
386
+ }, [collections, onNavigate])
407
387
 
408
- // ── Recent activity ─────────────────────────────────────────────────────
409
- const [activityLimit, setActivityLimit] = useState(8)
410
388
  const activity = useMemo(() => {
411
389
  const docs = stats?.recentDocuments ?? []
412
- return docs.slice(0, activityLimit).map((d) => {
390
+ return docs.slice(0, 5).map((d) => {
413
391
  const col = collections.find((c) => c.slug === d.collection)
414
392
  return {
415
393
  ...d,
416
394
  typeLabel: col ? collectionLabel(col, false) : d.collection,
417
395
  relTime: relativeTime(d.updatedAt),
418
396
  statusInfo: statusBadge(d.status),
397
+ verb: activityVerb(d.status),
419
398
  editPath: editPathForDoc(col, d.collection, d.id),
420
399
  }
421
400
  })
422
- // `now` keeps the relative timestamps fresh on a long-open tab.
423
- // eslint-disable-next-line react-hooks/exhaustive-deps
424
- }, [stats, collections, activityLimit, now])
425
-
426
- // ── Publishing queue (scheduled docs only) ──────────────────────────────
427
- const publishQueue = useMemo(() => {
428
- const docs = stats?.recentDocuments ?? []
429
- return docs
430
- .filter((d) => d.status === 'SCHEDULED')
431
- .slice(0, 5)
432
- .map((d) => {
433
- const col = collections.find((c) => c.slug === d.collection)
434
- return {
435
- id: d.id,
436
- collection: d.collection,
437
- title: d.title || 'Untitled',
438
- type: col ? collectionLabel(col, false) : d.collection,
439
- date: relativeTime(d.updatedAt),
440
- author: d.author,
441
- editPath: editPathForDoc(col, d.collection, d.id),
442
- }
443
- })
444
401
  // eslint-disable-next-line react-hooks/exhaustive-deps
445
402
  }, [stats, collections, now])
446
403
 
447
- // ── Content health (sourced from /stats/content-health) ─────────────────
448
- // Persisted by the nightly content-health cron. The four issue rows
449
- // map 1:1 to ContentIssueType in the schema; the labels are
450
- // user-facing and intentionally read like the reference dashboard.
451
404
  const contentHealth = useMemo(() => {
452
405
  const counts = contentHealthData?.counts ?? {}
453
406
  const score = contentHealthData?.score ?? 100
454
- const label = contentHealthData?.label ?? 'Good'
455
- const tone: 'ok' | 'warn' | 'err' | 'muted' =
456
- score >= 70 ? 'ok' : score >= 40 ? 'warn' : score > 0 ? 'err' : 'muted'
457
-
458
- // Issue list — only render rows that have non-zero counts so the
459
- // card stays compact when the corpus is healthy. The empty state
460
- // below picks up when all four are zero.
461
- const issues: { kind: string; label: string; count: number; tone: 'warn' | 'err' }[] = []
407
+ const issues: { kind: string; label: string; count: number; dot: string }[] = []
462
408
  const missingMeta = counts['MISSING_META_DESCRIPTION'] ?? 0
463
409
  const brokenLinks = counts['BROKEN_INTERNAL_LINK'] ?? 0
464
410
  const missingAlt = counts['MISSING_ALT_TEXT'] ?? 0
@@ -468,55 +414,44 @@ export function Dashboard({ config, session, onNavigate }: DashboardProps) {
468
414
  kind: 'MISSING_META_DESCRIPTION',
469
415
  label: 'Missing meta descriptions',
470
416
  count: missingMeta,
471
- tone: 'warn',
417
+ dot: 'var(--warn)',
472
418
  })
473
419
  if (brokenLinks > 0)
474
420
  issues.push({
475
421
  kind: 'BROKEN_INTERNAL_LINK',
476
422
  label: 'Broken internal links',
477
423
  count: brokenLinks,
478
- tone: 'err',
424
+ dot: 'var(--err)',
479
425
  })
480
426
  if (missingAlt > 0)
481
427
  issues.push({
482
428
  kind: 'MISSING_ALT_TEXT',
483
429
  label: 'Missing alt text',
484
430
  count: missingAlt,
485
- tone: 'warn',
431
+ dot: 'var(--warn)',
486
432
  })
487
433
  if (outdated > 0)
488
434
  issues.push({
489
435
  kind: 'OUTDATED_CONTENT',
490
436
  label: 'Outdated content (90+ days)',
491
437
  count: outdated,
492
- tone: 'warn',
438
+ dot: 'var(--sub)',
493
439
  })
494
-
495
440
  return {
496
441
  score,
497
- label,
498
- tone,
442
+ label: contentHealthData?.label ?? 'Good',
499
443
  issues,
444
+ total: contentHealthData?.totalIssues ?? issues.reduce((sum, i) => sum + i.count, 0),
500
445
  hasData: contentHealthData !== null,
501
446
  loading: contentHealthLoading,
502
- } as const
447
+ }
503
448
  }, [contentHealthData, contentHealthLoading])
504
449
 
505
- const totalIssues = contentHealth.issues.reduce((s, i) => s + i.count, 0)
506
-
507
- // ── Onboarding (empty-site getting-started block) ───────────────────────
508
- // Signals come exclusively from data already fetched above (/stats +
509
- // /stats/api-delivery) — see OnboardingBlock.tsx for the per-step
510
- // derivation rationale. When the site is effectively empty (zero
511
- // posts+pages AND zero media) the onboarding block REPLACES the
512
- // Recent Activity / Publishing Queue / Content Health grid.
513
450
  const onboardingSignals: OnboardingSignals = useMemo(() => {
514
451
  const counts = stats?.collectionCounts ?? {}
515
452
  const contentCollections = collections.filter(
516
453
  (c) => c.type === 'post' || c.type === 'page' || c.slug === 'posts' || c.slug === 'pages',
517
454
  )
518
- // No post/page collections configured → fall back to the total document
519
- // count so a populated site never regresses to the onboarding view.
520
455
  const postsAndPagesCount =
521
456
  contentCollections.length > 0
522
457
  ? contentCollections.reduce((sum, c) => sum + (counts[c.slug] ?? 0), 0)
@@ -530,427 +465,973 @@ export function Dashboard({ config, session, onNavigate }: DashboardProps) {
530
465
  }
531
466
  }, [stats, collections, delivery])
532
467
 
533
- // Belt-and-braces: any recent activity means the site is not empty even
534
- // if collection counts are missing/stale, so never hide it behind
535
- // onboarding.
536
468
  const showOnboarding =
537
469
  stats !== null &&
538
470
  (stats.recentDocuments?.length ?? 0) === 0 &&
539
471
  shouldShowOnboarding(onboardingSignals)
540
472
 
541
- // ── Render ──────────────────────────────────────────────────────────────
473
+ const analyticsConnected = report?.analyticsConnected ?? false
474
+ const comparing = Boolean(report?.compareRange)
475
+ const comparisonRange = comparisonFor(range.compare, range.start, range.end)
476
+ const effectiveMetric: DashboardMetric =
477
+ (metric === 'sessions' || metric === 'views') && !analyticsConnected ? 'entries' : metric
478
+ const metricMeta = METRIC_META[effectiveMetric]
479
+ const totals = report?.totals
480
+ const entriesCur = totals?.entries.cur ?? 0
481
+ const entriesPrev = totals?.entries.prev ?? null
482
+ const sessionsCur = totals?.sessions.cur ?? null
483
+ const sessionsPrev = totals?.sessions.prev ?? null
484
+ const viewsCur = totals?.views.cur ?? null
485
+ const viewsPrev = totals?.views.prev ?? null
486
+ const publishedCur = totals?.published.cur ?? 0
487
+ const publishedPrev = totals?.published.prev ?? null
488
+ const convCur =
489
+ sessionsCur !== null && sessionsCur !== 0
490
+ ? (entriesCur / sessionsCur) * 100
491
+ : sessionsCur === 0
492
+ ? 0
493
+ : null
494
+ const convPrev =
495
+ sessionsPrev !== null && sessionsPrev !== 0 && entriesPrev !== null
496
+ ? (entriesPrev / sessionsPrev) * 100
497
+ : sessionsPrev === 0
498
+ ? 0
499
+ : null
542
500
 
543
- if (loading && !stats) {
544
- return (
545
- <div className="flex h-64 items-center justify-center p-4 sm:p-6">
546
- <Loader2 className="text-brand h-6 w-6 animate-spin" />
547
- </div>
501
+ const chartSeries = report?.series[effectiveMetric] ?? []
502
+ const chartCompare = report?.compare?.[effectiveMetric] ?? null
503
+ const chartCurTotal =
504
+ effectiveMetric === 'entries'
505
+ ? entriesCur
506
+ : effectiveMetric === 'published'
507
+ ? publishedCur
508
+ : effectiveMetric === 'sessions'
509
+ ? (sessionsCur ?? 0)
510
+ : (viewsCur ?? 0)
511
+ const chartPrevTotal =
512
+ effectiveMetric === 'entries'
513
+ ? entriesPrev
514
+ : effectiveMetric === 'published'
515
+ ? publishedPrev
516
+ : effectiveMetric === 'sessions'
517
+ ? sessionsPrev
518
+ : viewsPrev
519
+ const chartDelta = chartPrevTotal !== null ? deltaPercent(chartCurTotal, chartPrevTotal) : null
520
+ const chartAria =
521
+ chartDelta === null || !comparing
522
+ ? `${metricMeta.label}, ${number.format(chartCurTotal)} this period`
523
+ : `${metricMeta.label}, ${number.format(chartCurTotal)} this period, ${chartDelta >= 0 ? 'up' : 'down'} ${Math.abs(chartDelta).toFixed(1)}% from ${number.format(chartPrevTotal ?? 0)}`
524
+
525
+ const unread = report?.unreadEntries ?? 0
526
+
527
+ function exportCsv() {
528
+ if (!report) return
529
+ const lines: string[] = []
530
+ lines.push(
531
+ [
532
+ 'date',
533
+ 'entries',
534
+ 'entries_comparison',
535
+ 'sessions',
536
+ 'sessions_comparison',
537
+ 'pageviews',
538
+ 'pageviews_comparison',
539
+ 'published',
540
+ 'published_comparison',
541
+ ].join(','),
542
+ )
543
+ report.series.entries?.forEach((point, index) => {
544
+ lines.push(
545
+ [
546
+ point.date,
547
+ point.v,
548
+ report.compare?.entries?.[index]?.v ?? '',
549
+ report.series.sessions?.[index]?.v ?? '',
550
+ report.compare?.sessions?.[index]?.v ?? '',
551
+ report.series.views?.[index]?.v ?? '',
552
+ report.compare?.views?.[index]?.v ?? '',
553
+ report.series.published?.[index]?.v ?? '',
554
+ report.compare?.published?.[index]?.v ?? '',
555
+ ]
556
+ .map(csvCell)
557
+ .join(','),
558
+ )
559
+ })
560
+ lines.push('')
561
+ lines.push('measure,this_period,comparison')
562
+ lines.push(['Form entries', entriesCur, entriesPrev].map(csvCell).join(','))
563
+ lines.push(['Organic sessions', sessionsCur, sessionsPrev].map(csvCell).join(','))
564
+ lines.push(['Pageviews', viewsCur, viewsPrev].map(csvCell).join(','))
565
+ lines.push(
566
+ [
567
+ 'Entries / day',
568
+ (entriesCur / report.range.days).toFixed(1),
569
+ entriesPrev !== null ? (entriesPrev / report.range.days).toFixed(1) : '',
570
+ ]
571
+ .map(csvCell)
572
+ .join(','),
573
+ )
574
+ lines.push(
575
+ [
576
+ 'Conversion rate',
577
+ convCur !== null ? `${convCur.toFixed(2)}%` : '',
578
+ convPrev !== null ? `${convPrev.toFixed(2)}%` : '',
579
+ ]
580
+ .map(csvCell)
581
+ .join(','),
548
582
  )
583
+ lines.push('')
584
+ lines.push('path,title,sessions,sessions_comparison,entries,entries_comparison')
585
+ for (const page of report.topPages) {
586
+ lines.push(
587
+ [page.path, page.title, page.sessions, page.sessionsPrev, page.entries, page.entriesPrev]
588
+ .map(csvCell)
589
+ .join(','),
590
+ )
591
+ }
592
+
593
+ const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8' })
594
+ const url = URL.createObjectURL(blob)
595
+ const anchor = document.createElement('a')
596
+ anchor.href = url
597
+ anchor.download = `prenta-dashboard_${report.range.start}_${report.range.end}.csv`
598
+ anchor.click()
599
+ URL.revokeObjectURL(url)
549
600
  }
550
601
 
602
+ const kpis = [
603
+ {
604
+ key: 'entries' as const,
605
+ label: 'Form entries',
606
+ icon: Inbox,
607
+ value: number.format(entriesCur),
608
+ cur: entriesCur,
609
+ prev: entriesPrev,
610
+ prevLabel: entriesPrev !== null ? number.format(entriesPrev) : '',
611
+ series: report?.series.entries ?? [],
612
+ compareSeries: report?.compare?.entries ?? null,
613
+ selectable: true,
614
+ unavailable: false,
615
+ },
616
+ {
617
+ key: 'sessions' as const,
618
+ label: 'Organic sessions',
619
+ icon: Globe,
620
+ value: sessionsCur !== null ? number.format(sessionsCur) : '—',
621
+ cur: sessionsCur,
622
+ prev: sessionsPrev,
623
+ prevLabel: sessionsPrev !== null ? number.format(sessionsPrev) : '',
624
+ series: report?.series.sessions ?? null,
625
+ compareSeries: report?.compare?.sessions ?? null,
626
+ selectable: analyticsConnected,
627
+ unavailable: !analyticsConnected,
628
+ },
629
+ {
630
+ key: 'views' as const,
631
+ label: 'Pageviews',
632
+ icon: Eye,
633
+ value: viewsCur !== null ? number.format(viewsCur) : '—',
634
+ cur: viewsCur,
635
+ prev: viewsPrev,
636
+ prevLabel: viewsPrev !== null ? number.format(viewsPrev) : '',
637
+ series: report?.series.views ?? null,
638
+ compareSeries: report?.compare?.views ?? null,
639
+ selectable: analyticsConnected,
640
+ unavailable: !analyticsConnected,
641
+ },
642
+ {
643
+ key: 'published' as const,
644
+ label: 'Content published',
645
+ icon: FileText,
646
+ value: number.format(publishedCur),
647
+ cur: publishedCur,
648
+ prev: publishedPrev,
649
+ prevLabel: publishedPrev !== null ? number.format(publishedPrev) : '',
650
+ series: report?.series.published ?? [],
651
+ compareSeries: report?.compare?.published ?? null,
652
+ selectable: true,
653
+ unavailable: false,
654
+ },
655
+ ]
656
+
551
657
  return (
552
- <div className="w-full space-y-5 p-4 sm:p-6 lg:px-8">
553
- {/* Health banners ────────────────────────────────────────────── */}
554
- {health && health.status === 'degraded' && (
555
- <div className="border-info/30 bg-info/10 flex items-start gap-3 rounded-lg border p-4">
556
- <Database className="text-info mt-0.5 h-5 w-5 shrink-0" />
557
- <div className="min-w-0 flex-1">
558
- <span className="text-info text-sm font-medium">Database setup required</span>
559
- <p className="text-muted-foreground mt-0.5 text-xs">
560
- {!health.databaseConnected
561
- ? 'Cannot connect to the database. Check your DATABASE_URL environment variable.'
562
- : !health.secretConfigured
563
- ? 'CMS secret not configured. Set CMS_SECRET or CMS_SESSION_SECRET (min 32 characters).'
564
- : `Some CMS models are missing: ${Object.entries(health.models)
565
- .filter(([, v]) => !v)
566
- .map(([k]) => k)
567
- .join(', ')}. Run your database migrations.`}
568
- </p>
569
- </div>
570
- </div>
571
- )}
572
-
573
- {error && exhausted && (
574
- <div className="border-warning/30 bg-warn-l flex items-center gap-3 rounded-lg border p-4">
575
- <AlertTriangle className="text-warning h-5 w-5 shrink-0" />
576
- <span className="text-warning flex-1 text-sm">
577
- Some dashboard data may be unavailable.
578
- </span>
579
- <button
580
- onClick={refetch}
581
- className="border-warning/40 text-warning hover:bg-warn-l rounded-lg border px-3 py-1 text-sm transition-colors"
582
- >
583
- Retry
584
- </button>
585
- </div>
586
- )}
587
-
588
- {/* Hero greeting ─────────────────────────────────────────────────
589
- Per the design, the primary "+ New Post" and "View Site" actions
590
- sit on the right of the hero (`.dash-hdr` → `.dh-r`), not in the
591
- top bar. The quick-action row below keeps the wider authoring
592
- shortcuts. */}
593
- <div className="flex flex-wrap items-start justify-between gap-3">
594
- <div className="flex flex-col gap-1 sm:gap-0.5">
595
- <h1 className="text-foreground">
596
- {greeting}, {userName} <span aria-hidden>👋</span>
597
- </h1>
598
- {/* data-volatile: the literal date changes daily — visual tests mask it. */}
599
- <p className="text-muted-foreground text-sm" data-volatile>
600
- {dateStr}
601
- {totalIssues > 0 && (
602
- <span className="hidden sm:inline">
603
- {' · '}
604
- {totalIssues} content item{totalIssues === 1 ? '' : 's'} need attention
658
+ <div className="mx-auto w-full max-w-[1520px] p-[20px_24px_48px]">
659
+ <div className="flex flex-col gap-[14px]">
660
+ {health && health.status === 'degraded' && (
661
+ <div className="flex items-start gap-3 rounded-[10px] border border-[var(--info)] bg-[var(--info-l)] p-4">
662
+ <Database className="mt-0.5 h-5 w-5 shrink-0 text-[var(--info)]" aria-hidden />
663
+ <div className="min-w-0 flex-1">
664
+ <span className="text-sm font-medium text-[var(--info)]">
665
+ Database setup required
605
666
  </span>
606
- )}
607
- </p>
608
- </div>
609
- {/* Header actions collapse to icons at tablet and mobile; New Post
610
- floats above the tab bar on mobile. */}
611
- <div data-header-actions="" className="flex items-center gap-2">
612
- <button
613
- type="button"
614
- onClick={() => nav(heroNewPostPath)}
615
- data-variant="primary"
616
- data-fab=""
617
- className="bg-primary text-primary-foreground hover:bg-primary/90 focus-visible:ring-ring inline-flex items-center gap-1.5 rounded-lg px-3.5 py-1.5 text-sm font-medium shadow-sm transition-colors focus:outline-none focus-visible:ring-2"
618
- >
619
- <Plus className="h-3.5 w-3.5" aria-hidden />
620
- New Post
621
- </button>
622
- {siteUrl ? (
623
- <a
624
- href={siteUrl}
625
- target="_blank"
626
- rel="noopener noreferrer"
627
- data-variant="secondary"
628
- className="border-border bg-card text-foreground hover:bg-accent inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors"
629
- >
630
- <ExternalLink className="h-3.5 w-3.5" aria-hidden />
631
- View Site
632
- </a>
633
- ) : null}
634
- </div>
635
- </div>
667
+ <p className="mt-0.5 text-xs text-[var(--sub)]">
668
+ {!health.databaseConnected
669
+ ? 'Cannot connect to the database. Check your DATABASE_URL environment variable.'
670
+ : !health.secretConfigured
671
+ ? 'CMS secret not configured. Set CMS_SECRET or CMS_SESSION_SECRET (min 32 characters).'
672
+ : `Some CMS models are missing: ${Object.entries(health.models)
673
+ .filter(([, v]) => !v)
674
+ .map(([k]) => k)
675
+ .join(', ')}. Run your database migrations.`}
676
+ </p>
677
+ </div>
678
+ </div>
679
+ )}
636
680
 
637
- {/* Quick actions ──────────────────────────────────────────────── */}
638
- <div className="-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 [scrollbar-width:thin]">
639
- {quickActions.map((a) => (
640
- <button
641
- key={a.label}
642
- onClick={a.onClick}
643
- className="border-border bg-card hover:border-brand/50 hover:bg-brand/10 hover:text-brand inline-flex shrink-0 items-center gap-1.5 rounded-lg border px-3.5 py-2 text-sm shadow-sm transition-colors"
644
- >
645
- <a.icon className="h-3.5 w-3.5" />
646
- {a.label}
647
- </button>
648
- ))}
649
- </div>
681
+ {error && exhausted && (
682
+ <div className="flex items-center gap-3 rounded-[10px] border border-[var(--warn)] bg-[var(--warn-l)] p-4">
683
+ <AlertTriangle className="h-5 w-5 shrink-0 text-[var(--warn)]" aria-hidden />
684
+ <span className="flex-1 text-sm text-[var(--warn)]">
685
+ Some dashboard data may be unavailable.
686
+ </span>
687
+ <Button type="button" variant="secondary" size="sm" onClick={refetch}>
688
+ Retry
689
+ </Button>
690
+ </div>
691
+ )}
650
692
 
651
- {/* Stat cards ─────────────────────────────────────────────────── */}
652
- <div data-kpi-grid="" className={kpiGridClass(statCards.length)}>
653
- {statCards.map((card, index) => {
654
- const span = kpiCardSpan(index, statCards.length)
655
- const Inner = (
656
- <>
657
- <div
658
- className={`mb-3 flex h-8 w-8 items-center justify-center rounded-lg ${card.iconBg}`}
659
- >
660
- <card.icon className={`h-4 w-4 ${card.iconColor}`} />
661
- </div>
662
- <div className="flex items-baseline gap-1">
663
- <span className="text-foreground text-2xl leading-none font-medium tracking-tight">
664
- {card.value}
665
- </span>
666
- {card.unit && (
667
- <span className="text-muted-foreground text-sm font-medium">{card.unit}</span>
668
- )}
669
- </div>
670
- <p className="text-muted-foreground mt-1 text-xs">{card.label}</p>
671
- {card.hint && (
672
- <p
673
- className={`mt-1.5 text-[11px] ${card.hintUp ? 'text-success' : 'text-muted-foreground'}`}
674
- >
675
- {card.hint}
676
- </p>
693
+ <header className="mb-[4px] flex flex-wrap items-end gap-4">
694
+ <div>
695
+ <h1 className="text-[23px] leading-[1.15] font-bold tracking-[-0.6px] text-[var(--txt)]">
696
+ {greeting}, {userName}
697
+ </h1>
698
+ <p className="mt-1 text-[13px] text-[var(--sub)]">
699
+ {unread === 0 ? (
700
+ <>
701
+ No unread leads ·{' '}
702
+ <button
703
+ type="button"
704
+ className="text-[var(--acc)] hover:underline"
705
+ onClick={() => nav('/forms/entries?filter=unread')}
706
+ >
707
+ open the inbox
708
+ </button>
709
+ </>
710
+ ) : (
711
+ <>
712
+ {unread} unread lead{unread === 1 ? '' : 's'} waiting ·{' '}
713
+ <button
714
+ type="button"
715
+ className="text-[var(--acc)] hover:underline"
716
+ onClick={() => nav('/forms/entries?filter=unread')}
717
+ >
718
+ open the inbox
719
+ </button>
720
+ </>
677
721
  )}
678
- </>
679
- )
722
+ </p>
723
+ </div>
724
+ <div className="ml-auto flex flex-wrap items-center gap-2">
725
+ <DateRangePicker value={range} onChange={setRange} />
726
+ <Button
727
+ type="button"
728
+ variant="secondary"
729
+ aria-label="Export"
730
+ onClick={exportCsv}
731
+ disabled={!report}
732
+ className="h-11 px-[11px]"
733
+ leftIcon={<Download size={14} aria-hidden />}
734
+ >
735
+ <span className="max-[1024px]:hidden">Export</span>
736
+ </Button>
737
+ </div>
738
+ </header>
680
739
 
681
- return card.href ? (
740
+ <div className="grid [grid-template-columns:repeat(auto-fit,minmax(146px,1fr))] gap-2 max-[768px]:flex max-[768px]:overflow-x-auto max-[768px]:pb-1">
741
+ {quickActions.map((action) => (
682
742
  <button
683
- key={card.label}
743
+ key={action.label}
684
744
  type="button"
685
- onClick={() => nav(card.href!)}
686
- className={`bg-card border-border rounded-xl border p-4 text-left shadow-sm transition-shadow hover:shadow-md ${span}`}
745
+ onClick={action.onClick}
746
+ className="flex shrink-0 items-center gap-2 rounded-[9px] border border-[var(--bdr)] bg-[var(--card)] px-[13px] py-[11px] text-[13px] font-medium whitespace-nowrap text-[var(--txt)] transition hover:-translate-y-px hover:border-[var(--acc-m)] hover:bg-[var(--acc-l)] hover:text-[var(--acc)]"
687
747
  >
688
- {Inner}
748
+ <Plus size={14} className="shrink-0 text-[var(--acc)]" aria-hidden />
749
+ {action.label}
689
750
  </button>
690
- ) : (
691
- <div
692
- key={card.label}
693
- className={`bg-card border-border rounded-xl border p-4 shadow-sm ${span}`}
694
- >
695
- {Inner}
696
- </div>
697
- )
698
- })}
699
- </div>
751
+ ))}
752
+ </div>
700
753
 
701
- {/* Onboarding (empty site) or the main grid ──────────────────── */}
702
- {showOnboarding ? (
703
- <OnboardingBlock signals={onboardingSignals} onNavigate={onNavigate} />
704
- ) : (
705
- // One column up to 1024px (cms-layouts.css `.grid2`, tablet).
706
- <div className="not-narrow:grid-cols-[minmax(0,1fr)_320px] grid grid-cols-1 gap-4">
707
- {/* Recent Activity ───────────────────────────────────────── */}
708
- <PanelSection
709
- title="Recent Activity"
710
- description="Last 7 days across all content"
711
- action={
712
- (stats?.recentDocuments?.length ?? 0) > 8 ? (
713
- <button
714
- className="text-brand text-xs font-medium hover:underline"
715
- onClick={() => setActivityLimit((n) => (n >= 20 ? 8 : 20))}
754
+ <div data-kpi-grid="" className={kpiGridClass(5)}>
755
+ {reportLoading && !report
756
+ ? [0, 1, 2, 3, 4].map((index) => (
757
+ <div
758
+ key={index}
759
+ aria-hidden
760
+ className={`rounded-[10px] border border-[var(--bdr)] bg-[var(--card)] p-[14px_15px_10px] shadow-[var(--shd)] ${kpiCardSpan(index, 5)}`}
716
761
  >
717
- {activityLimit >= 20 ? 'Show less' : 'Show more'}
718
- </button>
719
- ) : undefined
720
- }
721
- >
722
- {activity.length === 0 ? (
723
- <EmptyState
724
- icon={Activity}
725
- title="No activity yet"
726
- subtitle="Content changes will appear here as your team works."
727
- />
728
- ) : (
729
- <ul role="list" className="divide-border divide-y">
730
- {activity.map((it) => (
731
- <li key={it.id}>
732
- <button
733
- type="button"
734
- onClick={() => nav(it.editPath)}
735
- className={PANEL_LIST_ROW_CLASS}
736
- >
737
- <div className="flex min-w-0 items-start gap-3">
738
- <AuthorAvatar name={it.author} size={28} className="mt-0.5" />
739
- <div className="min-w-0 flex-1">
740
- <p className="text-foreground truncate text-sm leading-snug">
741
- <span className="font-medium">
742
- &ldquo;{it.title || 'Untitled'}&rdquo;
743
- </span>{' '}
744
- <span className="text-muted-foreground">— {it.typeLabel}</span>
745
- </p>
746
- <div className="text-muted-foreground mt-1 flex flex-wrap items-center gap-2 text-[11px]">
747
- <span
748
- className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${it.statusInfo.cls}`}
749
- >
750
- {it.statusInfo.label}
751
- </span>
752
- <span className="max-w-[120px] truncate">{it.author}</span>
753
- <span aria-hidden>·</span>
754
- <span>{it.relTime}</span>
755
- </div>
756
- </div>
757
- </div>
758
- </button>
759
- </li>
760
- ))}
761
- </ul>
762
- )}
763
- </PanelSection>
764
-
765
- {/* Right column ─────────────────────────────────────────── */}
766
- <aside className="flex min-w-0 flex-col gap-4">
767
- {/* Publishing Queue */}
768
- <PanelSection
769
- title="Publishing Queue"
770
- description={`${publishQueue.length} item${publishQueue.length === 1 ? '' : 's'} scheduled`}
771
- action={
772
- <button
773
- className="text-brand text-xs font-medium hover:underline disabled:cursor-default disabled:no-underline disabled:opacity-50"
774
- disabled={publishQueue.length === 0}
775
- onClick={() => {
776
- const first = publishQueue[0]
777
- if (first) nav(first.editPath)
762
+ <div className="h-[14px] w-24 rounded bg-[var(--bg)]" />
763
+ <div className="mt-[10px] h-[32px] w-[70%] rounded bg-[var(--bg)]" />
764
+ <div className="mt-[10px] ml-auto h-[30px] w-[76px] rounded bg-[var(--bg)]" />
765
+ </div>
766
+ ))
767
+ : [
768
+ ...kpis.slice(0, 3),
769
+ {
770
+ key: 'conv' as const,
771
+ label: 'Conversion rate',
772
+ icon: Target,
773
+ value: convCur !== null ? convCur.toFixed(2) : '—',
774
+ unit: convCur !== null ? '%' : undefined,
775
+ cur: convCur,
776
+ prev: convPrev,
777
+ prevLabel: convPrev !== null ? `${convPrev.toFixed(2)}%` : '',
778
+ series: null,
779
+ compareSeries: null,
780
+ selectable: false,
781
+ unavailable: !analyticsConnected,
782
+ },
783
+ kpis[3]!,
784
+ ].map((kpi, index) => (
785
+ <KpiCard
786
+ key={kpi.key}
787
+ label={kpi.label}
788
+ icon={kpi.icon}
789
+ value={kpi.value}
790
+ unit={'unit' in kpi ? kpi.unit : undefined}
791
+ cur={kpi.cur}
792
+ prev={kpi.prev}
793
+ prevLabel={kpi.prevLabel}
794
+ compare={comparing}
795
+ series={kpi.series}
796
+ compareSeries={kpi.compareSeries}
797
+ selected={kpi.key === effectiveMetric}
798
+ selectable={kpi.selectable}
799
+ unavailable={kpi.unavailable}
800
+ onSelect={() => {
801
+ if (kpi.key !== 'conv') setMetric(kpi.key as DashboardMetric)
778
802
  }}
779
- >
780
- Manage
781
- </button>
782
- }
783
- >
784
- {publishQueue.length === 0 ? (
785
- <EmptyState
786
- icon={Clock}
787
- title="No scheduled content"
788
- subtitle="Scheduled posts and pages appear here."
789
- compact
803
+ onConnect={() => nav('/settings')}
804
+ spanClass={kpiCardSpan(index, 5)}
790
805
  />
791
- ) : (
792
- <ul role="list" className="divide-border divide-y">
793
- {publishQueue.map((q) => (
794
- <li key={q.id}>
806
+ ))}
807
+ </div>
808
+
809
+ <DashboardCard
810
+ title={`${metricMeta.label} over time`}
811
+ subtitle={`${report?.range.days ?? inclusiveDays(range.start, range.end)} days · ${rangeLabel(range.start, range.end)}${
812
+ comparing && comparisonRange
813
+ ? ` vs ${rangeLabel(comparisonRange[0], comparisonRange[1])}`
814
+ : ''
815
+ }`}
816
+ action={
817
+ <div className="flex flex-wrap items-center gap-[14px]">
818
+ <span className="flex items-center gap-[6px] text-[11.5px] text-[var(--sub)]">
819
+ <i className="block h-[3px] w-[14px] rounded-[2px] bg-[var(--acc)]" aria-hidden />
820
+ This period{' '}
821
+ <b className="ml-[2px] text-[var(--txt)]">{number.format(chartCurTotal)}</b>
822
+ </span>
823
+ {comparing ? (
824
+ <>
825
+ <span className="flex items-center gap-[6px] text-[11.5px] text-[var(--sub)]">
826
+ <i
827
+ className="block h-[2px] w-[14px] rounded-[2px] bg-[repeating-linear-gradient(90deg,var(--muted)_0_4px,transparent_4px_7px)]"
828
+ aria-hidden
829
+ />
830
+ Comparison{' '}
831
+ <b className="ml-[2px] text-[var(--sub)]">
832
+ {number.format(chartPrevTotal ?? 0)}
833
+ </b>
834
+ </span>
835
+ {chartPrevTotal !== null ? (
836
+ <Delta cur={chartCurTotal} prev={chartPrevTotal} />
837
+ ) : null}
838
+ </>
839
+ ) : null}
840
+ </div>
841
+ }
842
+ >
843
+ {reportLoading && !report ? (
844
+ <div className="relative px-2 pt-[14px] pb-1" aria-hidden>
845
+ <div className="flex h-[244px] flex-col justify-between py-3">
846
+ {[0, 1, 2, 3, 4].map((line) => (
847
+ <div key={line} className="h-px bg-[var(--bdr)]" />
848
+ ))}
849
+ </div>
850
+ </div>
851
+ ) : (
852
+ <TrendChart
853
+ cur={chartSeries}
854
+ prev={comparing ? chartCompare : null}
855
+ format={(value) => number.format(Math.round(value))}
856
+ ariaLabel={chartAria}
857
+ />
858
+ )}
859
+ </DashboardCard>
860
+
861
+ {showOnboarding ? (
862
+ <OnboardingBlock signals={onboardingSignals} onNavigate={onNavigate} />
863
+ ) : (
864
+ <>
865
+ <div className="grid gap-[14px] min-[1181px]:grid-cols-[1.45fr_1fr]">
866
+ <DashboardCard
867
+ title="Top landing pages"
868
+ subtitle="Sessions and entries, measured against the comparison period"
869
+ >
870
+ {!analyticsConnected ? (
871
+ <EmptyState
872
+ icon={Globe}
873
+ title="Analytics isn't connected"
874
+ subtitle="Connect analytics to see sessions and entries by landing page."
875
+ action={
795
876
  <button
796
877
  type="button"
797
- onClick={() => nav(q.editPath)}
798
- className={`${PANEL_LIST_ROW_CLASS} flex min-w-0 cursor-pointer items-center gap-2.5`}
878
+ onClick={() => nav('/settings')}
879
+ className="text-[12.5px] font-semibold text-[var(--acc)] hover:underline"
799
880
  >
800
- <span className="bg-warning h-2 w-2 shrink-0 rounded-full" aria-hidden />
801
- <div className="min-w-0 flex-1">
802
- <p className="text-foreground truncate text-sm font-medium">{q.title}</p>
803
- <p className="text-muted-foreground truncate text-[11px]">
804
- {q.date} · {q.author}
805
- </p>
806
- </div>
807
- <span className="border-border bg-background text-muted-foreground shrink-0 rounded border px-1.5 py-0.5 text-[10px] capitalize">
808
- {q.type}
809
- </span>
881
+ Connect analytics
810
882
  </button>
811
- </li>
812
- ))}
813
- </ul>
814
- )}
815
- </PanelSection>
816
-
817
- <PanelSection
818
- title="Content Health"
819
- description="SEO & quality issues"
820
- action={
821
- <button
822
- className="text-brand text-xs font-medium hover:underline"
823
- onClick={() => nav('/seo')}
824
- >
825
- Fix issues
826
- </button>
827
- }
828
- >
829
- <div className="px-6 pt-4 pb-2.5">
830
- <div className="mb-1.5 flex items-baseline justify-between">
831
- <p className="text-foreground text-2xl leading-none font-medium tracking-tight">
832
- {contentHealth.score > 0 ? contentHealth.score : '—'}
833
- {contentHealth.score > 0 && (
834
- <span className="text-muted-foreground ml-0.5 text-sm font-normal">/100</span>
835
- )}
836
- </p>
837
- <span
838
- className={`text-xs font-medium ${
839
- contentHealth.tone === 'ok'
840
- ? 'text-success'
841
- : contentHealth.tone === 'warn'
842
- ? 'text-warning'
843
- : contentHealth.tone === 'err'
844
- ? 'text-destructive dark:text-red-400'
845
- : 'text-muted-foreground'
846
- }`}
847
- >
848
- {contentHealth.label}
849
- </span>
850
- </div>
851
- <div className="bg-muted h-1.5 overflow-hidden rounded-full">
883
+ }
884
+ />
885
+ ) : report?.topPages.length ? (
852
886
  <div
853
- className={`h-full rounded-full transition-all ${
854
- contentHealth.tone === 'ok'
855
- ? 'bg-success'
856
- : contentHealth.tone === 'warn'
857
- ? 'bg-warning'
858
- : contentHealth.tone === 'err'
859
- ? 'bg-destructive'
860
- : 'bg-muted-foreground/40'
861
- }`}
862
- style={{ width: `${Math.max(0, Math.min(100, contentHealth.score))}%` }}
887
+ className="overflow-x-auto"
888
+ tabIndex={0}
889
+ role="region"
890
+ aria-label="Top landing pages table"
891
+ >
892
+ <table
893
+ className="w-full min-w-[560px] border-collapse"
894
+ aria-label="Top landing pages"
895
+ >
896
+ <thead>
897
+ <tr>
898
+ <th className="sticky left-0 bg-[var(--bg)] px-[14px] py-2 text-left text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
899
+ Page
900
+ </th>
901
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
902
+ Sessions
903
+ </th>
904
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
905
+ Entries
906
+ </th>
907
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
908
+ Conv.
909
+ </th>
910
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
911
+ Change
912
+ </th>
913
+ </tr>
914
+ </thead>
915
+ <tbody>
916
+ {report.topPages.map((page) => {
917
+ const col = page.collection
918
+ ? collections.find((item) => item.slug === page.collection)
919
+ : undefined
920
+ const pageCell = (
921
+ <>
922
+ <span className="block max-w-[280px] truncate text-[12.5px] font-medium text-[var(--txt)]">
923
+ {page.title}
924
+ </span>
925
+ <span className="mt-[1px] block font-mono text-[11px] text-[var(--sub)]">
926
+ {page.path}
927
+ </span>
928
+ </>
929
+ )
930
+ return (
931
+ <tr key={page.path} className="group hover:bg-[var(--bg)]">
932
+ <td className="sticky left-0 bg-[var(--card)] px-[14px] py-[10px] group-hover:bg-[var(--bg)]">
933
+ {page.docId ? (
934
+ <button
935
+ type="button"
936
+ className="block text-left"
937
+ onClick={() =>
938
+ nav(editPathForDoc(col, page.collection ?? '', page.docId!))
939
+ }
940
+ >
941
+ {pageCell}
942
+ </button>
943
+ ) : (
944
+ pageCell
945
+ )}
946
+ </td>
947
+ <td className="px-[14px] py-[10px] text-right align-middle tabular-nums">
948
+ <span className="text-[13.5px] font-[650] text-[var(--txt)]">
949
+ {number.format(page.sessions)}
950
+ </span>
951
+ {comparing && page.sessionsPrev !== null ? (
952
+ <div className="text-[11px] text-[var(--sub)]">
953
+ was {number.format(page.sessionsPrev)}
954
+ </div>
955
+ ) : null}
956
+ </td>
957
+ <td className="px-[14px] py-[10px] text-right align-middle tabular-nums">
958
+ <span className="text-[13.5px] font-[650] text-[var(--txt)]">
959
+ {number.format(page.entries)}
960
+ </span>
961
+ {comparing && page.entriesPrev !== null ? (
962
+ <div className="text-[11px] text-[var(--sub)]">
963
+ was {number.format(page.entriesPrev)}
964
+ </div>
965
+ ) : null}
966
+ </td>
967
+ <td className="px-[14px] py-[10px] text-right text-[13.5px] font-[650] text-[var(--txt)] tabular-nums">
968
+ {page.sessions
969
+ ? ((page.entries / page.sessions) * 100).toFixed(2)
970
+ : '0.00'}
971
+ %
972
+ </td>
973
+ <td className="px-[14px] py-[10px] text-right">
974
+ {comparing && page.sessionsPrev !== null ? (
975
+ <Delta cur={page.sessions} prev={page.sessionsPrev} />
976
+ ) : (
977
+ <span className="text-[11px] text-[var(--sub)]">—</span>
978
+ )}
979
+ </td>
980
+ </tr>
981
+ )
982
+ })}
983
+ </tbody>
984
+ </table>
985
+ </div>
986
+ ) : (
987
+ <EmptyState
988
+ icon={Search}
989
+ title="No landing pages yet"
990
+ subtitle="Pages with sessions in this period will appear here."
863
991
  />
864
- </div>
865
- </div>
866
- {contentHealth.issues.length === 0 ? (
867
- <div className="text-muted-foreground px-6 pt-1 pb-4 text-xs">
868
- No outstanding issues. Nice work.
869
- </div>
870
- ) : (
871
- <ul role="list" className="divide-border divide-y">
872
- {contentHealth.issues.map((iss, i) => (
873
- <li key={i}>
992
+ )}
993
+ </DashboardCard>
994
+
995
+ <DashboardCard
996
+ title="Entries by form"
997
+ subtitle="Solid bar this period, grey bar comparison"
998
+ >
999
+ <div className="flex flex-col gap-[13px] px-4 pt-3 pb-[14px]">
1000
+ {(report?.entriesByForm ?? []).map((form) => {
1001
+ const max = Math.max(
1002
+ ...(report?.entriesByForm.map((item) =>
1003
+ Math.max(item.cur, item.prev ?? 0),
1004
+ ) ?? [1]),
1005
+ 1,
1006
+ )
1007
+ return (
874
1008
  <button
1009
+ key={form.slug || form.name}
875
1010
  type="button"
876
- onClick={() => nav('/seo')}
877
- className={`${PANEL_LIST_ROW_CLASS} flex items-center gap-2.5 py-3.5`}
1011
+ onClick={() => nav(`/forms/entries?form=${encodeURIComponent(form.slug)}`)}
1012
+ className="block w-full text-left"
878
1013
  >
879
- <span
880
- className={`h-1.5 w-1.5 shrink-0 rounded-full ${
881
- iss.tone === 'err'
882
- ? 'bg-destructive'
883
- : iss.tone === 'warn'
884
- ? 'bg-warning'
885
- : 'bg-muted-foreground'
886
- }`}
887
- aria-hidden
888
- />
889
- <span className="text-muted-foreground flex-1 truncate text-xs">
890
- {iss.label}
891
- </span>
892
- <span
893
- className={`shrink-0 text-sm font-medium ${
894
- iss.tone === 'err'
895
- ? 'text-destructive dark:text-red-400'
896
- : iss.tone === 'warn'
897
- ? 'text-warning'
898
- : 'text-muted-foreground'
899
- }`}
900
- >
901
- {iss.count}
902
- </span>
903
- <ChevronRight className="text-muted-foreground/60 h-3.5 w-3.5 shrink-0" />
1014
+ <div className="flex items-baseline gap-2 text-[12.5px]">
1015
+ <b className="font-[550] text-[var(--txt)]">{form.name}</b>
1016
+ {comparing && form.prev !== null ? (
1017
+ <Delta cur={form.cur} prev={form.prev} />
1018
+ ) : null}
1019
+ <span className="ml-auto text-[13px] font-bold text-[var(--txt)] tabular-nums">
1020
+ {number.format(form.cur)}
1021
+ </span>
1022
+ </div>
1023
+ <div className="relative mt-[6px] h-4">
1024
+ {comparing && form.prev !== null ? (
1025
+ <div
1026
+ className="absolute top-0 left-0 h-[6px] rounded-full bg-[var(--bdr)]"
1027
+ style={{ width: `${(form.prev / max) * 100}%` }}
1028
+ aria-hidden
1029
+ />
1030
+ ) : null}
1031
+ <div
1032
+ className="absolute left-0 h-2 rounded-full bg-[var(--acc)] transition-[width] duration-300"
1033
+ style={{
1034
+ width: `${(form.cur / max) * 100}%`,
1035
+ top: comparing ? 8 : 4,
1036
+ }}
1037
+ aria-hidden
1038
+ />
1039
+ </div>
904
1040
  </button>
905
- </li>
906
- ))}
907
- </ul>
908
- )}
909
- </PanelSection>
910
- </aside>
1041
+ )
1042
+ })}
1043
+ {(report?.entriesByForm.length ?? 0) === 0 ? (
1044
+ <p className="py-4 text-center text-[12.5px] text-[var(--sub)]">
1045
+ No forms yet. Entries will be grouped here once a form exists.
1046
+ </p>
1047
+ ) : null}
1048
+ </div>
1049
+ </DashboardCard>
1050
+ </div>
1051
+
1052
+ <div className="grid gap-[14px] min-[1181px]:grid-cols-[1.45fr_1fr]">
1053
+ <DashboardCard
1054
+ title="Recent activity"
1055
+ subtitle="Across all content types"
1056
+ action={
1057
+ <button
1058
+ type="button"
1059
+ className="text-[12.5px] text-[var(--acc)] hover:underline"
1060
+ onClick={() => nav('/posts')}
1061
+ >
1062
+ View all
1063
+ </button>
1064
+ }
1065
+ >
1066
+ {activity.length === 0 ? (
1067
+ <EmptyState
1068
+ icon={Activity}
1069
+ title="No activity yet"
1070
+ subtitle="Content changes will appear here as your team works."
1071
+ />
1072
+ ) : (
1073
+ <ul role="list">
1074
+ {activity.map((item) => (
1075
+ <li key={item.id} className="border-b border-[var(--bdr)] last:border-b-0">
1076
+ <button
1077
+ type="button"
1078
+ onClick={() => nav(item.editPath)}
1079
+ className="flex w-full items-start gap-[11px] px-4 py-[10px] text-left transition hover:bg-[var(--bg)]"
1080
+ >
1081
+ <AuthorAvatar name={item.author} size={28} className="shrink-0" />
1082
+ <span className="min-w-0 flex-1">
1083
+ <span className="block truncate text-[13px] font-medium text-[var(--txt)]">
1084
+ {item.title || 'Untitled'}
1085
+ </span>
1086
+ <span className="mt-[2px] block text-[11.5px] text-[var(--sub)]">
1087
+ {item.typeLabel} {item.verb} by {item.author}
1088
+ </span>
1089
+ </span>
1090
+ <span className="flex shrink-0 flex-col items-end gap-1">
1091
+ <span
1092
+ className={`inline-flex rounded-[4px] px-[6px] py-[1.5px] text-[10px] font-bold tracking-[0.2px] ${item.statusInfo.cls}`}
1093
+ >
1094
+ {item.statusInfo.label}
1095
+ </span>
1096
+ <span className="text-[11px] text-[var(--sub)]">
1097
+ {item.relTime === 'Yesterday' ||
1098
+ item.relTime === 'just now' ||
1099
+ item.relTime.endsWith(' ago') ||
1100
+ item.relTime.includes('/')
1101
+ ? item.relTime
1102
+ : `${item.relTime} ago`}
1103
+ </span>
1104
+ </span>
1105
+ </button>
1106
+ </li>
1107
+ ))}
1108
+ </ul>
1109
+ )}
1110
+ </DashboardCard>
1111
+
1112
+ <DashboardCard title="Period summary" subtitle={rangeLabel(range.start, range.end)}>
1113
+ <div
1114
+ className="overflow-x-auto"
1115
+ tabIndex={0}
1116
+ role="region"
1117
+ aria-label="Period summary table"
1118
+ >
1119
+ <table
1120
+ className="w-full min-w-[420px] border-collapse"
1121
+ aria-label="Period summary"
1122
+ >
1123
+ <thead>
1124
+ <tr>
1125
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-left text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
1126
+ Measure
1127
+ </th>
1128
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
1129
+ This period
1130
+ </th>
1131
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
1132
+ Comparison
1133
+ </th>
1134
+ <th className="bg-[var(--bg)] px-[14px] py-2 text-right text-[10px] font-bold tracking-[0.6px] text-[var(--sub)] uppercase">
1135
+ Δ
1136
+ </th>
1137
+ </tr>
1138
+ </thead>
1139
+ <tbody>
1140
+ {[
1141
+ {
1142
+ label: 'Form entries',
1143
+ cur: entriesCur,
1144
+ prev: entriesPrev,
1145
+ fmt: (value: number) => number.format(Math.round(value)),
1146
+ },
1147
+ {
1148
+ label: 'Organic sessions',
1149
+ cur: sessionsCur,
1150
+ prev: sessionsPrev,
1151
+ fmt: (value: number) => number.format(Math.round(value)),
1152
+ },
1153
+ {
1154
+ label: 'Pageviews',
1155
+ cur: viewsCur,
1156
+ prev: viewsPrev,
1157
+ fmt: (value: number) => number.format(Math.round(value)),
1158
+ },
1159
+ {
1160
+ label: 'Entries / day',
1161
+ cur:
1162
+ entriesCur /
1163
+ (report?.range.days ?? inclusiveDays(range.start, range.end)),
1164
+ prev:
1165
+ entriesPrev !== null
1166
+ ? entriesPrev /
1167
+ (report?.range.days ?? inclusiveDays(range.start, range.end))
1168
+ : null,
1169
+ fmt: (value: number) => value.toFixed(1),
1170
+ },
1171
+ {
1172
+ label: 'Conversion rate',
1173
+ cur: convCur,
1174
+ prev: convPrev,
1175
+ fmt: (value: number) => `${value.toFixed(2)}%`,
1176
+ },
1177
+ ].map((row) => (
1178
+ <tr key={row.label} className="hover:bg-[var(--bg)]">
1179
+ <td className="px-[14px] py-[10px] text-[13px] text-[var(--sub)]">
1180
+ {row.label}
1181
+ </td>
1182
+ <td className="px-[14px] py-[10px] text-right text-[13.5px] font-[650] text-[var(--txt)] tabular-nums">
1183
+ {row.cur !== null ? row.fmt(row.cur) : '—'}
1184
+ </td>
1185
+ <td className="px-[14px] py-[10px] text-right text-[11px] text-[var(--sub)] tabular-nums">
1186
+ {comparing && row.prev !== null ? row.fmt(row.prev) : '—'}
1187
+ </td>
1188
+ <td className="px-[14px] py-[10px] text-right">
1189
+ {comparing && row.cur !== null && row.prev !== null ? (
1190
+ <Delta cur={row.cur} prev={row.prev} />
1191
+ ) : (
1192
+ <span className="text-[11px] text-[var(--sub)]">—</span>
1193
+ )}
1194
+ </td>
1195
+ </tr>
1196
+ ))}
1197
+ </tbody>
1198
+ </table>
1199
+ </div>
1200
+ </DashboardCard>
1201
+ </div>
1202
+
1203
+ <div className="grid gap-[14px] min-[821px]:max-[1180px]:grid-cols-2 min-[1181px]:grid-cols-3">
1204
+ <DashboardCard
1205
+ title="Content health"
1206
+ subtitle="SEO & quality issues"
1207
+ action={
1208
+ <button
1209
+ type="button"
1210
+ className="text-[12.5px] text-[var(--acc)] hover:underline"
1211
+ onClick={() => nav('/seo')}
1212
+ >
1213
+ Open SEO
1214
+ </button>
1215
+ }
1216
+ >
1217
+ <div className="flex items-center gap-[14px] border-b border-[var(--bdr)] px-4 py-[15px]">
1218
+ <HealthRing score={contentHealth.score} />
1219
+ <div>
1220
+ <div className="text-[13.5px] font-semibold text-[var(--txt)]">
1221
+ {contentHealth.score}/100 · {contentHealth.label}
1222
+ </div>
1223
+ <div className="mt-[3px] text-[11.5px] leading-[1.5] text-[var(--sub)]">
1224
+ {contentHealth.total} issues across {contentHealth.issues.length} categories
1225
+ </div>
1226
+ </div>
1227
+ </div>
1228
+ {contentHealth.loading && !contentHealth.hasData ? (
1229
+ <div className="flex flex-col gap-2 px-4 py-3" aria-hidden>
1230
+ {[0, 1, 2].map((row) => (
1231
+ <div key={row} className="h-[18px] rounded bg-[var(--bg)]" />
1232
+ ))}
1233
+ </div>
1234
+ ) : contentHealth.issues.length === 0 ? (
1235
+ <p className="px-4 py-4 text-[12.5px] text-[var(--sub)]">
1236
+ No outstanding issues. Nice work.
1237
+ </p>
1238
+ ) : (
1239
+ contentHealth.issues.map((issue) => (
1240
+ <button
1241
+ key={issue.kind}
1242
+ type="button"
1243
+ onClick={() => nav('/seo')}
1244
+ className="flex w-full items-center gap-[9px] border-b border-[var(--bdr)] px-4 py-[9px] text-left text-[12.5px] text-[var(--sub)] transition last:border-b-0 hover:bg-[var(--bg)]"
1245
+ >
1246
+ <span
1247
+ className="h-[7px] w-[7px] shrink-0 rounded-full"
1248
+ style={{ background: issue.dot }}
1249
+ aria-hidden
1250
+ />
1251
+ {issue.label}
1252
+ <b className="ml-auto font-bold text-[var(--txt)] tabular-nums">
1253
+ {issue.count}
1254
+ </b>
1255
+ </button>
1256
+ ))
1257
+ )}
1258
+ </DashboardCard>
1259
+
1260
+ <DashboardCard
1261
+ title="Delivery API"
1262
+ subtitle="Headless content delivery · last 24 hours"
1263
+ action={
1264
+ <button
1265
+ type="button"
1266
+ className="text-[12.5px] text-[var(--acc)] hover:underline"
1267
+ onClick={() => nav('/settings?tab=api-keys')}
1268
+ >
1269
+ API docs
1270
+ </button>
1271
+ }
1272
+ >
1273
+ <DeliveryGrid delivery={delivery} loading={deliveryLoading} />
1274
+ </DashboardCard>
1275
+
1276
+ <div className="min-[821px]:max-[1180px]:col-span-full">
1277
+ <DashboardCard
1278
+ title="Publishing queue"
1279
+ subtitle={`${scheduled?.total ?? 0} items scheduled`}
1280
+ action={
1281
+ <button
1282
+ type="button"
1283
+ className="text-[12.5px] text-[var(--acc)] hover:underline"
1284
+ onClick={() => nav('/posts?status=scheduled')}
1285
+ >
1286
+ Manage
1287
+ </button>
1288
+ }
1289
+ >
1290
+ {(scheduled?.items.length ?? 0) === 0 ? (
1291
+ <EmptyState
1292
+ icon={Clock}
1293
+ title="No scheduled content"
1294
+ subtitle="Scheduled posts and pages appear here."
1295
+ compact
1296
+ />
1297
+ ) : (
1298
+ <ul role="list">
1299
+ {scheduled!.items.map((item) => {
1300
+ const col = collections.find((entry) => entry.slug === item.collection)
1301
+ const date = new Date(item.scheduledFor)
1302
+ return (
1303
+ <li
1304
+ key={item.id}
1305
+ className="border-b border-[var(--bdr)] last:border-b-0"
1306
+ >
1307
+ <button
1308
+ type="button"
1309
+ onClick={() => nav(editPathForDoc(col, item.collection, item.id))}
1310
+ className="flex w-full items-center gap-[11px] px-4 py-[11px] text-left transition hover:bg-[var(--bg)]"
1311
+ >
1312
+ <span className="w-[42px] shrink-0 rounded-[8px] bg-[var(--acc-l)] px-0 py-[5px] text-center leading-[1.1]">
1313
+ <b className="block text-[15px] font-bold text-[var(--acc)]">
1314
+ {date.getDate()}
1315
+ </b>
1316
+ <span className="block text-[9.5px] font-bold tracking-[0.5px] text-[var(--acc)] uppercase opacity-75">
1317
+ {date.toLocaleDateString('en-US', { month: 'short' })}
1318
+ </span>
1319
+ </span>
1320
+ <span className="min-w-0">
1321
+ <span className="block truncate text-[13px] font-medium text-[var(--txt)]">
1322
+ {item.title}
1323
+ </span>
1324
+ <span className="mt-[2px] block truncate text-[11.5px] text-[var(--sub)]">
1325
+ {col ? collectionLabel(col, false) : item.collection} ·{' '}
1326
+ {item.author}
1327
+ </span>
1328
+ </span>
1329
+ </button>
1330
+ </li>
1331
+ )
1332
+ })}
1333
+ </ul>
1334
+ )}
1335
+ </DashboardCard>
1336
+ </div>
1337
+ </div>
1338
+ </>
1339
+ )}
1340
+ </div>
1341
+ </div>
1342
+ )
1343
+ }
1344
+
1345
+ function DashboardCard({
1346
+ title,
1347
+ subtitle,
1348
+ action,
1349
+ children,
1350
+ }: {
1351
+ title: string
1352
+ subtitle?: string
1353
+ action?: ReactNode
1354
+ children: ReactNode
1355
+ }) {
1356
+ return (
1357
+ <section className="overflow-hidden rounded-[10px] border border-[var(--bdr)] bg-[var(--card)] shadow-[var(--shd)]">
1358
+ <header className="flex items-center gap-[10px] border-b border-[var(--bdr)] px-4 py-[13px]">
1359
+ <div className="min-w-0">
1360
+ <h2 className="text-[14px] font-semibold text-[var(--txt)]">{title}</h2>
1361
+ {subtitle ? <p className="mt-[2px] text-[11.5px] text-[var(--sub)]">{subtitle}</p> : null}
911
1362
  </div>
912
- )}
913
-
914
- {/* Delivery API ──────────────────────────────────────────────────
915
- Headless content delivery metrics aggregated over the last
916
- 24h from `prenta_api_request_metrics`. Populated in real-time
917
- by the request logger in handler-factory.ts — no cron
918
- required. Empty-state messaging differentiates "we haven't
919
- collected enough data yet" from "we have data and it shows
920
- 0" so editors don't think the dashboard is broken on a
921
- quiet weekend. */}
922
- <PanelSection
923
- title="Delivery API"
924
- description="Headless content delivery · last 24 hours"
925
- action={
926
- <button
927
- className="text-brand inline-flex items-center gap-1 text-xs font-medium hover:underline"
928
- onClick={() => nav('/settings?tab=api-keys')}
929
- >
930
- API docs <ExternalLink className="h-3 w-3" />
931
- </button>
932
- }
1363
+ {action ? <div className="ml-auto">{action}</div> : null}
1364
+ </header>
1365
+ {children}
1366
+ </section>
1367
+ )
1368
+ }
1369
+
1370
+ function HealthRing({ score }: { score: number }) {
1371
+ const radius = 26
1372
+ const circumference = 2 * Math.PI * radius
1373
+ const color = score >= 70 ? 'var(--suc)' : score >= 40 ? 'var(--warn)' : 'var(--err)'
1374
+ return (
1375
+ <div className="relative h-16 w-16 shrink-0" aria-hidden>
1376
+ <svg width="64" height="64">
1377
+ <circle cx="32" cy="32" r={radius} fill="none" stroke="var(--bdr)" strokeWidth="6" />
1378
+ <circle
1379
+ cx="32"
1380
+ cy="32"
1381
+ r={radius}
1382
+ fill="none"
1383
+ stroke={color}
1384
+ strokeWidth="6"
1385
+ strokeLinecap="round"
1386
+ strokeDasharray={circumference}
1387
+ strokeDashoffset={circumference * (1 - Math.max(0, Math.min(100, score)) / 100)}
1388
+ transform="rotate(-90 32 32)"
1389
+ />
1390
+ </svg>
1391
+ <div
1392
+ className="absolute inset-0 flex items-center justify-center text-[20px] font-bold tracking-[-0.5px]"
1393
+ style={{ color }}
933
1394
  >
934
- <DeliveryGrid delivery={delivery} loading={deliveryLoading} />
935
- </PanelSection>
1395
+ {score}
1396
+ </div>
936
1397
  </div>
937
1398
  )
938
1399
  }
939
1400
 
940
- // ─── Delivery API grid ──────────────────────────────────────────────────────
1401
+ function EmptyState({
1402
+ icon: Icon,
1403
+ title,
1404
+ subtitle,
1405
+ compact = false,
1406
+ action,
1407
+ }: {
1408
+ icon: LucideIcon
1409
+ title: string
1410
+ subtitle: string
1411
+ compact?: boolean
1412
+ action?: ReactNode
1413
+ }) {
1414
+ return (
1415
+ <div
1416
+ className={`flex flex-col items-center justify-center gap-1.5 text-center ${compact ? 'px-4 py-6' : 'px-6 py-10'}`}
1417
+ >
1418
+ <Icon className="mb-1 h-7 w-7 text-[var(--muted)]" aria-hidden />
1419
+ <p className="text-sm font-medium text-[var(--txt)]">{title}</p>
1420
+ <p className="max-w-xs text-xs text-[var(--sub)]">{subtitle}</p>
1421
+ {action}
1422
+ </div>
1423
+ )
1424
+ }
941
1425
 
942
1426
  function DeliveryGrid({ delivery, loading }: { delivery: DeliveryStats | null; loading: boolean }) {
943
1427
  if (loading && !delivery) {
944
1428
  return (
945
- <div
946
- className="divide-border grid grid-cols-2 divide-x divide-y lg:grid-cols-4 lg:divide-y-0"
947
- aria-busy
948
- >
949
- {[0, 1, 2, 3].map((i) => (
950
- <div key={i} className="px-6 py-4">
951
- <div className="bg-muted mb-2 h-3 w-24 rounded" />
952
- <div className="bg-muted mb-1.5 h-7 w-20 rounded" />
953
- <div className="bg-muted h-3 w-28 rounded" />
1429
+ <div className="grid grid-cols-2 gap-px bg-[var(--bdr)]" aria-busy>
1430
+ {[0, 1, 2, 3].map((tile) => (
1431
+ <div key={tile} className="bg-[var(--card)] p-[13px_16px]">
1432
+ <div className="mb-2 h-3 w-24 rounded bg-[var(--bg)]" />
1433
+ <div className="mb-1.5 h-6 w-20 rounded bg-[var(--bg)]" />
1434
+ <div className="h-3 w-28 rounded bg-[var(--bg)]" />
954
1435
  </div>
955
1436
  ))}
956
1437
  </div>
@@ -959,75 +1440,69 @@ function DeliveryGrid({ delivery, loading }: { delivery: DeliveryStats | null; l
959
1440
 
960
1441
  const hasData = delivery?.hasData ?? false
961
1442
  const requests = delivery?.requests24h ?? 0
962
- const delta: number | null = delivery?.deltaPercent ?? null
1443
+ const delta = delivery?.deltaPercent ?? null
963
1444
  const errorRate = delivery?.errorRate ?? 0
964
1445
  const avgLatency = delivery?.avgLatencyMs ?? 0
965
1446
  const p95Latency = delivery?.p95LatencyMs ?? 0
966
1447
  const webhookTotal = delivery?.webhookCount ?? 0
967
1448
  const webhookActive = delivery?.webhookActiveCount ?? 0
968
1449
 
969
- // Pretty-print large numbers (14_823 → "14.8K") so the tile stays
970
- // readable at the dashboard's compact density.
971
- const requestsLabel = formatLargeNumber(requests)
972
- const errorRatePct = (errorRate * 100).toFixed(2)
1450
+ const tiles = [
1451
+ {
1452
+ icon: Activity,
1453
+ label: 'Requests (24h)',
1454
+ value: hasData ? formatLargeNumber(requests) : '—',
1455
+ sub: !hasData
1456
+ ? 'no traffic recorded yet'
1457
+ : delta === null
1458
+ ? 'no prior baseline'
1459
+ : `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}% vs yesterday`,
1460
+ },
1461
+ {
1462
+ icon: AlertCircle,
1463
+ label: 'Error rate',
1464
+ value: hasData ? `${(errorRate * 100).toFixed(2)}%` : '—',
1465
+ sub: !hasData
1466
+ ? 'no traffic recorded yet'
1467
+ : errorRate < 0.005
1468
+ ? 'healthy'
1469
+ : errorRate < 0.05
1470
+ ? 'elevated'
1471
+ : 'investigate',
1472
+ },
1473
+ {
1474
+ icon: Gauge,
1475
+ label: 'Avg response',
1476
+ value: hasData ? `${Math.round(avgLatency)}ms` : '—',
1477
+ sub: hasData ? `p95 · ${p95Latency}ms` : 'no traffic recorded yet',
1478
+ },
1479
+ {
1480
+ icon: Zap,
1481
+ label: 'Webhooks',
1482
+ value: `${webhookActive} / ${webhookTotal}`,
1483
+ sub:
1484
+ webhookTotal === 0
1485
+ ? 'none configured'
1486
+ : webhookActive === webhookTotal
1487
+ ? 'All active'
1488
+ : `${webhookTotal - webhookActive} paused`,
1489
+ },
1490
+ ]
973
1491
 
974
1492
  return (
975
- <div className="divide-border grid grid-cols-2 divide-x divide-y lg:grid-cols-4 lg:divide-y-0">
976
- <DeliveryTile
977
- icon={Activity}
978
- label="API Requests (24h)"
979
- value={hasData ? requestsLabel : '—'}
980
- sub={
981
- !hasData
982
- ? 'no traffic recorded yet'
983
- : delta === null
984
- ? 'no prior baseline'
985
- : `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}% vs yesterday`
986
- }
987
- subIcon={
988
- hasData && typeof delta === 'number'
989
- ? delta >= 0
990
- ? TrendingUp
991
- : TrendingDown
992
- : undefined
993
- }
994
- tone={hasData ? (delta && delta >= 0 ? 'ok' : 'muted') : 'muted'}
995
- />
996
- <DeliveryTile
997
- icon={AlertCircle}
998
- label="Error Rate"
999
- value={hasData ? `${errorRatePct}%` : '—'}
1000
- sub={
1001
- !hasData
1002
- ? 'no traffic recorded yet'
1003
- : errorRate < 0.005
1004
- ? 'healthy'
1005
- : errorRate < 0.05
1006
- ? 'elevated'
1007
- : 'investigate'
1008
- }
1009
- tone={!hasData ? 'muted' : errorRate < 0.005 ? 'ok' : errorRate < 0.05 ? 'warn' : 'err'}
1010
- />
1011
- <DeliveryTile
1012
- icon={Gauge}
1013
- label="Avg Response Time"
1014
- value={hasData ? `${Math.round(avgLatency)}ms` : '—'}
1015
- sub={hasData ? `p95: ${p95Latency}ms` : 'no traffic recorded yet'}
1016
- tone={!hasData ? 'muted' : avgLatency < 200 ? 'ok' : avgLatency < 600 ? 'warn' : 'err'}
1017
- />
1018
- <DeliveryTile
1019
- icon={Zap}
1020
- label="Active Webhooks"
1021
- value={`${webhookActive} / ${webhookTotal}`}
1022
- sub={
1023
- webhookTotal === 0
1024
- ? 'none configured'
1025
- : webhookActive === webhookTotal
1026
- ? 'All active'
1027
- : `${webhookTotal - webhookActive} paused`
1028
- }
1029
- tone={webhookTotal === 0 ? 'muted' : webhookActive === webhookTotal ? 'ok' : 'warn'}
1030
- />
1493
+ <div className="grid grid-cols-2 gap-px bg-[var(--bdr)]">
1494
+ {tiles.map((tile) => (
1495
+ <div key={tile.label} className="bg-[var(--card)] p-[13px_16px]">
1496
+ <div className="flex items-center gap-[6px] text-[10.5px] font-bold tracking-[0.5px] text-[var(--sub)] uppercase">
1497
+ <tile.icon size={13} aria-hidden />
1498
+ {tile.label}
1499
+ </div>
1500
+ <p className="mt-[5px] text-[20px] leading-tight font-bold tracking-[-0.5px] text-[var(--txt)] tabular-nums">
1501
+ {tile.value}
1502
+ </p>
1503
+ <p className="mt-[2px] text-[11px] text-[var(--sub)]">{tile.sub}</p>
1504
+ </div>
1505
+ ))}
1031
1506
  </div>
1032
1507
  )
1033
1508
  }
@@ -1038,67 +1513,3 @@ function formatLargeNumber(n: number): string {
1038
1513
  if (n < 1_000_000) return `${(n / 1000).toFixed(0)}K`
1039
1514
  return `${(n / 1_000_000).toFixed(1)}M`
1040
1515
  }
1041
-
1042
- // ─── Sub-components (kept in-file: smaller bundle, no extra module hops) ────
1043
-
1044
- function EmptyState({
1045
- icon: Icon,
1046
- title,
1047
- subtitle,
1048
- compact = false,
1049
- }: {
1050
- icon: LucideIcon
1051
- title: string
1052
- subtitle: string
1053
- compact?: boolean
1054
- }) {
1055
- return (
1056
- <div
1057
- className={`flex flex-col items-center justify-center gap-1.5 text-center ${compact ? 'px-4 py-6' : 'px-6 py-10'}`}
1058
- >
1059
- <Icon className="text-muted-foreground/50 mb-1 h-7 w-7" aria-hidden />
1060
- <p className="text-foreground text-sm font-medium">{title}</p>
1061
- <p className="text-muted-foreground max-w-xs text-xs">{subtitle}</p>
1062
- </div>
1063
- )
1064
- }
1065
-
1066
- function DeliveryTile({
1067
- icon: Icon,
1068
- label,
1069
- value,
1070
- sub,
1071
- subIcon: SubIcon,
1072
- tone = 'muted',
1073
- }: {
1074
- icon: LucideIcon
1075
- label: string
1076
- value: string
1077
- sub?: string
1078
- subIcon?: LucideIcon
1079
- tone?: 'ok' | 'warn' | 'err' | 'muted'
1080
- }) {
1081
- const subTone =
1082
- tone === 'ok'
1083
- ? 'text-success'
1084
- : tone === 'warn'
1085
- ? 'text-warning'
1086
- : tone === 'err'
1087
- ? 'text-destructive dark:text-red-400'
1088
- : 'text-muted-foreground'
1089
- return (
1090
- <div className="px-6 py-4">
1091
- <div className="text-muted-foreground mb-1 flex items-center gap-1.5">
1092
- <Icon className="h-3.5 w-3.5" aria-hidden />
1093
- <span className="text-[11px] font-medium">{label}</span>
1094
- </div>
1095
- <p className="text-foreground text-xl leading-tight font-medium tracking-tight">{value}</p>
1096
- {sub && (
1097
- <p className={`mt-0.5 inline-flex items-center gap-1 text-[11px] ${subTone}`}>
1098
- {SubIcon && <SubIcon className="h-3 w-3 shrink-0" aria-hidden />}
1099
- {sub}
1100
- </p>
1101
- )}
1102
- </div>
1103
- )
1104
- }