-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
949 lines (926 loc) · 45.6 KB
/
app.js
File metadata and controls
949 lines (926 loc) · 45.6 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
// Utility & feedback helpers
function speakCue(text) {
try {
if ('speechSynthesis' in window) {
const utter = new SpeechSynthesisUtterance(text);
utter.rate = 1.05;
window.speechSynthesis.speak(utter);
}
} catch(e) {}
}
function vibrate(pattern) { if (navigator.vibrate) navigator.vibrate(pattern); }
function formatTime(seconds) { const m = Math.floor(seconds/60); const s = seconds % 60; return `${m}:${s.toString().padStart(2,'0')}`; }
// Save workout completion
function markWorkoutComplete(week, day){
let progress = JSON.parse(localStorage.getItem('c25k_progress')||'{}');
if(!progress[week]) progress[week]={};
progress[week][day]=true;
localStorage.setItem('c25k_progress', JSON.stringify(progress));
}
// Couch to 5K Trainer App
// Basic structure and event listeners
document.addEventListener('DOMContentLoaded', function() {
const sections = {
home: document.getElementById('home'),
schedule: document.getElementById('schedule'),
workout: document.getElementById('workout'),
progress: document.getElementById('progress')
};
const settingsPanel = document.getElementById('settingsPanel');
const openSettingsBtn = document.getElementById('openSettingsBtn');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
const nav = document.getElementById('mainNav');
function showSection(name){
Object.entries(sections).forEach(([key,el])=>{
if(!el) return;
if(key===name){
el.hidden=false;
el.classList.add('fadeIn');
setTimeout(()=>el.classList.remove('fadeIn'),400);
} else {
el.hidden=true;
}
});
localStorage.setItem('c25k_last_section', name);
}
function setActiveNav(name){
if(!nav) return; nav.querySelectorAll('.navBtn').forEach(btn=>{
const target = btn.getAttribute('data-section');
if(target===name) btn.classList.add('active'); else btn.classList.remove('active');
});
}
if(nav){
nav.querySelectorAll('.navBtn').forEach(btn=>{
btn.addEventListener('click', ()=>{
const target = btn.getAttribute('data-section');
if(target==='settingsPanel') { settingsPanel.hidden=false; settingsPanel.focus(); return; }
settingsPanel.hidden = true;
showSection(target);
setActiveNav(target);
if(target==='schedule' && !sections.schedule.dataset.rendered) renderSchedule();
if(target==='progress') renderProgress();
});
});
const last = localStorage.getItem('c25k_last_section') || 'home';
setActiveNav(last);
showSection(last);
}
// Settings panel (initial assignment already above)
// Ensure settings gear always opens panel (will rewire later too)
if(openSettingsBtn) openSettingsBtn.addEventListener('click', ()=>{ openSettings(); });
if(closeSettingsBtn) closeSettingsBtn.onclick = ()=>{ closeSettings(); };
function openSettings(){ settingsPanel.hidden=false; trapFocus(settingsPanel); }
function closeSettings(){ settingsPanel.hidden=true; releaseFocus(); openSettingsBtn.focus(); }
// Settings logic continued
const timerSpeedInput = document.getElementById('timerSpeed');
const timerSpeedValue = document.getElementById('timerSpeedValue');
const soundVolumeInput = document.getElementById('soundVolume');
const soundVolumeValue = document.getElementById('soundVolumeValue');
const colorThemeSelect = document.getElementById('colorTheme');
const beepToneSelect = document.getElementById('beepToneSelect');
const resetProgressBtn = document.getElementById('resetProgressBtn');
const avgPaceInput = document.getElementById('avgPaceInput');
const autoNextCheckbox = document.getElementById('autoNextCheckbox');
const enhancedHapticsCheckbox = document.getElementById('enhancedHapticsCheckbox');
const exportProgressBtn = document.getElementById('exportProgressBtn');
const importProgressBtn = document.getElementById('importProgressBtn');
const importProgressFile = document.getElementById('importProgressFile');
const installAppBtn = document.getElementById('installAppBtn');
const weightInput = document.getElementById('weightInput');
const weightUnitSelect = document.getElementById('weightUnitSelect');
const hydrationCheckbox = document.getElementById('hydrationReminderCheckbox');
const batterySaverCheckbox = document.getElementById('batterySaverCheckbox');
const shareImageBtn = document.getElementById('shareImageBtn');
// Load settings
if (localStorage.getItem('c25k_timer_speed')) timerSpeedInput.value = localStorage.getItem('c25k_timer_speed');
if (localStorage.getItem('c25k_sound_volume')) soundVolumeInput.value = localStorage.getItem('c25k_sound_volume');
if (localStorage.getItem('c25k_color_theme')) colorThemeSelect.value = localStorage.getItem('c25k_color_theme');
if (localStorage.getItem('c25k_beep_tone')) beepToneSelect.value = localStorage.getItem('c25k_beep_tone');
if (localStorage.getItem('c25k_avg_pace')) avgPaceInput.value = localStorage.getItem('c25k_avg_pace');
if (localStorage.getItem('c25k_auto_next')) autoNextCheckbox.checked = localStorage.getItem('c25k_auto_next')==='1';
if (localStorage.getItem('c25k_enhanced_haptics')) enhancedHapticsCheckbox.checked = localStorage.getItem('c25k_enhanced_haptics')==='1';
if (localStorage.getItem('c25k_weight')) weightInput.value = localStorage.getItem('c25k_weight');
if (localStorage.getItem('c25k_weight_unit')) weightUnitSelect.value = localStorage.getItem('c25k_weight_unit');
if (localStorage.getItem('c25k_hydration')) hydrationCheckbox.checked = localStorage.getItem('c25k_hydration')==='1';
if (localStorage.getItem('c25k_battery_saver')==='1'){ batterySaverCheckbox.checked=true; document.body.classList.add('battery-saver'); }
timerSpeedValue.textContent = timerSpeedInput.value + 'x';
soundVolumeValue.textContent = Math.round(soundVolumeInput.value * 100) + '%';
// Open/close panel
if(openSettingsBtn) openSettingsBtn.onclick = function() { openSettings(); };
closeSettingsBtn.onclick = function() { closeSettings(); };
// Update settings
timerSpeedInput.oninput = function() {
timerSpeedValue.textContent = timerSpeedInput.value + 'x';
localStorage.setItem('c25k_timer_speed', timerSpeedInput.value);
};
soundVolumeInput.oninput = function() {
soundVolumeValue.textContent = Math.round(soundVolumeInput.value * 100) + '%';
localStorage.setItem('c25k_sound_volume', soundVolumeInput.value);
};
colorThemeSelect.onchange = function() {
localStorage.setItem('c25k_color_theme', colorThemeSelect.value);
applyTheme(colorThemeSelect.value);
};
beepToneSelect.onchange = function(){
localStorage.setItem('c25k_beep_tone', beepToneSelect.value);
speakCue(`${beepToneSelect.value} tone selected`);
};
avgPaceInput.oninput = function(){
if(avgPaceInput.value){ localStorage.setItem('c25k_avg_pace', avgPaceInput.value); }
};
autoNextCheckbox.onchange = function(){ localStorage.setItem('c25k_auto_next', autoNextCheckbox.checked?'1':'0'); };
enhancedHapticsCheckbox.onchange = function(){ localStorage.setItem('c25k_enhanced_haptics', enhancedHapticsCheckbox.checked?'1':'0'); };
weightInput.oninput = function(){ if(weightInput.value) localStorage.setItem('c25k_weight', weightInput.value); };
weightUnitSelect.onchange = function(){ localStorage.setItem('c25k_weight_unit', weightUnitSelect.value); };
hydrationCheckbox.onchange = function(){ localStorage.setItem('c25k_hydration', hydrationCheckbox.checked?'1':'0'); };
batterySaverCheckbox.onchange = function(){ localStorage.setItem('c25k_battery_saver', batterySaverCheckbox.checked?'1':'0'); document.body.classList.toggle('battery-saver', batterySaverCheckbox.checked); };
if(exportProgressBtn){
exportProgressBtn.onclick=()=>{
const data = {
progress: JSON.parse(localStorage.getItem('c25k_progress')||'{}'),
settings: {
timer_speed: localStorage.getItem('c25k_timer_speed'),
sound_volume: localStorage.getItem('c25k_sound_volume'),
color_theme: localStorage.getItem('c25k_color_theme'),
beep_tone: localStorage.getItem('c25k_beep_tone'),
avg_pace: localStorage.getItem('c25k_avg_pace'),
auto_next: localStorage.getItem('c25k_auto_next'),
enhanced_haptics: localStorage.getItem('c25k_enhanced_haptics')
}
};
const blob = new Blob([JSON.stringify(data,null,2)], {type:'application/json'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href=url; a.download='c25k-progress.json'; a.click(); URL.revokeObjectURL(url);
};
}
if(importProgressBtn && importProgressFile){
importProgressBtn.onclick=()=> importProgressFile.click();
importProgressFile.onchange=(e)=>{
const file = e.target.files[0]; if(!file) return;
const reader = new FileReader();
reader.onload=()=>{
try{
const data = JSON.parse(reader.result);
if(data.progress){ localStorage.setItem('c25k_progress', JSON.stringify(data.progress)); }
if(data.settings){
Object.entries(data.settings).forEach(([k,v])=>{
if(v!==undefined && v!==null) localStorage.setItem('c25k_'+k, v);
});
}
alert('Import successful. Reloading...'); location.reload();
}catch(err){ alert('Invalid file.'); }
};
reader.readAsText(file);
};
}
if(resetProgressBtn){
resetProgressBtn.onclick=()=>{
if(confirm('Reset all workout progress? This cannot be undone.')){
localStorage.removeItem('c25k_progress');
alert('Progress reset.');
const sec = document.getElementById('schedule');
if(sec){ sec.dataset.rendered=''; sec.innerHTML=''; }
}
};
}
// Apply theme
function applyTheme(theme) {
if (theme === 'dark') {
document.body.style.background = '#222';
document.body.style.color = '#fff';
} else if (theme === 'light') {
document.body.style.background = '#fff';
document.body.style.color = '#222';
} else {
document.body.style.background = '#f4f8fb';
document.body.style.color = '#222';
}
}
applyTheme(colorThemeSelect.value);
// Reminder setup
const reminderTimeInput = document.getElementById('reminderTime');
const setReminderBtn = document.getElementById('setReminderBtn');
if (setReminderBtn && reminderTimeInput) {
// Load saved reminder time
const savedTime = localStorage.getItem('c25k_reminder_time');
if (savedTime) reminderTimeInput.value = savedTime;
setReminderBtn.onclick = function() {
const time = reminderTimeInput.value;
if (!time) {
alert('Please select a time for your reminder.');
return;
}
localStorage.setItem('c25k_reminder_time', time);
// Request notification permission
if (Notification && Notification.permission !== 'granted') {
Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
alert('Reminder set! You will be notified at ' + time + ' each day.');
} else {
alert('Notifications are blocked. Please enable them in your browser settings.');
}
});
} else {
alert('Reminder set! You will be notified at ' + time + ' each day.');
}
};
// Schedule notification check every minute
setInterval(function() {
const time = localStorage.getItem('c25k_reminder_time');
if (!time || Notification.permission !== 'granted') return;
const now = new Date();
const [h, m] = time.split(':');
if (now.getHours() === parseInt(h) && now.getMinutes() === parseInt(m)) {
// Only notify once per day
const lastNotified = localStorage.getItem('c25k_last_notified');
const today = now.toISOString().slice(0,10);
if (lastNotified !== today) {
new Notification('Couch to 5K', { body: 'Time for your workout! 🏃♂️' });
localStorage.setItem('c25k_last_notified', today);
}
}
}, 60000);
}
const startBtn = document.getElementById('startBtn');
if(startBtn) startBtn.addEventListener('click', ()=>{ showSection('schedule'); setActiveNav('schedule'); if(!sections.schedule.dataset.rendered) renderSchedule(); });
// (removed duplicate renderSchedule)
function renderSchedule() {
const weeks = 9;
const daysPerWeek = 3;
let progress = JSON.parse(localStorage.getItem('c25k_progress') || '{}');
let html = '<h2>Choose Your Workout</h2><div class="weeks">';
for (let w = 1; w <= weeks; w++) {
html += `<div class="week"><strong>Week ${w}</strong><div class="days">`;
for (let d = 1; d <= daysPerWeek; d++) {
let done = progress[w] && progress[w][d];
html += `<button class="dayBtn" data-week="${w}" data-day="${d}" aria-pressed="${!!done}" ${done? 'disabled':''}>Day ${d}${done ? ' ✓' : ''}</button>`;
}
html += '</div></div>';
}
html += '</div>';
sections.schedule.innerHTML = html;
sections.schedule.dataset.rendered = '1';
// Add event listeners for day buttons
document.querySelectorAll('.dayBtn').forEach(btn => {
btn.addEventListener('click', function() {
const week = this.getAttribute('data-week');
const day = this.getAttribute('data-day');
showSection('workout');
setActiveNav('workout');
startWorkout(week, day);
});
});
}
// Prepare workout screen but keep Start button disabled until a workout is loaded
const globalStartBtn = document.getElementById('startIntervalBtn');
if(globalStartBtn){
globalStartBtn.disabled = true;
globalStartBtn.title = 'Select a week/day from Schedule first';
globalStartBtn.addEventListener('click', function(){
if(this.disabled){
speakCue('Pick a workout from the schedule first');
}
}, { once:false });
}
function startWorkout(week, day) {
const canvas = document.getElementById('progressCanvas');
const playMusicBtn = document.getElementById('playMusicBtn');
// Legacy audio element removed in favor of external streaming launch
const intervalCueEl = document.getElementById('intervalCue');
const timerDisplayEl = document.getElementById('timerDisplay');
const startIntervalBtn = document.getElementById('startIntervalBtn');
initMusicLauncher();
const intervalPlanWrap = document.getElementById('intervalPlanWrap');
const intervalPlanList = document.getElementById('intervalPlanList');
const intervalTotalTimeEl = document.getElementById('intervalTotalTime');
// Full Couch to 5K interval definitions for Weeks 1-9
// Source: NHS/C25K standard plans
const workouts = {
1: [
Array(1).fill().map(() => [
{ type: 'Warmup Walk', duration: 300 },
...Array(8).fill().flatMap(() => [
{ type: 'Run', duration: 60 },
{ type: 'Walk', duration: 90 }
]),
{ type: 'Cooldown Walk', duration: 300 }
])[0],
Array(1).fill().map(() => [
{ type: 'Warmup Walk', duration: 300 },
...Array(8).fill().flatMap(() => [
{ type: 'Run', duration: 60 },
{ type: 'Walk', duration: 90 }
]),
{ type: 'Cooldown Walk', duration: 300 }
])[0],
Array(1).fill().map(() => [
{ type: 'Warmup Walk', duration: 300 },
...Array(8).fill().flatMap(() => [
{ type: 'Run', duration: 60 },
{ type: 'Walk', duration: 90 }
]),
{ type: 'Cooldown Walk', duration: 300 }
])[0]
],
2: [
Array(1).fill().map(() => [
{ type: 'Warmup Walk', duration: 300 },
...Array(6).fill().flatMap(() => [
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 120 }
]),
{ type: 'Cooldown Walk', duration: 300 }
])[0],
Array(1).fill().map(() => [
{ type: 'Warmup Walk', duration: 300 },
...Array(6).fill().flatMap(() => [
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 120 }
]),
{ type: 'Cooldown Walk', duration: 300 }
])[0],
Array(1).fill().map(() => [
{ type: 'Warmup Walk', duration: 300 },
...Array(6).fill().flatMap(() => [
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 120 }
]),
{ type: 'Cooldown Walk', duration: 300 }
])[0]
],
3: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 180 },
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 180 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 180 },
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 180 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 180 },
{ type: 'Run', duration: 90 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 180 },
{ type: 'Cooldown Walk', duration: 300 }
]
],
4: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Walk', duration: 150 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Walk', duration: 150 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Walk', duration: 150 },
{ type: 'Run', duration: 180 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Cooldown Walk', duration: 300 }
]
],
5: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 300 },
{ type: 'Walk', duration: 180 },
{ type: 'Run', duration: 300 },
{ type: 'Walk', duration: 180 },
{ type: 'Run', duration: 300 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 600 },
{ type: 'Walk', duration: 300 },
{ type: 'Run', duration: 600 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1200 },
{ type: 'Cooldown Walk', duration: 300 }
]
],
6: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 300 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 600 },
{ type: 'Walk', duration: 90 },
{ type: 'Run', duration: 300 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 600 },
{ type: 'Walk', duration: 120 },
{ type: 'Run', duration: 600 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1500 },
{ type: 'Cooldown Walk', duration: 300 }
]
],
7: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1500 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1500 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1500 },
{ type: 'Cooldown Walk', duration: 300 }
]
],
8: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1680 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1800 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1800 },
{ type: 'Cooldown Walk', duration: 300 }
]
],
9: [
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1800 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1800 },
{ type: 'Cooldown Walk', duration: 300 }
],
[
{ type: 'Warmup Walk', duration: 300 },
{ type: 'Run', duration: 1800 },
{ type: 'Cooldown Walk', duration: 300 }
]
]
};
week = parseInt(week); day = parseInt(day);
const intervals = workouts[week][day-1];
if(!intervals) { intervalCueEl.textContent = 'Workout not found'; return; }
if(canvas) canvas.style.display='block';
// Build interval plan list before starting
if(intervalPlanWrap && intervalPlanList){
intervalPlanWrap.hidden = false;
let total = 0;
intervalPlanList.innerHTML = intervals.map((iv, idx)=>{ total += iv.duration; const cls = intervalTypeClass(iv.type); return `<li data-idx="${idx}" class="${cls}"><span class="intervalType">${iv.type}</span><span class="intervalDur">${formatTime(iv.duration)}</span></li>`; }).join('');
if(intervalTotalTimeEl) intervalTotalTimeEl.textContent = formatTime(total);
}
if(startIntervalBtn){
startIntervalBtn.disabled=false;
startIntervalBtn.title='Start this workout';
startIntervalBtn.onclick=()=> beginIntervals(intervals, week, day, {canvas, intervalCueEl, timerDisplayEl});
}
const toggleBtn = document.getElementById('toggleIntervalPlanBtn');
if(toggleBtn && intervalPlanWrap){
toggleBtn.onclick=()=>{
const collapsed = intervalPlanWrap.classList.toggle('collapsed');
toggleBtn.textContent = collapsed? 'Expand':'Collapse';
toggleBtn.setAttribute('aria-expanded', (!collapsed).toString());
};
}
}
function beginIntervals(intervals, week, day, ctxRefs){
const {canvas, intervalCueEl, timerDisplayEl} = ctxRefs;
const intervalPlanList = document.getElementById('intervalPlanList');
const planItems = intervalPlanList ? Array.from(intervalPlanList.querySelectorAll('li')) : [];
const remainingEl = document.getElementById('remainingIntervals');
const totalIntervals = intervals.length;
let current = 0;
let timeLeft = intervals[0].duration;
intervalCueEl.textContent = intervals[0].type;
timerDisplayEl.textContent = formatTime(timeLeft);
drawProgress(canvas,0,timeLeft,intervals[0].type);
speakCue(`Start ${intervals[0].type}`); doHaptics('start'); playBeep();
if(planItems.length){ planItems[0].classList.add('active'); }
let last = Date.now();
let speed = parseFloat(localStorage.getItem('c25k_timer_speed')||'1');
const workoutControls = document.getElementById('workoutControls');
if(workoutControls) workoutControls.style.display='flex';
let paused=false, stopped=false;
let announcedHalf=false; let intervalHalfTarget = intervals[current].duration/2;
const pauseBtn=document.getElementById('pauseWorkoutBtn');
const stopBtn=document.getElementById('stopWorkoutBtn');
const skipBtn=document.getElementById('skipIntervalBtn');
if(pauseBtn) pauseBtn.onclick=()=>{ paused=!paused; pauseBtn.textContent=paused?'Resume':'Pause Workout'; };
if(stopBtn) stopBtn.onclick=()=>{ stopped=true; cleanup(); };
if(skipBtn) skipBtn.onclick=()=>{ if(!stopped){ timeLeft=0; } };
const timer = setInterval(()=>{
if(stopped) return clearInterval(timer);
if(paused) { last=Date.now(); return; }
const now=Date.now();
if(now-last >= 1000/speed){
timeLeft--; last=now;
if(timeLeft<0) timeLeft=0;
timerDisplayEl.textContent = formatTime(timeLeft);
if(remainingEl) remainingEl.textContent = `Remaining: ${totalIntervals-current}/${totalIntervals}`;
if(!announcedHalf && timeLeft===Math.floor(intervalHalfTarget)){
// Halfway cue for long segments (>= 5 min)
if(intervals[current].duration >= 300){ speakCue('Halfway'); doHaptics('transition'); }
announcedHalf=true;
}
drawProgress(canvas,1-(timeLeft/intervals[current].duration),timeLeft,intervals[current].type);
// Pre-cue next interval at 5s remaining
if(timeLeft===5 && current < intervals.length-1){ speakCue(`Next ${intervals[current+1].type}`); }
if(timeLeft===0){
current++;
if(current<intervals.length){
timeLeft = intervals[current].duration;
intervalCueEl.textContent = intervals[current].type;
speakCue(`Start ${intervals[current].type}`); doHaptics('transition'); playBeep();
drawProgress(canvas,0,timeLeft,intervals[current].type);
if(planItems.length){
planItems.forEach((li,i)=>{
li.classList.toggle('active', i===current);
if(i<current) li.classList.add('completed');
});
}
announcedHalf=false; intervalHalfTarget = intervals[current].duration/2;
} else {
intervalCueEl.textContent = 'Workout Complete!';
timerDisplayEl.textContent = '';
drawProgress(canvas,1,0,'Complete');
playCelebrate(); doHaptics('complete'); markWorkoutComplete(week,day); cleanup();
if(localStorage.getItem('c25k_auto_next')==='1') scheduleNextAuto(week,day);
if(planItems.length){ planItems.forEach(li=>{ li.classList.remove('active'); li.classList.add('completed'); }); }
}
}
}
},100);
function cleanup(){
clearInterval(timer);
const workoutControls = document.getElementById('workoutControls');
if(workoutControls) workoutControls.style.display='none';
}
}
function scheduleNextAuto(week,day){
let w=parseInt(week), d=parseInt(day);
d++; if(d>3){ d=1; w++; }
if(w>9) return;
setTimeout(()=>{
showSection('schedule'); setActiveNav('schedule');
// ensure schedule rendered then auto-start next if available
if(!document.getElementById('schedule').dataset.rendered) renderSchedule();
const btn = document.querySelector(`.dayBtn[data-week='${w}'][data-day='${d}']`);
if(btn && !btn.disabled){ btn.click(); setTimeout(()=>document.getElementById('startIntervalBtn')?.click(), 600); }
}, 2500);
}
// Music launcher logic
function initMusicLauncher(){
const optionsWrap = document.getElementById('musicOptions');
const launchRow = document.getElementById('launchMusicRow');
const chosenSpan = document.getElementById('chosenMusicService');
const launchBtn = document.getElementById('launchMusicBtn');
const changeBtn = document.getElementById('changeMusicServiceBtn');
if(!optionsWrap || !launchRow) return;
const saved = localStorage.getItem('c25k_music_service');
if(saved){
chosenSpan.textContent = formatServiceName(saved);
launchRow.hidden = false;
optionsWrap.style.display='none';
}
optionsWrap.querySelectorAll('.musicServiceBtn').forEach(btn=>{
btn.onclick=()=>{
const service = btn.dataset.service;
localStorage.setItem('c25k_music_service', service);
chosenSpan.textContent = formatServiceName(service);
launchRow.hidden = false;
optionsWrap.style.display='none';
};
});
if(changeBtn){
changeBtn.onclick=()=>{
launchRow.hidden = true;
optionsWrap.style.display='flex';
};
}
if(launchBtn){
launchBtn.onclick=()=>{
const svc = localStorage.getItem('c25k_music_service');
if(!svc){ alert('Select a music service first.'); return; }
const url = buildServiceUrl(svc);
// Attempt open via protocol first for installed apps
const protocolUrl = buildProtocolUrl(svc);
let opened = false;
if(protocolUrl){
const a = document.createElement('a');
a.href=protocolUrl;
a.style.display='none';
document.body.appendChild(a);
a.click();
setTimeout(()=>{ if(!opened) window.open(url,'_blank'); a.remove(); }, 800);
} else {
window.open(url,'_blank');
}
};
}
}
function formatServiceName(key){
return key==='spotify'?'Spotify': key==='youtube'?'YouTube Music': key==='apple'?'Apple Music': key;
}
function buildServiceUrl(key){
switch(key){
case 'spotify': return 'https://open.spotify.com/search/running%20motivation';
case 'youtube': return 'https://music.youtube.com/search?q=running%20workout%20playlist';
case 'apple': return 'https://music.apple.com/us/search?term=running%20workout';
default: return 'https://google.com/search?q=running+workout+music';
}
}
function buildProtocolUrl(key){
switch(key){
case 'spotify': return 'spotify:search:running%20motivation';
case 'apple': return null; // Apple Music protocol varies by device
case 'youtube': return null; // YT Music protocol limited
default: return null;
}
}
// Focus trap utilities
let lastFocusElement = null; let focusTrapActive=false;
function trapFocus(container){
lastFocusElement = document.activeElement;
focusTrapActive=true;
function handleKey(e){
if(!focusTrapActive) return;
if(e.key==='Escape'){ closeSettings(); }
if(e.key==='Tab'){
const focusable = container.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
const list = Array.from(focusable).filter(el=>!el.disabled && el.offsetParent!==null);
if(!list.length) return;
const first=list[0]; const last=list[list.length-1];
if(e.shiftKey && document.activeElement===first){ e.preventDefault(); last.focus(); }
else if(!e.shiftKey && document.activeElement===last){ e.preventDefault(); first.focus(); }
}
}
container.addEventListener('keydown', handleKey);
}
function releaseFocus(){ focusTrapActive=false; if(lastFocusElement) lastFocusElement.focus(); }
});
// Inject fade animation styles if missing
(function injectFade(){
if(document.getElementById('fadeStyles')) return;
const style=document.createElement('style'); style.id='fadeStyles';
style.textContent='.fadeIn{animation:fadeIn .35s ease both}@keyframes fadeIn{0%{opacity:0;transform:translateY(6px)}100%{opacity:1;transform:translateY(0)}}';
document.head.appendChild(style);
})();
// PWA install & service worker
if('serviceWorker' in navigator){
window.addEventListener('load', ()=>{
navigator.serviceWorker.register('./sw.js').catch(()=>{});
});
}
let deferredPrompt=null;
window.addEventListener('beforeinstallprompt', (e)=>{
e.preventDefault();
deferredPrompt=e;
const btn=document.getElementById('installAppBtn');
if(btn){ btn.hidden=false; btn.onclick=async ()=>{ btn.disabled=true; try{ await deferredPrompt.prompt(); }catch{} finally{ btn.hidden=true; } }; }
});
// Render progress data
function renderProgress(){
const container = document.getElementById('progressContent');
if(!container) return;
let progress = JSON.parse(localStorage.getItem('c25k_progress')||'{}');
let totalWorkouts=0;
for(let w=1; w<=9; w++){
for(let d=1; d<=3; d++) if(progress[w] && progress[w][d]) totalWorkouts++;
}
const avgPace = parseFloat(localStorage.getItem('c25k_avg_pace')||'11'); // minutes per mile
// Estimate distance: assume avg 30 min early workouts scaling upward; use total seconds of completed intervals if we want precision
// Simplified: 1 workout time average ~ (25 + (weekIndex*3)) minutes
let estMinutes=0; let progressData = JSON.parse(localStorage.getItem('c25k_progress')||'{}');
for(let w=1; w<=9; w++){
for(let d=1; d<=3; d++) if(progressData[w] && progressData[w][d]) estMinutes += (25 + (w-1)*3);
}
const estMiles = (estMinutes/avgPace).toFixed(1);
const weight = parseFloat(localStorage.getItem('c25k_weight')||'170');
const unit = localStorage.getItem('c25k_weight_unit')||'lb';
const weightKg = unit==='kg'? weight : weight * 0.45359237;
// Rough calorie estimate: MET*weight(kg)*time(hr). Use MET 8 for running segments approximation.
// Convert estMinutes to hours.
const met = 8; const hours = estMinutes/60; const estCalories = Math.round(met * weightKg * hours);
let html = `<p><strong>Total Workouts:</strong> ${totalWorkouts}<br><strong>Est. Distance:</strong> ${estMiles} mi<br><strong>Est. Calories:</strong> ${estCalories} kcal<br><strong>Avg Pace Setting:</strong> ${avgPace} min/mi<br><strong>Weight:</strong> ${weight} ${unit}</p>`;
container.innerHTML = html;
const shareBtn = document.getElementById('shareProgressBtn');
if(shareBtn){
shareBtn.onclick = ()=>{
let shareText = `My Couch to 5K Progress: ${totalWorkouts} workouts, ${estMiles} miles, ${estCalories} kcal! #CouchTo5K`;
if(navigator.share){ navigator.share({text:shareText}); }
else { navigator.clipboard.writeText(shareText); alert('Progress copied to clipboard'); }
};
}
const shareImageBtn = document.getElementById('shareImageBtn');
if(shareImageBtn){
shareImageBtn.onclick=()=> generateShareImage(totalWorkouts, estMiles, estCalories, avgPace);
}
}
// Simple beep sound for interval transitions
function playBeep() {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
const tone = localStorage.getItem('c25k_beep_tone') || 'sine';
osc.type = tone;
osc.frequency.value = 880;
// Use settings volume
let vol = parseFloat(localStorage.getItem('c25k_sound_volume') || '0.2');
gain.gain.value = vol;
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + 0.18);
osc.onended = () => ctx.close();
} catch (e) {}
}
// Celebration sound for workout completion
function playCelebrate() {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = 'triangle';
osc.frequency.setValueAtTime(440, ctx.currentTime);
osc.frequency.linearRampToValueAtTime(1760, ctx.currentTime + 0.5);
let vol = parseFloat(localStorage.getItem('c25k_sound_volume') || '0.2');
gain.gain.value = vol;
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + 0.6);
osc.onended = () => ctx.close();
} catch (e) {}
}
// Draw circular progress bar
function drawProgress(canvas, percent, timeLeft, intervalType) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 60;
// Background circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#e0e0e0';
ctx.lineWidth = 10;
ctx.stroke();
// Progress arc with color transition
const startColor = [33, 150, 243]; // blue
const endColor = [67, 233, 123]; // green
const r = Math.round(startColor[0] + (endColor[0] - startColor[0]) * percent);
const g = Math.round(startColor[1] + (endColor[1] - startColor[1]) * percent);
const b = Math.round(startColor[2] + (endColor[2] - startColor[2]) * percent);
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -0.5 * Math.PI, (2 * Math.PI * percent) - 0.5 * Math.PI);
ctx.strokeStyle = `rgb(${r},${g},${b})`;
ctx.lineWidth = 10;
ctx.stroke();
// Inner circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius - 18, 0, 2 * Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
// Timer text
ctx.font = 'bold 2em Segoe UI, Arial';
ctx.fillStyle = '#2196f3';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(timeLeft > 0 ? timeLeft : '', centerX, centerY - 10);
// Interval type text
ctx.font = '1em Segoe UI, Arial';
ctx.fillStyle = '#43e97b';
ctx.fillText(intervalType, centerX, centerY + 22);
}
function doHaptics(kind){
const enhanced = localStorage.getItem('c25k_enhanced_haptics')==='1';
if(!navigator.vibrate) return;
if(!enhanced){
if(kind==='complete') vibrate([200,100,200]); else vibrate(200);
return;
}
switch(kind){
case 'start': vibrate([80,40,80]); break;
case 'transition': vibrate([60,30,60]); break;
case 'complete': vibrate([120,60,120,60,200]); break;
default: vibrate(150);
}
}
// Hydration reminder loop (every 7 minutes during workout if enabled)
let hydrationIntervalRef=null;
function startHydrationReminders(){
if(localStorage.getItem('c25k_hydration')!=='1') return;
clearInterval(hydrationIntervalRef);
hydrationIntervalRef = setInterval(()=>{
speakCue('Hydrate if needed'); doHaptics('transition');
}, 7*60*1000);
}
function stopHydrationReminders(){ clearInterval(hydrationIntervalRef); }
// Enhance beginIntervals to start/stop hydration reminders
(function patchHydration(){
const originalBegin = beginIntervals;
beginIntervals = function(intervals, week, day, ctxRefs){
startHydrationReminders();
originalBegin(intervals, week, day, ctxRefs);
// monkey patch cleanup to also stop hydration when workout complete; we wrap cleanup by observing haptics complete (markWorkoutComplete already called)
const stopFn = stopHydrationReminders; // captured
const observer = new MutationObserver(()=>{
const cue=document.getElementById('intervalCue');
if(cue && cue.textContent.includes('Complete')){ stopFn(); observer.disconnect(); }
});
observer.observe(document.body,{subtree:true,childList:true,characterData:true});
};
})();
// Generate shareable image (canvas) with stats
function generateShareImage(totalWorkouts, estMiles, estCalories, avgPace){
try {
const w=800, h=420; const cvs=document.createElement('canvas'); cvs.width=w; cvs.height=h; const ctx=cvs.getContext('2d');
ctx.fillStyle='#111'; ctx.fillRect(0,0,w,h);
const grad=ctx.createLinearGradient(0,0,w,h); grad.addColorStop(0,'#1d4ed8'); grad.addColorStop(1,'#0f172a'); ctx.fillStyle=grad; ctx.fillRect(0,0,w,h);
ctx.fillStyle='#fff'; ctx.font='700 42px Inter, Segoe UI, Arial'; ctx.fillText('Couch to 5K Progress',40,70);
ctx.font='400 22px Inter, Segoe UI, Arial';
const lines=[`Workouts: ${totalWorkouts}`,`Distance: ${estMiles} mi`,`Calories: ${estCalories} kcal`,`Avg Pace: ${avgPace} min/mi`];
lines.forEach((l,i)=> ctx.fillText(l,40,140+i*40));
ctx.font='600 18px Inter, Segoe UI, Arial'; ctx.fillStyle='#93c5fd'; ctx.fillText('Keep pushing toward your 5K! #CouchTo5K',40,h-50);
cvs.toBlob(blob=>{
if(!blob) return;
const file = new File([blob],'c25k-progress.png',{type:'image/png'});
if(navigator.canShare && navigator.canShare({files:[file]})){
navigator.share({files:[file], text:'My Couch to 5K progress!', title:'Couch to 5K'}).catch(()=>{});
} else {
const url = URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download='c25k-progress.png'; a.click(); URL.revokeObjectURL(url);
}
},'image/png');
} catch(e){ alert('Unable to create share image'); }
}
// Map interval type to CSS class
function intervalTypeClass(type){
if(type==='Run') return 'type-Run';
if(type==='Walk') return 'type-Walk';
if(type==='Warmup Walk') return 'type-warmup';
if(type==='Cooldown Walk') return 'type-cooldown';
return '';
}
// formatTime now defined earlier