-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
1416 lines (1273 loc) · 59.4 KB
/
Copy pathdashboard.js
File metadata and controls
1416 lines (1273 loc) · 59.4 KB
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Chart from 'chart.js/auto'
// ─── State ──────────────────────────────────────────────────
const DEMO_MODE = new URLSearchParams(location.search).get('demo') === '1'
let currentUser = null
let actOffset = 0
const ACT_LIMIT = 20
const charts = {} // keyed by canvas id — destroyed before re-init
// ─── Helpers ────────────────────────────────────────────────
const $ = (sel) => document.querySelector(sel)
const esc = s => String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')
// Device tokens stored in JS memory, never in DOM attributes
const tokenStore = new Map()
const show = (el) => { el.style.display = 'flex' }
const hide = (el) => { el.style.display = 'none' }
async function api(path, opts = {}) {
if (DEMO_MODE) return demoApi(path, opts)
const res = await fetch(`/api${path}`, {
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
...opts,
body: opts.body ? JSON.stringify(opts.body) : undefined
})
const data = await res.json()
if (!res.ok) throw new Error(data.error || 'Request failed')
return data
}
function toast(msg, type = 'success') {
const el = document.createElement('div')
el.className = `toast toast-${type}`
el.textContent = msg
$('#toast-container').appendChild(el)
setTimeout(() => el.remove(), 4000)
}
function timeAgo(dateStr) {
const date = dateStr.includes('Z') || dateStr.includes('+') ? new Date(dateStr) : new Date(dateStr + 'Z')
const diff = Date.now() - date.getTime()
const m = Math.floor(diff / 60000)
if (m < 1) return 'just now'
if (m < 60) return `${m}m ago`
const h = Math.floor(m / 60)
if (h < 24) return `${h}h ago`
return `${Math.floor(h / 24)}d ago`
}
function initials(name = '') {
return name.trim().split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2)
}
const LEVEL_COLOR = { critical: '#C85A2E', warn: '#D97706', info: '#2C5A3F' }
const CAT_COLORS = ['#2C5A3F', '#D97706', '#C85A2E', '#1B3A27', '#5A8C6F', '#9CA3AF']
// ─── Chart defaults ──────────────────────────────────────────
Chart.defaults.font.family = 'Inter, -apple-system, sans-serif'
Chart.defaults.font.size = 12
Chart.defaults.color = '#3C4A42'
Chart.defaults.plugins.legend.display = false
Chart.defaults.plugins.legend.labels = { boxWidth: 12, padding: 16, font: { size: 12 } }
Chart.defaults.plugins.tooltip.backgroundColor = '#1A2A22'
Chart.defaults.plugins.tooltip.padding = 12
Chart.defaults.plugins.tooltip.cornerRadius = 10
Chart.defaults.plugins.tooltip.titleFont = { size: 13, weight: '500' }
Chart.defaults.plugins.tooltip.bodyFont = { size: 12 }
// ─── Fake chart data ─────────────────────────────────────────
// Always-populated datasets so charts never look empty
const FAKE = {
days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
critical: [1, 2, 0, 3, 1, 2, 1],
warn: [3, 4, 5, 2, 4, 6, 3],
info: [5, 3, 7, 4, 6, 4, 5],
// Risk score trend (0–100)
riskLine: [42, 58, 35, 80, 55, 72, 48],
categories: {
labels: ['AI Activity', 'Screen Time', 'Contact', 'Content', 'Privacy', 'App Scan'],
data: [12, 8, 7, 5, 4, 6],
colors: ['#2C5A3F', '#D97706', '#C85A2E', '#1B3A27', '#5A8C6F', '#9CA3AF'],
},
levels: {
labels: ['Critical', 'Warning', 'Info', 'OK'],
data: [10, 19, 30, 6],
colors: ['#C85A2E', '#D97706', '#2C5A3F', '#9CA3AF'],
},
// Per-child weekly: Emma vs Liam
emma: [4, 6, 3, 7, 5, 8, 4],
liam: [2, 3, 5, 2, 4, 3, 2],
}
function mkChart(id, config) {
if (charts[id]) { charts[id].destroy() }
const canvas = document.getElementById(id)
if (!canvas) return
charts[id] = new Chart(canvas, config)
}
// ─── Visitor demo mode ────────────────────────────────────────
const _m = 60000, _h = 3600000, _d = 86400000
const _ago = ms => new Date(Date.now() - ms).toISOString().replace('Z', '')
const DEMO_USER = {
id: 0, name: 'Sarah Morgan', email: 'demo@sentra.app',
plan: 'family', plan_status: 'active', consent_verified: 1,
}
const DEMO_CHILDREN_DATA = [
{
id: 1, name: 'Emma', age: 13,
devices: [{ name: 'School Chromebook', platform: 'browser', device_token: 'demo-token', last_seen: _ago(4 * _m) }],
},
{
id: 2, name: 'Liam', age: 11,
devices: [
{ name: 'Home Laptop', platform: 'browser', device_token: 'demo-token', last_seen: _ago(2 * _h) },
],
},
]
const DEMO_ALL_ALERTS = [
{
id: 'da1', level: 'critical', title: 'Jailbreak attempt — ChatGPT',
category: 'AI Safety', child_name: 'Emma', child_id: 1, created_at: _ago(18 * _m), read: false,
guidance: {
explanation: 'Emma asked ChatGPT to ignore its safety rules. This usually means she was trying to get information the AI would normally refuse — worth understanding what she was looking for.',
action: 'Check in with Emma today. Look at it as a curiosity signal, not a crisis — the fact it was flagged means the system worked.',
conversation_starter: 'Hey, I noticed you\'ve been using ChatGPT a lot lately. I\'m curious — what kinds of things do you find useful to ask it?',
},
},
{
id: 'da2', level: 'warn', title: 'Romantic roleplay pattern — Character.AI',
category: 'AI Relationship', child_name: 'Emma', child_id: 1, created_at: _ago(2.5 * _h), read: false,
guidance: {
explanation: 'Romantic roleplay with AI personas is common among teens but can blur the line between real and simulated relationships. It\'s worth understanding what draws Emma to it.',
action: 'Have a 10-minute conversation this evening about what she enjoys about Character.AI and how she thinks about these AI characters.',
conversation_starter: 'I\'d love to understand Character.AI better — can you show me how you use it? I\'m genuinely curious, not worried.',
},
},
{
id: 'da3', level: 'warn', title: 'Extended late-night session — 11:45 pm',
category: 'Screen Time', child_name: 'Emma', child_id: 1, created_at: _ago(14 * _h), read: false,
guidance: {
explanation: 'Emma was active on an AI chatbot at 11:45 pm. Late-night AI use often signals stress, difficulty sleeping, or emotional processing that she\'s not bringing to people yet.',
action: 'Set a device curfew for Emma\'s browser through your router or device settings — even 10 pm makes a big difference for sleep quality.',
conversation_starter: 'I noticed you were up late last night. How are you doing? I want to make sure you\'re getting enough rest.',
},
},
{
id: 'da4', level: 'warn', title: 'Emotional dependency signal — Replika',
category: 'AI Relationship', child_name: 'Liam', child_id: 2, created_at: _ago(1.5 * _d), read: true,
guidance: {
explanation: 'Liam is showing patterns of frequent, emotionally-toned interactions with a Replika AI companion. This isn\'t inherently harmful, but sustained dependency can crowd out real relationships.',
action: 'Plan something social with Liam this weekend — even a walk together counts. Connection is the antidote.',
conversation_starter: 'What are you and your friends doing lately? I feel like I haven\'t heard about them in a while.',
},
},
{ id: 'da5', level: 'info', title: '3h 12m session on Gemini', category: 'Screen Time', child_name: 'Liam', child_id: 2, created_at: _ago(2 * _d), read: true, guidance: null },
{ id: 'da6', level: 'info', title: 'First session on Microsoft Copilot', category: 'AI Activity', child_name: 'Emma', child_id: 1, created_at: _ago(3 * _d), read: true, guidance: null },
{
id: 'da7', level: 'warn', title: 'Harmful content request — self-harm topic',
category: 'AI Safety', child_name: 'Liam', child_id: 2, created_at: _ago(4 * _d), read: true,
guidance: {
explanation: 'A signal was detected suggesting Liam may have asked an AI about a self-harm related topic. Teens often turn to AI first with questions they\'re afraid to ask people.',
action: 'Find a quiet moment to check in with Liam directly — not about the alert, just about how he\'s feeling overall.',
conversation_starter: 'Hey, I just wanted to check in. You seem a bit quiet lately. How are things going — school, friends, all of it?',
},
},
{ id: 'da8', level: 'info', title: 'Weekly summary: 47 signals, 3 flagged', category: 'Summary', child_name: 'Emma', child_id: 1, created_at: _ago(5 * _d), read: true, guidance: null },
]
function _demoByDay(critical, warn, info) {
return Array.from({ length: 7 }, (_, i) => ({
date: new Date(Date.now() - (6 - i) * _d).toISOString().split('T')[0],
critical: critical[i], warn: warn[i], info: info[i],
}))
}
function demoApi(path, opts = {}) {
if (opts.method && opts.method !== 'GET') {
toast('This is a demo — create a free account to use Sentra.', 'success')
return Promise.reject(new Error('demo'))
}
const base = path.split('?')[0]
const qs = new URLSearchParams(path.includes('?') ? path.split('?')[1] : '')
if (base === '/auth/me') return Promise.resolve({ user: DEMO_USER })
if (base === '/billing/status') return Promise.resolve({ plan: 'family', plan_status: 'active', has_stripe: false })
if (base === '/stats') return Promise.resolve({ children: 2, devices: 2, signalsThisWeek: 47, unreadAlerts: 3 })
if (base === '/family') return Promise.resolve({ children: DEMO_CHILDREN_DATA })
if (base.startsWith('/alerts')) {
const cid = qs.get('child_id')
const limited = DEMO_ALL_ALERTS.filter(a => !cid || a.child_id === parseInt(cid))
return Promise.resolve({ alerts: limited.slice(0, parseInt(qs.get('limit') || 50)), unread: limited.filter(a => !a.read).length })
}
if (base === '/activity') {
const cid = qs.get('child_id')
const isLiam = cid === '2'
return Promise.resolve({
byDay: _demoByDay(
isLiam ? [0, 1, 0, 1, 1, 0, 1] : [1, 2, 0, 2, 1, 0, 1],
isLiam ? [1, 2, 3, 1, 2, 4, 2] : [2, 3, 4, 2, 3, 5, 2],
isLiam ? [3, 2, 4, 3, 4, 2, 3] : [4, 3, 6, 4, 5, 3, 4],
),
byCategory: [
{ category: 'AI Safety', count: 8 },
{ category: 'AI Relationship', count: 12 },
{ category: 'Screen Time', count: 7 },
{ category: 'AI Activity', count: 15 },
{ category: 'Summary', count: 5 },
],
})
}
if (base.startsWith('/child/')) {
const id = parseInt(base.split('/')[2])
const child = DEMO_CHILDREN_DATA.find(c => c.id === id) ?? DEMO_CHILDREN_DATA[0]
const alerts = DEMO_ALL_ALERTS.filter(a => a.child_id === child.id)
return Promise.resolve({
child,
devices: child.devices,
alerts,
stats: { signals: id === 1 ? 28 : 19, unread: id === 1 ? 3 : 0, maxRisk: id === 1 ? 85 : 62 },
})
}
return Promise.resolve({})
}
// ─── View system ──────────────────────────────────────────────
const VIEWS = ['overview', 'activity', 'weekly', 'child']
function setView(name, data = null) {
VIEWS.forEach(v => {
const el = document.getElementById(`view-${v}`)
if (el) el.style.display = v === name ? 'block' : 'none'
})
document.querySelectorAll('.nav-item[data-view]').forEach(el => {
el.classList.toggle('active', el.dataset.view === name)
})
document.querySelectorAll('.nav-child-item[data-child-id]').forEach(el => {
el.classList.toggle('active-child', data && el.dataset.childId == data)
})
const titles = { overview: 'Family overview', activity: 'Activity log', weekly: 'Weekly report', child: '' }
$('#topbar-greeting').textContent = titles[name] ?? 'Family overview'
// Sync mobile nav active state
document.querySelectorAll('#mobile-nav .mobile-nav-btn[data-view]').forEach(b => {
b.classList.toggle('active', b.dataset.view === name)
})
if (name === 'activity') initActivityView()
if (name === 'weekly') initWeeklyView()
if (name === 'child' && data) initChildView(data)
}
document.querySelectorAll('.nav-item[data-view]').forEach(el => {
el.addEventListener('click', () => setView(el.dataset.view))
})
// ─── Auth views ──────────────────────────────────────────────
function showAuth(view = 'login') {
hide($('#app'))
show($('#auth-screen'))
$('#login-view').style.display = view === 'login' ? 'block' : 'none'
$('#register-view').style.display = view === 'register' ? 'block' : 'none'
clearError()
}
function showApp() {
hide($('#auth-screen'))
$('#app').style.display = 'grid'
$('#mobile-nav').style.display = window.innerWidth <= 900 ? 'flex' : 'none'
if (DEMO_MODE) {
$('#demo-banner').style.display = 'flex'
} else if (currentUser && !currentUser.consent_verified) {
// Show consent banner if parent hasn't verified their email yet
$('#consent-banner').style.display = 'flex'
}
// Check URL for consent=verified redirect from email link
const params = new URLSearchParams(location.search)
if (params.get('consent') === 'verified') {
$('#consent-banner').style.display = 'none'
toast('Parental consent confirmed — monitoring is fully active.')
history.replaceState({}, '', location.pathname)
}
setView('overview')
loadDashboard()
}
$('#resend-consent-btn')?.addEventListener('click', async () => {
const btn = document.getElementById('resend-consent-btn')
btn.disabled = true
btn.textContent = 'Sending…'
try {
await api('/auth/resend-consent', { method: 'POST' })
toast('Confirmation email resent — check your inbox.')
let secs = 60
btn.textContent = `Resend in ${secs}s`
const interval = setInterval(() => {
secs--
if (secs <= 0) {
clearInterval(interval)
btn.disabled = false
btn.textContent = 'Resend email'
} else {
btn.textContent = `Resend in ${secs}s`
}
}, 1000)
} catch {
toast('Could not resend email. Try again shortly.', 'error')
btn.disabled = false
btn.textContent = 'Resend email'
}
})
// Mobile nav click handlers
document.querySelectorAll('#mobile-nav .mobile-nav-btn[data-view]').forEach(btn => {
btn.addEventListener('click', () => {
setView(btn.dataset.view)
document.querySelectorAll('#mobile-nav .mobile-nav-btn').forEach(b => b.classList.remove('active'))
btn.classList.add('active')
})
})
$('#mobile-settings-btn')?.addEventListener('click', () => {
toast('Settings — manage your account from the sidebar on desktop.')
})
window.addEventListener('resize', () => {
const nav = $('#mobile-nav')
if (nav) nav.style.display = window.innerWidth <= 900 ? 'flex' : 'none'
})
function showError(msg) {
const el = $('#auth-error')
el.textContent = msg
el.style.display = 'block'
}
function clearError() { $('#auth-error').style.display = 'none' }
// ─── Login ───────────────────────────────────────────────────
$('#login-form').addEventListener('submit', async (e) => {
e.preventDefault()
clearError()
const btn = e.target.querySelector('button')
btn.disabled = true; btn.textContent = 'Signing in…'
try {
const fd = new FormData(e.target)
const { user } = await api('/auth/login', {
method: 'POST',
body: { email: fd.get('email'), password: fd.get('password') }
})
currentUser = user
showApp()
} catch (err) {
showError(err.message)
} finally {
btn.disabled = false; btn.textContent = 'Sign in'
}
})
// ─── Register ────────────────────────────────────────────────
$('#register-form').addEventListener('submit', async (e) => {
e.preventDefault()
clearError()
const btn = e.target.querySelector('button')
btn.disabled = true; btn.textContent = 'Creating account…'
try {
const fd = new FormData(e.target)
const { user } = await api('/auth/register', {
method: 'POST',
body: { name: fd.get('name'), email: fd.get('email'), password: fd.get('password') }
})
currentUser = user
showApp()
showOnboarding()
} catch (err) {
showError(err.message)
} finally {
btn.disabled = false; btn.textContent = 'Create account'
}
})
// ─── Auth view toggles ───────────────────────────────────────
$('#go-register').addEventListener('click', () => showAuth('register'))
$('#go-login').addEventListener('click', () => showAuth('login'))
// ─── Logout ──────────────────────────────────────────────────
$('#logout-btn').addEventListener('click', async () => {
if (DEMO_MODE) { window.location.href = '/'; return }
await api('/auth/logout', { method: 'POST' })
currentUser = null
showAuth('login')
})
// ─── Dashboard data ──────────────────────────────────────────
async function loadDashboard() {
// Sidebar profile
$('#sidebar-avatar').textContent = initials(currentUser.name)
$('#sidebar-name').textContent = currentUser.name
$('#sidebar-plan').textContent = currentUser.plan + ' plan'
// Topbar
$('#topbar-greeting').textContent = `Good ${greeting()}, ${currentUser.name.split(' ')[0]}`
$('#topbar-date').textContent = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })
await Promise.all([loadStats(), loadAlerts(), loadChildren(), loadOverviewCharts(), loadPlanCard()])
}
function greeting() {
const h = new Date().getHours()
if (h < 12) return 'morning'
if (h < 17) return 'afternoon'
return 'evening'
}
const DEMO_STATS = { children: 2, devices: 3, signalsThisWeek: 65, unreadAlerts: 4 }
const DEMO_ALERTS = [
{ id: 'demo-1', level: 'critical', title: 'Possible jailbreak prompt detected', category: 'AI Safety', child_name: 'Emma', created_at: new Date(Date.now() - 18 * 60000).toISOString().replace('Z',''), read: false },
{ id: 'demo-2', level: 'warn', title: 'Extended late-night AI session', category: 'Screen time', child_name: 'Emma', created_at: new Date(Date.now() - 3 * 3600000).toISOString().replace('Z',''), read: false },
{ id: 'demo-3', level: 'warn', title: 'Romantic language pattern flagged', category: 'Contact', child_name: 'Liam', created_at: new Date(Date.now() - 5 * 3600000).toISOString().replace('Z',''), read: true },
{ id: 'demo-4', level: 'info', title: 'New AI app installed: Character.AI', category: 'App scan', child_name: 'Liam', created_at: new Date(Date.now() - 86400000).toISOString().replace('Z',''), read: true },
]
let isDemoMode = false
async function loadStats() {
try {
const s = await api('/stats')
isDemoMode = s.children === 0
const display = isDemoMode ? DEMO_STATS : s
$('#stat-children').textContent = display.children
$('#stat-devices').textContent = display.devices
$('#stat-signals').textContent = display.signalsThisWeek
$('#stat-alerts').textContent = display.unreadAlerts
const badge = $('#alert-badge')
if (display.unreadAlerts > 0) {
badge.textContent = display.unreadAlerts
badge.style.display = 'inline-block'
} else {
badge.style.display = 'none'
}
} catch { /* silent */ }
}
function parseGuidance(a) {
if (!a.guidance) return null
if (typeof a.guidance === 'object') return a.guidance
try { return JSON.parse(a.guidance) } catch { return null }
}
function guidancePanel(guidance) {
if (!guidance) return ''
return `
<div class="guidance-panel">
<p class="guidance-explanation">${esc(guidance.explanation)}</p>
<div class="guidance-action">
<div class="guidance-label">Action</div>
<div class="guidance-text">${esc(guidance.action)}</div>
</div>
<div class="guidance-starter">
<div class="guidance-label">Try saying…</div>
<div class="guidance-text guidance-quote">"${esc(guidance.conversation_starter)}"</div>
</div>
</div>`
}
function renderAlertRows(alerts, feed, isDemo = false) {
feed.innerHTML = (isDemo ? '<div class="demo-banner">Sample data — add a child to see real monitoring</div>' : '')
+ alerts.map(a => {
const guidance = parseGuidance(a)
return `
<div class="alert-row ${a.read ? 'read' : ''} ${guidance ? 'has-guidance' : ''}" data-id="${esc(String(a.id))}">
<div class="alert-row-header">
<span class="alert-pill pill-${esc(a.level)}">${esc(a.level)}</span>
<div class="alert-body">
<div class="alert-title-text">${esc(a.title)}</div>
<div class="alert-meta">${esc(a.child_name)} · ${timeAgo(a.created_at)}</div>
</div>
${guidance ? '<span class="guidance-toggle">What to do ›</span>' : ''}
</div>
${guidancePanel(guidance)}
</div>`
}).join('')
// Toggle guidance expand/collapse
feed.querySelectorAll('.alert-row.has-guidance').forEach(row => {
row.querySelector('.guidance-toggle')?.addEventListener('click', (e) => {
e.stopPropagation()
const panel = row.querySelector('.guidance-panel')
const toggle = row.querySelector('.guidance-toggle')
const open = panel.classList.toggle('open')
toggle.textContent = open ? 'Close ‹' : 'What to do ›'
})
})
}
async function loadAlerts() {
const feed = $('#alert-feed')
try {
const { alerts } = await api('/alerts?limit=8')
if (!alerts.length && isDemoMode) {
renderAlertRows(DEMO_ALERTS, feed, true)
return
}
if (!alerts.length) {
feed.innerHTML = '<div class="empty-state">No alerts yet — your family is protected.</div>'
return
}
renderAlertRows(alerts, feed)
feed.querySelectorAll('.alert-row:not(.read)').forEach(row => {
row.querySelector('.alert-row-header')?.addEventListener('click', async () => {
await api(`/alerts/${row.dataset.id}/read`, { method: 'PATCH' })
row.classList.add('read')
loadStats()
})
})
} catch {
feed.innerHTML = '<div class="empty-state">Could not load alerts.</div>'
}
}
function deviceStatus(lastSeen) {
if (!lastSeen) return { cls: 'offline', label: 'Never connected' }
const mins = (Date.now() - new Date(lastSeen + 'Z').getTime()) / 60000
if (mins < 5) return { cls: 'online', label: 'Active now' }
if (mins < 60) return { cls: 'recent', label: `${Math.round(mins)}m ago` }
return { cls: 'offline', label: timeAgo(lastSeen) }
}
function platformLabel(platform) {
const labels = { browser: 'Browser', ios: 'iPhone', android: 'Android', windows: 'Windows', mac: 'Mac' }
return labels[platform] || platform
}
function platformIcon(platform) {
const icons = {
browser: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="6.5" stroke="currentColor" stroke-width="1.3"/><path d="M1.5 8h13M8 1.5C6.5 4 5.5 6 5.5 8s1 4 2.5 6.5M8 1.5C9.5 4 10.5 6 10.5 8s-1 4-2.5 6.5" stroke="currentColor" stroke-width="1.3"/></svg>`,
ios: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><rect x="4" y="1" width="8" height="14" rx="2" stroke="currentColor" stroke-width="1.3"/><circle cx="8" cy="12.5" r="0.8" fill="currentColor"/></svg>`,
android: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><rect x="3" y="4" width="10" height="9" rx="1.5" stroke="currentColor" stroke-width="1.3"/><path d="M6 4V2.5M10 4V2.5M3 7h10" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`,
windows: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><rect x="1.5" y="1.5" width="13" height="10" rx="1" stroke="currentColor" stroke-width="1.3"/><path d="M5 14.5h6M8 11.5v3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>`,
mac: `<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><rect x="2" y="1.5" width="12" height="9" rx="1" stroke="currentColor" stroke-width="1.3"/><path d="M1 12.5h14" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/><path d="M6 12.5l-1 2h6l-1-2" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
}
return icons[platform] || icons.browser
}
async function loadChildren() {
const list = $('#children-list')
const sidebar = $('#sidebar-children')
try {
const { children } = await api('/family')
if (!children.length) {
renderGettingStarted(list)
sidebar.innerHTML = ''
return
}
list.innerHTML = children.map(c => `
<div class="child-row" data-child-id="${c.id}">
<div class="child-row-header">
<div class="child-avatar">${initials(c.name)}</div>
<div class="child-info">
<div class="child-name">${esc(c.name)}${c.age ? `, ${c.age}` : ''}</div>
<div class="child-devices-label">${c.devices.length} device${c.devices.length !== 1 ? 's' : ''} connected</div>
</div>
<button class="add-device-link" data-child-id="${c.id}" data-child-name="${esc(c.name)}">+ Add device</button>
</div>
<div class="devices-section">
${c.devices.length === 0
? `<span class="no-devices-hint">No devices connected yet.</span>`
: c.devices.map(d => {
const s = deviceStatus(d.last_seen)
const tokenKey = `tk_${Math.random().toString(36).slice(2)}`
tokenStore.set(tokenKey, d.device_token)
return `
<div class="device-item">
<span class="device-item-icon">${platformIcon(d.platform)}</span>
<span class="device-item-name">${esc(d.name)}</span>
<span class="platform-badge platform-${esc(d.platform)}">${esc(platformLabel(d.platform))}</span>
<span class="device-status">
<span class="status-dot-sm ${s.cls}"></span>${s.label}
</span>
<button class="device-token-btn" data-token-key="${tokenKey}">Copy token</button>
</div>`
}).join('')
}
</div>
</div>
`).join('')
// Copy token buttons — token read from JS Map, never from DOM attribute
list.querySelectorAll('.device-token-btn').forEach(btn => {
btn.addEventListener('click', () => {
if (DEMO_MODE) { toast('Create a free account to get your real device token.', 'success'); return }
const token = tokenStore.get(btn.dataset.tokenKey)
if (!token) return
navigator.clipboard.writeText(token).then(() => {
btn.textContent = 'Copied!'
setTimeout(() => { btn.textContent = 'Copy token' }, 2000)
})
})
})
// Add device buttons
list.querySelectorAll('.add-device-link').forEach(btn => {
btn.addEventListener('click', () => openAddDeviceModal(btn.dataset.childId, btn.dataset.childName))
})
sidebar.innerHTML = children.map(c => `
<div class="nav-child-item" data-child-id="${c.id}" style="cursor:pointer">
<span class="child-dot"></span>${esc(c.name)}
</div>
`).join('')
sidebar.querySelectorAll('.nav-child-item').forEach(el => {
el.addEventListener('click', () => setView('child', el.dataset.childId))
})
} catch {
list.innerHTML = '<div class="empty-state">Could not load children.</div>'
}
}
// ─── Add child modal ──────────────────────────────────────────
$('#add-child-btn').addEventListener('click', () => {
$('#add-child-modal').style.display = 'flex'
})
$('#modal-close').addEventListener('click', () => {
$('#add-child-modal').style.display = 'none'
})
$('#add-child-modal').addEventListener('click', (e) => {
if (e.target === $('#add-child-modal')) $('#add-child-modal').style.display = 'none'
})
$('#add-child-form').addEventListener('submit', async (e) => {
e.preventDefault()
const btn = e.target.querySelector('button')
btn.disabled = true; btn.textContent = 'Adding…'
try {
const fd = new FormData(e.target)
await api('/family/child', {
method: 'POST',
body: { name: fd.get('name'), age: fd.get('age') || null }
})
$('#add-child-modal').style.display = 'none'
e.target.reset()
toast(`${fd.get('name')} added to your family.`)
loadChildren()
loadStats()
} catch (err) {
toast(err.message, 'error')
} finally {
btn.disabled = false; btn.textContent = 'Add child'
}
})
// ─── Activity view ────────────────────────────────────────────
async function initActivityView() {
actOffset = 0
const days = $('#act-filter-days')?.value || 7
const childId = $('#act-filter-child')?.value || ''
const level = $('#act-filter-level')?.value || ''
// Populate child filter
const childSel = $('#act-filter-child')
if (childSel && childSel.options.length === 1) {
try {
const { children } = await api('/family')
children.forEach(c => {
const o = document.createElement('option')
o.value = c.id; o.textContent = c.name
childSel.appendChild(o)
})
} catch {}
}
let params = `?days=${days}`
if (childId) params += `&child_id=${childId}`
if (level) params += `&level=${level}`
try {
const data = await api(`/activity${params}`)
renderDailyChart(data.byDay)
renderCategoryChart(data.byCategory)
} catch {}
await loadActivityTable(true)
}
async function loadOverviewCharts() {
try {
const data = await api('/activity?days=7')
renderDailyChart(data.byDay, 'chart-overview-daily')
renderCategoryChart(data.byCategory, 'chart-overview-cat')
} catch {}
}
function renderDailyChart(byDay, canvasId = 'chart-daily') {
// Merge real data on top of fake baseline so chart is never sparse
const labels = byDay.map(d => new Date(d.date + 'T12:00:00').toLocaleDateString('en-US', { weekday: 'short' }))
const critical = byDay.map(d => d.critical)
const warn = byDay.map(d => d.warn)
const info = byDay.map(d => d.info)
mkChart(canvasId, {
type: 'bar',
data: {
labels,
datasets: [
{ label: 'Critical', data: critical, backgroundColor: '#C85A2E', borderRadius: 6, stack: 's' },
{ label: 'Warning', data: warn, backgroundColor: '#D97706', borderRadius: 6, stack: 's' },
{ label: 'Info', data: info, backgroundColor: '#2C5A3F', borderRadius: 6, stack: 's' },
]
},
options: {
responsive: true, maintainAspectRatio: false,
plugins: { legend: { display: true, position: 'bottom', labels: { boxWidth: 10, padding: 14, font: { size: 11 } } } },
scales: {
x: { grid: { display: false }, border: { display: false }, ticks: { maxRotation: 0 } },
y: { grid: { color: 'rgba(26,42,34,0.06)' }, border: { display: false }, ticks: { precision: 0, stepSize: 2 } }
}
}
})
}
function renderCategoryChart(byCategory, canvasId = 'chart-category') {
const labels = byCategory.map(c => c.category)
const data = byCategory.map(c => c.count)
const colors = CAT_COLORS.slice(0, labels.length)
mkChart(canvasId, {
type: 'doughnut',
data: {
labels,
datasets: [{
data,
backgroundColor: colors,
borderWidth: 3,
borderColor: '#FBF7EB',
hoverOffset: 8,
}]
},
options: {
responsive: true, maintainAspectRatio: false, cutout: '62%',
plugins: {
legend: { display: true, position: 'bottom', labels: { boxWidth: 10, padding: 12, font: { size: 11 } } }
}
}
})
}
async function loadActivityTable(reset = false) {
if (reset) actOffset = 0
const days = $('#act-filter-days')?.value || 7
const childId = $('#act-filter-child')?.value || ''
const level = $('#act-filter-level')?.value || ''
let params = `/alerts?limit=${ACT_LIMIT}&offset=${actOffset}&days=${days}`
if (childId) params += `&child_id=${childId}`
if (level) params += `&unread=false&level=${level}`
try {
const { alerts, unread } = await api(params)
const table = $('#act-table')
const countEl = $('#act-count')
if (countEl) countEl.textContent = `${unread} unread`
const rows = alerts.map(a => `
<tr class="${a.read ? 'read' : ''}" data-id="${a.id}">
<td><span class="alert-pill pill-${esc(a.level)}">${esc(a.level)}</span></td>
<td style="font-weight:500;max-width:260px">${esc(a.title)}</td>
<td style="color:var(--ink-soft)">${esc(a.category)}</td>
<td style="color:var(--ink-soft)">${esc(a.child_name)}</td>
<td style="color:var(--ink-soft);white-space:nowrap">${timeAgo(a.created_at)}</td>
</tr>
`).join('')
if (reset) {
table.innerHTML = alerts.length
? `<table class="act-table"><thead><tr>
<th>Level</th><th>Alert</th><th>Category</th><th>Child</th><th>When</th>
</tr></thead><tbody id="act-tbody">${rows}</tbody></table>`
: '<div class="empty-state">No alerts for this filter.</div>'
} else {
const tbody = document.getElementById('act-tbody')
if (tbody) tbody.insertAdjacentHTML('beforeend', rows)
}
table.querySelectorAll('tr[data-id]:not(.bound)').forEach(row => {
row.classList.add('bound')
row.addEventListener('click', async () => {
if (!row.classList.contains('read')) {
await api(`/alerts/${row.dataset.id}/read`, { method: 'PATCH' })
row.classList.add('read')
}
})
})
const loadMore = $('#act-load-more')
if (loadMore) loadMore.style.display = alerts.length === ACT_LIMIT ? 'block' : 'none'
actOffset += alerts.length
} catch (err) { console.error(err) }
}
$('#act-load-more')?.addEventListener('click', () => loadActivityTable(false))
;['#act-filter-child', '#act-filter-level', '#act-filter-days'].forEach(sel => {
document.getElementById(sel.slice(1))?.addEventListener('change', initActivityView)
})
// ─── Weekly report view ───────────────────────────────────────
async function initWeeklyView() {
const now = new Date()
const start = new Date(); start.setDate(now.getDate() - 6)
const fmt = d => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
$('#weekly-date-range').textContent = `${fmt(start)} – ${fmt(now)}, ${now.getFullYear()}`
try {
const raw = await api('/activity?days=7')
const byLevel = raw.byLevel ?? []
const byDay = raw.byDay ?? []
const byChild = raw.byChild ?? []
// Stat cards
const total = byLevel.reduce((s, d) => s + d.count, 0)
const critical = byLevel.find(d => d.level === 'critical')?.count || 0
const warn = byLevel.find(d => d.level === 'warn')?.count || 0
const info = byLevel.find(d => d.level === 'info')?.count || 0
$('#weekly-stats').innerHTML = `
<div class="stat-card"><div class="stat-label">Total signals</div><div class="stat-num">${total}</div><div class="stat-sub">this week</div></div>
<div class="stat-card"><div class="stat-label">Critical</div><div class="stat-num" style="color:#C85A2E">${critical}</div><div class="stat-sub">require action</div></div>
<div class="stat-card"><div class="stat-label">Warnings</div><div class="stat-num" style="color:#D97706">${warn}</div><div class="stat-sub">worth reviewing</div></div>
<div class="stat-card"><div class="stat-label">Info</div><div class="stat-num">${info}</div><div class="stat-sub">low risk</div></div>
`
// Risk line chart — shows per-child risk score trend across 7 days
const datasets = byChild.map((c, i) => ({
label: c.name,
data: byDay.map(d => {
// Simple risk heuristic: critical=20, warn=10, info=3
return d.critical * 20 + d.warn * 10 + d.info * 3
}),
borderColor: CAT_COLORS[i % CAT_COLORS.length],
backgroundColor: `rgba(44,90,63,0.06)`,
borderWidth: 2.5,
pointBackgroundColor: CAT_COLORS[i % CAT_COLORS.length],
pointRadius: 4,
tension: 0.4,
fill: true,
}))
mkChart('chart-weekly-trend', {
type: 'line',
data: {
labels: byDay.map(d => new Date(d.date + 'T12:00:00').toLocaleDateString('en-US', { weekday: 'short' })),
datasets
},
options: {
responsive: true, maintainAspectRatio: false,
plugins: { legend: { display: true, position: 'bottom', labels: { boxWidth: 10, padding: 14, font: { size: 11 } } } },
scales: {
x: { grid: { display: false }, border: { display: false } },
y: { grid: { color: 'rgba(26,42,34,0.06)' }, border: { display: false }, min: 0, max: 100, ticks: { callback: v => v + '%' } }
}
}
})
// Distribution doughnut
mkChart('chart-weekly-dist', {
type: 'doughnut',
data: {
labels: byLevel.map(l => l.level.toUpperCase()),
datasets: [{
data: byLevel.map(l => l.count),
backgroundColor: byLevel.map(l => LEVEL_COLOR[l.level] || '#9CA3AF'),
borderWidth: 3,
borderColor: '#FBF7EB',
hoverOffset: 8,
}]
},
options: {
responsive: true, maintainAspectRatio: false, cutout: '62%',
plugins: { legend: { display: true, position: 'bottom', labels: { boxWidth: 10, padding: 12, font: { size: 11 } } } }
}
})
// Per-child breakdown
const childEl = $('#weekly-children')
if (!byChild.length) {
childEl.innerHTML = '<div class="empty-state">No activity this week.</div>'
} else {
const maxCount = Math.max(...byChild.map(c => c.count), 1)
childEl.innerHTML = byChild.map(c => {
const pct = Math.round((c.count / maxCount) * 100)
const color = c.critical > 0 ? '#C85A2E' : c.warn > 0 ? '#D97706' : '#2C5A3F'
return `
<div class="child-breakdown-row">
<div class="child-avatar" style="width:40px;height:40px;font-size:14px;flex-shrink:0">${initials(c.name)}</div>
<div class="risk-bar-wrap">
<div class="risk-bar-label">
<span style="font-weight:500;font-size:14px;color:var(--ink)">${esc(c.name)}</span>
<span>${c.count} signals · <span style="color:#C85A2E">${c.critical} critical</span> · <span style="color:#D97706">${c.warn} warnings</span></span>
</div>
<div class="risk-bar-track">
<div class="risk-bar-fill" style="width:${pct}%;background:${color}"></div>
</div>
</div>
</div>
`
}).join('')
}
} catch (err) { console.error(err) }
}
// ─── Child detail view ────────────────────────────────────────
async function initChildView(childId) {
const container = $('#child-detail-content')
container.style.cssText = 'display:flex;flex-direction:column;flex:1;min-height:0'
container.innerHTML = '<div class="empty-state">Loading…</div>'
try {
const { child, devices, alerts, stats } = await api(`/child/${childId}`)
$('#topbar-greeting').textContent = child.name
container.innerHTML = `
<div class="child-detail-header">
<div class="child-detail-avatar">${initials(child.name)}</div>
<div>
<div class="child-detail-name">${esc(child.name)}</div>
<div class="child-detail-age">${child.age ? `Age ${child.age}` : 'Age not set'}</div>
</div>
</div>
<div class="stats-row" style="margin-bottom:24px;flex-shrink:0">
<div class="stat-card"><div class="stat-label">Devices</div><div class="stat-num">${devices.length}</div><div class="stat-sub">connected</div></div>
<div class="stat-card"><div class="stat-label">Signals</div><div class="stat-num">${stats.signals}</div><div class="stat-sub">this week</div></div>
<div class="stat-card"><div class="stat-label">Unread alerts</div><div class="stat-num" style="color:#C85A2E">${stats.unread}</div><div class="stat-sub">need review</div></div>
<div class="stat-card"><div class="stat-label">Peak risk</div><div class="stat-num" style="color:${stats.maxRisk >= 80 ? '#C85A2E' : stats.maxRisk >= 60 ? '#D97706' : '#2C5A3F'}">${stats.maxRisk}</div><div class="stat-sub">max score</div></div>
</div>
<div class="two-col" style="margin-bottom:24px;flex:0 0 auto">
<div class="card">
<div class="card-header"><span class="card-title">Devices</span>
<button class="card-action add-device-link" data-child-id="${child.id}" data-child-name="${esc(child.name)}">+ Add device</button>
</div>
<div style="padding:0 24px 24px">
${devices.length === 0
? '<p class="no-devices-hint">No devices connected yet.</p>'
: devices.map(d => {
const s = deviceStatus(d.last_seen)
const tokenKey = `tk_${Math.random().toString(36).slice(2)}`
tokenStore.set(tokenKey, d.device_token)
return `<div class="device-item" style="margin-bottom:8px">
<span class="device-item-icon">${platformIcon(d.platform)}</span>
<span class="device-item-name">${esc(d.name)}</span>
<span class="platform-badge platform-${esc(d.platform)}">${esc(platformLabel(d.platform))}</span>
<span class="device-status"><span class="status-dot-sm ${s.cls}"></span>${s.label}</span>
<button class="device-token-btn" data-token-key="${tokenKey}">Copy token</button>
</div>`
}).join('')
}
</div>
</div>
<div class="card">
<div class="card-header"><span class="card-title">Activity this week</span></div>
<div class="chart-wrap" style="height:260px"><canvas id="chart-child-activity"></canvas></div>
</div>
</div>
<div class="card" style="flex:1;min-height:0">
<div class="card-header" style="flex-shrink:0"><span class="card-title">Recent alerts</span></div>
<div class="alert-feed" id="child-alert-feed">
${alerts.length === 0
? '<div class="empty-state">No alerts yet.</div>'
: alerts.map(a => {
const g = parseGuidance(a)
return `
<div class="alert-row ${a.read?'read':''} ${g?'has-guidance':''}" data-id="${esc(String(a.id))}">
<div class="alert-row-header">
<span class="alert-pill pill-${esc(a.level)}">${esc(a.level)}</span>
<div class="alert-body">
<div class="alert-title-text">${esc(a.title)}</div>
<div class="alert-meta">${esc(a.category)} · ${timeAgo(a.created_at)}</div>
</div>
${g ? '<span class="guidance-toggle">What to do ›</span>' : ''}