File size: 28,966 Bytes
c6aa66a
 
 
 
 
 
2cc4145
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf243
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e085e1
 
 
 
 
c6aa66a
 
 
 
 
 
3e085e1
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
3e085e1
c6aa66a
 
 
3e085e1
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55e5697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca9ee10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
3e085e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e085e1
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf243
c6aa66a
 
 
 
 
 
55e5697
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca9ee10
 
 
 
 
 
 
c6aa66a
 
 
 
55e5697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf243
55e5697
98cf243
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
98cf243
c6aa66a
 
98cf243
c6aa66a
 
 
 
 
 
ca9ee10
c6aa66a
 
 
 
 
ca9ee10
 
 
 
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
ca9ee10
c6aa66a
ca9ee10
c6aa66a
 
ca9ee10
c6aa66a
ca9ee10
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
ca9ee10
c6aa66a
 
ca9ee10
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca9ee10
c6aa66a
 
 
ca9ee10
c6aa66a
 
 
 
 
 
 
 
ca9ee10
 
 
 
 
 
 
 
 
 
 
c6aa66a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Docent AI β€” Admin Dashboard</title>
  <meta name="theme-color" content="#0f1117" />
  <link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
  <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32.png" />
  <link rel="apple-touch-icon" href="/static/apple-touch-icon.png" />
  <script>
    (function () {
      var t = localStorage.getItem('docent-theme');
      if (t) document.documentElement.dataset.theme = t;
    })();
  </script>
  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    :root {
      color-scheme: dark;
      --bg: #0f1117; --bg2: #131722; --surface: #1a1d27; --surface2: #22263a;
      --border: #2e3350; --accent: #76b900; --accent-dk: #5c9100;
      --accent-tint: rgba(118, 185, 0, .12);
      --text: #e8eaf0; --text-muted: #8b90a8;
      --hover: #272c43; --scroll-thumb: #2e3350;
      --warn: #ffb84d; --warn-tint: rgba(255, 184, 77, .12); --danger: #e74c3c;
      --radius: 16px; --font: 'Segoe UI', system-ui, sans-serif;
      --shadow: 0 8px 28px rgba(0, 0, 0, .28);
    }
    [data-theme="light"] {
      color-scheme: light;
      --bg: #eef1f6; --bg2: #e6ebf3; --surface: #ffffff; --surface2: #f1f3f8;
      --border: #d7dce6; --accent: #6aa800; --accent-dk: #578a00;
      --accent-tint: rgba(106, 168, 0, .12);
      --text: #1c2130; --text-muted: #68708a;
      --hover: #e5e9f2; --scroll-thumb: #c3cad8;
      --warn: #c07c00; --warn-tint: rgba(192, 124, 0, .1);
      --shadow: 0 8px 28px rgba(30, 40, 70, .09);
    }

    body {
      font-family: var(--font); color: var(--text); min-height: 100vh;
      background: radial-gradient(1200px 500px at 80% -10%, var(--accent-tint), transparent),
                  linear-gradient(180deg, var(--bg2), var(--bg) 320px);
      transition: color .25s;
    }

    * { scrollbar-width: thin; scrollbar-color: var(--scroll-thumb) transparent; }
    ::-webkit-scrollbar { width: 8px; height: 8px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: var(--scroll-thumb); border-radius: 4px; }
    ::-webkit-scrollbar-thumb:hover { background: var(--accent); }

    /* ── Top bar ── */
    .topbar {
      display: flex; align-items: center; gap: 14px;
      padding: 14px 30px;
      background: color-mix(in srgb, var(--surface) 82%, transparent);
      backdrop-filter: blur(10px);
      border-bottom: 1px solid var(--border);
      position: sticky; top: 0; z-index: 5;
    }
    .brand-tile {
      width: 40px; height: 40px; flex-shrink: 0;
      display: flex; align-items: center; justify-content: center;
      background: linear-gradient(135deg, var(--accent), var(--accent-dk));
      border-radius: 12px; color: #000; font-size: 1.05rem;
      box-shadow: 0 4px 14px var(--accent-tint);
    }
    .topbar-text { flex: 1; min-width: 0; }
    .topbar h1 { font-size: 1.05rem; font-weight: 700; letter-spacing: .02em; }
    .topbar .sub { font-size: .72rem; color: var(--text-muted); }

    .btn {
      display: inline-flex; align-items: center; justify-content: center; gap: 8px;
      height: 40px; padding: 0 18px;
      font-size: .84rem; font-weight: 600; font-family: var(--font);
      border-radius: 999px; cursor: pointer; text-decoration: none;
      transition: background .2s, border-color .2s, color .2s, transform .12s;
      flex-shrink: 0;
    }
    .btn:active { transform: scale(.97); }
    .btn-accent {
      background: var(--accent); color: #000; border: 1px solid var(--accent);
    }
    .btn-accent:hover { background: var(--accent-dk); border-color: var(--accent-dk); }
    .btn-ghost {
      background: transparent; color: var(--text); border: 1px solid var(--border);
    }
    .btn-ghost:hover { border-color: var(--accent); color: var(--accent); }
    .btn.icon-only { width: 40px; padding: 0; }
    .btn.btn-small { height: 30px; padding: 0 13px; font-size: .74rem; }
    .btn svg { width: 17px; height: 17px; }

    .wrap { max-width: 1160px; margin: 0 auto; padding: 30px 22px 70px; }

    .state { text-align: center; color: var(--text-muted); padding: 100px 20px; font-size: .95rem; }
    .state a { color: var(--accent); }

    /* ── Page head row ── */
    .page-head {
      display: flex; align-items: center; justify-content: space-between;
      gap: 12px; margin-bottom: 20px; flex-wrap: wrap;
    }
    .page-head h2 { font-size: 1.3rem; font-weight: 700; }
    .page-head .updated { font-size: .74rem; color: var(--text-muted); }

    /* ── Stat cards ── */
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
    .card {
      display: flex; align-items: center; gap: 14px;
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 18px;
      box-shadow: var(--shadow);
      transition: transform .15s, border-color .15s;
    }
    .card:hover { transform: translateY(-3px); border-color: var(--accent); }
    .card .tile {
      width: 46px; height: 46px; flex-shrink: 0;
      display: flex; align-items: center; justify-content: center;
      background: var(--accent-tint); border-radius: 13px; font-size: 1.25rem;
    }
    .card.warn .tile { background: var(--warn-tint); }
    .card .value { font-size: 1.6rem; font-weight: 700; color: var(--text); line-height: 1.15; }
    .card.warn .value { color: var(--warn); }
    .card .label { font-size: .7rem; color: var(--text-muted); letter-spacing: .07em; text-transform: uppercase; }

    /* ── Panels ── */
    .panel {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 24px; margin-top: 20px;
      box-shadow: var(--shadow);
    }
    .panel-head {
      display: flex; align-items: center; gap: 10px; margin-bottom: 18px;
    }
    .panel-head .p-ico {
      width: 30px; height: 30px; flex-shrink: 0;
      display: flex; align-items: center; justify-content: center;
      background: var(--accent-tint); border-radius: 9px; font-size: .95rem;
    }
    .panel-head h3 { font-size: .95rem; font-weight: 700; flex: 1; }
    .panel-head .hint { font-size: .72rem; color: var(--text-muted); }

    /* minmax(0, …) lets tracks shrink below their content width β€” long PDF
       filenames must ellipsize instead of stretching the page */
    .two-col { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 20px; margin-top: 20px; }
    .two-col .panel { margin-top: 0; min-width: 0; }
    @media (max-width: 860px) { .two-col { grid-template-columns: minmax(0, 1fr); } }

    /* ── Daily activity chart ── */
    .chart {
      display: flex; align-items: flex-end; gap: 7px; height: 170px;
      padding-top: 24px; border-bottom: 1px solid var(--border);
    }
    .chart .col { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; gap: 7px; height: 100%; justify-content: flex-end; }
    .chart .bar {
      width: 100%; max-width: 42px; border-radius: 7px 7px 0 0;
      background: linear-gradient(180deg, var(--accent), var(--accent-dk));
      min-height: 3px; position: relative; cursor: default;
      transition: filter .15s;
    }
    .chart .bar.zero { background: var(--surface2); }
    .chart .bar:hover { filter: brightness(1.2); }
    .chart .bar .n {
      position: absolute; top: -20px; left: 50%; transform: translateX(-50%);
      font-size: .68rem; color: var(--text); font-weight: 700;
    }
    .chart-days { display: flex; gap: 7px; margin-top: 8px; }
    .chart-days span { flex: 1; min-width: 0; overflow: hidden; text-align: center; font-size: .62rem; color: var(--text-muted); white-space: nowrap; }

    /* ── Cited docs bars ── */
    .hbar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 11px; }
    .hbar-name { flex: 0 0 44%; min-width: 0; font-size: .78rem; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .hbar-track { flex: 1; background: var(--surface2); border-radius: 8px; height: 16px; overflow: hidden; }
    .hbar-fill {
      height: 100%; background: linear-gradient(90deg, var(--accent-dk), var(--accent));
      border-radius: 8px; transition: width .6s cubic-bezier(.2, .8, .3, 1);
    }
    .hbar-count { flex: 0 0 34px; font-size: .78rem; color: var(--accent); font-weight: 700; text-align: right; }

    /* ── Feedback ── */
    .fb-split { display: flex; height: 18px; border-radius: 9px; overflow: hidden; background: var(--surface2); margin-bottom: 10px; }
    .fb-up { background: linear-gradient(90deg, var(--accent-dk), var(--accent)); transition: width .6s; }
    .fb-down { background: var(--danger); transition: width .6s; }
    .fb-legend { display: flex; justify-content: space-between; font-size: .78rem; color: var(--text-muted); }

    /* ── Lists ── */
    .qlist { list-style: none; display: flex; flex-direction: column; gap: 9px; }
    .qlist li {
      font-size: .84rem; padding: 11px 14px; background: var(--surface2);
      border-radius: 10px; border-left: 3px solid var(--warn); line-height: 1.5;
      word-break: break-word;
    }
    .qlist li.empty { border-left-color: var(--border); color: var(--text-muted); font-style: italic; }

    /* ── Confirmation modal (same behaviour as the chat app's) ── */
    .confirm-modal { position: fixed; inset: 0; z-index: 80; display: flex; align-items: center; justify-content: center; padding: 20px; }
    .confirm-modal.hidden { display: none; }
    .confirm-backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, .55); }
    .confirm-card {
      position: relative; width: 100%; max-width: 360px;
      background: var(--surface); border: 1px solid var(--border);
      border-radius: 16px; padding: 22px;
    }
    .confirm-text { font-size: .92rem; line-height: 1.55; word-break: break-word; }
    .confirm-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; }
    .confirm-btn {
      padding: 9px 18px; border-radius: 10px; font-size: .86rem; font-weight: 600;
      font-family: var(--font); cursor: pointer;
    }
    .confirm-btn.cancel { background: var(--surface2); border: 1px solid var(--border); color: var(--text); }
    .confirm-btn.cancel:hover { border-color: var(--accent); }
    .confirm-btn.danger { background: #c0392b; border: 1px solid #c0392b; color: #fff; }
    .confirm-btn.danger:hover { background: #a93226; }
    .confirm-btn.danger:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
    .confirm-hint { margin-top: 12px; text-align: center; font-size: .7rem; color: var(--text-muted); }

    /* ── Motion system (matches the chat app) ── */
    :root { --ease: cubic-bezier(.22, .61, .36, 1); }

    @keyframes rise-in {
      from { opacity: 0; transform: translateY(14px); }
      to   { opacity: 1; transform: none; }
    }
    @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
    @keyframes pop-in {
      from { opacity: 0; transform: translateY(10px) scale(.96); }
      to   { opacity: 1; transform: none; }
    }
    @keyframes bar-grow { from { transform: scaleY(0); } to { transform: scaleY(1); } }
    @keyframes width-grow { from { width: 0; } }
    @keyframes spin { to { transform: rotate(360deg); } }

    .topbar { animation: rise-in .45s var(--ease) both; }
    .page-head { animation: rise-in .45s var(--ease) both .06s; }

    /* Stat cards and panels cascade in on every (re)render */
    .card { animation: pop-in .45s var(--ease) both; }
    .card:nth-child(1) { animation-delay: .05s; }
    .card:nth-child(2) { animation-delay: .11s; }
    .card:nth-child(3) { animation-delay: .17s; }
    .card:nth-child(4) { animation-delay: .23s; }
    .card:nth-child(5) { animation-delay: .29s; }
    .panel { animation: rise-in .5s var(--ease) both .18s; }
    .two-col .panel:nth-child(2) { animation-delay: .26s; }

    .card { transition: transform .18s var(--ease), box-shadow .18s var(--ease); }
    .card:hover { transform: translateY(-2px); box-shadow: 0 8px 22px rgba(0, 0, 0, .18); }

    /* Chart bars grow up from the baseline, one after another */
    .chart .bar { transform-origin: bottom; animation: bar-grow .55s var(--ease) both; }
    .chart .bar .n { animation: fade-in .3s var(--ease) both .5s; }

    /* Cited-documents bars sweep to their width */
    .hbar-fill { animation: width-grow .7s var(--ease) both .15s; }
    .qlist li, .doclist li { animation: rise-in .4s var(--ease) both; }

    .btn { transition: background .2s, border-color .2s, color .2s, transform .16s var(--ease), box-shadow .16s var(--ease); }
    .btn:hover { transform: translateY(-1px); }
    .btn:active { transform: translateY(0) scale(.97); }

    #refreshBtn.loading svg { animation: spin .7s linear infinite; }

    .confirm-backdrop { animation: fade-in .25s var(--ease) both; }
    .confirm-card { animation: pop-in .28s var(--ease) both; }

    /* Theme switch: colours sweep instead of snapping */
    html.theme-anim, html.theme-anim *, html.theme-anim *::before, html.theme-anim *::after {
      transition: background-color .35s var(--ease), color .35s var(--ease),
                  border-color .35s var(--ease), fill .35s var(--ease), stroke .35s var(--ease) !important;
    }

    @media (prefers-reduced-motion: reduce) {
      *, *::before, *::after {
        animation-duration: .01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: .01ms !important;
      }
    }

    .doclist { list-style: none; display: flex; flex-direction: column; gap: 7px; max-height: 280px; overflow-y: auto; padding-right: 4px; }
    .doclist li {
      font-size: .78rem; padding: 8px 11px; background: var(--surface2);
      border-radius: 9px; border-left: 3px solid var(--accent); word-break: break-all;
      transition: background .15s;
    }
    .doclist li:hover { background: var(--hover); }
    .hidden { display: none !important; }

    /* ── Mobile ── */
    @media (max-width: 640px) {
      .topbar { padding: 10px 12px; gap: 8px; }
      .topbar .sub { display: none; }
      .topbar h1 { font-size: .95rem; }
      .brand-tile { width: 36px; height: 36px; border-radius: 10px; }
      .btn { height: 36px; padding: 0 12px; font-size: .78rem; }
      .btn.icon-only { width: 36px; }
      .btn .btn-label { display: none; }   /* back button becomes icon-only */
      .btn-accent { padding: 0 10px; }

      .wrap { padding: 18px 12px 50px; }
      .page-head h2 { font-size: 1.1rem; }

      .grid { grid-template-columns: 1fr 1fr; gap: 10px; }
      .card { padding: 13px; gap: 10px; border-radius: 13px; }
      .card .tile { width: 38px; height: 38px; font-size: 1.05rem; border-radius: 10px; }
      .card .value { font-size: 1.25rem; }
      .card .label { font-size: .62rem; }

      .panel { padding: 16px 14px; border-radius: 13px; margin-top: 14px; }
      .two-col { gap: 14px; margin-top: 14px; }

      .chart { height: 120px; gap: 3px; }
      .chart .bar .n { display: none; }            /* numbers overlap on tiny bars */
      .chart-days { gap: 3px; }
      .chart-days span { font-size: .52rem; }
      .chart-days span:nth-child(even) { visibility: hidden; } /* every other date */

      .hbar-name { flex-basis: 40%; font-size: .7rem; }
      .hbar-count { flex-basis: 26px; font-size: .72rem; }
      .qlist li { font-size: .78rem; padding: 9px 11px; }
    }
  </style>
</head>
<body>

  <header class="topbar">
    <span class="brand-tile">&#9670;</span>
    <div class="topbar-text">
      <h1>Admin Dashboard</h1>
      <p class="sub">Docent AI β€” usage analytics &amp; knowledge-base health</p>
    </div>
    <button class="btn btn-ghost icon-only" id="themeBtn" type="button" title="Toggle light/dark mode"></button>
    <button class="btn btn-ghost icon-only" id="refreshBtn" type="button" title="Refresh data">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
    </button>
    <a class="btn btn-accent" href="/">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
      <span class="btn-label">Back to chat</span>
    </a>
  </header>

  <div class="wrap">
    <div class="state" id="state">Loading dashboard…</div>

    <div id="dash" class="hidden">
      <div class="page-head">
        <h2>Overview</h2>
        <span class="updated" id="updatedAt"></span>
      </div>

      <div class="grid" id="statGrid"></div>

      <div class="panel">
        <div class="panel-head">
          <span class="p-ico">&#128200;</span>
          <h3>Questions per day</h3>
          <span class="hint">last 14 days</span>
        </div>
        <div class="chart" id="chart"></div>
        <div class="chart-days" id="chartDays"></div>
      </div>

      <div class="two-col">
        <div class="panel">
          <div class="panel-head">
            <span class="p-ico">&#128196;</span>
            <h3>Most cited documents</h3>
          </div>
          <div id="citedBars"></div>
        </div>
        <div class="panel">
          <div class="panel-head">
            <span class="p-ico">&#128077;</span>
            <h3>Answer feedback</h3>
          </div>
          <div class="fb-split" id="fbSplit"></div>
          <div class="fb-legend" id="fbLegend"></div>

          <div class="panel-head" style="margin-top:26px">
            <span class="p-ico">&#128218;</span>
            <h3>Knowledge base</h3>
            <span class="hint" id="docCount"></span>
          </div>
          <ul class="doclist" id="docList"></ul>
        </div>
      </div>

      <div class="panel">
        <div class="panel-head">
          <span class="p-ico">&#10067;</span>
          <h3>Questions the bot could not answer</h3>
          <span class="hint">candidates for missing policies</span>
          <button class="btn btn-ghost btn-small" id="clearUnansweredBtn" type="button" title="Clear this list">Clear all</button>
        </div>
        <ul class="qlist" id="unansweredList"></ul>
      </div>
    </div>
  </div>

  <!-- ── Confirmation modal ── -->
  <div class="confirm-modal hidden" id="confirmModal">
    <div class="confirm-backdrop" id="confirmBackdrop"></div>
    <div class="confirm-card">
      <p class="confirm-text" id="confirmText">Are you sure?</p>
      <div class="confirm-actions">
        <button type="button" class="confirm-btn cancel" id="confirmCancel">Cancel</button>
        <button type="button" class="confirm-btn danger" id="confirmOk">Clear</button>
      </div>
      <p class="confirm-hint">Enter to confirm &middot; Esc to cancel</p>
    </div>
  </div>

  <script>
    const stateEl = document.getElementById('state');
    const dashEl  = document.getElementById('dash');
    let sb = null;

    /* Theme toggle (shared localStorage key with the chat app) */
    const themeBtn = document.getElementById('themeBtn');
    const ICON_SUN = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>`;
    const ICON_MOON = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`;

    function applyTheme(theme) {
      document.documentElement.dataset.theme = theme;
      localStorage.setItem('docent-theme', theme);
      themeBtn.innerHTML = theme === 'light' ? ICON_MOON : ICON_SUN;
    }
    themeBtn.addEventListener('click', () => {
      // Sweep the colour change instead of snapping (class lives ~450ms)
      document.documentElement.classList.add('theme-anim');
      clearTimeout(themeBtn._t);
      themeBtn._t = setTimeout(() => document.documentElement.classList.remove('theme-anim'), 450);
      applyTheme(document.documentElement.dataset.theme === 'light' ? 'dark' : 'light');
    });
    applyTheme(localStorage.getItem('docent-theme') || 'dark');

    document.getElementById('refreshBtn').addEventListener('click', () => loadData());

    /* Promise-based confirmation modal β€” Enter confirms, Esc cancels */
    const confirmModal    = document.getElementById('confirmModal');
    const confirmText     = document.getElementById('confirmText');
    const confirmOk       = document.getElementById('confirmOk');
    const confirmCancel   = document.getElementById('confirmCancel');
    const confirmBackdrop = document.getElementById('confirmBackdrop');

    function confirmDialog(text, okLabel = 'Clear') {
      return new Promise(resolve => {
        confirmText.textContent = text;
        confirmOk.textContent = okLabel;
        confirmModal.classList.remove('hidden');

        const done = (value) => {
          confirmModal.classList.add('hidden');
          document.removeEventListener('keydown', onKey, true);
          confirmOk.removeEventListener('click', ok);
          confirmCancel.removeEventListener('click', cancel);
          confirmBackdrop.removeEventListener('click', cancel);
          resolve(value);
        };
        const ok = () => done(true);
        const cancel = () => done(false);
        const onKey = (e) => {
          if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); ok(); }
          else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cancel(); }
        };

        confirmOk.addEventListener('click', ok);
        confirmCancel.addEventListener('click', cancel);
        confirmBackdrop.addEventListener('click', cancel);
        document.addEventListener('keydown', onKey, true);
        confirmOk.focus();
      });
    }

    document.getElementById('clearUnansweredBtn').addEventListener('click', async () => {
      if (!await confirmDialog('Clear all unanswered questions from the dashboard?', 'Clear all')) return;
      try {
        const res = await authedFetch('/analytics/clear-unanswered', { method: 'POST' });
        if (!res.ok) throw new Error();
        await loadData();
      } catch {
        alert('Could not clear the list β€” please try again.');
      }
    });

    function esc(s) {
      return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    async function authedFetch(url, options = {}) {
      const { data } = await sb.auth.getSession();
      const token = data.session ? data.session.access_token : null;
      return fetch(url, { ...options, headers: token ? { Authorization: `Bearer ${token}` } : {} });
    }

    function card(icon, label, value, warn = false) {
      return `<div class="card${warn ? ' warn' : ''}">
        <span class="tile">${icon}</span>
        <div>
          <div class="value" data-count="${value}">${value}</div>
          <div class="label">${label}</div>
        </div>
      </div>`;
    }

    /* Stat numbers count up from 0 as their card lands */
    function countUp(el) {
      const target = parseInt(el.dataset.count, 10);
      if (!Number.isFinite(target) || target <= 0) return;
      const dur = 700, t0 = performance.now();
      const tick = (t) => {
        const p = Math.min(1, (t - t0) / dur);
        const eased = 1 - Math.pow(1 - p, 3); // ease-out cubic
        el.textContent = Math.round(target * eased);
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }

    function render(a, docs) {
      document.getElementById('statGrid').innerHTML =
        card('&#128172;', 'Questions asked', a.total_questions ?? 0) +
        card('&#128101;', 'Conversations', a.total_conversations ?? 0) +
        card('&#128196;', 'Documents', a.total_documents ?? 0) +
        card('&#129513;', 'Indexed chunks', a.total_chunks ?? 0) +
        card('&#10067;', 'Unanswered', a.unanswered_count ?? 0, (a.unanswered_count ?? 0) > 0);
      document.querySelectorAll('#statGrid .value').forEach(countUp);

      // Daily chart β€” bars rise one after another, left to right
      const daily = a.daily_questions || [];
      const max = Math.max(1, ...daily.map(d => d.count));
      document.getElementById('chart').innerHTML = daily.map((d, i) => `
        <div class="col">
          <div class="bar${d.count ? '' : ' zero'}"
               style="height:${Math.max(2, Math.round((d.count / max) * 100))}%; animation-delay:${i * 35}ms"
               title="${d.date}: ${d.count} question${d.count === 1 ? '' : 's'}">
            ${d.count ? `<span class="n">${d.count}</span>` : ''}
          </div>
        </div>`).join('');
      document.getElementById('chartDays').innerHTML =
        daily.map(d => `<span>${d.date.slice(5)}</span>`).join('');

      // Cited documents
      const cited = a.top_documents || [];
      const cmax = Math.max(1, ...cited.map(d => d.citations));
      document.getElementById('citedBars').innerHTML = cited.length
        ? cited.map((d, i) => `
          <div class="hbar-row">
            <span class="hbar-name" title="${esc(d.file)}">${esc(d.file)}</span>
            <div class="hbar-track"><div class="hbar-fill" style="width:${Math.round((d.citations / cmax) * 100)}%; animation-delay:${150 + i * 80}ms"></div></div>
            <span class="hbar-count">${d.citations}</span>
          </div>`).join('')
        : '<p style="font-size:.8rem;color:var(--text-muted);font-style:italic">No citations yet.</p>';

      // Feedback split
      const up = a.feedback?.up ?? 0, down = a.feedback?.down ?? 0, total = up + down;
      const upPct = total ? Math.round((up / total) * 100) : 50;
      document.getElementById('fbSplit').innerHTML =
        `<div class="fb-up" style="width:${total ? upPct : 0}%"></div><div class="fb-down" style="width:${total ? 100 - upPct : 0}%"></div>`;
      document.getElementById('fbLegend').innerHTML = total
        ? `<span>&#128077; ${up} helpful (${upPct}%)</span><span>&#128078; ${down} not helpful</span>`
        : '<span>No feedback yet</span>';

      // Documents
      document.getElementById('docCount').textContent = `${(docs || []).length} files`;
      document.getElementById('docList').innerHTML = (docs || []).map((d, i) => `<li style="animation-delay:${Math.min(i * 40, 400)}ms">${esc(d)}</li>`).join('')
        || '<li style="border-left-color:var(--border);color:var(--text-muted);font-style:italic">No documents ingested</li>';

      // Unanswered
      document.getElementById('unansweredList').innerHTML = (a.recent_unanswered || []).map((q, i) => `<li style="animation-delay:${Math.min(i * 50, 400)}ms">${esc(q)}</li>`).join('')
        || '<li class="empty">None β€” every question found an answer in the documents.</li>';

      document.getElementById('updatedAt').textContent = `Updated ${new Date().toLocaleTimeString()}`;
      stateEl.classList.add('hidden');
      dashEl.classList.remove('hidden');
    }

    async function loadData() {
      const refreshBtn = document.getElementById('refreshBtn');
      refreshBtn.classList.add('loading');
      try {
        const [aRes, dRes] = await Promise.all([authedFetch('/analytics'), authedFetch('/documents')]);
        if (!aRes.ok) throw new Error('Could not load analytics.');
        const analytics = await aRes.json();
        const docs = dRes.ok ? (await dRes.json()).documents : [];
        render(analytics, docs);
      } finally {
        refreshBtn.classList.remove('loading');
      }
    }

    async function boot() {
      try {
        const cfg = await (await fetch('/config')).json();
        if (!cfg.configured || !window.supabase) throw new Error('Server not configured.');
        sb = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey);

        const { data } = await sb.auth.getSession();
        if (!data.session) {
          stateEl.innerHTML = 'You are not logged in. <a href="/">Go to the app</a> and log in as an admin first.';
          return;
        }

        const meRes = await authedFetch('/me');
        const me = await meRes.json();
        if (!me.is_admin) {
          stateEl.innerHTML = 'This dashboard is for admins only. <a href="/">Back to chat</a>';
          return;
        }

        await loadData();
      } catch (err) {
        stateEl.innerHTML = `${esc(err.message || 'Could not load the dashboard.')} <a href="/">Back to chat</a>`;
      }
    }

    boot();
  </script>
</body>
</html>