-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
859 lines (718 loc) · 25.1 KB
/
script.js
File metadata and controls
859 lines (718 loc) · 25.1 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
// Active tab
let activeTab = 'beer'; // 'beer' or 'shot'
// Beer cooldown state
let beerDuration = 1;
let beerEndTime = null;
// Shot cooldown state
let shotDuration = 1;
let shotEndTime = null;
// Timer management
let timerInterval = null;
let soundEnabled = true; // Sound enabled by default
let notificationsEnabled = true; // Notifications enabled by default
// Custom duration spinner state
let customHours = 1;
let customMinutes = 0;
// History tracking
let beerHistory = [];
let shotHistory = [];
// Helper functions to get/set active cooldown
function getActiveDuration() {
return activeTab === 'beer' ? beerDuration : shotDuration;
}
function setActiveDuration(value) {
if (activeTab === 'beer') {
beerDuration = value;
} else {
shotDuration = value;
}
}
function getActiveEndTime() {
return activeTab === 'beer' ? beerEndTime : shotEndTime;
}
function setActiveEndTime(value) {
if (activeTab === 'beer') {
beerEndTime = value;
} else {
shotEndTime = value;
}
}
function getInactiveDuration() {
return activeTab === 'beer' ? shotDuration : beerDuration;
}
function getInactiveEndTime() {
return activeTab === 'beer' ? shotEndTime : beerEndTime;
}
// History functions
function getTodayKey() {
const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
return `beercd_history_${today}`;
}
function loadHistory() {
const todayKey = getTodayKey();
const saved = localStorage.getItem(todayKey);
if (saved) {
const parsed = JSON.parse(saved);
beerHistory = parsed.beers || [];
shotHistory = parsed.shots || [];
} else {
beerHistory = [];
shotHistory = [];
}
}
function saveHistory() {
const todayKey = getTodayKey();
localStorage.setItem(todayKey, JSON.stringify({
beers: beerHistory,
shots: shotHistory
}));
updateCounterBadge();
updateHistoryDisplay();
}
function trackDrink(type) {
const now = new Date();
const time = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
if (type === 'beer') {
beerHistory.push(time);
} else if (type === 'shot') {
shotHistory.push(time);
}
saveHistory();
}
function updateCounterBadge() {
document.getElementById('beerCount').textContent = '🍺 ' + beerHistory.length;
document.getElementById('shotCount').textContent = '🍸 ' + shotHistory.length;
}
function updateHistoryDisplay() {
const historyList = document.getElementById('historyList');
const allDrinks = [];
beerHistory.forEach(time => allDrinks.push({ time, type: 'beer' }));
shotHistory.forEach(time => allDrinks.push({ time, type: 'shot' }));
// Sort by time
allDrinks.sort((a, b) => a.time.localeCompare(b.time));
if (allDrinks.length === 0) {
historyList.innerHTML = '<div class="empty-history">No drinks yet today</div>';
return;
}
historyList.innerHTML = allDrinks.map(drink =>
`<div class="history-item">${drink.time} ${drink.type === 'beer' ? '🍺' : '🍸'}</div>`
).join('');
}
function toggleHistory() {
const section = document.getElementById('historySection');
const icon = document.getElementById('historyIcon');
if (section.style.display === 'none') {
section.style.display = 'block';
icon.textContent = '▲';
} else {
section.style.display = 'none';
icon.textContent = '▼';
}
}
function resetHistory() {
if (confirm('Clear today\'s history?')) {
beerHistory = [];
shotHistory = [];
saveHistory();
}
}
// Load saved cooldown state from localStorage
function loadCooldownState() {
// Load history
loadHistory();
updateCounterBadge();
updateHistoryDisplay();
// Load beer state
const savedBeerDuration = localStorage.getItem('beercd_beer_duration');
const savedBeerEndTime = localStorage.getItem('beercd_beer_endTime');
if (savedBeerDuration) {
beerDuration = parseFloat(savedBeerDuration);
}
if (savedBeerEndTime) {
beerEndTime = parseInt(savedBeerEndTime);
const now = Date.now();
if (beerEndTime <= now) {
beerEndTime = null;
}
}
// Load shot state
const savedShotDuration = localStorage.getItem('beercd_shot_duration');
const savedShotEndTime = localStorage.getItem('beercd_shot_endTime');
if (savedShotDuration) {
shotDuration = parseFloat(savedShotDuration);
}
if (savedShotEndTime) {
shotEndTime = parseInt(savedShotEndTime);
const now = Date.now();
if (shotEndTime <= now) {
shotEndTime = null;
}
}
// Load settings
const savedSoundEnabled = localStorage.getItem('beercd_soundEnabled');
const savedNotificationsEnabled = localStorage.getItem('beercd_notificationsEnabled');
if (savedSoundEnabled !== null) {
soundEnabled = savedSoundEnabled === 'true';
updateSoundToggle();
}
if (savedNotificationsEnabled !== null) {
notificationsEnabled = savedNotificationsEnabled === 'true';
}
// Check if we have notification permission
if ('Notification' in window && Notification.permission === 'granted') {
notificationsEnabled = true;
}
// Start timer if any cooldown is active
if (beerEndTime || shotEndTime) {
startTimer();
}
updateDisplay();
}
// Save cooldown state to localStorage
function saveCooldownState() {
// Save beer state
if (beerEndTime) {
localStorage.setItem('beercd_beer_endTime', beerEndTime.toString());
} else {
localStorage.removeItem('beercd_beer_endTime');
}
localStorage.setItem('beercd_beer_duration', beerDuration.toString());
// Save shot state
if (shotEndTime) {
localStorage.setItem('beercd_shot_endTime', shotEndTime.toString());
} else {
localStorage.removeItem('beercd_shot_endTime');
}
localStorage.setItem('beercd_shot_duration', shotDuration.toString());
// Save settings
localStorage.setItem('beercd_soundEnabled', soundEnabled.toString());
localStorage.setItem('beercd_notificationsEnabled', notificationsEnabled.toString());
}
// Play sound effect (beer or shot depending on active tab)
function playBeerSound() {
if (!soundEnabled) return;
const audioId = activeTab === 'beer' ? 'beerSound' : 'shotSound';
const audio = document.getElementById(audioId);
if (audio) {
// Set volume to 25% to make it less loud (some MP3s are mastered very loud)
audio.volume = 0.25;
// Reset to beginning in case it's already playing
audio.currentTime = 0;
audio.play().catch(err => {
// Silently fail if audio can't play (e.g., no sound file or autoplay restrictions)
console.log('Audio play failed (this is okay if no sound file is provided):', err);
});
}
}
// Toggle sound on/off
function toggleSound() {
soundEnabled = !soundEnabled;
saveCooldownState();
updateSoundToggle();
}
// Update sound toggle button appearance
function updateSoundToggle() {
const soundIcon = document.getElementById('soundIcon');
const soundToggle = document.getElementById('soundToggle');
if (soundIcon && soundToggle) {
soundIcon.textContent = soundEnabled ? '🔊' : '🔇';
soundToggle.classList.toggle('muted', !soundEnabled);
}
}
// Show bubbly beer animation or glittery shot animation
function showBeerAnimation() {
const overlay = document.getElementById('beerAnimation');
if (!overlay) return;
const bubblesContainer = overlay.querySelector('.bubbles-container');
bubblesContainer.innerHTML = ''; // Clear existing particles
if (activeTab === 'beer') {
// Beer: bubbles rising up
for (let i = 0; i < 30; i++) {
const bubble = document.createElement('div');
bubble.className = 'bubble';
bubble.style.left = Math.random() * 100 + '%';
bubble.style.animationDelay = Math.random() * 2 + 's';
bubble.style.animationDuration = (Math.random() * 2 + 2) + 's';
bubble.style.width = bubble.style.height = (Math.random() * 15 + 5) + 'px';
bubblesContainer.appendChild(bubble);
}
} else {
// Shot: glittery rainbow stars bursting
const rainbowColors = [
'#ff0000', // Red
'#ff7700', // Orange
'#ffff00', // Yellow
'#00ff00', // Green
'#0099ff', // Blue
'#6633ff', // Purple
'#ff3388' // Pink
];
for (let i = 0; i < 50; i++) {
const star = document.createElement('div');
star.className = 'star';
star.style.left = Math.random() * 100 + '%';
star.style.top = Math.random() * 100 + '%';
star.style.animationDelay = Math.random() * 0.5 + 's';
star.style.animationDuration = (Math.random() * 1 + 1.5) + 's';
star.style.width = star.style.height = (Math.random() * 8 + 3) + 'px';
// Random rainbow color
const color = rainbowColors[Math.floor(Math.random() * rainbowColors.length)];
star.style.setProperty('--star-color', color);
// Random burst direction
const angle = Math.random() * Math.PI * 2;
const distance = Math.random() * 200 + 100;
const tx = Math.cos(angle) * distance;
const ty = Math.sin(angle) * distance;
star.style.setProperty('--tx', tx + 'px');
star.style.setProperty('--ty', ty + 'px');
bubblesContainer.appendChild(star);
}
}
// Show overlay with appropriate background
if (activeTab === 'beer') {
overlay.style.background = 'linear-gradient(135deg, rgba(139, 69, 19, 0.9) 0%, rgba(101, 67, 33, 0.9) 100%)';
} else {
overlay.style.background = 'rgba(0, 0, 0, 0.8)';
}
overlay.classList.add('active');
// Hide after animation completes
setTimeout(() => {
overlay.classList.remove('active');
}, 3000); // 3 seconds
}
// Request notification permission
async function requestNotificationPermission() {
if (!('Notification' in window)) {
console.log('This browser does not support notifications');
return false;
}
if (Notification.permission === 'granted') {
notificationsEnabled = true;
return true;
}
if (Notification.permission !== 'denied') {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
notificationsEnabled = true;
saveCooldownState();
return true;
}
}
return false;
}
// Show notification when timer expires
function showTimerNotification() {
if (!('Notification' in window)) {
// Fallback for browsers without Notification support
alert('🍺 BeerCD - Cooldown Complete!\nYour cooldown timer has finished.');
return;
}
if (Notification.permission === 'granted') {
const notification = new Notification('🍺 BeerCD - Cooldown Complete!', {
body: 'Your cooldown timer has finished.',
icon: 'https://ini272.github.io/beercd/icons/icon-192x192.png',
badge: 'https://ini272.github.io/beercd/icons/icon-192x192.png',
tag: 'beercd-cooldown-complete',
requireInteraction: false
});
// Close notification after 5 seconds
setTimeout(() => {
notification.close();
}, 5000);
// Focus app when notification is clicked
notification.onclick = () => {
window.focus();
notification.close();
};
} else {
// Fallback if permission not granted
alert('🍺 BeerCD - Cooldown Complete!\nYour cooldown timer has finished.');
}
}
// Check if timer expired while app was closed
function checkExpiredTimer() {
if (!cooldownEndTime) return;
const now = Date.now();
if (cooldownEndTime <= now && notificationsEnabled) {
// Timer expired while app was closed - show notification
showTimerNotification();
}
}
// Start the cooldown
async function startCooldown() {
// Always reset/start a new cooldown when button is clicked
const activeEndTime = getActiveEndTime();
if (activeEndTime) {
setActiveEndTime(null);
}
// Request notification permission if not already granted
await requestNotificationPermission();
// Play sound and show animation
playBeerSound();
showBeerAnimation();
// Track the drink
trackDrink(activeTab);
const now = Date.now();
const activeDuration = getActiveDuration();
setActiveEndTime(now + (activeDuration * 60 * 60 * 1000));
saveCooldownState();
startTimer();
updateDisplay();
// Visual feedback
document.querySelector('.timer-display').classList.add('cooldown-active');
// Show stop button
const stopButton = document.getElementById('stopButton');
if (stopButton) {
stopButton.style.display = 'flex';
}
// Schedule notification via service worker
scheduleNotification();
}
// Stop the cooldown (called by stop button)
function stopCooldown() {
setActiveEndTime(null);
saveCooldownState();
updateDisplay();
// Hide stop button
const stopButton = document.getElementById('stopButton');
if (stopButton) {
stopButton.style.display = 'none';
}
document.querySelector('.timer-display').classList.remove('cooldown-active');
}
// Schedule notification in service worker
function scheduleNotification() {
if (!notificationsEnabled || !('serviceWorker' in navigator)) {
return;
}
// Send message to service worker with timer end time
navigator.serviceWorker.ready.then(registration => {
registration.active.postMessage({
type: 'SCHEDULE_NOTIFICATION',
endTime: cooldownEndTime
});
});
}
// Start the timer
function startTimer() {
if (timerInterval) {
clearInterval(timerInterval);
}
timerInterval = setInterval(() => {
updateDisplay();
const now = Date.now();
if (cooldownEndTime <= now) {
// Cooldown expired
showTimerNotification();
clearCooldown();
// Don't show alert if notification was shown
if (!notificationsEnabled) {
alert('Cooldown complete! 🍺');
}
}
}, 1000);
updateDisplay();
}
// Update the display
function updateDisplay() {
const timeDisplay = document.getElementById('timeDisplay');
const statusDisplay = document.getElementById('statusDisplay');
const refreshIcon = document.getElementById('refreshIcon');
const stopButton = document.getElementById('stopButton');
const inactivePreview = document.getElementById('inactivePreview');
const inactiveTime = document.getElementById('inactiveTime');
const activeEndTime = getActiveEndTime();
const inactiveEndTime = getInactiveEndTime();
// Update inactive timer preview
if (inactiveEndTime) {
const now = Date.now();
const inactiveRemaining = Math.max(0, inactiveEndTime - now);
if (inactiveRemaining > 0) {
const iHours = Math.floor(inactiveRemaining / (1000 * 60 * 60));
const iMinutes = Math.floor((inactiveRemaining % (1000 * 60 * 60)) / (1000 * 60));
const iSeconds = Math.floor((inactiveRemaining % (1000 * 60)) / 1000);
inactiveTime.textContent = String(iHours).padStart(2, '0') + ':' + String(iMinutes).padStart(2, '0') + ':' + String(iSeconds).padStart(2, '0');
inactivePreview.style.display = 'block';
} else {
inactivePreview.style.display = 'none';
}
} else {
inactivePreview.style.display = 'none';
}
// Update active timer
if (!activeEndTime) {
timeDisplay.textContent = '--:--:--';
statusDisplay.textContent = 'Ready';
if (refreshIcon) {
refreshIcon.style.display = 'none';
}
if (stopButton) {
stopButton.style.display = 'none';
}
return;
}
const now = Date.now();
const remaining = Math.max(0, activeEndTime - now);
if (remaining === 0) {
timeDisplay.textContent = '00:00:00';
statusDisplay.textContent = 'Cooldown Complete!';
if (refreshIcon) {
refreshIcon.style.display = 'none';
}
if (stopButton) {
stopButton.style.display = 'none';
}
setActiveEndTime(null);
saveCooldownState();
return;
}
const hours = Math.floor(remaining / (1000 * 60 * 60));
const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((remaining % (1000 * 60)) / 1000);
timeDisplay.textContent =
String(hours).padStart(2, '0') + ':' +
String(minutes).padStart(2, '0') + ':' +
String(seconds).padStart(2, '0');
statusDisplay.textContent = 'Cooldown Active';
if (refreshIcon) {
refreshIcon.style.display = 'flex';
}
if (stopButton) {
stopButton.style.display = 'flex';
}
}
// Switch between beer and shot tabs
function switchTab(tab) {
activeTab = tab;
// Update tab UI
document.getElementById('beerTab').classList.toggle('active', tab === 'beer');
document.getElementById('shotTab').classList.toggle('active', tab === 'shot');
// Update button icon
document.getElementById('buttonIcon').textContent = tab === 'beer' ? '🍺' : '🍸';
// Update inactive preview label
const label = document.getElementById('inactiveLabel');
label.textContent = tab === 'beer' ? 'Shot: ' : 'Beer: ';
// Sync custom spinner from active duration
syncCustomSpinnerFromActive();
// Update display
updateDisplay();
}
// Toggle custom duration section
function toggleCustomDuration() {
const section = document.getElementById('customSection');
const toggle = document.getElementById('customToggle');
const icon = document.getElementById('toggleIcon');
if (section.style.display === 'none') {
section.style.display = 'block';
icon.textContent = '▲';
} else {
section.style.display = 'none';
icon.textContent = '▼';
}
}
// Set preset duration and update UI
function setPresetDuration(hours) {
setActiveDuration(hours);
saveCooldownState();
updatePresetButtonsUI();
updateCustomSpinnerDisplay();
}
// Sync custom spinner from active duration (called when switching tabs)
function syncCustomSpinnerFromActive() {
const activeDuration = getActiveDuration();
customHours = Math.floor(activeDuration);
customMinutes = Math.round((activeDuration - customHours) * 60);
updateCustomSpinnerDisplay();
}
// Update custom spinner display (only updates DOM, doesn't reset values)
function updateCustomSpinnerDisplay() {
const hourDisplay = document.getElementById('hourDisplay');
const minuteDisplay = document.getElementById('minuteDisplay');
if (hourDisplay) {
hourDisplay.value = customHours;
}
if (minuteDisplay) {
minuteDisplay.value = String(customMinutes).padStart(2, '0');
}
updateLivePreview();
}
// Handle direct hour input
function onHourInput() {
const hourDisplay = document.getElementById('hourDisplay');
let hours = parseInt(hourDisplay.value) || 0;
// Validate range
if (hours < 0) hours = 0;
if (hours > 23) hours = 23;
customHours = hours;
hourDisplay.value = hours;
updateLivePreview();
}
// Handle direct minute input
function onMinuteInput() {
const minuteDisplay = document.getElementById('minuteDisplay');
let minutes = parseInt(minuteDisplay.value) || 0;
// Validate range
if (minutes < 0) minutes = 0;
if (minutes > 59) minutes = 59;
customMinutes = minutes;
minuteDisplay.value = String(minutes).padStart(2, '0');
updateLivePreview();
}
// Increment hour
function incrementHour() {
if (customHours < 23) {
customHours++;
updateCustomSpinnerDisplay();
}
}
// Decrement hour
function decrementHour() {
if (customHours > 0) {
customHours--;
updateCustomSpinnerDisplay();
}
}
// Increment minute
function incrementMinute() {
if (customMinutes < 59) {
customMinutes++;
updateCustomSpinnerDisplay();
}
}
// Decrement minute
function decrementMinute() {
if (customMinutes > 0) {
customMinutes--;
updateCustomSpinnerDisplay();
}
}
// Update live preview text
function updateLivePreview() {
const totalMinutes = customHours * 60 + customMinutes;
const displayHours = Math.floor(totalMinutes / 60);
const displayMinutes = totalMinutes % 60;
let preview = '';
if (displayHours > 0) {
preview += displayHours + 'h';
}
if (displayMinutes > 0 || preview === '') {
if (preview) preview += ' ';
preview += displayMinutes + 'm';
}
document.getElementById('livePreview').textContent = preview;
}
// Apply custom duration
function applyCustomDuration() {
const totalMinutes = customHours * 60 + customMinutes;
// Validate: minimum 1 minute
if (totalMinutes < 1) {
alert('Please set a duration of at least 1 minute');
return;
}
const newDuration = totalMinutes / 60; // Convert back to hours
setActiveDuration(newDuration);
saveCooldownState();
updatePresetButtonsUI();
// Visual feedback
const btn = document.querySelector('.apply-custom-btn');
if (btn) {
btn.textContent = 'Applied!';
btn.style.backgroundColor = '#6b8e23';
setTimeout(() => {
btn.textContent = 'Apply';
btn.style.backgroundColor = '';
}, 1500);
}
}
// Reset custom duration to current active duration
function resetCustomDuration() {
syncCustomSpinnerFromActive();
updateCustomSpinnerDisplay();
}
// Update preset button UI to show which is active
function updatePresetButtonsUI() {
const presets = [
{ value: 0.25, hours: 0, minutes: 15 },
{ value: 0.5, hours: 0, minutes: 30 },
{ value: 1, hours: 1, minutes: 0 },
{ value: 2, hours: 2, minutes: 0 },
{ value: 3, hours: 3, minutes: 0 }
];
const activeDuration = getActiveDuration();
const buttons = document.querySelectorAll('.preset-btn');
buttons.forEach((btn, idx) => {
const preset = presets[idx];
const match = Math.abs(activeDuration - preset.value) < 0.01;
btn.classList.toggle('active', match);
});
}
// Handle visibility changes (app backgrounded/foregrounded)
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
// App became visible - update display immediately
updateDisplay();
// Check if any cooldowns expired while in background
const now = Date.now();
const activeEndTime = getActiveEndTime();
if (activeEndTime && activeEndTime <= now) {
if (notificationsEnabled) {
showTimerNotification();
} else {
alert('Cooldown complete! 🍺');
}
setActiveEndTime(null);
saveCooldownState();
} else if (!timerInterval && (beerEndTime || shotEndTime)) {
// Restart timer if it was stopped
startTimer();
}
}
});
// Handle page focus/blur for additional reliability
window.addEventListener('focus', () => {
if (beerEndTime || shotEndTime) {
updateDisplay();
const now = Date.now();
const activeEndTime = getActiveEndTime();
if (activeEndTime && activeEndTime <= now) {
if (notificationsEnabled) {
showTimerNotification();
} else {
alert('Cooldown complete! 🍺');
}
setActiveEndTime(null);
saveCooldownState();
} else if (!timerInterval) {
startTimer();
}
}
});
// Theme toggle
function toggleTheme() {
const isDark = document.body.classList.toggle('dark-mode');
localStorage.setItem('beercd_darkMode', isDark);
updateThemeIcon();
}
function updateThemeIcon() {
const icon = document.getElementById('themeIcon');
const isDark = document.body.classList.contains('dark-mode');
icon.textContent = isDark ? '☀️' : '🌙';
}
function loadThemePreference() {
const saved = localStorage.getItem('beercd_darkMode');
if (saved === 'false') {
document.body.classList.remove('dark-mode');
} else {
// Dark mode by default
document.body.classList.add('dark-mode');
}
updateThemeIcon();
}
// Initialize on page load
window.addEventListener('DOMContentLoaded', () => {
loadThemePreference();
loadCooldownState();
updateSoundToggle();
updateCustomSpinnerDisplay();
updatePresetButtonsUI();
});