-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1612 lines (1426 loc) · 72.7 KB
/
index.html
File metadata and controls
1612 lines (1426 loc) · 72.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Driver Training Portal</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary: #2563eb;
--primary-dark: #1d4ed8;
--success: #16a34a;
--danger: #dc2626;
--warning: #d97706;
--muted: #64748b;
--light: #f8fafc;
--dark: #0f172a;
--border: #e2e8f0;
--shadow-sm: 0 1px 2px 0 rgba(0,0,0,0.05);
--shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1),0 2px 4px -1px rgba(0,0,0,0.06);
--shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1),0 4px 6px -2px rgba(0,0,0,0.05);
--radius-sm: 0.375rem;
--radius-md: 0.5rem;
--radius-lg: 0.75rem;
--radius-full: 9999px;
--transition: all 0.2s ease;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%; width: 100%;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
font-size: 16px; line-height: 1.5; color: var(--dark);
background-color: #f1f5f9;
background-image: url('trucks.jpg');
background-size: cover; background-position: center; background-attachment: fixed;
}
body::before { content: ""; position: fixed; inset: 0; background: rgba(255,255,255,0.92); z-index: -1; }
#app { min-height: 100%; display: flex; flex-direction: column; }
.container { width: 100%; max-width: 1200px; margin: 0 auto; padding: 1rem; }
/* Sections */
.section { display: none; flex: 1; padding: 1.5rem 0; }
.section.active { display: block; animation: fadeIn 0.3s ease; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
/* Cards */
.card { background: white; border-radius: var(--radius-md); box-shadow: var(--shadow-sm); overflow: hidden; transition: var(--transition); }
.card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.card-header { padding: 1rem 1.25rem; border-bottom: 1px solid var(--border); }
.card-body { padding: 1.25rem; }
.card-footer { padding: 1rem 1.25rem; border-top: 1px solid var(--border); }
/* Typography */
h1, h2, h3, h4 { font-weight: 600; line-height: 1.25; margin-bottom: 0.75rem; }
h1 { font-size: 2rem; } h2 { font-size: 1.5rem; } h3 { font-size: 1.25rem; } h4 { font-size: 1rem; }
.text-muted { color: var(--muted); }
.text-sm { font-size: 0.875rem; }
.text-center { text-align: center; }
/* Buttons */
.btn { display: inline-flex; align-items: center; justify-content: center; padding: 0.5rem 1rem; font-size: 0.875rem; font-weight: 500; line-height: 1.5; border-radius: var(--radius-sm); border: 1px solid transparent; cursor: pointer; transition: var(--transition); user-select: none; text-decoration: none; white-space: nowrap; }
.btn:disabled { opacity: 0.6; cursor: not-allowed; }
.btn-sm { padding: 0.375rem 0.75rem; font-size: 0.8125rem; }
.btn-lg { padding: 0.75rem 1.5rem; font-size: 1rem; }
.btn-block { display: flex; width: 100%; }
.btn-primary { background-color: var(--primary); color: white; }
.btn-primary:hover { background-color: var(--primary-dark); }
.btn-success { background-color: var(--success); color: white; }
.btn-success:hover { background-color: #15803d; }
.btn-danger { background-color: var(--danger); color: white; }
.btn-danger:hover { background-color: #b91c1c; }
.btn-muted { background-color: var(--muted); color: white; }
.btn-muted:hover { background-color: #475569; }
.btn-outline { background-color: transparent; border-color: var(--border); color: var(--dark); }
.btn-outline:hover { background-color: #f8fafc; }
/* Forms */
.form-group { margin-bottom: 1rem; }
.form-label { display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.875rem; }
.form-control { display: block; width: 100%; padding: 0.5rem 0.75rem; font-size: 0.875rem; line-height: 1.5; color: var(--dark); background-color: white; border: 1px solid var(--border); border-radius: var(--radius-sm); transition: border-color 0.15s ease; }
.form-control:focus { outline: 0; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
select.form-control { appearance: none; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e"); background-position: right 0.5rem center; background-repeat: no-repeat; background-size: 1.5em 1.5em; padding-right: 2.5rem; }
/* Badges */
.badge { display: inline-flex; align-items: center; padding: 0.25rem 0.5rem; font-size: 0.75rem; font-weight: 500; line-height: 1; border-radius: var(--radius-full); background-color: #e2e8f0; color: #334155; }
.badge-primary { background-color: #dbeafe; color: #1e40af; }
.badge-success { background-color: #dcfce7; color: #166534; }
.badge-warning { background-color: #fef3c7; color: #92400e; }
.badge-danger { background-color: #fee2e2; color: #991b1b; }
/* Alerts */
.alert { padding: 1rem; border-radius: var(--radius-sm); margin-bottom: 1rem; }
.alert-info { background-color: #dbeafe; color: #1e40af; }
.alert-success { background-color: #dcfce7; color: #166534; }
.alert-warning { background-color: #fef3c7; color: #92400e; }
.alert-danger { background-color: #fee2e2; color: #991b1b; }
/* Layout Utilities */
.flex { display: flex; }
.flex-col { flex-direction: column; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.gap-1 { gap: 0.25rem; } .gap-2 { gap: 0.5rem; } .gap-3 { gap: 1rem; } .gap-4 { gap: 1.5rem; } .gap-5 { gap: 2rem; }
.mt-1 { margin-top: 0.25rem; } .mt-2 { margin-top: 0.5rem; } .mt-3 { margin-top: 1rem; } .mt-4 { margin-top: 1.5rem; } .mt-5 { margin-top: 2rem; }
.mb-1 { margin-bottom: 0.25rem; } .mb-2 { margin-bottom: 0.5rem; } .mb-3 { margin-bottom: 1rem; } .mb-4 { margin-bottom: 1.5rem; } .mb-5 { margin-bottom: 2rem; }
/* Dashboard Specific */
.dashboard-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1rem; }
.driver-badge { display: inline-flex; align-items: center; padding: 0.5rem 1rem; background-color: var(--dark); color: white; border-radius: var(--radius-full); font-weight: 500; font-size: 0.875rem; box-shadow: var(--shadow-sm); }
.tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; overflow-x: auto; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
.tab { padding: 0.5rem 1rem; border-radius: var(--radius-full); background-color: #e2e8f0; color: #334155; font-weight: 500; font-size: 0.875rem; cursor: pointer; transition: var(--transition); white-space: nowrap; }
.tab.active { background-color: var(--dark); color: white; }
.tabpanel { display: none; } .tabpanel.active { display: block; animation: fadeIn 0.3s ease; }
.video-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1rem; }
@media (max-width: 768px) { .video-grid { grid-template-columns: 1fr; } }
/* Video Player */
.video-player-container { width: 100%; max-width: 800px; margin: 0 auto; }
.video-player { width: 100%; aspect-ratio: 16/9; background-color: black; border-radius: var(--radius-md); overflow: hidden; }
.video-player iframe, .video-player video { width: 100%; height: 100%; border: none; }
/* Completion Section */
.completion-section { position: fixed; bottom: 1.5rem; left: 50%; transform: translateX(-50%); background: white; padding: 1rem 1.5rem; border-radius: var(--radius-md); box-shadow: var(--shadow-lg); z-index: 10; display: none; max-width: 90%; width: 400px; }
/* Toast */
.toast { position: fixed; top: 1rem; left: 50%; transform: translateX(-50%); background-color: var(--dark); color: white; padding: 0.75rem 1.25rem; border-radius: var(--radius-md); box-shadow: var(--shadow-lg); z-index: 50; display: none; max-width: 90%; width: 350px; text-align: center; }
/* Loading Spinner */
.spinner { display: inline-block; width: 1.5rem; height: 1.5rem; border: 3px solid rgba(255,255,255,0.3); border-radius: 50%; border-top-color: white; animation: spin 1s ease-in-out infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
/* Local Only Badge */
.local-only { background-color: #ffedd5; color: #9a3412; border: 1px solid #fed7aa; padding: 0.125rem 0.5rem; border-radius: var(--radius-full); font-size: 0.75rem; margin-left: 0.5rem; }
/* Responsive Adjustments */
@media (max-width: 640px) {
body::before { background: rgba(255,255,255,0.96); }
.section { padding: 1rem 0; }
.dashboard-header { flex-direction: column; align-items: flex-start; }
.completion-section { width: calc(100% - 2rem); }
}
/* Paper-like background for empty states */
#lobbyEmpty, #historyEmpty {
display: inline-block; background-color: rgba(255, 255, 255, 0.9);
padding: 0.75rem 1rem; border-radius: var(--radius-md); box-shadow: var(--shadow-sm);
color: var(--dark); border: 1px solid var(--border);
}
</style>
</head>
<body>
<div id="app">
<!-- Language Selection -->
<section id="languageSection" class="section active">
<div class="container">
<div class="card" style="max-width: 480px; margin: 0 auto;">
<div class="card-header text-center">
<h2 id="langTitle">Select Language</h2>
</div>
<div class="card-body">
<div class="form-group">
<select id="languageSelect" class="form-control" required></select>
</div>
<button id="continueBtn" class="btn btn-primary btn-block">Continue</button>
<button id="adminLoginBtn" class="btn btn-outline btn-block mt-3">Admin Login</button>
</div>
</div>
</div>
</section>
<!-- Driver Check-In -->
<section id="checkinForm" class="section">
<div class="container">
<div class="card" style="max-width: 480px; margin: 0 auto;">
<div class="card-header text-center">
<h2 id="formTitle">Driver Check-In</h2>
</div>
<div class="card-body">
<div class="form-group">
<input type="text" id="name" list="driverNames" class="form-control" placeholder="Full Name" required />
<datalist id="driverNames"></datalist>
</div>
<div class="form-group">
<input type="text" id="truck" class="form-control" placeholder="Truck Number" required />
</div>
<div class="flex gap-2">
<button id="backBtn" class="btn btn-danger flex-1">Back</button>
<button id="submitBtn" class="btn btn-primary flex-2">Continue to Dashboard</button>
</div>
</div>
</div>
</div>
</section>
<!-- Training Dashboard -->
<section id="dashboardSection" class="section">
<div class="container">
<div class="dashboard-header">
<h2 id="dashTitle">Training Dashboard</h2>
<div class="flex items-center gap-3">
<div id="driverBadge" class="driver-badge">—</div>
<button id="adminPanelBtn" class="btn btn-muted" style="display: none;">Admin Panel</button>
</div>
</div>
<div class="tabs">
<div class="tab active" data-tab="lobby" id="tabLobby">Lobby (Assigned)</div>
<div class="tab" data-tab="history" id="tabHistory">History (Completed)</div>
<button id="sortBtn" class="btn btn-muted">Sort: Recent</button>
<div style="flex: 1;"></div>
<button id="syncBtn" class="btn btn-muted">Sync Pending</button>
<button id="changeDriverBtn" class="btn btn-danger">Change Driver</button>
</div>
<div id="lobby" class="tabpanel active">
<div id="lobbyList" class="video-grid"></div>
<p id="lobbyEmpty" class="text-center text-muted mt-4" style="display: none;">No pending trainings. Great job!</p>
</div>
<div id="history" class="tabpanel">
<div id="historyList" class="video-grid"></div>
<p id="historyEmpty" class="text-center text-muted mt-4" style="display: none;">No completed trainings yet.</p>
</div>
</div>
</section>
<!-- Video Player -->
<section id="videoSection" class="section">
<div class="container">
<div class="flex justify-between items-center mb-4">
<button id="closeBtn" class="btn btn-danger">Cancel</button>
<h3 id="activeVideoTitle" class="text-center"></h3>
</div>
<div id="videoNote" class="alert alert-info" style="display: none;"></div>
<div class="video-player-container">
<div id="videoContainer" class="video-player"></div>
</div>
</div>
</section>
<!-- Completion Section -->
<div id="completionSection" class="completion-section">
<button id="completeBtn" class="btn btn-success btn-block">Mark Complete</button>
</div>
<!-- Admin Login -->
<section id="adminLoginSection" class="section">
<div class="container">
<div class="card" style="max-width: 480px; margin: 0 auto;">
<div class="card-header text-center">
<h2>Admin Login</h2>
</div>
<div class="card-body">
<div class="form-group">
<input type="email" id="adminEmail" class="form-control" placeholder="Corporate Email" />
</div>
<div class="form-group">
<input type="password" id="adminPassword" class="form-control" placeholder="Password" />
</div>
<div class="form-group">
<input type="password" id="adminCode" class="form-control" placeholder="Access Code" />
</div>
<p class="text-sm text-muted text-center">Use corporate email + password, or access code</p>
<div class="flex gap-2 mt-4">
<button id="adminBackBtn" class="btn btn-danger flex-1">Back</button>
<button id="adminSubmitBtn" class="btn btn-primary flex-2">Login</button>
</div>
</div>
</div>
</div>
</section>
<!-- Admin Panel -->
<section id="adminPanelSection" class="section">
<div class="container">
<div class="card">
<div class="card-header">
<h2 class="text-center">Training Admin Panel</h2>
</div>
<div class="card-body">
<div class="flex flex-col gap-4">
<div class="card">
<div class="card-header">
<h3>Add New Training</h3>
</div>
<div class="card-body">
<div class="flex gap-3 flex-wrap">
<div class="form-group flex-1" style="min-width: 200px;">
<label for="adminLangSelect" class="form-label">Language</label>
<select id="adminLangSelect" class="form-control" required>
<option value="">Select Language</option>
</select>
</div>
<div class="form-group flex-1" style="min-width: 200px;">
<label for="newLangName" class="form-label">New Language</label>
<div class="flex gap-2">
<input type="text" id="newLangName" class="form-control" placeholder="Language Name" />
<button id="addLangBtn" class="btn btn-muted">Add</button>
</div>
</div>
</div>
<div class="form-group mt-3">
<label for="videoTitle" class="form-label">Title</label>
<input type="text" id="videoTitle" class="form-control" placeholder="Training Title" required />
</div>
<div class="flex gap-3 flex-wrap">
<div class="form-group flex-1" style="min-width: 200px;">
<label for="videoType" class="form-label">Video Type</label>
<select id="videoType" class="form-control" required>
<option value="">Select Type</option>
<option value="youtube">YouTube</option>
<option value="drive">Google Drive</option>
<option value="mp4">MP4 URL</option>
<option value="local">Upload Video</option>
</select>
</div>
<div class="form-group flex-1" style="min-width: 200px;">
<label id="videoSourceLabel" for="videoId" class="form-label">YouTube ID/URL</label>
<input type="text" id="videoId" class="form-control" placeholder="YouTube ID or URL" />
<input type="file" id="videoFile" class="form-control mt-2" accept="video/*" style="display: none;" />
</div>
</div>
<div class="form-group mt-3">
<label for="videoNoteAdmin" class="form-label">Notes (Optional)</label>
<textarea id="videoNoteAdmin" class="form-control" rows="2" placeholder="Additional information for drivers"></textarea>
</div>
<button id="saveVideoBtn" class="btn btn-primary btn-block mt-4">Save Training</button>
</div>
</div>
<div class="card">
<div class="card-header">
<h3>Manage Trainings</h3>
</div>
<div class="card-body">
<div id="adminVideoItems" class="flex flex-col gap-3"></div>
</div>
</div>
</div>
</div>
<div class="card-footer text-center">
<button id="adminLogoutBtn" class="btn btn-danger">Logout</button>
</div>
</div>
</div>
</section>
</div>
<!-- Toast Notification -->
<div id="toast" class="toast"></div>
<!-- Light query helpers -->
<script>
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
</script>
<!-- YouTube API -->
<script src="https://www.youtube.com/iframe_api"></script>
<script>
// ======= CONFIGURATION =======
const CONFIG = {
BASE_URL: 'https://script.google.com/macros/s/AKfycbyKO9F0m-VP89q2RTMpLgkKWMuUoKOR8HqReocgIrdqe7ZM1tyisLqhNDSnujdXHGyfYA/exec',
MIN_WATCH_SECONDS: 40,
REVEAL_BEFORE_END: 10,
ALLOW_SEEK_TOLERANCE: 1.25,
// Admin authentication
ADMIN_EMAIL_SUFFIX: '@alistairgroup.com',
ADMIN_ACCESS_CODE: 'AG-TRAINING-2025',
ADMIN_CREDENTIALS: {
'admin@alistairgroup.com': 'admin123',
'training@alistairgroup.com': 'training123'
},
// Logging policy
LOG_SESSION_START: false,
LOG_COURSE_STARTED: true,
// Local storage keys
STORAGE_KEYS: {
PENDING_EVENTS: 'driver_training_pending_events_v2',
LANGUAGE: 'driver_training_lang_v1',
SORT_PREFERENCE: 'driver_training_lobby_sort_v1',
CUSTOM_LANGS: 'driver_training_custom_langs_v1',
DRIVER_STATE: 'driver_training_driverstate_',
ADMIN_AUTH: 'driver_training_admin_auth_v1'
},
// IndexedDB for local videos
DB_NAME: 'driver_training_db',
DB_STORE: 'videos'
};
/* ======= DEMO PURGE DEFINITIONS (removes old sample trainings) ======= */
const DEMO_IDS = new Set(['eng-001','swa-002','bem-003','por-004']);
const DEMO_TITLES = new Set([
'Driver Tiredness, Fatigue and Road Safety',
'Kampeni ya Usalama kwa Madereva',
'Kampeni ya Ukusalama kwa Abapashi',
'Campanha de Segurança para Motoristas'
]);
const DEMO_PURGE_FLAG = 'driver_training_demo_purged_v1';
/* ==================================================================== */
// ====== TRANSLATIONS ======
const TRANSLATIONS = {
English: {
code: 'en', dir: 'ltr',
langTitle: 'Select Language',
choose: '-- Choose a Language --',
pageTitle: 'Driver Training Portal',
continue: 'Continue', back: 'Back', cancel: 'Cancel Video',
formTitle: 'Driver Check-In', name: 'Full Name', truck: 'Truck Number',
submit: 'Continue to Dashboard', complete: 'Training Completed!',
dash: 'Training Dashboard', lobby: 'Lobby (Assigned)', history: 'History (Completed)',
sync: 'Sync Pending', change: 'Change Driver', play: 'Start Training',
status: 'Status', assigned: 'Assigned', duration: 'Duration',
noPending: 'No pending trainings. Great job!', noHistory: 'No completed trainings yet.',
loadingVideo: 'Preparing training...', adminLogin: 'Admin Login',
sort: 'Sort', recent: 'Recent', oldest: 'Oldest', alertSelectLang: 'Please select a language.',
alertFillAll: 'Please fill in all fields.', localOnly: 'Local Only'
},
Swahili: {
code: 'sw', dir: 'ltr',
langTitle: 'Chagua Lugha',
choose: '-- Chagua Lugha --',
pageTitle: 'Kuingia kwa Dereva',
continue: 'Endelea', back: 'Rudi', cancel: 'Sitisha Video',
formTitle: 'Kuingia kwa Dereva', name: 'Jina Kamili', truck: 'Namba ya Gari',
submit: 'Nenda kwenye Dashibodi', complete: 'Mafunzo yamekamilika!',
dash: 'Dashibodi ya Mafunzo', lobby: 'Ukumbi (Zilizokabidhiwa)', history: 'Historia (Zilizokamilika)',
sync: 'Sawazisha', change: 'Badilisha Dereva', play: 'Anza Mafunzo',
status: 'Hali', assigned: 'Iliyokabidhiwa', duration: 'Muda',
noPending: 'Hakuna mafunzo yanayosubiri. Kazi nzuri!', noHistory: 'Bado hakuna mafunzo yaliyokamilika.',
loadingVideo: 'Inapakia mafunzo...', adminLogin: 'Ingia kwa Admin',
sort: 'Panga', recent: 'Za Hivi Karibuni', oldest: 'Za Zamani',
alertSelectLang: 'Tafadhali chagua lugha.', alertFillAll: 'Tafadhali jaza sehemu zote.',
localOnly: 'Ya Ndani Tu'
},
Bemba: {
code: 'bem', dir: 'ltr',
langTitle: 'Sankeni Ululimi', choose: '-- Sankeni Ululimi --',
pageTitle: 'Ifyebo fya Kwingilila', continue: 'Tendekela', back: 'Baya', cancel: 'Fumya Video',
formTitle: 'Ifyebo fya Kwingilila', name: 'Amashina Yonse', truck: 'Namba ya Motoka',
submit: 'Ya ku Dashboard', complete: 'Ifyakusambilila fyapwa!',
dash: 'Dashboard ya Ifyakusambilila', lobby: 'Lobby (Ifyasalwike)', history: 'Historia (Fyapwa)',
sync: 'Sync', change: 'Chinja Umupashi', play: 'Anza Ifyakusambilila',
status: 'Inshita', assigned: 'Lyasangwa', duration: 'Ubushiku',
noPending: 'Tapali ifyasangwa. Umucinshi!', noHistory: 'Tachapwa nangu kamo pano.',
loadingVideo: 'Ukupakila ifyakusambilila...', adminLogin: 'Admin Login',
sort: 'Teekanya', recent: 'Ifyapya', oldest: 'Ifyakale',
alertSelectLang: 'Sankeni ululimi.', alertFillAll: 'Sambilileni ifyose.',
localOnly: 'Ya Konse Konse'
},
Portuguese: {
code: 'pt', dir: 'ltr',
langTitle: 'Selecione o Idioma', choose: '-- Selecione o Idioma --',
pageTitle: 'Portal de Treinamento', continue: 'Continuar', back: 'Voltar', cancel: 'Cancelar Vídeo',
formTitle: 'Registro do Motorista', name: 'Nome Completo', truck: 'Número do Caminhão',
submit: 'Ir para o Painel', complete: 'Treinamento Concluído!',
dash: 'Painel de Treinamentos', lobby: 'Lobby (Atribuídos)', history: 'Histórico (Concluídos)',
sync: 'Sincronizar', change: 'Trocar Motorista', play: 'Iniciar Treinamento',
status: 'Estado', assigned: 'Atribuído', duration: 'Duração',
noPending: 'Sem treinamentos pendentes. Bom trabalho!', noHistory: 'Ainda não há treinamentos concluídos.',
loadingVideo: 'Preparando treinamento...', adminLogin: 'Login do Administrador',
sort: 'Ordenar', recent: 'Mais recentes', oldest: 'Mais antigas',
alertSelectLang: 'Selecione um idioma.', alertFillAll: 'Preencha todos os campos.',
localOnly: 'Apenas Local'
}
};
// ====== CORE FUNCTIONALITY ======
class DriverTrainingApp {
constructor() {
// State
this.selectedLang = localStorage.getItem(CONFIG.STORAGE_KEYS.LANGUAGE) || 'English';
this.lobbySort = localStorage.getItem(CONFIG.STORAGE_KEYS.SORT_PREFERENCE) || 'recent';
this.driver = { name: '', truck: '' };
this.driverList = [];
this.assignments = [];
this.currentAssignment = null;
this.isAdminViewing = false;
// Video state
this.ytPlayer = null;
this.progressPoll = null;
this.maxAllowedTime = 0;
this.watchedSeconds = 0;
this.minReached = false;
this.startTime = null;
this.rowId = '';
this.currentObjectUrl = '';
// Init
this.initDOM();
this.initEventListeners();
this.applyTranslations(this.selectedLang);
this.loadDrivers();
this.showAdminPanel(this.isAdminLoggedIn());
/* One-time purge of legacy demo trainings */
if (!localStorage.getItem(DEMO_PURGE_FLAG)) {
this.purgeDemoVideos();
localStorage.setItem(DEMO_PURGE_FLAG, '1');
}
this.renderAdminVideoList();
// Auto-sync when back online
window.addEventListener('online', () => this.flushPendingEvents());
}
/* ===== Purge demo trainings from local storage & in-memory ===== */
purgeDemoVideos() {
const custom = this.loadCustomLangs();
let changed = false;
Object.entries(custom).forEach(([lang, data]) => {
const list = Array.isArray(data?.videos) ? data.videos : [];
const filtered = list.filter(v => {
const id = (v?.id || '').trim();
const title = (v?.title || '').trim();
return !DEMO_IDS.has(id) && !DEMO_TITLES.has(title);
});
if (filtered.length !== list.length) {
custom[lang].videos = filtered;
changed = true;
}
});
if (changed) this.saveCustomLangs(custom);
if (Array.isArray(this.assignments) && this.assignments.length) {
this.assignments = this.assignments.filter(a => {
const id = (a?.id || '').trim();
const title = (a?.title || '').trim();
return !DEMO_IDS.has(id) && !DEMO_TITLES.has(title);
});
}
}
// ====== DOM INITIALIZATION ======
initDOM() {
this.populateLanguageSelect();
this.populateAdminLangSelect();
}
// ====== EVENT LISTENERS ======
initEventListeners() {
// Language selection
$('#languageSelect').addEventListener('change', () => {
this.selectedLang = $('#languageSelect').value || 'English';
localStorage.setItem(CONFIG.STORAGE_KEYS.LANGUAGE, this.selectedLang);
this.applyTranslations(this.selectedLang);
if (this.assignments.length) this.renderDashboard(this.assignments);
});
// Continue to check-in
$('#continueBtn').addEventListener('click', () => {
if (!$('#languageSelect').value) {
const t = this.getTranslations()[this.selectedLang] || TRANSLATIONS.English;
this.showToast(t.alertSelectLang || 'Please select a language.');
return;
}
this.selectedLang = $('#languageSelect').value;
localStorage.setItem(CONFIG.STORAGE_KEYS.LANGUAGE, this.selectedLang);
this.applyTranslations(this.selectedLang);
$('#languageSection').classList.remove('active');
$('#checkinForm').classList.add('active');
});
// Back from check-in
$('#backBtn').addEventListener('click', () => {
$('#name').value = '';
$('#truck').value = '';
$('#languageSelect').value = this.selectedLang;
this.applyTranslations(this.selectedLang);
$('#checkinForm').classList.remove('active');
$('#languageSection').classList.add('active');
});
// Check-in submit
$('#submitBtn').addEventListener('click', async (e) => {
e.preventDefault();
const t = this.getTranslations()[this.selectedLang] || TRANSLATIONS.English;
if (!$('#name').value.trim() || !$('#truck').value.trim()) {
this.showToast(t.alertFillAll || 'Please fill in all fields.');
return;
}
$('#submitBtn').disabled = true;
this.driver = {
name: $('#name').value.trim(),
truck: $('#truck').value.trim()
};
const driverState = this.loadDriverState();
driverState.lang = this.selectedLang;
this.saveDriverState(driverState);
$('#driverBadge').textContent = `${this.driver.name} • ${this.driver.truck}`;
this.applyTranslations(this.selectedLang);
$('#checkinForm').classList.remove('active');
$('#dashboardSection').classList.add('active');
await this.loadDriverData();
$('#submitBtn').disabled = false;
});
// Name autocomplete
$('#name').addEventListener('input', () => {
const match = this.driverList.find(d =>
d.name.toLowerCase() === $('#name').value.toLowerCase()
);
$('#truck').value = match ? match.truck : '';
});
// Tabs
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => this.setActiveTab(tab.dataset.tab));
});
// Sort
$('#sortBtn').addEventListener('click', () => {
this.lobbySort = this.lobbySort === 'recent' ? 'oldest' : 'recent';
localStorage.setItem(CONFIG.STORAGE_KEYS.SORT_PREFERENCE, this.lobbySort);
this.applyTranslations(this.selectedLang);
this.renderDashboard(this.assignments);
});
// Change driver
$('#changeDriverBtn').addEventListener('click', () => {
$('#dashboardSection').classList.remove('active');
$('#checkinForm').classList.add('active');
this.applyTranslations(this.selectedLang);
});
// Sync
$('#syncBtn').addEventListener('click', () => this.flushPendingEvents());
// Video close
$('#closeBtn').addEventListener('click', () => this.closeVideoPlayer());
// Completion
document.addEventListener('click', (e) => {
if (e.target && e.target.id === 'completeBtn') this.submitCompletion();
});
// Admin login nav
$('#adminLoginBtn').addEventListener('click', () => {
$('#languageSection').classList.remove('active');
$('#adminLoginSection').classList.add('active');
});
$('#adminBackBtn').addEventListener('click', () => {
$('#adminLoginSection').classList.remove('active');
$('#languageSection').classList.add('active');
});
// Admin login
$('#adminSubmitBtn').addEventListener('click', () => {
const email = $('#adminEmail').value.trim().toLowerCase();
const password = $('#adminPassword').value.trim();
const code = $('#adminCode').value.trim();
const codeOK = code && code === CONFIG.ADMIN_ACCESS_CODE;
const corpOK = email.endsWith(CONFIG.ADMIN_EMAIL_SUFFIX);
const mapOK = CONFIG.ADMIN_CREDENTIALS[email] && CONFIG.ADMIN_CREDENTIALS[email] === password;
const allow = codeOK || (corpOK && mapOK);
if (!allow) {
this.showToast('Invalid admin credentials');
return;
}
this.setAdminLoggedIn(true);
$('#adminEmail').value = '';
$('#adminPassword').value = '';
$('#adminCode').value = '';
$('#adminLoginSection').classList.remove('active');
$('#adminPanelSection').classList.add('active');
this.showAdminPanel(true);
});
// Admin nav button
$('#adminPanelBtn').addEventListener('click', () => {
$('#dashboardSection').classList.remove('active');
$('#adminPanelSection').classList.add('active');
});
// Admin logout
$('#adminLogoutBtn').addEventListener('click', () => {
this.setAdminLoggedIn(false);
$('#adminPanelSection').classList.remove('active');
$('#languageSection').classList.add('active');
this.showAdminPanel(false);
});
// Admin: add language
$('#addLangBtn').addEventListener('click', () => {
const langName = $('#newLangName').value.trim();
if (!langName) { this.showToast('Please enter a language name'); return; }
const custom = this.loadCustomLangs();
if (custom[langName]) { this.showToast('This language already exists'); return; }
custom[langName] = { translations: {}, videos: [] };
this.saveCustomLangs(custom);
this.populateLanguageSelect();
this.populateAdminLangSelect();
$('#newLangName').value = '';
this.showToast(`Language "${langName}" added`);
});
// Admin: video type switch
$('#videoType').addEventListener('change', () => {
const type = $('#videoType').value;
$('#videoId').style.display = type === 'local' ? 'none' : 'block';
$('#videoFile').style.display = type === 'local' ? 'block' : 'none';
const label = $('#videoSourceLabel');
if (type === 'youtube') label.textContent = 'YouTube ID/URL';
else if (type === 'drive') label.textContent = 'Google Drive URL';
else if (type === 'mp4') label.textContent = 'MP4 URL';
else label.textContent = 'Video File';
});
// Admin: save video
$('#saveVideoBtn').addEventListener('click', async () => {
const lang = $('#adminLangSelect').value;
const title = $('#videoTitle').value.trim();
const type = $('#videoType').value;
const note = $('#videoNoteAdmin').value.trim();
if (!lang || !title || !type) {
this.showToast('Please fill all required fields');
return;
}
let videoData = { id: this.generateId(), title, type, note };
try {
if (type === 'youtube') {
const idOrUrl = $('#videoId').value.trim();
const videoId = this.parseYouTubeId(idOrUrl);
if (!videoId) { this.showToast('Invalid YouTube ID or URL'); return; }
videoData.videoId = videoId;
} else if (type === 'drive') {
const url = $('#videoId').value.trim();
const driveId = this.extractDriveFileId(url);
if (!driveId) { this.showToast('Invalid Google Drive link'); return; }
videoData.driveId = driveId;
} else if (type === 'mp4') {
const url = $('#videoId').value.trim();
if (!/^https?:\/\//i.test(url)) { this.showToast('Enter a valid MP4 URL'); return; }
videoData.url = url;
} else if (type === 'local') {
const file = $('#videoFile').files?.[0];
if (!file) { this.showToast('Choose a video file'); return; }
const localKey = videoData.id;
try { await this.idbPut(localKey, file); videoData.localKey = localKey; }
catch (e) { console.error('Failed to store video:', e); this.showToast('Failed to store video file'); return; }
}
// Save locally
const vmap = this.getVideoLinks();
const list = (vmap[lang] || []).filter(v => v.id !== videoData.id).concat(videoData);
this.setVideoLinksForLang(lang, list);
// Try sync to server (skip local)
if (type !== 'local') {
try { await this.postAdminVideo({ language: lang, ...videoData }); } catch (e) { /* offline ok */ }
}
// Reset form
$('#videoTitle').value = ''; $('#videoType').value = '';
$('#videoId').value = ''; $('#videoFile').value = ''; $('#videoFile').style.display = 'none';
$('#videoNoteAdmin').value = '';
// Refresh lists
this.renderAdminVideoList();
if (this.assignments) {
const assignment = {
id: videoData.id, title, language: lang, source: videoData, status: 'assigned',
assignedAt: new Date().toISOString().slice(0, 10), isAdminAdded: true
};
this.assignments.push(assignment);
this.renderDashboard(this.assignments);
}
this.showToast('Training saved successfully');
} catch (error) {
console.error('Error saving video:', error);
this.showToast('Error saving training');
}
});
}
// ====== CORE METHODS ======
async loadDriverData() {
let assignments = [];
let history = [];
$('#lobbyList').innerHTML = '';
$('#lobbyEmpty').style.display = 'none';
const softTimeout = new Promise(resolve => setTimeout(resolve, 1800));
const loadPromise = (async () => {
[assignments, history] = await Promise.all([
this.fetchAssignmentsMerged(),
this.fetchHistory(this.driver.name, this.driver.truck)
]);
})();
await Promise.race([loadPromise, softTimeout]);
if (!assignments.length) assignments = await this.fetchAssignmentsMerged();
// Merge, filter demos, and render
this.assignments = this.mergeServerHistory(assignments, history).filter(a => {
const id = (a?.id || '').trim();
const title = (a?.title || '').trim();
return !DEMO_IDS.has(id) && !DEMO_TITLES.has(title);
});
this.hydrateLocalWatchedFromServer(history);
this.renderDashboard(this.assignments);
await loadPromise; // ensure full data loaded
this.assignments = this.mergeServerHistory(assignments, history).filter(a => {
const id = (a?.id || '').trim();
const title = (a?.title || '').trim();
return !DEMO_IDS.has(id) && !DEMO_TITLES.has(title);
});
this.renderDashboard(this.assignments);
}
async startAssignment(assignment) {
this.currentAssignment = assignment;
this.maxAllowedTime = 0;
this.watchedSeconds = 0;
this.minReached = false;
this.selectedLang = assignment.language || this.selectedLang || 'English';
localStorage.setItem(CONFIG.STORAGE_KEYS.LANGUAGE, this.selectedLang);
this.applyTranslations(this.selectedLang);
this.startTime = new Date();
this.rowId = '';
if (CONFIG.LOG_COURSE_STARTED && !this.isAdminViewing) {
try {
const res = await this.postTrainingEvent({
op: 'start',
name: this.driver.name,
truck: this.driver.truck,
language: this.selectedLang,
videoTitle: assignment.title,
status: 'Course Started',
assignmentId: assignment.id
});
if (res?.row) this.rowId = res.row;
} catch (e) { /* queued */ }
}
$('#dashboardSection').classList.remove('active');
$('#videoSection').classList.add('active');
$('#activeVideoTitle').textContent = assignment.title;
this.showLoadingNote(true);
const vmap = this.getVideoLinks();
const meta = (vmap[this.selectedLang] || []).find(v => v.id === assignment.id) || assignment.source || {};
this.renderPlayer(meta);
}
renderPlayer(meta) {
const type = meta.type;
$('#videoContainer').innerHTML = '';
$('#completionSection').style.display = 'none';
if (type === 'youtube') {
const videoId = meta.videoId;
$('#videoContainer').innerHTML = '<div id="ytPlayer"></div>';
const initPlayer = () => {
this.ytPlayer = new YT.Player('ytPlayer', {
videoId, width: '100%', height: '100%',
playerVars: { controls: 1, disablekb: 1, fs: 0, modestbranding: 1, rel: 0, iv_load_policy: 3, playsinline: 1 },
events: { onReady: this.onYTReady.bind(this), onStateChange: this.onYTStateChange.bind(this) }
});
};
if (window.YT && window.YT.Player) { initPlayer(); }
else if (!window._ytReadyHooked) { window._ytReadyHooked = true; window.onYouTubeIframeAPIReady = () => initPlayer(); }
}
else if (type === 'mp4') {
const url = meta.url;
$('#videoContainer').innerHTML = `
<video id="trainingVideo" controls controlsList="nodownload noplaybackrate"
disablepictureinpicture playsinline></video>`;
const video = $('#trainingVideo');
video.src = url;
video.addEventListener('loadeddata', () => this.showLoadingNote(false), { once: true });
video.addEventListener('canplay', () => this.showLoadingNote(false), { once: true });
video.playbackRate = 1;
video.addEventListener('ratechange', () => { if (video.playbackRate !== 1) video.playbackRate = 1; });
video.addEventListener('seeking', () => {
if (video.currentTime > this.maxAllowedTime + CONFIG.ALLOW_SEEK_TOLERANCE) video.currentTime = this.maxAllowedTime;
});
video.addEventListener('timeupdate', () => {
if (video.currentTime > this.maxAllowedTime) this.maxAllowedTime = video.currentTime;
this.watchedSeconds = Math.max(this.watchedSeconds, Math.floor(this.maxAllowedTime));
if (!this.minReached && this.watchedSeconds >= CONFIG.MIN_WATCH_SECONDS) { this.minReached = true; $('#completionSection').style.display = 'block'; }
const remaining = video.duration - video.currentTime;
if (remaining <= CONFIG.REVEAL_BEFORE_END) $('#completionSection').style.display = 'block';
});
video.addEventListener('ended', () => this.autoComplete());
video.play().catch(() => { this.showToast('Tap play to start the video'); });
}
else if (type === 'drive') {
const fid = meta.driveId;
const src = `https://drive.google.com/file/d/${fid}/preview`;
const iframe = document.createElement('iframe');
iframe.src = src; iframe.allow = 'autoplay; encrypted-media'; iframe.allowFullscreen = true;
iframe.onload = () => this.showLoadingNote(false);
$('#videoContainer').appendChild(iframe);
let seconds = 0;
const timer = setInterval(() => {
seconds++; this.watchedSeconds = Math.max(this.watchedSeconds, seconds);
if (!this.minReached && seconds >= CONFIG.MIN_WATCH_SECONDS) {
this.minReached = true; $('#completionSection').style.display = 'block'; clearInterval(timer);
}
}, 1000);
}
else if (type === 'local') {
this.idbGetUrl(meta.localKey).then(url => {
if (!url) { this.showLoadingNote(false); this.showToast('Local file missing on this device'); return; }
this.currentObjectUrl = url;
$('#videoContainer').innerHTML = `
<video id="trainingVideo" controls controlsList="nodownload noplaybackrate"
disablepictureinpicture playsinline></video>`;
const video = $('#trainingVideo');
video.src = url;
video.addEventListener('loadeddata', () => this.showLoadingNote(false), { once: true });
video.addEventListener('canplay', () => this.showLoadingNote(false), { once: true });
video.playbackRate = 1;
video.addEventListener('ratechange', () => { if (video.playbackRate !== 1) video.playbackRate = 1; });
video.addEventListener('seeking', () => {
if (video.currentTime > this.maxAllowedTime + CONFIG.ALLOW_SEEK_TOLERANCE) video.currentTime = this.maxAllowedTime;
});
video.addEventListener('timeupdate', () => {
if (video.currentTime > this.maxAllowedTime) this.maxAllowedTime = video.currentTime;
this.watchedSeconds = Math.max(this.watchedSeconds, Math.floor(this.maxAllowedTime));
if (!this.minReached && this.watchedSeconds >= CONFIG.MIN_WATCH_SECONDS) { this.minReached = true; $('#completionSection').style.display = 'block'; }
const remaining = video.duration - video.currentTime;
if (remaining <= CONFIG.REVEAL_BEFORE_END) $('#completionSection').style.display = 'block';
});
video.addEventListener('ended', () => this.autoComplete());
video.play().catch(() => { this.showToast('Tap play to start the video'); });
});
}
else {
this.showLoadingNote(false);
this.showToast('Video source missing');
}
}
async submitCompletion() {
const end = new Date();
const ms = end - this.startTime;
const durationMin = Math.max(1, Math.round(ms / 60000));
const payload = {
op: 'complete',
name: this.driver.name,
truck: this.driver.truck,
language: this.selectedLang,
videoTitle: this.currentAssignment?.title || 'Unknown',
status: 'Completed',
duration: `${durationMin} minutes`,
assignmentId: this.currentAssignment?.id,
updateRowId: this.rowId || ''
};
let ok = true;
try { await this.postTrainingEvent(payload); } catch (e) { ok = false; }
if (this.currentAssignment?.id) {
this.markWatched(this.currentAssignment.id, {
completedAt: new Date().toISOString().slice(0, 10),