-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3189 lines (2831 loc) · 95.9 KB
/
script.js
File metadata and controls
3189 lines (2831 loc) · 95.9 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
// Show timer digits only after Azeret Mono has loaded to prevent font flicker
(function () {
function showTimer() {
document.documentElement.classList.add('fonts-ready');
}
if (document.fonts?.load) {
document.fonts
.load('600 1em "Azeret Mono"')
.then(showTimer)
.catch(showTimer);
setTimeout(showTimer, 3000); // Show anyway if font fails or is slow
} else {
showTimer();
}
})();
// DOM Elements
let minutesDisplay,
secondsDisplay,
startBtn,
resetBtn,
fullscreenBtn,
settingsBtn,
settingsDialog,
closeSettingsBtn,
playerCountInput,
travellerCountInput,
accelerateBtn,
minuteButtons,
secondButtons,
infoBtn,
infoDialog,
closeInfoBtn,
whatsNewDialog,
closeWhatsNewBtn,
changeHistoryDialog,
closeChangeHistoryBtn;
// Utility functions
const connectivityUtils = {
isOnline: () => navigator.onLine,
addStatusListener: (onlineCallback, offlineCallback) => {
globalThis.addEventListener('online', onlineCallback);
globalThis.addEventListener('offline', offlineCallback);
},
removeStatusListener: (onlineCallback, offlineCallback) => {
globalThis.removeEventListener('online', onlineCallback);
globalThis.removeEventListener('offline', offlineCallback);
},
};
const orientationUtils = {
isPortrait: () => globalThis.matchMedia('(orientation: portrait)').matches,
addOrientationListener: (callback) => {
globalThis
.matchMedia('(orientation: portrait)')
.addEventListener('change', (e) => {
callback(e.matches);
});
},
removeOrientationListener: (callback) => {
globalThis
.matchMedia('(orientation: portrait)')
.removeEventListener('change', callback);
},
};
const youtubeUtils = {
play: () => {
if (playMusic && youtubePlayer?.playVideo) {
youtubePlayer.playVideo();
}
},
pause: () => {
if (playMusic && youtubePlayer?.pauseVideo) {
youtubePlayer.pauseVideo();
}
},
stop: () => {
if (playMusic && youtubePlayer?.stopVideo) {
youtubePlayer.stopVideo();
}
},
};
const timerUtils = {
stop: () => {
clearInterval(timerId);
isRunning = false;
updateDisplay();
},
updateButtonStates: (buttons, activeButton) => {
buttons.forEach((btn) => btn.classList.remove('active'));
if (activeButton) {
activeButton.classList.add('active');
}
},
holdToActivate: (button, holdDuration, onProgress, onComplete) => {
let startTime;
let animationFrame;
let holdTimer;
const start = (e) => {
// Prevent text selection during hold
e.preventDefault();
startTime = Date.now();
const animate = () => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / holdDuration, 1);
if (onProgress) {
button.style.setProperty('--progress-width', `${progress * 100}%`);
onProgress(progress);
}
if (progress < 1) {
animationFrame = requestAnimationFrame(animate);
}
};
animate();
holdTimer = setTimeout(() => {
if (onComplete) {
onComplete();
}
}, holdDuration);
};
const cancel = () => {
if (animationFrame) {
cancelAnimationFrame(animationFrame);
}
if (holdTimer) {
clearTimeout(holdTimer);
}
if (onProgress) {
button.style.setProperty('--progress-width', '0%');
onProgress(0);
}
};
// Add event listeners with passive option where appropriate
button.addEventListener('mousedown', start);
button.addEventListener('touchstart', start, { passive: false }); // We need preventDefault, so can't be passive
button.addEventListener('mouseup', cancel, { passive: true });
button.addEventListener('mouseleave', cancel, { passive: true });
button.addEventListener('touchend', cancel, { passive: true });
button.addEventListener('touchcancel', cancel, { passive: true });
},
};
// Keyboard shortcuts utilities
const keyboardShortcutsUtils = {
isValidShortcut: (event) => {
// Allow single keys, but exclude some system keys
const excludedKeys = [
'F1',
'F2',
'F3',
'F4',
'F5',
'F6',
'F7',
'F8',
'F9',
'F10',
'F11',
'F12',
];
const key = event.key.toUpperCase();
return (
!excludedKeys.includes(key) &&
!event.ctrlKey &&
!event.altKey &&
!event.metaKey
);
},
checkConflict: (newKey, currentAction) => {
for (const [action, key] of Object.entries(keyboardShortcuts)) {
if (action !== currentAction && key === newKey) {
return action;
}
}
return null;
},
updateShortcutDisplay: (inputId, key) => {
const input = document.getElementById(inputId);
if (input) {
if (key === ' ') {
input.value = 'Space';
} else if (key === '') {
input.value = '';
} else {
input.value = key;
}
}
},
loadShortcuts: () => {
keyboardShortcutsUtils.updateShortcutDisplay(
'shortcutSettings',
keyboardShortcuts.settings
);
keyboardShortcutsUtils.updateShortcutDisplay(
'shortcutWakeUp',
keyboardShortcuts.wakeUp
);
keyboardShortcutsUtils.updateShortcutDisplay(
'shortcutReset',
keyboardShortcuts.reset
);
keyboardShortcutsUtils.updateShortcutDisplay(
'shortcutAccelerate',
keyboardShortcuts.accelerate
);
keyboardShortcutsUtils.updateShortcutDisplay(
'shortcutFullscreen',
keyboardShortcuts.fullscreen
);
keyboardShortcutsUtils.updateShortcutDisplay(
'shortcutInfo',
keyboardShortcuts.info
);
},
resetToDefaults: () => {
// Explicitly reset to defaults, clearing any corrupted data
keyboardShortcuts = { ...DEFAULT_KEYBOARD_SHORTCUTS };
// Update the UI immediately
keyboardShortcutsUtils.loadShortcuts();
// Update shortcut hints on buttons
updateWakeUpShortcutHint();
updateAccelerateShortcutHint();
// Save the clean defaults to localStorage
saveSettings();
console.log('Keyboard shortcuts reset to defaults:', keyboardShortcuts);
},
// Nuclear option: completely remove and recreate the keyboardShortcuts key
forceReset: () => {
// Get current settings
const savedSettings = localStorage.getItem('quickTimerSettings');
if (savedSettings) {
const settings = JSON.parse(savedSettings);
// Remove the keyboardShortcuts key completely
delete settings.keyboardShortcuts;
// Save settings without keyboardShortcuts
localStorage.setItem('quickTimerSettings', JSON.stringify(settings));
}
// Reset to defaults
keyboardShortcuts = { ...DEFAULT_KEYBOARD_SHORTCUTS };
// Update the UI immediately
keyboardShortcutsUtils.loadShortcuts();
updateWakeUpShortcutHint();
updateAccelerateShortcutHint();
// Save the clean defaults to localStorage
saveSettings();
console.log(
'Keyboard shortcuts force reset (key deleted and recreated):',
keyboardShortcuts
);
},
clearAll: () => {
// Clear all shortcuts (set to empty strings)
keyboardShortcuts = {
settings: '',
wakeUp: '',
reset: '',
accelerate: '',
fullscreen: '',
info: '',
};
// Update the UI immediately
keyboardShortcutsUtils.loadShortcuts();
// Update shortcut hints on buttons
updateWakeUpShortcutHint();
updateAccelerateShortcutHint();
// Save the cleared shortcuts to localStorage
saveSettings();
console.log('All keyboard shortcuts cleared:', keyboardShortcuts);
},
};
// Button Labels
const BUTTON_LABELS = {
WAKE_UP: '⏰ Wake Up!',
PAUSE: '⏸️ Pause Day',
RESUME: '▶️ Resume Day',
RESET: '🔄 Reset Day',
ACCELERATE: '⏩ Accelerate Time',
ACCELERATE_CONFIRM: 'Confirm…',
ACCELERATE_TIME_FLIES: '{time flies}',
START_DAY: (day) => `▶ Start Day ${day}`,
FULLSCREEN: {
ENTER:
'<svg viewBox="0 0 24 24" width="24" height="24" class="fullscreen-icon"><path fill="currentColor" d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>',
EXIT: '<svg viewBox="0 0 24 24" width="24" height="24" class="fullscreen-icon"><path fill="currentColor" d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/></svg>',
},
};
// Default YouTube playlist URL
const DEFAULT_YOUTUBE_PLAYLIST =
'https://www.youtube.com/watch?v=TInSYXP9ZB8&list=PLhCDyBm6z1NwkkOAyQAMQkeberU9rwMcc';
const ATMOSPHERIC_PLAYLIST =
'https://www.youtube.com/watch?v=1oCIZjPxthY&list=PLhCDyBm6z1NyrifTlGYj55uPb6xrlgBih';
// YouTube API Key (placeholder - replace with actual key if needed)
const YOUTUBE_API_KEY = 'YOUR_YOUTUBE_API_KEY_HERE';
// Import version tracking from changelog
import { APP_VERSION, CHANGELOG } from './changelog.js';
// Audio Elements
let endSound = null;
let wakeUpSound = null;
let nominationsOpenSound = null;
let previewSound = null; // New audio element for previews
// Wake Lock state
let wakeLock = null;
// Timer state
let timeLeft = 0;
let timerId = null;
let isRunning = false;
let selectedSeconds = 0;
let selectedMinutes = 0;
let normalInterval = 1000; // Normal 1 second interval
let currentInterval = normalInterval;
let wakeUpTimeout = null;
let isEndSoundPlaying = false; // New state variable
let hasReset = false; // New state variable to track reset state
let accelerateConfirmTimeout = null;
// Game pace multipliers
const PACE_MULTIPLIERS = {
relaxed: 1,
normal: 0.8, // 20% faster than relaxed
speedy: 0.5, // 50% faster than relaxed
blitz: 0.33, // 67% faster than relaxed
};
// Settings state
let playerCount = 10; // Default to 10 players
let travellerCount = 0; // Default to 0 travellers
let isFirstLoad = false;
let currentDay = null;
/** Day number → preset index used for that day. Only presets we skipped get 💀; used presets keep "Day N"; rest renumbered from current. */
let usedPresetByDay = {};
/** Preset day indices permanently hidden when their day ended (countdown reached zero). Never shown again until new game. */
let hiddenPresetDays = [];
/** True only when the timer has run out this day (dusk); used so we show compact preset list only then, not when e.g. clicking a preset. */
let isDuskPresetView = false;
let currentPace = 'normal'; // Default pace
let playMusic = false; // Default to false for new users
let playMusicAtNight = false; // Default to false for new users
let playSoundEffects = true; // Default to true for sound effects
let youtubeVolume = 15; // Default to 15%
let soundEffectsVolume = 75; // Default to 75%
let backgroundTheme = 'medieval-cartoon'; // Default background theme
let youtubePlaylistUrl = DEFAULT_YOUTUBE_PLAYLIST; // Default playlist
let keepDisplayOn = true; // Default to true for wake lock
let showPlayerCountQr = false; // Optional QR linking to count.arcane-scripts.net
let youtubePlayer = null;
let endOfDaySound = 'cathedral-bell-v2.mp3'; // Default end of day sound
let wakeUpSoundFile = 'chisel-bell-01-loud-v2.mp3'; // Default wake up sound
let nominationsOpenSoundFile = 'nominations-open-laura.mp3'; // Default nominations open sound
let acceptedPortraitWarning = false; // Default to false for portrait warning
let autoOpenNominations = false;
let autoOpenNominationsDelay = 60; // seconds
let autoOpenNominationsInterval = null;
let nominationsCountdownRemaining = 0;
// Keyboard shortcuts
const DEFAULT_KEYBOARD_SHORTCUTS = {
settings: 'q',
wakeUp: ' ',
reset: 'r',
accelerate: 'a',
fullscreen: 'f',
info: 'i',
};
let keyboardShortcuts = { ...DEFAULT_KEYBOARD_SHORTCUTS };
// Character amounts mapping
const characterAmounts = {
5: [3, 0, 1, 1],
6: [3, 1, 1, 1],
7: [5, 0, 1, 1],
8: [5, 1, 1, 1],
9: [5, 2, 1, 1],
10: [7, 0, 2, 1],
11: [7, 1, 2, 1],
12: [7, 2, 2, 1],
13: [9, 0, 3, 1],
14: [9, 1, 3, 1],
15: [9, 2, 3, 1],
};
// Helper function to re-enable all shortcut inputs
function reEnableShortcutInputs() {
document.querySelectorAll('.shortcut-input').forEach((el) => {
el.disabled = false;
el.style.opacity = '1';
});
}
// Start recording a new shortcut
function startShortcutRecording(input, action) {
// Clear any existing recording and restore their previous values
document.querySelectorAll('.shortcut-input.recording').forEach((el) => {
el.classList.remove('recording');
// Restore the previous value for any inputs that were in recording mode
const inputId = el.id;
const actionMap = {
shortcutSettings: 'settings',
shortcutWakeUp: 'wakeUp',
shortcutReset: 'reset',
shortcutAccelerate: 'accelerate',
shortcutFullscreen: 'fullscreen',
shortcutInfo: 'info',
};
const actionName = actionMap[inputId];
if (actionName && keyboardShortcuts[actionName]) {
keyboardShortcutsUtils.updateShortcutDisplay(
inputId,
keyboardShortcuts[actionName]
);
}
});
// Start recording this input
input.classList.add('recording');
input.value = 'Press a key...';
input.focus();
// Disable other shortcut inputs while recording
document.querySelectorAll('.shortcut-input').forEach((el) => {
if (el !== input) {
el.disabled = true;
el.style.opacity = '0.5';
}
});
const handleKeyDown = (e) => {
e.preventDefault();
e.stopPropagation();
if (e.key === 'Escape') {
// Cancel recording
input.classList.remove('recording');
keyboardShortcutsUtils.updateShortcutDisplay(
input.id,
keyboardShortcuts[action]
);
// Re-enable other shortcut inputs
reEnableShortcutInputs();
document.removeEventListener('keydown', handleKeyDown);
return;
}
if (keyboardShortcutsUtils.isValidShortcut(e)) {
const newKey = e.key;
// Check for conflicts
const conflict = keyboardShortcutsUtils.checkConflict(newKey, action);
if (conflict) {
// Show conflict warning
input.classList.add('shortcut-conflict');
input.value = `Conflict with ${conflict}`;
setTimeout(() => {
input.classList.remove('shortcut-conflict');
input.value = 'Press a key...';
}, 2000);
return;
}
// Update the shortcut
keyboardShortcuts[action] = newKey;
input.classList.remove('recording');
keyboardShortcutsUtils.updateShortcutDisplay(input.id, newKey);
// Re-enable other shortcut inputs
reEnableShortcutInputs();
// Update shortcut hints if changed
if (action === 'wakeUp') {
updateWakeUpShortcutHint();
}
if (action === 'accelerate') {
updateAccelerateShortcutHint();
}
saveSettings();
document.removeEventListener('keydown', handleKeyDown);
}
};
document.addEventListener('keydown', handleKeyDown);
}
// Helper function to update character amounts
function updateCharacterAmounts(count) {
const amounts = characterAmounts[count] || [0, 0, 0, 0];
document.getElementById('townsfolkAmount').textContent = amounts[0];
document.getElementById('outsiderAmount').textContent = amounts[1];
document.getElementById('minionAmount').textContent = amounts[2];
document.getElementById('demonAmount').textContent = amounts[3];
}
// Helper function to update wake up shortcut hint
function updateWakeUpShortcutHint() {
const hintElement = document.getElementById('wakeUpShortcutHint');
if (!hintElement) return;
const shortcutKey = keyboardShortcuts.wakeUp;
if (!shortcutKey) {
hintElement.textContent = '';
return;
}
// Special handling for MediaPlayPause
if (shortcutKey === 'MediaPlayPause') {
hintElement.innerHTML =
'<svg viewBox="0 0 24 24" width="16" height="12" style="vertical-align: middle;"><path fill="currentColor" d="M3 5v14l8-7z"/><path fill="currentColor" d="M14 5h2v14h-2zm4 0h2v14h-2z"/></svg>';
} else if (shortcutKey === ' ') {
hintElement.textContent = 'Space';
} else {
hintElement.textContent = shortcutKey.toUpperCase();
}
}
// Helper function to update accelerate shortcut hint
function updateAccelerateShortcutHint() {
const hintElement = document.getElementById('accelerateShortcutHint');
if (!hintElement) return;
const shortcutKey = keyboardShortcuts.accelerate;
if (!shortcutKey) {
hintElement.textContent = '';
return;
}
hintElement.textContent = shortcutKey.toUpperCase();
}
// Helper to set only the accelerate button label (preserves shortcut hint)
function setAccelerateButtonLabel(text) {
const textEl = accelerateBtn?.querySelector('.button-text');
if (textEl) textEl.textContent = text;
}
function getAccelerateButtonLabel() {
return accelerateBtn?.querySelector('.button-text')?.textContent ?? '';
}
// Helper function to update start button text (preserving the shortcut hint)
function updateStartButtonText(text) {
const buttonTextElement = startBtn.querySelector('.button-text');
if (buttonTextElement) {
buttonTextElement.textContent = text;
} else {
// Fallback if structure doesn't exist
startBtn.textContent = text;
}
}
// Helper function to update estimated game length
function updateEstimatedGameLength() {
const presets = generateDayPresets(playerCount);
let totalSeconds = 0;
presets.forEach((preset) => {
totalSeconds += preset.minutes * 60 + preset.seconds;
});
// Round up to the nearest minute
const totalMinutes = Math.ceil(totalSeconds / 60);
const estimatedGameLengthElement = document.getElementById(
'estimatedGameLength'
);
if (estimatedGameLengthElement) {
estimatedGameLengthElement.textContent = `${totalMinutes} minutes`;
}
}
// Request wake lock
async function requestWakeLock() {
if (!keepDisplayOn) return;
try {
wakeLock = await navigator.wakeLock.request('screen');
console.log('Wake Lock is active');
} catch (err) {
console.log(`Failed to request Wake Lock: ${err.name}, ${err.message}`);
}
}
// Release wake lock
async function releaseWakeLock() {
if (wakeLock) {
try {
await wakeLock.release();
wakeLock = null;
console.log('Wake Lock released');
} catch (err) {
console.log(`Failed to release Wake Lock: ${err.name}, ${err.message}`);
}
}
}
// Event listeners for wake lock
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'visible') {
await requestWakeLock();
} else {
await releaseWakeLock();
}
});
// Request wake lock and initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
try {
await requestWakeLock();
} catch (error) {
console.error('Error requesting wake lock:', error);
}
// Initialize audio
endSound = new Audio(`sounds/end-of-day/${endOfDaySound}`);
wakeUpSound = new Audio(`sounds/wake-up/${wakeUpSoundFile}`);
nominationsOpenSound = new Audio(
`sounds/nominations-open/${nominationsOpenSoundFile}`
);
// Add connectivity listeners
connectivityUtils.addStatusListener(
() => {
// When we come back online
if (playMusic) {
initYoutubePlayer();
// If timer is running, resume music after a short delay to allow player initialization
if (isRunning && timeLeft > 0) {
setTimeout(() => {
youtubeUtils.play();
}, 2000); // 2 second delay to allow player to initialize
}
}
},
() => {
// When we go offline, remove the YouTube player
const container = document.querySelector('.youtube-player-container');
if (container) {
container.remove();
}
youtubePlayer = null;
}
);
// Initialize DOM elements
minutesDisplay = document.getElementById('minutes');
secondsDisplay = document.getElementById('seconds');
startBtn = document.getElementById('startBtn');
updateStartButtonText(BUTTON_LABELS.WAKE_UP);
startBtn.disabled = false; // Ensure Wake Up button is enabled on load
resetBtn = document.getElementById('resetBtn');
resetBtn.textContent = BUTTON_LABELS.RESET;
resetBtn.disabled = true; // Reset button should be disabled initially
fullscreenBtn = document.getElementById('fullscreenBtn');
settingsBtn = document.getElementById('settingsBtn');
settingsDialog = document.getElementById('settingsDialog');
closeSettingsBtn = document.getElementById('closeSettings');
playerCountInput = document.getElementById('playerCount');
travellerCountInput = document.getElementById('travellerCount');
accelerateBtn = document.getElementById('accelerateBtn');
resetAccelerateButton();
accelerateBtn.disabled = true; // Accelerate button should be disabled initially
minuteButtons = document.querySelectorAll('.minute-btn');
secondButtons = document.querySelectorAll('.second-btn');
infoBtn = document.getElementById('infoBtn');
infoDialog = document.getElementById('infoDialog');
closeInfoBtn = document.getElementById('closeInfo');
whatsNewDialog = document.getElementById('whatsNewDialog');
closeWhatsNewBtn = document.getElementById('closeWhatsNew');
changeHistoryDialog = document.getElementById('changeHistoryDialog');
closeChangeHistoryBtn = document.getElementById('closeChangeHistory');
// Ensure change history dialog is closed on initialization
if (changeHistoryDialog) {
changeHistoryDialog.close();
// Also remove the 'open' attribute if present
changeHistoryDialog.removeAttribute('open');
// Double-check after a short delay in case something tries to open it
setTimeout(() => {
if (changeHistoryDialog.open) {
changeHistoryDialog.close();
changeHistoryDialog.removeAttribute('open');
}
}, 100);
}
// Add portrait warning dialog elements
const portraitWarningDialog = document.getElementById(
'portraitWarningDialog'
);
const acceptPortraitWarningBtn = document.getElementById(
'acceptPortraitWarning'
);
// Add event listener for accepting portrait warning
acceptPortraitWarningBtn.addEventListener('click', () => {
acceptedPortraitWarning = true;
saveSettings();
portraitWarningDialog.close();
});
// Add click-outside-to-close handler for portrait warning dialog
portraitWarningDialog.addEventListener('click', (e) => {
if (e.target === portraitWarningDialog) {
acceptedPortraitWarning = true;
saveSettings();
portraitWarningDialog.close();
}
});
// Check for portrait mode and show warning if needed
// Only show if actually in portrait mode and user hasn't accepted warning
if (orientationUtils.isPortrait() && !acceptedPortraitWarning) {
portraitWarningDialog.showModal();
} else {
// Ensure dialog is closed if we're in landscape mode
portraitWarningDialog.close();
}
// Add orientation change listener
orientationUtils.addOrientationListener((isPortrait) => {
if (isPortrait && !acceptedPortraitWarning) {
portraitWarningDialog.showModal();
} else if (!isPortrait) {
// Close dialog if user rotates back to landscape
portraitWarningDialog.close();
}
});
// Add event listener for "Use original playlist" link
document
.getElementById('useBardcorePlaylist')
.addEventListener('click', (e) => {
e.preventDefault();
const playlistInput = document.getElementById('youtubePlaylist');
playlistInput.value = DEFAULT_YOUTUBE_PLAYLIST;
youtubePlaylistUrl = DEFAULT_YOUTUBE_PLAYLIST;
saveSettings();
if (playMusic) {
initYoutubePlayer();
}
updateYoutubeLink();
});
document
.getElementById('useAtmosphericPlaylist')
.addEventListener('click', (e) => {
e.preventDefault();
const playlistInput = document.getElementById('youtubePlaylist');
playlistInput.value = ATMOSPHERIC_PLAYLIST;
youtubePlaylistUrl = ATMOSPHERIC_PLAYLIST;
saveSettings();
if (playMusic) {
initYoutubePlayer();
}
updateYoutubeLink();
});
// Add event listener for YouTube playlist input
document.getElementById('youtubePlaylist').addEventListener('change', () => {
updateYoutubePlaylist();
updateYoutubeLink();
});
// Add event listener for YouTube link
document
.getElementById('openYoutubePlaylist')
.addEventListener('click', (e) => {
if (!playMusic) {
e.preventDefault();
}
});
// Accelerate button: click -> "Confirm…", second click within 5s triggers acceleration
accelerateBtn.addEventListener('click', () => {
if (accelerateBtn.disabled) return;
if (getAccelerateButtonLabel() === BUTTON_LABELS.ACCELERATE) {
setAccelerateButtonLabel(BUTTON_LABELS.ACCELERATE_CONFIRM);
accelerateBtn.setAttribute(
'aria-label',
'Click again to accelerate time'
);
if (accelerateConfirmTimeout) clearTimeout(accelerateConfirmTimeout);
accelerateConfirmTimeout = setTimeout(() => {
accelerateConfirmTimeout = null;
resetAccelerateButton();
}, ACCELERATE_CONFIRM_SECONDS * 1000);
} else {
// Confirm: clear timeout, show "time flies", disable, then accelerate
if (accelerateConfirmTimeout) {
clearTimeout(accelerateConfirmTimeout);
accelerateConfirmTimeout = null;
}
setAccelerateButtonLabel(BUTTON_LABELS.ACCELERATE_TIME_FLIES);
accelerateBtn.disabled = true;
accelerateTime();
}
});
// Add event listeners
startBtn.addEventListener('click', startTimer);
resetBtn.addEventListener('click', resetTimer);
fullscreenBtn.addEventListener('click', toggleFullscreen);
settingsBtn.addEventListener('click', openSettings);
closeSettingsBtn.addEventListener('click', closeSettings);
infoBtn.addEventListener('click', openInfo);
closeInfoBtn.addEventListener('click', closeInfo);
playerCountInput.addEventListener('change', updatePlayerCount);
playerCountInput.addEventListener('input', updatePlayerCount);
travellerCountInput.addEventListener('change', updateTravellerCount);
travellerCountInput.addEventListener('input', updateTravellerCount);
document
.getElementById('startNewGame')
.addEventListener('click', startNewGame);
document.getElementById('gamePace').addEventListener('change', (e) => {
updateGamePace(e.target.value);
});
document
.getElementById('playMusic')
.addEventListener('change', updateMusicPlayback);
document.getElementById('playMusicAtNight').addEventListener('change', () => {
playMusicAtNight = document.getElementById('playMusicAtNight').checked;
saveSettings();
});
document
.getElementById('youtubePlaylist')
.addEventListener('change', updateYoutubePlaylist);
document
.getElementById('musicVolume')
.addEventListener('input', updateYoutubeVolume);
document
.getElementById('playSoundEffects')
.addEventListener('change', updateSoundEffects);
document
.getElementById('soundEffectsVolume')
.addEventListener('input', updateSoundEffectsVolume);
document.getElementById('keepDisplayOn').addEventListener('change', (e) => {
keepDisplayOn = e.target.checked;
saveSettings();
if (keepDisplayOn) {
requestWakeLock();
} else {
releaseWakeLock();
}
});
document
.getElementById('backgroundTheme')
.addEventListener('change', updateBackgroundTheme);
document.getElementById('showPlayerCountQr').addEventListener('change', (e) => {
showPlayerCountQr = e.target.checked;
document
.getElementById('playerCountQrWrapper')
.classList.toggle('visible', showPlayerCountQr);
saveSettings();
});
// Add keyboard shortcuts event listeners
document.querySelectorAll('.shortcut-input').forEach((input) => {
input.addEventListener('click', () => {
// Map input IDs to shortcut action names
const actionMap = {
shortcutSettings: 'settings',
shortcutWakeUp: 'wakeUp',
shortcutReset: 'reset',
shortcutAccelerate: 'accelerate',
shortcutFullscreen: 'fullscreen',
shortcutInfo: 'info',
};
const action = actionMap[input.id];
startShortcutRecording(input, action);
});
});
document.getElementById('resetShortcuts').addEventListener('click', () => {
if (
confirm(
'Are you sure you want to reset all keyboard shortcuts to their default values? This cannot be undone.'
)
) {
keyboardShortcutsUtils.forceReset();
}
});
document.getElementById('clearShortcuts').addEventListener('click', () => {
if (
confirm(
'Are you sure you want to clear all keyboard shortcuts? This will remove all shortcut assignments.'
)
) {
keyboardShortcutsUtils.clearAll();
}
});
// Add click handlers for preset buttons
minuteButtons.forEach((btn) => {
btn.addEventListener('click', handleMinuteClick);
});
secondButtons.forEach((btn) => {
btn.addEventListener('click', handleSecondClick);
});
// Add What's New dialog event listeners
closeWhatsNewBtn.addEventListener('click', closeWhatsNew);
whatsNewDialog.addEventListener('click', (e) => {
if (e.target === whatsNewDialog) {
closeWhatsNew();
}
});
// Add View Full History link event listener
document.getElementById('viewFullHistory').addEventListener('click', (e) => {
e.preventDefault();
closeWhatsNew();
showChangeHistory();
});
// Add Change History dialog event listeners
if (closeChangeHistoryBtn) {
closeChangeHistoryBtn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
closeChangeHistory();
});
}
if (changeHistoryDialog) {
changeHistoryDialog.addEventListener('click', (e) => {
if (e.target === changeHistoryDialog) {
closeChangeHistory();
}
});
}
// Add event listeners for sound preview buttons
document.querySelectorAll('.preview-sound').forEach((button) => {
button.addEventListener('click', () => {
const type = button.dataset.type;
const select = button.parentElement.querySelector('select');
const soundFile = select.value;
// Stop any currently playing preview
if (previewSound) {
previewSound.pause();
previewSound.currentTime = 0;
document
.querySelectorAll('.preview-sound')
.forEach((btn) => btn.classList.remove('playing'));
}
// Create and play the new preview (nominations-open uses its own folder)
const previewPath =
type === 'nominations-open'
? `sounds/nominations-open/${soundFile}`
: `sounds/${type}/${soundFile}`;
previewSound = new Audio(previewPath);
button.classList.add('playing');
previewSound.addEventListener(
'ended',
() => {
button.classList.remove('playing');