-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
6173 lines (5394 loc) · 235 KB
/
Copy pathcode.js
File metadata and controls
6173 lines (5394 loc) · 235 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
// LENTANDO - Progress At Your Pace
// Copyright (c) 2026 Frank Force
'use strict';
const debugMode = true; // Enables debug logging and test data generators. Automatically set to false in release builds.
// ========== DEBUG TIME SYSTEM ==========
// Allows advancing time for testing badges, day boundaries, etc.
let debugTimeOffset = 0;
function now() {
return Date.now() + debugTimeOffset;
}
function currentDate() {
return new Date(now());
}
// Debug functions are only exposed on window when debugMode is true
if (debugMode) {
function debugAdvanceTime(hours) {
debugTimeOffset += hours * 60 * 60 * 1000;
console.log(`⏰ Time advanced by ${hours}h. Virtual date: ${currentDate().toLocaleString()}`);
render();
}
function debugSetDate(dateString) {
const targetTime = new Date(dateString).getTime();
debugTimeOffset = targetTime - Date.now();
console.log(`⏰ Time set to ${currentDate().toLocaleString()}`);
render();
}
function debugResetTime() {
debugTimeOffset = 0;
console.log('⏰ Time reset to real time');
render();
}
function debugGetTime() {
console.log(`Current virtual time: ${currentDate().toLocaleString()}`);
console.log(`Offset: ${debugTimeOffset / (1000 * 60 * 60)} hours`);
return currentDate();
}
window.debugAdvanceTime = debugAdvanceTime;
window.debugSetDate = debugSetDate;
window.debugResetTime = debugResetTime;
window.debugGetTime = debugGetTime;
}
// ========== CONSTANTS ==========
const STORAGE_EVENTS = 'ht_events';
const STORAGE_SETTINGS = 'ht_settings';
const STORAGE_TODOS = 'ht_todos';
const STORAGE_THEME = 'ht_theme';
const STORAGE_BADGES = 'ht_badges';
const STORAGE_LOGIN_SKIPPED = 'ht_login_skipped';
const STORAGE_VERSION = 'ht_data_version';
const STORAGE_DELETED_IDS = 'ht_deleted_ids';
const STORAGE_DELETED_TODO_IDS = 'ht_deleted_todo_ids';
const STORAGE_CLEARED_AT = 'ht_cleared_at';
const STORAGE_CONSOLIDATED_AT = 'ht_consolidated_at';
const DATA_VERSION = 3;
const ADDICTION_PROFILES = {
cannabis: {
sessionLabel: 'Use',
usedButtonLabel: 'Use',
substanceLabel: 'Type',
methodLabel: 'Method',
substances: ['thc', 'cbd', 'mix'],
substanceDisplay: { thc: 'THC', cbd: 'CBD', mix: 'Mix' },
methods: ['bong', 'vape', 'pipe', 'joint', 'edible', 'other'],
amounts: [0.5, 1, 1.5, 2, 3, 4, 5, 10, 20],
amountUnit: 'hits',
icons: { thc: '🌿', cbd: '🍃', mix: '🍂' }
},
alcohol: {
sessionLabel: 'Drink',
usedButtonLabel: 'Drink',
substanceLabel: 'Type',
substances: ['beer', 'wine', 'liquor'],
substanceDisplay: { beer: 'Beer', wine: 'Wine', liquor: 'Liquor' },
amounts: [0.5, 1, 1.5, 2, 3, 4, 5, 10, 20],
amountUnit: 'drinks',
icons: { beer: '🍺', wine: '🍷', liquor: '🥃' }
},
smoking: {
sessionLabel: 'Smoke',
usedButtonLabel: 'Smoke',
substanceLabel: 'Type',
substances: ['cigarette', 'vape', 'other'],
substanceDisplay: { cigarette: 'Cigarette', vape: 'Vape', other: 'Other' },
amounts: [0.5, 1, 1.5, 2, 3, 4, 5, 10, 20],
amountUnit: 'count',
icons: { cigarette: '🚬', vape: '💨', other: '🍂' }
},
custom: {
sessionLabel: 'Use',
usedButtonLabel: 'Use',
substanceLabel: 'Type',
methodLabel: 'Method',
substances: ['type1', 'type2', 'type3'],
substanceDisplay: { type1: 'Type 1', type2: 'Type 2', type3: 'Type 3' },
amounts: [0.5, 1, 1.5, 2, 3, 4, 5, 10, 20],
amountUnit: 'units',
icons: { type1: '⚡', type2: '⚡', type3: '⚡' }
}
};
function getProfile() {
const settings = DB.loadSettings();
let key = settings.addictionProfile || 'cannabis';
// Migrate legacy 'other' profile key to 'custom'
if (key === 'other') {
key = 'custom';
settings.addictionProfile = 'custom';
DB._settings = settings;
DB.saveSettings();
}
const base = ADDICTION_PROFILES[key];
if (!base) return ADDICTION_PROFILES.cannabis;
if (key !== 'custom') return base;
// Build custom profile with user overrides
return buildCustomProfile(settings);
}
function buildCustomProfile(settings) {
const base = ADDICTION_PROFILES.custom;
const cp = settings.customProfile || {};
const typeNames = cp.types || ['', '', ''];
const addictionName = cp.name || '';
const customIcons = cp.icons || ['⚡', '⚡', '⚡'];
// Build substances list — keep all 3 slots, use defaults for blanks
const substanceDisplay = {
type1: typeNames[0] || 'Type 1',
type2: typeNames[1] || 'Type 2',
type3: typeNames[2] || 'Type 3'
};
const icons = {
type1: customIcons[0] || '⚡',
type2: customIcons[1] || '⚡',
type3: customIcons[2] || '⚡'
};
return {
...base,
sessionLabel: addictionName || base.sessionLabel,
substanceDisplay,
icons,
methods: null,
methodLabel: null,
methodDisplay: {}
};
}
// User input options for logging events
const REASONS = ['habit', 'stress', 'social', 'reward','bored', 'pain', 'hungry', 'angry', 'lonely', 'tired'];
const INTENSITIES = [1, 2, 3, 4, 5];
const HABIT_DURATIONS = [0, 5, 10, 15, 20, 30, 45, 60, 120];
const OPTIONAL_FIELDS = new Set(['reason', 'trigger', 'intensity']);
// Timeouts and durations
const CHIP_TIMEOUT_MS = 10000;
const FLASH_ANIMATION_MS = 300;
const METRICS_REFRESH_MS = 30000;
const FIFTEEN_MINUTES_MS = 15 * 60 * 1000;
const TWO_HOURS_MS = 2 * 60 * 60 * 1000;
// Badge calculation thresholds
const GAP_MILESTONES = [1, 2, 4, 8, 12];
const TBREAK_MILESTONES = [1, 7, 14, 21, 30, 365];
const APP_STREAK_MILESTONES = [2, 7, 30, 365];
const EARLY_HOUR = 6;
const MAX_STREAK_DAYS = 60;
const CONSOLIDATION_DAYS = 60;
const COACHING_MESSAGES = [
'🌬️ Take 10 slow breaths',
'🌳 Step outside for a minute',
'📖 Read a few pages of a book',
'🎵 Put on a song you love',
'🍎 Grab a healthy snack',
'☕ Make a warm drink',
'🚿 Splash water on your face',
'🧘 Do a quick stretch',
'🚶 Go for a short walk',
'🧹 Tidy up one small thing',
'💪 One moment at a time',
'🏆 Every resist is a win',
'📞 Call a friend',
'🎨 Do something creative',
'🤸 Take a movement break',
'🧼 Wash your face or hands',
'🍬 Chew some gum or brush teeth',
'📽️ Watch a calming video',
'✍️ Write about how you feel',
'🕯️ Light a candle or incense',
'🦶 Feel your feet on the floor',
'🗑️ Throw away one piece of trash',
'🍽️ Wash or put away a few dishes',
'🐢 Small steps add up',
'🌊 This urge will pass',
'📦 Put it out of reach (for now)',
'🌱 Do something small for future you',
];
// Full activity catalog — add new activities here
const ALL_ACTIVITIES = [
// Quick Wins
{ key: 'water', emoji: '💧', label: 'Water', hasMinutes: false, hasCount: true, category: 'Quick Wins', color: '#29b6f6' },
{ key: 'breaths', emoji: '🌬️', label: 'Breathe', hasMinutes: true, hasCount: false, category: 'Quick Wins', color: '#5a9fd4' },
{ key: 'exercise', emoji: '🏃', label: 'Exercise', hasMinutes: true, hasCount: false, category: 'Body', color: '#e6cc22' },
{ key: 'outside', emoji: '🌳', label: 'Outside', hasMinutes: true, hasCount: false, category: 'Body', color: '#43a047' },
{ key: 'sleep', emoji: '🛏️', label: 'Sleep', hasMinutes: false, hasCount: false, category: 'Body', color: '#7986cb' },
// Body
{ key: 'walk', emoji: '🚶', label: 'Walk', hasMinutes: true, hasCount: false, category: 'Body', color: '#ff8f00' },
{ key: 'yoga', emoji: '🤸♂️', label: 'Yoga', hasMinutes: true, hasCount: false, category: 'Body', color: '#ab47bc' },
{ key: 'bike', emoji: '🚴', label: 'Bike', hasMinutes: true, hasCount: false, category: 'Body', color: '#00acc1' },
{ key: 'swim', emoji: '🏊', label: 'Swim', hasMinutes: true, hasCount: false, category: 'Body', color: '#26c6da' },
{ key: 'lift', emoji: '🏋️', label: 'Lift', hasMinutes: true, hasCount: false, category: 'Body', color: '#ef5350' },
{ key: 'sports', emoji: '⚽', label: 'Sports', hasMinutes: true, hasCount: false, category: 'Body', color: '#ffb74d' },
{ key: 'shower', emoji: '🛁', label: 'Shower', hasMinutes: false, hasCount: false, category: 'Body', color: '#80deea' },
{ key: 'meal', emoji: '🍎', label: 'Meal', hasMinutes: false, hasCount: false, category: 'Body', color: '#7cb342' },
{ key: 'vitamins', emoji: '💊', label: 'Vitamins', hasMinutes: false, hasCount: false, category: 'Body', color: '#aed581' },
// Mind
{ key: 'puzzle', emoji: '🧩', label: 'Puzzle', hasMinutes: true, hasCount: false, category: 'Mind', color: '#00897b' },
{ key: 'journal', emoji: '✍️', label: 'Journal', hasMinutes: true, hasCount: false, category: 'Mind', color: '#039be5' },
{ key: 'read', emoji: '📖', label: 'Read', hasMinutes: true, hasCount: false, category: 'Mind', color: '#f4511e' },
{ key: 'study', emoji: '📚', label: 'Study', hasMinutes: true, hasCount: false, category: 'Mind', color: '#7e57c2' },
{ key: 'focus', emoji: '🎯', label: 'Focus', hasMinutes: true, hasCount: false, category: 'Mind', color: '#8e24aa' },
{ key: 'listen', emoji: '🎧', label: 'Listen', hasMinutes: true, hasCount: false, category: 'Mind', color: '#ff7043' },
{ key: 'meditate', emoji: '🧘', label: 'Meditate', hasMinutes: true, hasCount: false, category: 'Mind', color: '#5c6bc0' },
{ key: 'pray', emoji: '🙏', label: 'Pray', hasMinutes: true, hasCount: false, category: 'Mind', color: '#ffa726' },
// Create
{ key: 'music', emoji: '🎵', label: 'Music', hasMinutes: true, hasCount: false, category: 'Create', color: '#f06292' },
{ key: 'art', emoji: '🎨', label: 'Art', hasMinutes: true, hasCount: false, category: 'Create', color: '#ff7043' },
{ key: 'photo', emoji: '📷', label: 'Photo', hasMinutes: false, hasCount: false, category: 'Create', color: '#ffd54f' },
{ key: 'build', emoji: '🛠️', label: 'Build', hasMinutes: true, hasCount: false, category: 'Create', color: '#78909c' },
{ key: 'cook', emoji: '🍳', label: 'Cook', hasMinutes: true, hasCount: false, category: 'Create', color: '#ef6c00' },
{ key: 'code', emoji: '💻', label: 'Code', hasMinutes: true, hasCount: false, category: 'Create', color: '#546e7a' },
{ key: 'game', emoji: '🎮', label: 'Game', hasMinutes: true, hasCount: false, category: 'Create', color: '#80cbc4' },
{ key: 'instrument', emoji: '🎸', label: 'Instrument', hasMinutes: true, hasCount: false, category: 'Create', color: '#7c4dff' },
// Connect
{ key: 'socialize', emoji: '👥', label: 'Socialize', hasMinutes: true, hasCount: false, category: 'Connect', color: '#ff8a65' },
{ key: 'call', emoji: '📞', label: 'Call', hasMinutes: true, hasCount: false, category: 'Connect', color: '#4db6ac' },
{ key: 'pet', emoji: '🐾', label: 'Pet', hasMinutes: false, hasCount: false, category: 'Connect', color: '#f48fb1' },
{ key: 'family', emoji: '👨👩👧', label: 'Family', hasMinutes: true, hasCount: false, category: 'Connect', color: '#ffcc80' },
{ key: 'volunteer', emoji: '🤝', label: 'Volunteer', hasMinutes: true, hasCount: false, category: 'Connect', color: '#a1887f' },
// Skills
{ key: 'language', emoji: '🌍', label: 'Language', hasMinutes: true, hasCount: false, category: 'Skills', color: '#00bcd4' },
// Ground
{ key: 'sunlight', emoji: '🌞', label: 'Sunlight', hasMinutes: true, hasCount: false, category: 'Ground', color: '#ffca28' },
{ key: 'garden', emoji: '🌼', label: 'Garden', hasMinutes: true, hasCount: false, category: 'Ground', color: '#a5d6a7' },
// Life
{ key: 'clean', emoji: '🧹', label: 'Clean', hasMinutes: true, hasCount: false, category: 'Life', color: '#8d6e63' },
{ key: 'errands', emoji: '🛒', label: 'Errands', hasMinutes: true, hasCount: false, category: 'Life', color: '#5e35b1' },
];
// Computed lookups from ALL_ACTIVITIES catalog
const HABIT_ICONS = Object.fromEntries(ALL_ACTIVITIES.map(a => [a.key, a.emoji]));
const HABIT_LABELS = Object.fromEntries(ALL_ACTIVITIES.map(a => [a.key, a.label]));
const HABIT_SHOW_CHIPS = Object.fromEntries(ALL_ACTIVITIES.map(a => [a.key, a.hasMinutes]));
const ACTIVITY_ORDER = Object.fromEntries(ALL_ACTIVITIES.map((a, i) => [a.key, i]));
// Badge definitions — maps badge IDs to their display properties
// Order determines the sort order of badges in the UI
const BADGE_DEFINITIONS = {
'welcome-back': { label: 'Welcome Back', icon: '👋', desc: 'Returned to tracking after 24+ hours away' },
'daily-checkin': { label: 'Showed Up', icon: '✅', desc: 'Logged at least one event, showing up is everything' },
'resist': { label: 'Resisted', icon: '💪', desc: 'Resisted an urge' },
'urge-surfed': { label: 'Urge Surfed', icon: '🏄', desc: 'Logged an urge and didn\'t use for 15+ minutes' },
'swap-completed': { label: 'Healthy Swap', icon: '🧩', desc: 'Logged an urge, then did a healthy action within 15 minutes' },
'intensity-logged': { label: 'Intensity Logged', icon: '🌡️', desc: 'Tracked urge intensity' },
'trigger-noted': { label: 'Trigger Identified', icon: '🔍', desc: 'Identified what triggered the urge' },
'full-report': { label: 'Full Report', icon: '📋', desc: 'Logged both intensity and trigger' },
'tough-resist': { label: 'Tough Resist', icon: '🦁', desc: 'Resisted a strong urge (intensity 4+)' },
'resist-streak': { label: 'Resist Streak', icon: '🛡️', desc: 'Resisted urges for multiple days in a row' },
'resist-majority': { label: 'Resist Majority', icon: '⚔️', desc: 'More resists than uses' },
'second-thought': { label: 'Reconsidered', icon: '💭', desc: 'Used undo to reconsider' },
'mindful': { label: 'Mindful Session', icon: '🌸', desc: 'Logged the reason for using' },
'good-start': { label: 'Strong Start', icon: '🚀', desc: 'Started the day with a positive action instead of using' },
'drank-water': { label: 'Drank Water', icon: '💧', desc: 'Logged water' },
'hydrated': { label: 'Hydrated', icon: '🌊', desc: 'Logged water 5+ times' },
'exercised': { label: 'Exercised', icon: '🏃', desc: 'Exercised or did a physical activity' },
'breathwork': { label: 'Breathwork', icon: '🌬️', desc: 'Did breathing exercises or meditation' },
'cleaned': { label: 'Tidied Up', icon: '🧹', desc: 'Tidied up or cleaned something' },
'went-outside': { label: 'Went Outside', icon: '🌳', desc: 'Spent time outside or got some fresh air' },
'habit-streak': { label: 'Habit Streak', icon: '🐢', desc: 'Logged healthy habits for consecutive days' },
'five-star-day': { label: 'All Routines Done', icon: '🌟', desc: 'Completed all of your selected healthy activities in one day' },
'gap-1h': { label: 'Gap 1h', icon: '🕐', desc: 'Maintained a 1+ hour gap between sessions (excludes gaps crossing 6am)' },
'gap-2h': { label: 'Gap 2h', icon: '🕑', desc: 'Maintained a 2+ hour gap between sessions (excludes gaps crossing 6am)' },
'gap-4h': { label: 'Gap 4h', icon: '🕓', desc: 'Maintained a 4+ hour gap between sessions (excludes gaps crossing 6am)' },
'gap-8h': { label: 'Gap 8h', icon: '🕗', desc: 'Maintained an 8+ hour gap between sessions (excludes gaps crossing 6am)' },
'gap-12h': { label: 'Gap 12h', icon: '🕛', desc: 'Maintained a 12+ hour gap between sessions (excludes gaps crossing 6am)' },
'no-back-to-back': { label: 'No Chain', icon: '🚦', desc: 'All sessions spaced 15+ minutes apart' },
'night-gap': { label: 'Good Night', icon: '🛏️', desc: 'Maintained a 12+ hour gap that crosses 6am' },
'cbd-night': { label: 'CBD Night', icon: '🌌', desc: 'Maintained a 12+ hour overnight gap excluding CBD use (cannabis tracking only)' },
'dose-half': { label: 'Reduced Dose', icon: '⚖️', desc: 'Used less than a full dose' },
'harm-reduction-vape': { label: 'Safer Choice', icon: '✨', desc: 'Chose vape over smoke' },
'vape-only': { label: 'Vape Only Day', icon: '💨', desc: 'Only used vape or edibles' },
'half-cbd-day': { label: 'Half CBD Day', icon: '🍂', desc: 'At least 50% of usage was CBD' },
'edibles-only': { label: 'Edibles Only Day', icon: '🍪', desc: 'Only used edibles' },
'one-session': { label: 'One Session', icon: '☝️', desc: 'Limited use to a single session' },
'microdose-day': { label: 'Small Amount', icon: '🤏', desc: 'Total amount used of 3 or less' },
'lower-amount': { label: 'Scaling Back', icon: '📉', desc: 'Used a smaller total amount than yesterday' },
'taper': { label: 'Tapering', icon: '📐', desc: 'Gradually reduced usage over 3 or more consecutive days' },
'first-later': { label: 'Held Off', icon: '⏰', desc: 'First session later than yesterday (after 6am)' },
'gap-above-avg': { label: 'Beat Your Average', icon: '⏳', desc: 'Average gap exceeded trailing 7-day average (excludes gaps crossing 6am)' },
'low-day': { label: 'Light Day', icon: '🎈', desc: 'Used less than half your trailing 7-day average' },
'no-cigarette': { label: 'No Cigarette Day', icon: '🧯', desc: 'Did not smoke cigarettes (smoking tracking only)' },
'no-liquor': { label: 'No Liquor Day', icon: '🥛', desc: 'Did not drink liquor (alcohol tracking only)' },
'cbd-only': { label: 'No THC Day', icon: '🍃', desc: 'Did not use THC (cannabis tracking only)' },
'night-skip': { label: 'No Night Use', icon: '🌠', desc: 'No use between midnight and 6am' },
'morning-skip': { label: 'No Morning Use', icon: '🌅', desc: 'No use between 6am and noon' },
'day-skip': { label: 'No Day Use', icon: '☀️', desc: 'No use between noon and 6pm' },
'evening-skip': { label: 'No Evening Use', icon: '🌙', desc: 'No use between 6pm and midnight' },
'zero-use': { label: 'Clear Day', icon: '🏅', desc: 'No use today' },
'app-streak': { label: 'App Streak', icon: '📱', desc: 'Used the app multiple days in a row' },
'week-streak': { label: 'App Week Streak', icon: '📅', desc: 'Used the app every day for a week' },
'month-streak': { label: 'App Month Streak', icon: '🗓️', desc: 'Used the app every day for a month' },
'year-streak': { label: 'App Year Streak', icon: '🎉', desc: 'Used the app every day for a year!' },
'tbreak-1d': { label: 'One Day', icon: '🌱', desc: '24 hour gap with no use' },
'tbreak-7d': { label: 'One Week', icon: '🌻', desc: 'One week with no use' },
'tbreak-14d': { label: 'Two Weeks', icon: '🍀', desc: 'Two weeks with no use' },
'tbreak-21d': { label: 'Three Weeks', icon: '🌴', desc: 'Three weeks with no use' },
'tbreak-30d': { label: 'One Month', icon: '🏆', desc: 'One month with no use' },
'tbreak-365d': { label: 'One Year', icon: '👑', desc: 'One year with no use!' },
};
Object.keys(BADGE_DEFINITIONS).forEach((key, index) => {
BADGE_DEFINITIONS[key].sortOrder = index;
});
function getBadgeDef(id) {
return BADGE_DEFINITIONS[id] || { label: 'Unknown Badge', icon: '❓', desc: '' };
}
const DEFAULT_ACTIVITIES = ['water', 'exercise', 'breaths'];
const DEFAULT_SETTINGS = {
addictionProfile: null, // Set on first launch
lastSubstance: 'thc',
lastMethod: 'bong',
lastAmount: 1.0,
showCoaching: true,
soundEnabled: true,
useButtonHidden: false,
customProfile: { name: '', types: ['', '', ''], icons: ['⚡', '⚡', '⚡'] },
reminderEnabled: false,
reminderHour: 18, // 24h format, default 6 PM
reminderMinute: 0,
selectedActivities: [...DEFAULT_ACTIVITIES],
};
function getSelectedActivities() {
const validKeys = new Set(ALL_ACTIVITIES.map(a => a.key));
const settings = DB.loadSettings();
const sel = settings.selectedActivities;
if (Array.isArray(sel)) {
if (sel.length === 0) return []; // user explicitly chose no activities
const filtered = sel.filter(k => validKeys.has(k));
if (filtered.length > 0) return filtered;
}
return [...DEFAULT_ACTIVITIES];
}
// ========== SOUND SYSTEM ==========
let ZZFXSound = null;
let SOUNDS = null;
async function initSounds() {
try {
const zzfxModule = await import('./zzfx.js');
ZZFXSound = zzfxModule.ZZFXSound;
// Pre-build sound samples using ZZFXSound class (params will be tuned later)
SOUNDS = {
used: new ZZFXSound([,,224,.02,.02,.08,1,1.7,-14,,,,,,6.7]),
resist: new ZZFXSound([,,422,.08,.26,.19,1,1.1,,-144,18,.07,.1,,,,,.84,.21,.5,520]),
habit: new ZZFXSound([2,,330,.02,.05,,,.8,,,27,.06,,,,,.1,.5,.03]),
habitChip: new ZZFXSound([,,990,,,.05,,9,20]),
undo: new ZZFXSound([,,150,.05,,.05,,1.3,,,,,,3]),
cooldown: new ZZFXSound([2,0,260,,.2,.2,,,,,,,,,,,.12,.3,.1]),
//badge: new ZZFXSound([3,.02,988,,,.4,,33,,,331,.1,,,,,,,,,-340]), // coin sound for badges, disabled for now
//click: new ZZFXSound([1.5,,300,,,.008,,,300,,,,,,,,,.5]), // short sound for UI clicks, disabled for now
};
} catch (e) {
console.error('Failed to load sound system:', e);
}
}
function playSound(soundName) {
if (!SOUNDS || !DB.loadSettings().soundEnabled) return;
try {
SOUNDS[soundName]?.play();
} catch (e) {
console.error('Failed to play sound:', soundName, e);
}
}
// ========== TINY HELPERS ==========
const $ = id => document.getElementById(id);
// Cache Intl formatters — creating these is expensive
const _timeFormatter = new Intl.DateTimeFormat([], { hour: 'numeric', minute: '2-digit' });
const _dateFormatter = new Intl.DateTimeFormat([], { weekday: 'short', month: 'short', day: 'numeric' });
let _uidCounter = 0;
function uid() {
return now().toString(36) + '-' + (++_uidCounter).toString(36) + '-' + Math.random().toString(36).substring(2, 9);
}
/** Extract creation timestamp from a uid()-generated ID (base36 prefix) */
function getUidTimestamp(id) {
if (!id || typeof id !== 'string') return 0;
const firstPart = id.split('-')[0];
const ts = parseInt(firstPart, 36);
return Number.isFinite(ts) ? ts : 0;
}
function safeSetItem(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (e) {
if (e.name === 'QuotaExceededError') {
alert('⚠️ Storage full - your data may not have saved.\n\nPlease export your data from Settings and clear old events to free up space.');
console.error('QuotaExceededError writing key:', key);
return false;
}
throw e;
}
}
window.safeSetItem = safeSetItem;
function flashEl(el) {
el.classList.add('flash');
setTimeout(() => el.classList.remove('flash'), FLASH_ANIMATION_MS);
}
function pulseEl(el) {
el.classList.add('pulse');
setTimeout(() => el.classList.remove('pulse'), 400);
}
function hapticFeedback() {
if (debugMode) console.log('Haptic feedback triggered');
if (navigator.vibrate) navigator.vibrate(50);
}
let toastTimeout = null;
function showToast(message, durationMs = 2000) {
clearTimeout(toastTimeout);
let toast = $('toast');
if (!toast) {
toast = document.createElement('div');
toast.id = 'toast';
toast.className = 'toast';
toast.setAttribute('role', 'status');
toast.setAttribute('aria-live', 'polite');
document.body.appendChild(toast);
}
toast.textContent = message;
toast.classList.add('show');
toastTimeout = setTimeout(() => {
toast.classList.remove('show');
}, durationMs);
}
function escapeHTML(str) {
if (typeof str !== 'string') return str == null ? '' : String(str);
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getStorageUsageDisplay() {
let total = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key?.startsWith('ht_')) {
total += (key.length + (localStorage.getItem(key)?.length || 0)) * 2;
}
}
const kb = total / 1024;
const maxKB = 5 * 1024; // ~5 MB
const pct = Math.min(100, (kb / maxKB) * 100);
const pctStr = pct < 1 ? '<1' : Math.round(pct).toString();
const sizeStr = kb > 1024 ? `${(kb / 1024).toFixed(1)} MB` : `${Math.round(kb)} KB`;
return `${pctStr}% (${sizeStr} of ~5 MB)`;
}
/** Clear all app localStorage keys and invalidate DB caches */
function clearAllStorage() {
localStorage.removeItem(STORAGE_EVENTS);
localStorage.removeItem(STORAGE_SETTINGS);
localStorage.removeItem(STORAGE_TODOS);
localStorage.removeItem(STORAGE_THEME);
localStorage.removeItem(STORAGE_BADGES);
localStorage.removeItem(STORAGE_LOGIN_SKIPPED);
localStorage.removeItem(STORAGE_VERSION);
localStorage.removeItem(STORAGE_DELETED_IDS);
localStorage.removeItem(STORAGE_DELETED_TODO_IDS);
localStorage.removeItem(STORAGE_CLEARED_AT);
localStorage.removeItem(STORAGE_CONSOLIDATED_AT);
localStorage.removeItem('ht_last_updated');
DB._events = null;
DB._settings = null;
DB._dateIndex = null;
}
/** Validate password strength. Returns error message or null if valid. */
function validatePassword(password) {
if (password.length < 8) return 'Password must be at least 8 characters';
if (!/[a-z]/.test(password)) return 'Password must contain a lowercase letter';
if (!/[A-Z]/.test(password)) return 'Password must contain an uppercase letter';
if (!/[0-9]/.test(password)) return 'Password must contain a number';
return null;
}
function timeOfDayMin(ts) {
const d = new Date(ts);
return d.getHours() * 60 + d.getMinutes();
}
// ========== DATE HELPERS ==========
const sortByTime = (a, b) => a.ts - b.ts;
const sortedByTime = (arr) => [...arr].sort(sortByTime);
const getHour = (ts) => new Date(ts).getHours();
const filterDaytime = (events) => events.filter(e => getHour(e.ts) >= EARLY_HOUR);
function dateKey(d) {
const date = d instanceof Date ? d : new Date(d);
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const dd = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${dd}`;
}
function todayKey() { return dateKey(currentDate()); }
function daysAgoKey(n) {
const d = currentDate();
d.setDate(d.getDate() - n);
return dateKey(d);
}
function formatTime(ts) {
return _timeFormatter.format(new Date(ts));
}
function formatDuration(ms) {
if (!Number.isFinite(ms) || ms < 0) return '—';
const totalMin = Math.floor(ms / 60000);
if (totalMin < 60) return totalMin + 'm';
const totalHours = Math.floor(totalMin / 60);
if (totalHours < 24) return totalHours + 'h ' + (totalMin % 60) + 'm';
const totalDays = Math.floor(totalHours / 24);
if (totalDays < 365) return totalDays + 'd ' + (totalHours % 24) + 'h ' + (totalMin % 60) + 'm';
const years = Math.floor(totalDays / 365);
const days = totalDays % 365;
const hours = totalHours % 24;
return years + 'y ' + days + 'd ' + hours + 'h ' + (totalMin % 60) + 'm';
}
function getLastNDays(n, offset = 0) {
return Array.from({ length: n }, (_, i) => daysAgoKey(n - 1 - i + offset));
}
function friendlyDate(key) {
if (key === todayKey()) return 'Today';
if (key === daysAgoKey(1)) return 'Yesterday';
return _dateFormatter.format(new Date(key + 'T12:00:00'));
}
// ========== DATA LAYER ==========
const DB = {
_events: null,
_settings: null,
_dateIndex: null,
_buildDateIndex() {
this._dateIndex = new Map();
for (const e of this._events) {
const key = dateKey(e.ts);
if (!this._dateIndex.has(key)) this._dateIndex.set(key, []);
this._dateIndex.get(key).push(e);
}
for (const [, arr] of this._dateIndex) {
arr.sort(sortByTime);
}
},
_invalidateDateIndex() {
this._dateIndex = null;
},
_migrateDataIfNeeded() {
try {
const raw = localStorage.getItem(STORAGE_VERSION);
const storedVersion = parseInt(raw, 10) || 0;
if (storedVersion >= DATA_VERSION) return;
// Brand-new install — no existing data to migrate, just stamp the version
if (raw === null && !localStorage.getItem(STORAGE_EVENTS) && !localStorage.getItem(STORAGE_BADGES)) {
safeSetItem(STORAGE_VERSION, DATA_VERSION.toString());
return;
}
console.log(`Migrating data from version ${storedVersion} to ${DATA_VERSION}`);
// Clean up any leftover old key
localStorage.removeItem('ht_wins');
safeSetItem(STORAGE_VERSION, DATA_VERSION.toString());
} catch (e) {
console.error('Data migration failed:', e);
}
},
loadEvents() {
if (this._events) return this._events;
try {
const data = localStorage.getItem(STORAGE_EVENTS);
this._events = data ? JSON.parse(data) : [];
this._migrateDataIfNeeded();
// Filter out deleted events using tombstone list
const deletedIds = this._getDeletedIds();
if (deletedIds.size > 0) {
this._events = this._events.filter(e => !deletedIds.has(e.id));
}
// Filter out events created before the last database clear
const clearedAt = parseInt(localStorage.getItem(STORAGE_CLEARED_AT) || '0', 10);
if (clearedAt > 0) {
this._events = this._events.filter(e => getUidTimestamp(e.id) > clearedAt);
}
} catch (e) {
console.error('Failed to load events from localStorage:', e);
alert('⚠️ Your saved data appears to be corrupted and could not be loaded. If you have cloud sync enabled, your data will be restored on next sync.');
this._events = [];
}
this._invalidateDateIndex();
return this._events;
},
_getDeletedIds() {
try {
const raw = JSON.parse(localStorage.getItem(STORAGE_DELETED_IDS) || '{}');
return new Set(Object.keys(raw));
} catch {
return new Set();
}
},
_addTombstone(eventId) {
try {
const raw = this._readTombstoneMap();
if (raw[eventId]) return;
raw[eventId] = now();
safeSetItem(STORAGE_DELETED_IDS, JSON.stringify(raw));
if (window.FirebaseSync) FirebaseSync.onDataChanged();
} catch (e) {
console.error('Failed to add tombstone:', e);
}
},
_readTombstoneMap() {
try {
const raw = JSON.parse(localStorage.getItem(STORAGE_DELETED_IDS) || '{}');
return (typeof raw === 'object' && raw !== null) ? raw : {};
} catch {
return {};
}
},
_cleanOldTombstones() {
try {
const raw = this._readTombstoneMap();
const entries = Object.entries(raw);
const cutoff = now() - (90 * 24 * 60 * 60 * 1000);
const cleaned = {};
for (const [id, deletedAt] of entries) {
if (deletedAt > cutoff) cleaned[id] = deletedAt;
}
if (Object.keys(cleaned).length < entries.length) {
safeSetItem(STORAGE_DELETED_IDS, JSON.stringify(cleaned));
if (debugMode) console.log(`[Tombstone] Cleaned ${entries.length - Object.keys(cleaned).length} old tombstones`);
}
} catch (e) {
console.error('Failed to clean tombstones:', e);
}
},
saveEvents() {
safeSetItem(STORAGE_EVENTS, JSON.stringify(this._events));
this._invalidateDateIndex();
if (window.FirebaseSync) FirebaseSync.onDataChanged();
},
loadSettings() {
if (this._settings) return this._settings;
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_SETTINGS));
this._settings = { ...DEFAULT_SETTINGS, ...saved };
} catch {
this._settings = { ...DEFAULT_SETTINGS };
}
return this._settings;
},
saveSettings() {
safeSetItem(STORAGE_SETTINGS, JSON.stringify(this._settings));
if (window.FirebaseSync) FirebaseSync.onDataChanged();
},
addEvent(evt) {
this.loadEvents();
this._events.push(evt);
this._invalidateDateIndex();
this.saveEvents();
return evt;
},
updateEvent(id, data) {
this.loadEvents();
const idx = this._events.findIndex(e => e.id === id);
if (idx === -1) return null;
Object.assign(this._events[idx], data);
this._events[idx].modifiedAt = now(); // Track edit time for sync conflict resolution
this._invalidateDateIndex(); // Rebuild index if timestamp changed
this.saveEvents();
return this._events[idx];
},
deleteEvent(id) {
this.loadEvents();
// Add to tombstone list before removing
this._addTombstone(id);
this._events = this._events.filter(e => e.id !== id);
this._invalidateDateIndex();
this.saveEvents();
// Clean up old tombstones periodically (every delete is fine, it's cheap)
this._cleanOldTombstones();
},
forDate(key) {
this.loadEvents();
if (!this._dateIndex) this._buildDateIndex();
return this._dateIndex.get(key) || [];
},
getAllDayKeys() {
this.loadEvents();
if (!this._dateIndex) this._buildDateIndex();
return Array.from(this._dateIndex.keys()).sort().reverse();
},
};
// Expose DB globally so firebase-sync.js can invalidate caches after cloud sync
window.DB = DB;
// Expose shared helpers for firebase-sync.js (ES module can't access code.js scope directly)
window.clearAllStorage = clearAllStorage;
window.validatePassword = validatePassword;
window.render = render;
window.showLandingPage = showLandingPage;
window.showLoginScreen = showLoginScreen;
window.hideLoginScreen = hideLoginScreen;
window.continueToApp = continueToApp;
/** Stop all background timers (called on logout) */
window.stopTimers = function() {
if (timerInterval) { clearInterval(timerInterval); timerInterval = null; }
if (chipTimeout) { clearTimeout(chipTimeout); chipTimeout = null; }
if (habitChipTimeout) { clearTimeout(habitChipTimeout); habitChipTimeout = null; }
if (undoHideTimeout) { clearTimeout(undoHideTimeout); undoHideTimeout = null; }
};
// ========== EVENT QUERY HELPERS ==========
function filterByType(events, type) { return events.filter(e => e.type === type); }
function filterUsed(events) { return filterByType(events, 'used'); }
function filterProfileUsed(events) {
const profile = getProfile();
const subs = new Set(profile.substances);
return filterUsed(events).filter(e => subs.has(e.substance));
}
function filterTHC(usedEvents) { return usedEvents.filter(e => e.substance === 'thc' || e.substance === 'mix'); }
function filterCBD(usedEvents) { return usedEvents.filter(e => e.substance === 'cbd'); }
function sumAmount(usedEvents) { return usedEvents.reduce((s, e) => s + (e.amount ?? 1), 0); }
function getHabits(events, habitType) {
const habits = filterByType(events, 'habit');
return habitType ? habits.filter(e => e.habit === habitType) : habits;
}
// ========== EVENT FACTORIES ==========
function createUsedEvent(substance, method, amount, reason) {
const sub = substance || 'thc';
const evt = { id: uid(), type: 'used', ts: now(), substance: sub, amount: amount != null ? amount : 1.0 };
if (method) evt.method = method;
if (reason) evt.reason = reason;
return evt;
}
function createResistedEvent(intensity, trigger) {
const evt = { id: uid(), type: 'resisted', ts: now() };
if (intensity) evt.intensity = intensity;
if (trigger) evt.trigger = trigger;
return evt;
}
function createHabitEvent(habit, minutes) {
const evt = { id: uid(), type: 'habit', ts: now(), habit };
if (minutes) evt.minutes = minutes;
return evt;
}
/** Remove null-valued keys from an object in-place. Returns true if any were removed. */
function stripNulls(obj) {
let stripped = false;
for (const k of Object.keys(obj)) {
if (obj[k] === null) { delete obj[k]; stripped = true; }
}
return stripped;
}
// ========== EVENT CONSOLIDATION ==========
/**
* Consolidate all events for a single day into one event per type-group.
* Groups: used→by substance, resisted→one per day, habit→by habit type.
* Keeps the most recent event per group, merges data into it, removes the rest.
* Returns true if any events were removed.
*/
/** Consolidation group key — same logic used for merging and absorbing past events */
function consolidationGroupKey(e) {
if (e.type === 'used') return 'used:' + (e.substance || 'unknown') + ':' + (e.reason || '');
if (e.type === 'resisted') return 'resisted:' + (e.trigger || '');
if (e.type === 'habit') return 'habit:' + (e.habit || 'unknown');
return 'other:' + e.id;
}
function consolidateDay(dayKey) {
DB.loadEvents();
const allEvents = DB._events;
// Partition events for this day vs everything else
const dayEvents = [];
const otherEvents = [];
for (const e of allEvents) {
if (dateKey(e.ts) === dayKey) dayEvents.push(e);
else otherEvents.push(e);
}
if (dayEvents.length === 0) return false;
// Group by consolidation key (preserves method/reason/trigger per group)
const groups = new Map();
for (const e of dayEvents) {
const key = consolidationGroupKey(e);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(e);
}
// Merge each group
const kept = [];
let changed = false;
for (const [, group] of groups) {
// Sort by ts descending — keep the most recent
group.sort((a, b) => b.ts - a.ts);
const keeper = group[0];
if (group.length > 1) {
changed = true;
if (!keeper.consolidated) {
// First-time merge: combine ALL events into the keeper
keeper.consolidated = group.length;
keeper.modifiedAt = now();
if (keeper.type === 'used') {
keeper.amount = group.reduce((s, e) => s + (e.amount ?? 1), 0);
// reason is identical within the group; method may vary → 'mixed'
const methods = [...new Set(group.map(e => e.method).filter(Boolean))];
if (methods.length > 1) keeper.method = 'mixed';
else if (methods.length === 1) keeper.method = methods[0];
} else if (keeper.type === 'resisted') {
keeper.intensity = group.reduce((s, e) => s + (e.intensity || 1), 0);
// trigger is identical within the group (grouped by it)
} else if (keeper.type === 'habit') {
if (keeper.habit === 'water') {
keeper.count = group.reduce((s, e) => s + (e.count || 1), 0);
delete keeper.minutes;
} else {
keeper.minutes = group.reduce((s, e) => s + ((e.minutes > 0) ? e.minutes : 5), 0);
}
}
}
// If keeper IS already consolidated: extras are stale sync strays.
// Discard them silently — they were already counted in the original merge.
// New past events are absorbed at the call site (saveCreateModal) instead.
} else if (!keeper.consolidated) {
// Single event not yet flagged
changed = true;
keeper.consolidated = 1;
keeper.modifiedAt = now();
}
kept.push(keeper);
}
if (!changed) return false;
DB._events = otherEvents.concat(kept);
DB._dateIndex = null;
return true;
}
/**
* Auto-consolidate events older than CONSOLIDATION_DAYS.
* Also cleans old tombstones. Called once on app start.
*/
function consolidateOldEvents() {
DB.loadEvents();
const cutoffKey = daysAgoKey(CONSOLIDATION_DAYS);
const allDayKeys = DB.getAllDayKeys(); // sorted reverse (newest first)
let anyChanged = false;
// Skip days already consolidated in a previous run (cleared after sync pulls new data)
const consolidatedAt = localStorage.getItem(STORAGE_CONSOLIDATED_AT) || '';
for (const dk of allDayKeys) {
if (dk >= cutoffKey) continue; // skip recent days
if (dk <= consolidatedAt) break; // already consolidated in a previous run (sorted newest-first)
// Skip days where all events are already consolidated
const dayEvts = DB.forDate(dk);
if (dayEvts.length > 0 && dayEvts.every(e => e.consolidated)) continue;
if (consolidateDay(dk)) anyChanged = true;
}
// Strip null-valued keys from all events (cleans ghost fields from old versions / Firebase)
for (const e of DB._events) {
if (stripNulls(e)) anyChanged = true;
}
if (anyChanged) {
DB.saveEvents();
if (debugMode) console.log('[Consolidation] Consolidated old events');
}
// Record the cutoff so future runs can skip days already consolidated
// (cleared after sync pulls to ensure new synced old events get re-checked)
safeSetItem(STORAGE_CONSOLIDATED_AT, cutoffKey);
// Also clean old tombstones using same cutoff
DB._cleanOldTombstones();
}
// ========== BADGE CALCULATION HELPERS ==========
function countUrgeSurfed(resisted, used) {
const CLUSTER_MS = 5 * 60 * 1000;
const sorted = sortedByTime(resisted);
return sorted.filter((r, i) => {
// Skip if this resist is within 5 minutes of the previous resist (cluster de-dupe)
if (i > 0 && r.ts - sorted[i - 1].ts <= CLUSTER_MS) {
return false;
}
// Check if 15+ minutes have passed and no use occurred within 15 minutes after
const timeSinceResist = now() - r.ts;
const usedAfter = used.some(u => u.ts > r.ts && u.ts - r.ts <= FIFTEEN_MINUTES_MS);
return timeSinceResist >= FIFTEEN_MINUTES_MS && !usedAfter;
}).length;
}
function countSwapCompleted(resisted, habits) {
const FIVE_MINUTES_MS = 5 * 60 * 1000;
const sorted = sortedByTime(resisted);
return sorted.filter((r, i) => {
// Skip if this resist is within 5 minutes of the previous resist (not first in cluster)
if (i > 0 && r.ts - sorted[i - 1].ts <= FIVE_MINUTES_MS) return false;
return habits.some(h => h.ts > r.ts && h.ts - r.ts <= FIFTEEN_MINUTES_MS);
}).length;
}
/** Check if a 6am boundary falls between two timestamps */
function gapCrosses6am(ts1, ts2) {
const d = new Date(ts1);
d.setHours(EARLY_HOUR, 0, 0, 0);
if (d.getTime() <= ts1) d.setDate(d.getDate() + 1);