Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
3528 lines (3077 loc) · 121 KB
/
Copy pathapp.js
File metadata and controls
3528 lines (3077 loc) · 121 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
// --- Family config (loaded from /api/config before anything renders) ---
let familyConfig = {
appName: "Daddy Daycare",
parentRoles: ["Dad", "Mom"],
kidRoles: ["Child 1", "Child 2"],
allRoles: ["Dad", "Mom", "Child 1", "Child 2"],
};
async function loadFamilyConfig() {
try {
const res = await fetch("/api/config");
if (res.ok) familyConfig = await res.json();
} catch { /* use defaults */ }
// Rebuild derived state from config
PARENT_USERS.clear();
for (const r of familyConfig.parentRoles) PARENT_USERS.add(r);
// Default avatars: parents get gendered emoji, kids get 🧒
const defaultParentEmojis = ["👨", "👩", "🧑", "👤"];
const defaultKidEmojis = ["🧒", "👧", "👦", "🧒"];
familyConfig.parentRoles.forEach((r, i) => {
if (!DEFAULT_AVATARS[r]) DEFAULT_AVATARS[r] = defaultParentEmojis[i] || "👤";
});
familyConfig.kidRoles.forEach((r, i) => {
if (!DEFAULT_AVATARS[r]) DEFAULT_AVATARS[r] = defaultKidEmojis[i] || "🧒";
});
// Merge family-specific extra streaks from schedule.config.js
const extra = window.SCHEDULE_CONFIG?.extraStreaks || {};
for (const [id, def] of Object.entries(extra)) STREAK_DEFS[id] = def;
}
// --- State ---
let currentUser = null;
let selectedRole = null;
let setupStep = 0;
let pendingPassword = "";
let draggedChoreId = null;
let dashboardClockTimer = null;
let dashboardRefreshTimer = null;
let dashboardRefreshInFlight = false;
let eggTimerIntervals = [];
let eggAdminInFlight = false;
let dashboardAudioContext = null;
let dashboardAlerts = [];
let dashboardAlertId = 0;
let dashboardShellBuilt = false;
let appState = {
tokens: {},
pending: [],
approved: [],
denied: [],
streaks: {},
avatars: {},
chores: [],
scheduleStatuses: {},
spendNotifications: [],
affirmations: [],
rewards: [],
active_eggs: [],
egg_accepts: [],
egg_challenges_meta: {},
egg_challenges_pending: [],
};
const SCHEDULE_STATUS_LABELS = {
"not-done": "Not Done",
"in-progress": "In Progress",
done: "Done"
};
const DASHBOARD_MODE_STORAGE_KEY = "daycare_dashboard_mode";
const DASHBOARD_THEME_MODE_STORAGE_KEY = "daycare_dashboard_theme_mode";
const AUTH_TOKEN_KEY = "daycare_token";
const AUTH_ROLE_KEY = "daycare_role";
const DEFAULT_AVATARS = {};
const PARENT_USERS = new Set();
const AVATAR_OUTPUT_SIZE = 180;
const MAX_AVATAR_FILE_BYTES = 8 * 1024 * 1024;
function isParentUser(user = currentUser) {
return typeof user === "string" && PARENT_USERS.has(user);
}
const STREAK_DEFS = {
helping: {
label: "🤝 Helping Streak",
goal: 5,
prompt: "Helped out today"
},
kindness: {
label: "💛 Kindness Streak",
goal: 7,
prompt: "Was kind today"
},
workout: {
label: "💪 Workout Streak",
goal: 0,
prompt: "Worked out today"
},
// Extra streaks from window.SCHEDULE_CONFIG.extraStreaks are merged in loadFamilyConfig
};
// --- Schedule (loaded from schedule.config.js via window.SCHEDULE_CONFIG) ---
function getDailyBlocks(date = new Date()) {
const cfg = window.SCHEDULE_CONFIG || {};
const t = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
const dateKey = `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,"0")}-${String(date.getDate()).padStart(2,"0")}`;
// Exact date overrides take highest priority
if (cfg.customDates && cfg.customDates[dateKey]) return cfg.customDates[dateKey];
// Date range override (e.g. transition week)
if (cfg.transitionRange) {
const [sy,sm,sd] = cfg.transitionRange.start, [ey,em,ed] = cfg.transitionRange.end;
const rangeStart = new Date(sy, sm-1, sd).getTime();
const rangeEnd = new Date(ey, em-1, ed).getTime();
if (t >= rangeStart && t <= rangeEnd) return cfg.transitionRange.blocks || [];
}
// Day-of-week block override (e.g. weekend-specific schedules)
const dow = date.getDay();
if (cfg.dayBlocks && cfg.dayBlocks[dow]) return cfg.dayBlocks[dow];
return cfg.dailyBlocks || [];
}
function getTodayScheduleKey(date = new Date()) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
function getScheduleStatuses() {
return appState.scheduleStatuses || {};
}
function getScheduleStatus(dayKey, blockId) {
const dayStatuses = getScheduleStatuses()[dayKey] || {};
return dayStatuses[blockId] || null;
}
function getScheduleSummary(dayKey) {
const [y, m, d] = dayKey.split('-').map(Number);
const blocks = getDailyBlocks(new Date(y, m - 1, d));
const summary = {
total: blocks.length,
done: 0,
inProgress: 0,
notDone: 0,
unmarked: 0
};
for (const block of blocks) {
const status = getScheduleStatus(dayKey, block.id);
if (status === "done") {
summary.done += 1;
} else if (status === "in-progress") {
summary.inProgress += 1;
} else if (status === "not-done") {
summary.notDone += 1;
} else {
summary.unmarked += 1;
}
}
return summary;
}
function getScheduleSummaryForStatuses(scheduleStatuses, dayKey) {
const [y, m, d] = dayKey.split('-').map(Number);
const blocks = getDailyBlocks(new Date(y, m - 1, d));
const summary = {
total: blocks.length,
done: 0,
inProgress: 0,
notDone: 0,
unmarked: 0
};
const dayStatuses = (scheduleStatuses && scheduleStatuses[dayKey]) || {};
for (const block of blocks) {
const status = dayStatuses[block.id] || null;
if (status === "done") {
summary.done += 1;
} else if (status === "in-progress") {
summary.inProgress += 1;
} else if (status === "not-done") {
summary.notDone += 1;
} else {
summary.unmarked += 1;
}
}
return summary;
}
function getScheduleContext(date = new Date()) {
const dow = date.getDay();
const currentIdx = getCurrentBlockIndex();
const scheduleKey = getTodayScheduleKey(date);
const theme = (window.SCHEDULE_CONFIG?.dayThemes || {})[dow] || null;
const week = getSummerWeek(date);
const blocks = getDailyBlocks(date);
const currentBlock = currentIdx === null ? null : blocks[currentIdx] || null;
const upcomingStart = currentIdx === null ? 0 : currentIdx + 1;
const upcomingBlocks = blocks.slice(upcomingStart, upcomingStart + 4);
const dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const dateStr = `${dayNames[dow]}, ${monthNames[date.getMonth()]} ${date.getDate()}`;
return {
dow,
currentIdx,
currentBlock,
upcomingBlocks,
scheduleKey,
theme,
week,
dateStr
};
}
function getStoredDashboardMode() {
return localStorage.getItem(DASHBOARD_MODE_STORAGE_KEY) === "on";
}
function getStoredDashboardThemeMode() {
const stored = localStorage.getItem(DASHBOARD_THEME_MODE_STORAGE_KEY);
return stored === "day" || stored === "night" ? stored : "auto";
}
function setStoredDashboardMode(enabled) {
if (enabled) {
localStorage.setItem(DASHBOARD_MODE_STORAGE_KEY, "on");
} else {
localStorage.removeItem(DASHBOARD_MODE_STORAGE_KEY);
}
}
function exitDashboard() {
setDashboardMode(false);
// If no one is logged in (entered from login screen), return to login
if (!currentUser) {
document.getElementById("login-screen").style.display = "flex";
document.getElementById("app").style.display = "none";
}
}
function setStoredDashboardThemeMode(mode) {
if (mode === "day" || mode === "night") {
localStorage.setItem(DASHBOARD_THEME_MODE_STORAGE_KEY, mode);
return;
}
localStorage.removeItem(DASHBOARD_THEME_MODE_STORAGE_KEY);
}
function isAutomaticNightHours(date = new Date()) {
const hour = date.getHours();
return hour >= 19 || hour < 7;
}
function isDashboardNightTheme(date = new Date()) {
const themeMode = getStoredDashboardThemeMode();
if (themeMode === "night") return true;
if (themeMode === "day") return false;
return isAutomaticNightHours(date);
}
function cycleDashboardThemeMode() {
if (!isParentUser()) {
return;
}
const currentMode = getStoredDashboardThemeMode();
const nextMode = currentMode === "auto" ? "night" : currentMode === "night" ? "day" : "auto";
setStoredDashboardThemeMode(nextMode);
renderDashboardMode();
}
function getDashboardThemeLabel() {
const mode = getStoredDashboardThemeMode();
if (mode === "night") return "Theme: Night";
if (mode === "day") return "Theme: Day";
return "Theme: Auto";
}
function isDashboardModeEnabled() {
return document.body.classList.contains("dashboard-mode");
}
function updateDashboardToggle() {
const button = document.getElementById("dashboard-toggle");
if (!button) return;
const enabled = isDashboardModeEnabled();
button.textContent = enabled ? "Exit TV Dashboard" : "Enable TV Dashboard";
button.classList.toggle("active", enabled);
}
function ensureDashboardAudio() {
const AudioContextCtor = window.AudioContext || window.webkitAudioContext;
if (!AudioContextCtor) {
return null;
}
if (!dashboardAudioContext) {
dashboardAudioContext = new AudioContextCtor();
}
if (dashboardAudioContext.state === "suspended") {
dashboardAudioContext.resume().catch(() => {});
}
return dashboardAudioContext;
}
function playDashboardSound(kind) {
const context = ensureDashboardAudio();
if (!context) return;
const sequences = {
success: [
{ freq: 523.25, duration: 0.12, gain: 0.05 },
{ freq: 659.25, duration: 0.14, gain: 0.06 },
{ freq: 783.99, duration: 0.18, gain: 0.07 }
],
achievement: [
{ freq: 523.25, duration: 0.1, gain: 0.05 },
{ freq: 659.25, duration: 0.12, gain: 0.06 },
{ freq: 783.99, duration: 0.12, gain: 0.07 },
{ freq: 1046.5, duration: 0.22, gain: 0.08 }
],
progress: [
{ freq: 440, duration: 0.12, gain: 0.045 },
{ freq: 587.33, duration: 0.16, gain: 0.05 }
],
warning: [
{ freq: 369.99, duration: 0.12, gain: 0.05, type: "triangle" },
{ freq: 329.63, duration: 0.16, gain: 0.045, type: "triangle" }
],
coins: [
{ freq: 523.25, duration: 0.07, gain: 0.07 },
{ freq: 659.25, duration: 0.07, gain: 0.07 },
{ freq: 783.99, duration: 0.07, gain: 0.08 },
{ freq: 1046.5, duration: 0.07, gain: 0.09 },
{ freq: 1318.5, duration: 0.13, gain: 0.10 }
],
levelup: [
{ freq: 392.00, duration: 0.09, gain: 0.06 },
{ freq: 523.25, duration: 0.09, gain: 0.07 },
{ freq: 659.25, duration: 0.09, gain: 0.08 },
{ freq: 783.99, duration: 0.09, gain: 0.08 },
{ freq: 1046.5, duration: 0.20, gain: 0.10 }
],
fanfare: [
{ freq: 392.00, duration: 0.10, gain: 0.07 },
{ freq: 523.25, duration: 0.10, gain: 0.08 },
{ freq: 659.25, duration: 0.10, gain: 0.09 },
{ freq: 783.99, duration: 0.14, gain: 0.10 },
{ freq: 1046.5, duration: 0.10, gain: 0.09 },
{ freq: 1318.5, duration: 0.28, gain: 0.12 }
]
};
const steps = sequences[kind] || sequences.progress;
let startAt = context.currentTime + 0.02;
for (const step of steps) {
const oscillator = context.createOscillator();
const gainNode = context.createGain();
const duration = step.duration || 0.15;
oscillator.type = step.type || "sine";
oscillator.frequency.setValueAtTime(step.freq, startAt);
gainNode.gain.setValueAtTime(0.0001, startAt);
gainNode.gain.exponentialRampToValueAtTime(step.gain || 0.05, startAt + 0.02);
gainNode.gain.exponentialRampToValueAtTime(0.0001, startAt + duration);
oscillator.connect(gainNode);
gainNode.connect(context.destination);
oscillator.start(startAt);
oscillator.stop(startAt + duration + 0.03);
startAt += duration * 0.82;
}
}
function triggerConfetti(intensity = 1) {
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:9999;";
const maxW = Math.min(window.innerWidth, 640);
const scale = maxW / window.innerWidth;
canvas.width = maxW;
canvas.height = Math.round(window.innerHeight * scale);
canvas.style.width = "100%";
canvas.style.height = "100%";
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
const colors = ["#ff6b6b","#ffd93d","#6bcb77","#4d96ff","#c77dff","#ff9f43","#00d2d3","#ff6348"];
const count = Math.round(28 * intensity);
const particles = Array.from({ length: count }, () => ({
x: Math.random() * canvas.width,
y: -20 - Math.random() * 80,
vx: (Math.random() - 0.5) * 7,
vy: Math.random() * 4 + 2,
color: colors[Math.floor(Math.random() * colors.length)],
w: Math.random() * 10 + 5,
h: Math.random() * 6 + 3,
rotation: Math.random() * 360,
rotSpeed: (Math.random() - 0.5) * 12,
opacity: 1
}));
let frame = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
let alive = false;
for (const p of particles) {
p.x += p.vx;
p.y += p.vy;
p.vy += 0.15;
p.rotation += p.rotSpeed;
if (frame > 90) p.opacity -= 0.018;
if (p.y < canvas.height + 30 && p.opacity > 0) alive = true;
ctx.save();
ctx.globalAlpha = Math.max(0, p.opacity);
ctx.translate(p.x, p.y);
ctx.rotate((p.rotation * Math.PI) / 180);
ctx.fillStyle = p.color;
ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
ctx.restore();
}
frame++;
if (alive && frame < 160) requestAnimationFrame(animate);
else canvas.remove();
}
requestAnimationFrame(animate);
}
function animateCounter(el, from, to, duration = 700) {
if (!el || from === to) return;
const start = performance.now();
function step(now) {
const t = Math.min((now - start) / duration, 1);
const eased = 1 - Math.pow(1 - t, 3);
el.textContent = Math.round(from + (to - from) * eased);
if (t < 1) requestAnimationFrame(step);
else el.textContent = to;
}
requestAnimationFrame(step);
}
const MOTIVATIONAL_MESSAGES = [
"Your team is unstoppable! 💪",
"Every kind act earns a sun token! ☀️",
"Work together, win together! 🤝",
"Kindness is the biggest superpower! 💛",
"The streak is on fire — keep going! 🔥",
"You guys are crushing it today! 🏆",
"Be kind once and watch it multiply! 🌟",
"Dad is so proud of you both! ❤️",
"Small acts, big rewards! ✨",
"Today is a great day to help! 🙌",
"Together you can do anything! 🎉",
"Keep that helping streak alive! 🔥",
];
function getDashboardMotivation() {
const idx = Math.floor(Date.now() / 60000) % MOTIVATIONAL_MESSAGES.length;
return MOTIVATIONAL_MESSAGES[idx];
}
function buildFloatingEmojisMarkup() {
const emojis = ["⭐","🏆","💛","🌟"];
return emojis.map((emoji, i) => {
const left = ((i * 23 + 6) % 90).toFixed(1);
const delay = (-(i * 4.5)).toFixed(1);
const dur = (18 + (i % 3) * 4).toFixed(1);
const size = (1.1 + (i % 2) * 0.3).toFixed(2);
return `<span class="db-float-emoji" style="left:${left}%;animation-delay:${delay}s;animation-duration:${dur}s;font-size:${size}rem;" aria-hidden="true">${emoji}</span>`;
}).join("");
}
function buildDashboardAvatarHtml(user) {
// Never embed data URLs in HTML strings — use data-avatar-user and applyDashboardAvatars()
return `<span class="db-avatar" data-avatar-user="${escapeHtml(user)}">${escapeHtml(getDefaultAvatar(user))}</span>`;
}
function applyDashboardAvatars(root) {
root.querySelectorAll("[data-avatar-user]").forEach(el => {
const user = el.dataset.avatarUser;
const avatarData = getAvatar(user);
if (avatarData) {
el.style.backgroundImage = `url("${avatarData}")`;
el.textContent = "";
} else {
el.style.backgroundImage = "none";
el.textContent = getDefaultAvatar(user);
}
});
}
function formatDashboardAlertTime(time) {
return new Date(time).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}
function pushDashboardAlert(type, title, detail, sound = "progress") {
dashboardAlerts = [{
id: ++dashboardAlertId,
type,
title,
detail,
time: Date.now()
}].concat(dashboardAlerts).slice(0, 8);
if (isParentUser() && isDashboardModeEnabled()) {
playDashboardSound(sound);
renderDashboardMode();
}
}
function buildDashboardSnapshot(state = appState) {
const dayKey = getTodayScheduleKey();
const tokens = state.tokens || {};
const streaks = state.streaks || {};
return {
dayKey,
summary: getScheduleSummaryForStatuses(state.scheduleStatuses || {}, dayKey),
pendingKeys: (state.pending || []).map(item => item.key).sort(),
spendKeys: (state.spendNotifications || []).map(item => `${item.time}|${item.user}|${item.rewardName}|${item.cost}`).sort(),
tokens: Object.fromEntries(familyConfig.kidRoles.map(r => [r, Number(tokens[r] || 0)])),
streaks: familyConfig.kidRoles.reduce((result, user) => {
result[user] = {};
for (const streakId of Object.keys(STREAK_DEFS)) {
const record = ((streaks[user] || {})[streakId]) || {};
result[user][streakId] = {
current: Number(record.current || 0),
best: Number(record.best || 0)
};
}
return result;
}, {})
};
}
function announceDashboardChanges(previousSnapshot, nextSnapshot, options = {}) {
if (!previousSnapshot || options.silent) {
return;
}
const doneDelta = nextSnapshot.summary.done - previousSnapshot.summary.done;
const progressDelta = nextSnapshot.summary.inProgress - previousSnapshot.summary.inProgress;
const missedDelta = nextSnapshot.summary.notDone - previousSnapshot.summary.notDone;
if (doneDelta > 0) {
pushDashboardAlert("success", "Schedule block completed! 🎉", `${doneDelta} block${doneDelta === 1 ? "" : "s"} moved to done.`, "levelup");
triggerConfetti(doneDelta);
}
if (progressDelta > 0) {
pushDashboardAlert("progress", "Something is underway 🚀", `${progressDelta} block${progressDelta === 1 ? " is" : "s are"} now in progress.`, "progress");
}
if (missedDelta > 0) {
pushDashboardAlert("warning", "Schedule adjusted", `${missedDelta} block${missedDelta === 1 ? " was" : "s were"} marked not done.`, "warning");
}
for (const user of familyConfig.kidRoles) {
const tokenDelta = nextSnapshot.tokens[user] - previousSnapshot.tokens[user];
if (tokenDelta > 0) {
pushDashboardAlert("success", `${user} earned ${tokenDelta} ☀️ tokens!`, `New balance: ${nextSnapshot.tokens[user]} ☀️`, "coins");
triggerConfetti(0.6);
}
}
const previousPendingKeys = new Set(previousSnapshot.pendingKeys);
for (const pendingKey of nextSnapshot.pendingKeys) {
if (!previousPendingKeys.has(pendingKey)) {
const pendingItem = getPending().find(item => item.key === pendingKey);
if (pendingItem) {
pushDashboardAlert("progress", `New approval for ${pendingItem.user}`, pendingLabel(pendingItem), "progress");
}
}
}
const previousSpendKeys = new Set(previousSnapshot.spendKeys);
for (const spendKey of nextSnapshot.spendKeys) {
if (!previousSpendKeys.has(spendKey)) {
const spendItem = getSpendNotifications().find(item => `${item.time}|${item.user}|${item.rewardName}|${item.cost}` === spendKey);
if (spendItem) {
pushDashboardAlert("success", `${spendItem.user} cashed out`, `${spendItem.rewardName} for ${spendItem.cost} ☀️`, "success");
}
}
}
for (const user of familyConfig.kidRoles) {
for (const [streakId, config] of Object.entries(STREAK_DEFS)) {
const previousRecord = previousSnapshot.streaks[user][streakId];
const nextRecord = nextSnapshot.streaks[user][streakId];
if (nextRecord.current > previousRecord.current) {
pushDashboardAlert("progress", `${user}'s ${config.label} moved! 🔥`, `Now at ${nextRecord.current} day${nextRecord.current === 1 ? "" : "s"}.`, "success");
}
if (config.goal > 0 && previousRecord.current < config.goal && nextRecord.current >= config.goal) {
pushDashboardAlert("achievement", `🏆 ${user} CRUSHED THE GOAL!`, `${config.label} hit ${config.goal} days — incredible!`, "fanfare");
triggerConfetti(2);
} else if (nextRecord.best > previousRecord.best && nextRecord.best > 0) {
pushDashboardAlert("achievement", `🌟 ${user} set a new best!`, `${config.label} best is now ${nextRecord.best} days.`, "fanfare");
triggerConfetti(1.2);
}
}
}
}
function buildDashboardAlertsMarkup() {
if (dashboardAlerts.length === 0) {
return '<p class="dashboard-empty">Alerts will appear here when the day changes shape.</p>';
}
return dashboardAlerts.map(alert => `
<div class="dashboard-alert-item dashboard-alert-${alert.type}">
<div>
<strong>${escapeHtml(alert.title)}</strong>
<span>${escapeHtml(alert.detail)}</span>
</div>
<small>${escapeHtml(formatDashboardAlertTime(alert.time))}</small>
</div>
`).join("");
}
function buildDashboardToastMarkup() {
if (dashboardAlerts.length === 0) {
return "";
}
return `
<div class="dashboard-toast-stack">
${dashboardAlerts.slice(0, 3).map(alert => `
<div class="dashboard-toast dashboard-alert-${alert.type}">
<strong>${escapeHtml(alert.title)}</strong>
<span>${escapeHtml(alert.detail)}</span>
</div>
`).join("")}
</div>
`;
}
function celebrateUser(user) {
const shell = document.getElementById("dashboard-shell");
if (!shell) return;
const card = shell.querySelector(`.db-score-${user.toLowerCase()}`);
if (!card) return;
const avatar = card.querySelector(".db-avatar");
if (!avatar) return;
avatar.classList.remove("db-avatar-celebrate");
void avatar.offsetWidth;
avatar.classList.add("db-avatar-celebrate");
avatar.addEventListener("animationend", () => avatar.classList.remove("db-avatar-celebrate"), { once: true });
}
let streakCometGuard = null;
function streakFlyAcross(user) {
if (streakCometGuard) return;
streakCometGuard = setTimeout(() => streakCometGuard = null, 1600);
const card = document.querySelector(`.db-streak-${user.toLowerCase()}`);
if (!card) return;
const avatarEl = card.querySelector(".db-avatar");
const originEl = (avatarEl && avatarEl.getBoundingClientRect().width > 0) ? avatarEl : card;
const rect = originEl.getBoundingClientRect();
const startX = rect.left + rect.width / 2;
const startY = rect.top + rect.height / 2;
const flyX = window.innerWidth - startX + 120;
const flyY = -(startY + 120);
const fireCount = 14;
let fires = "";
for (let i = 0; i < fireCount; i++) {
fires += `<span class="db-comet-fire" style="--i:${i}"></span>`;
}
const comet = document.createElement("div");
comet.className = "db-comet";
comet.style.setProperty("--start-x", startX + "px");
comet.style.setProperty("--start-y", startY + "px");
comet.style.setProperty("--fly-x", flyX + "px");
comet.style.setProperty("--fly-y", flyY + "px");
comet.innerHTML = `<span class="db-comet-avatar">${escapeHtml(getDefaultAvatar(user))}</span><span class="db-comet-trail">${fires}</span>`;
document.body.appendChild(comet);
void comet.offsetWidth;
comet.classList.add("db-comet-launch");
comet.addEventListener("animationend", () => { comet.remove(); }, { once: true });
}
function toggleDashboardMode() {
if (!isParentUser()) {
return;
}
setDashboardMode(!isDashboardModeEnabled());
}
async function enterLoginDashboard() {
await loadFamilyConfig();
await refreshState();
await loadPublicAvatars();
document.getElementById("login-screen").style.display = "none";
document.getElementById("app").style.display = "flex";
document.getElementById("parent-view").style.display = "none";
document.getElementById("kid-view").style.display = "none";
document.getElementById("wallet").style.display = "none";
document.getElementById("avatar-panel").style.display = "none";
document.getElementById("schedule-toggle").style.display = "none";
const panel = document.getElementById("dashboard-mode");
if (panel) panel.style.display = "block";
document.body.classList.add("dashboard-mode");
document.getElementById("app").classList.add("dashboard-mode");
setStoredDashboardMode(true);
ensureDashboardAudio();
renderDashboardMode();
syncDashboardClock();
syncDashboardRefresh();
}
function setDashboardMode(enabled) {
const shouldEnable = enabled && isParentUser();
const app = document.getElementById("app");
const panel = document.getElementById("dashboard-mode");
document.body.classList.toggle("dashboard-mode", shouldEnable);
if (app) {
app.classList.toggle("dashboard-mode", shouldEnable);
}
if (panel) {
panel.style.display = shouldEnable ? "block" : "none";
}
if (!shouldEnable) {
dashboardShellBuilt = false;
if (tickerTimeout) { clearTimeout(tickerTimeout); tickerTimeout = null; }
}
setStoredDashboardMode(shouldEnable);
updateDashboardToggle();
syncDashboardClock();
syncDashboardRefresh();
if (shouldEnable) {
ensureDashboardAudio();
renderDashboardMode();
}
}
function syncDashboardClock() {
if (dashboardClockTimer) {
clearInterval(dashboardClockTimer);
dashboardClockTimer = null;
}
if (isDashboardModeEnabled()) {
dashboardClockTimer = setInterval(() => {
renderDashboardMode();
}, 30000);
}
}
function syncDashboardRefresh() {
if (dashboardRefreshTimer) {
clearInterval(dashboardRefreshTimer);
dashboardRefreshTimer = null;
}
if (isDashboardModeEnabled()) {
dashboardRefreshTimer = setInterval(() => {
refreshDashboardData();
}, 60000);
}
}
async function refreshDashboardData() {
if (dashboardRefreshInFlight || !isDashboardModeEnabled()) {
return;
}
dashboardRefreshInFlight = true;
try {
await refreshState();
renderSchedule();
renderParentView();
} catch (err) {
pushDashboardAlert("warning", "Dashboard refresh missed", "Could not pull the latest family state from the server.", "warning");
} finally {
dashboardRefreshInFlight = false;
}
}
function buildDashboardBalancesMarkup() {
return familyConfig.kidRoles.map(user => {
const tokens = getTokens(user);
return `
<div class="dashboard-balance-card db-balance-${user.toLowerCase().replace(/\s+/g, "-")}">
<div class="db-balance-header">
${buildDashboardAvatarHtml(user)}
<span class="db-balance-name-text">${escapeHtml(user)}</span>
</div>
<div class="dashboard-balance-value" data-counter="${tokens}" data-user="${escapeHtml(user)}"><span class="db-token-num">${tokens}</span> <span>☀️</span></div>
</div>
`;
}).join("");
}
function buildDashboardPendingMarkup() {
const pending = getPending();
if (pending.length === 0) {
return '<p class="dashboard-empty">No pending approvals right now.</p>';
}
return pending.slice(0, 5).map(item => `
<div class="dashboard-list-item">
<strong>${escapeHtml(item.user)}</strong>
<span>${escapeHtml(pendingLabel(item))}</span>
</div>
`).join("");
}
function buildDashboardUpcomingMarkup(scheduleKey, blocks) {
if (blocks.length === 0) {
return '<p class="dashboard-empty">No more blocks after this. Wrap-up time.</p>';
}
return blocks.map(block => {
const status = getScheduleStatus(scheduleKey, block.id);
const statusText = status ? SCHEDULE_STATUS_LABELS[status] : "Unmarked";
const isDayWrap = block.id === "day-wrap";
const showCta = isDayWrap;
return `
<div class="dashboard-list-item dashboard-upcoming-item">
<div>
<strong>${escapeHtml(block.time)} · ${escapeHtml(block.label)}</strong>
<span>${escapeHtml(block.desc || "Planned block")}</span>
${showCta ? `<button type="button" class="affirmation-cta-btn" onclick="showAffirmationModal()">💛 Write an Affirmation</button>` : ""}
</div>
<em class="dashboard-mini-status${status ? ` schedule-status-${status}` : ""}">${escapeHtml(statusText)}</em>
</div>
`;
}).join("");
}
function buildDashboardSuggestedChoresMarkup(theme) {
if (!theme) {
return '<p class="dashboard-empty">Weekend mode. No suggested chore set for today.</p>';
}
const chores = theme.chores
.map(id => getChores().find(chore => chore.id === id))
.filter(Boolean)
.slice(0, 4);
if (chores.length === 0) {
return '<p class="dashboard-empty">No matching chores configured for today.</p>';
}
return chores.map(chore => `
<div class="dashboard-chip">${escapeHtml(chore.label)} · ${chore.amount} ☀️</div>
`).join("");
}
function buildDashboardSuggestedChoresChipsMarkup(theme) {
if (!theme) return "";
const chores = theme.chores
.map(id => getChores().find(chore => chore.id === id))
.filter(Boolean)
.slice(0, 3);
return chores.map(chore => `<span class="dashboard-pill">${escapeHtml(chore.label)} · ${chore.amount} ☀️</span>`).join("");
}
function buildDashboardStreakMarkup() {
return familyConfig.kidRoles.map(user => {
const streaks = Object.entries(STREAK_DEFS).map(([streakId, config]) => {
const record = getStreakRecord(user, streakId);
const current = record.current || 0;
const goal = config.goal || 0;
const goalHit = goal > 0 && current >= goal;
const fireCount = Math.min(current, goal > 0 ? goal : 7);
const fires = Array.from({ length: fireCount }, () => `<span class="db-fire">🔥</span>`).join("");
const barPct = goal > 0 ? Math.min(100, Math.round((current / goal) * 100)) : 0;
const barHtml = goal > 0
? `<div class="db-streak-bar"><div class="db-streak-bar-fill${goalHit ? " db-streak-goal" : ""}" style="width:${barPct}%"></div></div>`
: "";
const goalBadge = goalHit ? `<span class="db-goal-badge">GOAL! 🏆</span>` : (goal > 0 ? `<span class="db-streak-goal-text">${current}/${goal}</span>` : `<span class="db-streak-goal-text">${current} days</span>`);
return `
<div class="db-streak-row">
<div class="db-streak-label">${config.label}</div>
<div class="db-streak-fires">${fires || "<span class='db-streak-zero'>Start today!</span>"}</div>
${barHtml}
<div class="db-streak-meta">${goalBadge}</div>
</div>
`;
}).join("");
return `
<div class="dashboard-streak-card db-streak-${user.toLowerCase()}">
<h4 class="db-balance-header"><span class="db-avatar clickable-streak-avatar" data-avatar-user="${escapeHtml(user)}" onclick="streakFlyAcross('${escapeHtml(user)}')">${escapeHtml(getDefaultAvatar(user))}</span><span>${escapeHtml(user)}</span></h4>
${streaks}
</div>
`;
}).join("");
}
function renderDashboardMode() {
const shell = document.getElementById("dashboard-shell");
if (!shell || (!isParentUser() && !getStoredDashboardMode())) return;
if (!shell.querySelector(".dashboard-shell")) dashboardShellBuilt = false;
if (!dashboardShellBuilt) {
initDashboardShell(shell);
dashboardShellBuilt = true;
} else {
patchDashboardLive(shell);
}
}
function initDashboardShell(shell) {
const now = new Date();
const clock = now.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
const context = getScheduleContext(now);
const summary = getScheduleSummary(context.scheduleKey);
const nightTheme = isDashboardNightTheme(now);
const themeLabel = getDashboardThemeLabel();
const currentStatus = context.currentBlock ? getScheduleStatus(context.scheduleKey, context.currentBlock.id) : null;
const currentStatusText = currentStatus ? SCHEDULE_STATUS_LABELS[currentStatus] : "Unmarked";
const focusBlock = context.currentBlock || getDailyBlocks()[0];
const focusTitle = context.currentBlock ? focusBlock.label : "Day starts soon";
const focusSubtitle = context.currentBlock
? (focusBlock.desc || (context.theme ? (focusBlock.label.includes("Morning") ? context.theme.morning : context.theme.afternoon) : ""))
: `First block: ${focusBlock.time} · ${focusBlock.label}`;
const pending = getPending();
const suggestedChoresHtml = buildDashboardSuggestedChoresChipsMarkup(context.theme);
const motivation = getDashboardMotivation();
shell.innerHTML = `
<div class="dashboard-shell${nightTheme ? " dashboard-night" : ""}">
<div class="db-float-layer" aria-hidden="true">${buildFloatingEmojisMarkup()}</div>
<div id="db-toast-slot"></div>
<div class="dashboard-topbar">
<div>
<div class="dashboard-kicker">🍦 ${escapeHtml(familyConfig.appName)}</div>
<h1>${escapeHtml(context.dateStr)}${context.week ? ` · ${escapeHtml(context.week.emoji)} ${escapeHtml(context.week.label)}` : ""}</h1>
</div>
<div class="dashboard-topbar-actions">
<div id="db-clock" class="dashboard-clock db-clock-pulse">${escapeHtml(clock)}</div>
<button type="button" class="secondary-btn dashboard-theme-btn" onclick="cycleDashboardThemeMode()" id="db-theme-btn">${escapeHtml(themeLabel)}</button>
<button type="button" class="secondary-btn" onclick="exitDashboard()">Exit</button>
</div>
</div>
<div id="db-affirmation-ticker-wrap">${buildAffirmationTickerMarkup()}</div>
<div class="dashboard-hero">
<div class="dashboard-hero-main db-panel-enter">
<div class="dashboard-kicker" id="db-focus-kicker">Now · ${escapeHtml(focusBlock.time)}</div>
<h2 class="db-hero-title" id="db-focus-title">${escapeHtml(focusTitle)}</h2>
<p class="db-motivation" id="db-motivation">${escapeHtml(motivation)}</p>
<div class="dashboard-hero-meta" id="db-hero-meta">
<span class="dashboard-pill${currentStatus ? ` schedule-status-${currentStatus}` : ""}" id="db-status-pill">${escapeHtml(currentStatusText)}</span>
<span class="dashboard-pill" id="db-pending-pill">Pending ${pending.length}</span>
${suggestedChoresHtml}
</div>
</div>
<div class="dashboard-hero-scores db-panel-enter" style="animation-delay:0.04s">
<div class="dashboard-kicker">☀️ Token Scores</div>
<div class="db-scoreboard">
${familyConfig.kidRoles.map((kid, i) => `
<div class="db-scoreboard-card db-score-kid-${i} db-score-${kid.toLowerCase()}" onclick="celebrateUser('${escapeHtml(kid)}')">
${buildDashboardAvatarHtml(kid)}
<span class="db-scoreboard-name">${escapeHtml(kid)}</span>
<span class="db-scoreboard-num" id="db-score-kid-${i}">${getTokens(kid)}</span>
</div>
${i < familyConfig.kidRoles.length - 1 ? '<div class="db-scoreboard-divider">vs</div>' : ''}
`).join("")}
</div>
</div>
<div class="dashboard-hero-side db-panel-enter" style="animation-delay:0.08s">
<div class="dashboard-kicker">Today's Follow-Through</div>