-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.html
More file actions
1318 lines (1163 loc) · 107 KB
/
dashboard.html
File metadata and controls
1318 lines (1163 loc) · 107 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">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notify | Dashboard</title>
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' https://cdn.tailwindcss.com https://www.gstatic.com https://apis.google.com https://accounts.google.com 'unsafe-inline' 'unsafe-eval';
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net;
font-src 'self' https://fonts.gstatic.com https://cdn.jsdelivr.net;
img-src 'self' data: https://www.gstatic.com https://lh3.googleusercontent.com;
connect-src 'self' https://firestore.googleapis.com https://identitytoolkit.googleapis.com https://securetoken.googleapis.com https://www.googleapis.com https://content.googleapis.com https://classroom.googleapis.com;
frame-src 'self' https://accounts.google.com https://content.googleapis.com https://content-classroom.googleapis.com;
">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Poppins:wght@500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.2/css/all.min.css">
<script src="https://apis.google.com/js/api.js" async defer></script>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<style>
/* Base styling using Inter and Poppins fonts */
body { font-family: 'Inter', sans-serif; scroll-behavior: smooth; }
.font-poppins { font-family: 'Poppins', sans-serif; }
/* Custom input style */
.app-input {
padding: 0.75rem 1rem;
border-radius: 0.5rem;
border: 1px solid #d1d5db;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
font-family: 'Inter', sans-serif;
background-color: #f9fafb; /* gray-50 */
}
.app-input:focus {
border-color: #3b82f6;
box-shadow: 0 0 0 1px #3b82f6;
outline: none;
background-color: white;
}
button, a.btn-bubbly, input, select, textarea { font-family: 'Inter', sans-serif; }
h1, h2, h3, h4, .font-poppins { font-family: 'Poppins', sans-serif; }
.custom-scrollbar::-webkit-scrollbar { width: 8px; }
.custom-scrollbar::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 4px;}
.custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
.custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
.main-layout { height: calc(100vh - 4rem); }
/* Animations */
.fade-enter-from, .fade-leave-to { opacity: 0; transform: scale(0.95); }
.fade-enter-active, .fade-leave-active { transition: opacity 200ms ease-out, transform 200ms ease-out; }
.fade-enter-to, .fade-leave-from { opacity: 1; transform: scale(1); }
.btn-bubbly { transition: transform 0.1s ease-out; }
.btn-bubbly:active { transform: scale(0.95); }
.user-profile-menu-container { transition: transform 0.2s ease-out, opacity 0.2s ease-out; transform-origin: top right; }
.menu-item-icon { display: inline-flex; width: 1.25rem; height: 1.25rem; margin-right: 0.75rem; align-items: center; justify-content: center; }
.hand-status-card { background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); }
.raise-hand-btn { box-shadow: 0 4px 15px 0 rgba(59, 130, 246, 0.4); transition: all 0.3s ease; }
.raise-hand-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px 0 rgba(59, 130, 246, 0.5); }
/* Combined notification badge */
.class-notification-badge {
position: absolute; top: 4px; right: 8px; min-width: 1.5rem; height: 1.5rem; border-radius: 9999px;
color: white; font-size: 0.75rem; font-weight: bold; display: inline-flex; align-items: center;
justify-content: center; padding: 0 0.375rem;
}
.badge-hands { background-color: #ef4444; /* red-500 */ }
.badge-requests { background-color: #8b5cf6; /* violet-500 */ }
.badge-multiple { background: linear-gradient(45deg, #ef4444, #8b5cf6); }
/* Icon button with tooltip styles */
.tooltip-container { position: relative; display: flex; flex-direction: column; align-items: center; }
.tooltip-button { width: 3rem; height: 3rem; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; transition: background-color 0.2s, color 0.2s; }
.tooltip-text {
visibility: hidden; opacity: 0; width: max-content; background-color: #1f2937; color: #fff; text-align: center;
border-radius: 0.375rem; padding: 4px 8px; position: absolute; z-index: 10; bottom: -28px; font-size: 0.75rem;
font-weight: 500; transition: opacity 0.2s ease-out; pointer-events: none;
}
.tooltip-container:hover .tooltip-text { visibility: visible; opacity: 1; }
/* Redesigned Schedule Picker */
.schedule-time-input-container { display: flex; align-items: center; }
.schedule-time-input { width: 100px; text-align: center; font-family: 'Poppins', sans-serif; font-weight: 500; }
.period-selector { display: flex; margin-left: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; overflow: hidden; }
.period-btn { padding: 0.75rem 1rem; border: none; background-color: #f9fafb; color: #6b7280; cursor: pointer; transition: background-color 0.2s, color 0.2s; font-family: 'Inter', sans-serif;}
.period-btn.active { background-color: #3b82f6; color: white; }
/* Custom styles for the new co-teacher request and hand queue action buttons */
.request-action-group {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.request-action-group button {
width: 80px; /* fixed width for better alignment */
padding: 0.5rem 0.5rem;
font-size: 0.75rem; /* text-xs */
}
.comment-split-btn {
display: flex;
flex-direction: column;
padding: 0; /* reset padding for split buttons */
}
.comment-split-btn button {
width: 100%;
padding: 0.25rem 0.5rem;
border-radius: 0;
line-height: 1;
}
.comment-split-btn button:first-child {
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;
}
.comment-split-btn button:last-child {
border-bottom-left-radius: 0.5rem;
border-bottom-right-radius: 0.5rem;
}
/* Style for the fixed settings view content - REMOVED SETTINGS-CONTENT-WRAPPER */
/* To prevent content shift, we apply padding to the main scrollable area */
#main-content-area {
padding-right: 18px; /* Fixed padding to account for potential scrollbar width */
}
/* NEW: Pulsing animation for teacher request button */
@keyframes pulse-border {
0%, 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); }
50% { box-shadow: 0 0 0 6px rgba(59, 130, 246, 0); }
}
.request-pulse {
animation: pulse-border 2s infinite;
}
</style>
</head>
<body class="bg-slate-100 h-screen overflow-hidden">
<div class="flex flex-col h-full">
<header class="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-30 h-16 flex-shrink-0">
<div class="max-w-full mx-auto px-6 lg:px-8">
<div class="flex justify-between items-center h-16">
<a href="index.html" class="flex items-center space-x-3">
<svg class="w-7 h-7 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg>
<h1 class="text-xl font-bold text-gray-800">Notify</h1>
</a>
<div class="relative">
<button id="user-profile-btn" type="button" class="btn-bubbly flex items-center justify-center w-10 h-10 rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-transform duration-150 hover:scale-105">
<img id="user-profile-pic" class="w-full h-full rounded-lg object-cover hidden" src="" alt="User profile picture">
<div id="user-profile-initial" class="w-full h-full rounded-lg flex items-center justify-center bg-gradient-to-br from-blue-600 to-indigo-700 text-white font-bold text-lg hidden"></div>
</button>
<div id="user-profile-menu" class="user-profile-menu-container absolute right-0 mt-2 w-72 rounded-xl shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none hidden" role="menu">
<div class="p-4 bg-gray-50 border-b border-gray-100 rounded-t-xl">
<div class="flex items-center">
<div class="flex-shrink-0">
<img id="user-profile-pic-menu" class="h-12 w-12 rounded-full object-cover hidden" src="" alt="">
<div id="user-profile-initial-menu" class="h-12 w-12 rounded-full flex items-center justify-center bg-gradient-to-br from-blue-600 to-indigo-700 text-white font-bold text-xl hidden"></div>
</div>
<div class="ml-3 min-w-0">
<div id="user-display-name-container" class="marquee-container"><p id="user-display-name-menu" class="text-lg font-bold font-poppins text-gray-800 truncate">Loading...</p></div>
<div id="user-email-container" class="marquee-container"><p id="user-email-menu" class="text-sm text-gray-500 truncate">Loading...</p></div>
</div>
</div>
</div>
<div class="py-1" role="none">
<a href="settings.html" class="font-medium text-gray-700 block px-4 py-2 text-sm hover:bg-gray-100 flex items-center" role="menuitem" tabindex="-1">
<span class="menu-item-icon"><i class="fa-solid fa-sliders text-gray-400"></i></span>
<span>Settings</span>
</a>
<a href="#" id="logout-btn" class="font-medium text-gray-700 block px-4 py-2 text-sm hover:bg-gray-100 flex items-center" role="menuitem" tabindex="-1">
<span class="menu-item-icon"><i class="fa-solid fa-right-from-bracket text-gray-400"></i></span>
<span>Logout</span>
</a>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="flex flex-1 main-layout overflow-hidden">
<aside class="w-72 bg-white border-r border-gray-200 flex flex-col flex-shrink-0">
<div id="class-list-container" class="flex-grow p-4 overflow-y-auto custom-scrollbar">
<h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-3 px-2">My Classes</h2>
<ul id="class-list" class="space-y-1"></ul>
<div id="no-classes-sidebar" class="text-center text-sm text-gray-500 mt-4 hidden"><p>No classes yet.</p></div>
</div>
<div id="teacher-sidebar-actions" class="p-4 border-t border-gray-200 hidden">
<button id="new-class-btn" class="w-full bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors duration-150 flex items-center justify-center space-x-2 btn-bubbly"><i class="fa-solid fa-plus w-5 h-5"></i><span>New Class</span></button>
<button id="join-class-btn-main" class="mt-2 w-full bg-green-500 text-white font-semibold py-2 px-4 rounded-lg hover:bg-green-600 transition-colors duration-150 flex items-center justify-center space-x-2 btn-bubbly text-sm"><i class="fa-solid fa-user-plus w-5 h-5"></i><span>Join Class</span></button>
</div>
</aside>
<main class="flex-1 flex flex-col overflow-hidden">
<div id="main-content-area" class="flex-1 overflow-y-scroll bg-slate-100 p-6 sm:p-8 custom-scrollbar"></div>
</main>
</div>
</div>
<div id="modal-backdrop" class="fixed inset-0 bg-gray-900 bg-opacity-60 z-40 hidden"></div>
<div id="modal-container" class="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none"></div>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-auth-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-firestore-compat.js"></script>
<script src="../firebase-config.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
let currentUser = null, userData = null, currentClassId = null, currentRoster = null;
let allLoadedClasses = {}, classQueues = {}, classRequests = {}, unsubscribes = [], queueUnsubscribers = {};
let currentClassView = 'overview';
let classDocUnsubscribe = null; // Listener for the current class document
const mainContentArea = document.getElementById('main-content-area');
const classListEl = document.getElementById('class-list');
const modalContainer = document.getElementById('modal-container');
const modalBackdrop = document.getElementById('modal-backdrop');
function onFirebaseReady(callback) { const i = setInterval(() => { if (typeof firebase !== 'undefined') { clearInterval(i); callback(); } }, 50); }
onFirebaseReady(() => {
const app = firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const db = firebase.firestore();
const FieldValue = firebase.firestore.FieldValue; // Alias for brevity
auth.onAuthStateChanged(user => {
if (user) { currentUser = user; fetchUserData(user.uid); }
else { window.location.href = 'login.html'; }
});
async function fetchUserData(uid) {
const doc = await db.collection('users').doc(uid).get();
if (doc.exists) {
userData = { uid, ...doc.data() };
updateProfileUI(currentUser, userData);
listenForClasses(uid);
renderMainContent();
initializeScheduleChecker();
initializeRequestRecycler(); // NEW: Start request recycler
} else { auth.signOut(); }
}
function updateProfileUI(user, data) {
document.getElementById('user-display-name-menu').textContent = data.username;
document.getElementById('user-email-menu').textContent = user.email;
const pics = [document.getElementById('user-profile-pic'), document.getElementById('user-profile-pic-menu')];
const initials = [document.getElementById('user-profile-initial'), document.getElementById('user-profile-initial-menu')];
if (user.photoURL) {
pics.forEach(el => { el.src = user.photoURL; el.classList.remove('hidden'); });
initials.forEach(el => el.classList.add('hidden'));
} else {
const i = data.username.charAt(0).toUpperCase();
initials.forEach(el => { el.textContent = i; el.classList.remove('hidden'); });
pics.forEach(el => el.classList.add('hidden'));
}
document.getElementById('teacher-sidebar-actions').classList.toggle('hidden', data.role !== 'teacher');
}
function updateGlobalUI() {
updateDocumentTitle();
renderClassList(Object.values(allLoadedClasses));
}
function updateDocumentTitle() {
let handsCount = 0, requestsCount = 0;
if (userData && allLoadedClasses && classQueues && classRequests) {
for (const id in allLoadedClasses) {
const cls = allLoadedClasses[id];
if (cls) {
const isOwner = cls.teacherId === userData.uid;
const isCoTeacher = (cls.teacherIds || []).includes(userData.uid);
if(isOwner || isCoTeacher) handsCount += (classQueues[id] || []).length;
// Only count 'pending' requests for the badge
if(isOwner) requestsCount += (classRequests[id] || []).filter(req => req.status === 'pending').length;
}
}
}
const totalCount = handsCount + requestsCount;
document.title = totalCount > 0 ? `(${totalCount}) Notify | Dashboard` : 'Notify | Dashboard';
}
function listenForClasses(uid) {
unsubscribes.forEach(unsub => unsub()); unsubscribes = [];
Object.values(queueUnsubscribers).forEach(unsub => unsub()); queueUnsubscribers = {};
allLoadedClasses = {};
const process = (snapshot) => {
snapshot.docChanges().forEach(change => {
const id = change.doc.id, data = { id, ...change.doc.data() };
if (change.type === 'removed') {
delete allLoadedClasses[id]; delete classQueues[id]; delete classRequests[id];
if (queueUnsubscribers[id]) { queueUnsubscribers[id](); delete queueUnsubscribers[id]; }
} else {
allLoadedClasses[id] = data;
const isOwner = data.teacherId === uid;
const isCoTeacher = (data.teacherIds || []).includes(uid);
if ((isOwner || isCoTeacher) && !queueUnsubscribers[`hands_${id}`]) {
queueUnsubscribers[`hands_${id}`] = db.collection('classes').doc(id).collection('raisedHands')
.onSnapshot(qSnap => {
classQueues[id] = qSnap.docs.map(d => ({ id: d.id, ...d.data() }));
updateGlobalUI();
if(currentClassId === id) renderMainContent();
});
}
if(isOwner && !queueUnsubscribers[`requests_${id}`]){
// NEW: Listen to all, then filter 'pending' for count and 'recyclable' for reuse
queueUnsubscribers[`requests_${id}`] = db.collection('classes').doc(id).collection('coTeacherRequests')
.onSnapshot(rSnap => {
classRequests[id] = rSnap.docs.map(d => ({ id: d.id, ...d.data() }));
updateGlobalUI();
if(currentClassId === id) renderMainContent();
});
}
}
});
updateGlobalUI();
};
unsubscribes.push(db.collection('classes').where('teacherId', '==', uid).onSnapshot(process));
unsubscribes.push(db.collection('classes').where('studentIds', 'array-contains', uid).onSnapshot(process));
unsubscribes.push(db.collection('classes').where('teacherIds', 'array-contains', uid).onSnapshot(process));
}
function renderClassList(classes) {
document.getElementById('no-classes-sidebar').classList.toggle('hidden', classes.length > 0);
classListEl.innerHTML = '';
classes.sort((a, b) => (a.createdAt?.seconds || 0) - (b.createdAt?.seconds || 0)).forEach(cls => {
const li = document.createElement('li');
const isActive = currentClassId === cls.id;
const activeClasses = isActive ? 'bg-blue-100 text-blue-800 font-semibold' : 'text-gray-700 hover:bg-slate-100 hover:text-gray-900';
const handsCount = classQueues[cls.id]?.length || 0;
// Filter requests to only count pending ones for the badge
const reqCount = (classRequests[cls.id] || []).filter(req => req.status === 'pending').length;
let badge = '';
if(handsCount > 0 && reqCount > 0) badge = `<span class="class-notification-badge badge-multiple">${handsCount + reqCount}</span>`;
else if(handsCount > 0) badge = `<span class="class-notification-badge badge-hands">${handsCount}</span>`;
else if(reqCount > 0) badge = `<span class="class-notification-badge badge-requests">${reqCount}</span>`;
li.innerHTML = `<button data-class-id="${cls.id}" class="w-full text-left px-3 py-2.5 rounded-md font-medium text-sm transition-colors btn-bubbly relative flex justify-between items-center ${activeClasses}"><span>${escapeHtml(cls.name)}</span>${badge}</button>`;
classListEl.appendChild(li);
});
}
async function selectClass(id) {
// Cleanup previous class listener
if (classDocUnsubscribe) classDocUnsubscribe();
classDocUnsubscribe = null;
currentClassId = id; currentClassView = 'overview'; currentRoster = null;
if (id) {
await fetchRosterData(allLoadedClasses[id]);
// Setup listener for the class document itself (for settings/toggle changes)
classDocUnsubscribe = db.collection('classes').doc(id).onSnapshot(docSnap => {
if(docSnap.exists) {
allLoadedClasses[id] = {id, ...docSnap.data()};
updateGlobalUI(); // Update list count if needed
if (currentClassId === id) renderMainContent(); // Re-render current view if data changed
} else {
// Class deleted remotely
delete allLoadedClasses[id];
selectClass(null);
}
});
}
renderMainContent();
}
async function fetchRosterData(data) {
if (!data) return;
const ids = [data.teacherId, ...(data.teacherIds || []), ...(data.studentIds || [])].filter(id => id);
if (ids.length === 0) { currentRoster = { owner: {}, coTeachers: [], students: [] }; return; }
const userBatches = [];
for (let i = 0; i < ids.length; i += 10) {
userBatches.push(ids.slice(i, i + 10));
}
const users = {};
for(const batch of userBatches){
const docs = await db.collection('users').where(firebase.firestore.FieldPath.documentId(), 'in', batch).get();
docs.forEach(doc => { users[doc.id] = doc.data(); });
}
currentRoster = {
owner: { id: data.teacherId, ...users[data.teacherId] },
coTeachers: (data.teacherIds || []).map(id => ({ id, ...users[id] })),
students: (data.studentIds || []).map(id => ({ id, ...users[id] }))
};
}
// NEW: Schedule Helper Functions
function isTimeInSchedule(enableAt, disableAt) {
if (!enableAt || !disableAt) return true; // No meaningful schedule set means always active
const now = new Date();
const currentMinutes = now.getHours() * 60 + now.getMinutes();
const [hE, mE] = enableAt.split(':').map(Number);
const [hD, mD] = disableAt.split(':').map(Number);
const enableMinutes = hE * 60 + mE;
const disableMinutes = hD * 60 + mD;
if (enableMinutes === disableMinutes) {
return true; // Enable and disable are the same time, treat as always enabled
}
if (enableMinutes < disableMinutes) {
// Simple case: 08:00 to 17:00 (no midnight wrap)
return currentMinutes >= enableMinutes && currentMinutes < disableMinutes;
} else {
// Wrap-around case: 22:00 to 02:00
// Time is in schedule if it's after enable OR before disable
return currentMinutes >= enableMinutes || currentMinutes < disableMinutes;
}
}
function getEffectiveHandRaisingStatus(cls, isOwner) {
const hasSchedule = cls.schedule?.enableAt && cls.schedule?.disableAt;
const dbEnabled = cls.handRaisingEnabled === undefined ? true : cls.handRaisingEnabled; // Default to true if undefined
if (!hasSchedule) {
return {
enabled: dbEnabled,
override: false,
message: dbEnabled ? '' : 'Manually Paused'
};
}
const isScheduledTime = isTimeInSchedule(cls.schedule.enableAt, cls.schedule.disableAt);
let effectiveEnabled = isScheduledTime;
let override = false;
let message = '';
if (isScheduledTime) {
if (!dbEnabled) { // Scheduled ON, but DB is OFF -> Manual override to PAUSE
effectiveEnabled = false;
override = true;
message = isOwner ? 'Manually Paused (Override Schedule)' : 'Paused by Teacher (Override)';
} else {
// Effective ON, no override
}
} else { // Not scheduled time
effectiveEnabled = false;
message = 'Paused (Outside Schedule)';
if (dbEnabled) { // Scheduled OFF, but DB is ON -> Manual override to RESUME
effectiveEnabled = true;
override = true;
message = isOwner ? 'Manually Resumed (Override Schedule)' : 'Resumed by Teacher (Override)';
}
}
return {
enabled: effectiveEnabled,
override: override,
message: message
};
}
function renderMainContent() {
if (currentClassId && allLoadedClasses[currentClassId]) {
const data = allLoadedClasses[currentClassId];
const queue = classQueues[currentClassId] || [];
// Filter requests to only show pending ones on the requests tab
const pendingRequests = (classRequests[currentClassId] || []).filter(req => req.status === 'pending');
const isOwner = data.teacherId === userData.uid;
const isCoTeacher = (data.teacherIds || []).includes(userData.uid);
// Pass pending requests to the template
mainContentArea.innerHTML = TPL.classView(data, userData, isOwner, isCoTeacher, queue, pendingRequests, currentClassView, currentRoster);
document.body.dispatchEvent(new CustomEvent('mainContentRendered'));
} else { mainContentArea.innerHTML = TPL.emptyState(userData); }
}
function showModal(html) { modalContainer.innerHTML = html; modalBackdrop.classList.remove('hidden'); const d = modalContainer.firstElementChild; d.classList.add('fade-enter-from'); setTimeout(() => d.classList.remove('fade-enter-from'), 10); }
function hideModal() { const d=modalContainer.firstElementChild; if(d){d.classList.add('fade-leave-to');modalBackdrop.classList.add('fade-leave-to');setTimeout(() => {modalContainer.innerHTML='';modalBackdrop.classList.add('hidden');modalBackdrop.classList.remove('fade-leave-to');}, 200);}}
function escapeHtml(text) { if(typeof text!=='string')return'';const d=document.createElement('div');d.textContent=text;return d.innerHTML; }
async function createNewClass(name) { const code=Math.random().toString(36).substring(2,10).toUpperCase(); const coTeacherCode = 'T' + Math.random().toString(36).substring(2,9).toUpperCase(); await db.collection('classes').add({name,teacherId:currentUser.uid,teacherIds:[],code,coTeacherCode,studentIds:[],pendingStudentEmails:[],handRaisingEnabled:true,schedule:{enableAt:'',disableAt:''},createdAt:FieldValue.serverTimestamp()});hideModal();}
async function joinClass(code) {
const studentQuery = db.collection('classes').where('code', '==', code).limit(1).get();
const teacherQuery = db.collection('classes').where('coTeacherCode', '==', code).limit(1).get();
const [studentSnap, teacherSnap] = await Promise.all([studentQuery, teacherQuery]);
if (teacherSnap.empty && studentSnap.empty) { showModal(TPL.messageModal('Error','Invalid class code.','red')); return; }
if (!teacherSnap.empty) { // Co-teacher join
const classDoc = teacherSnap.docs[0];
const classData = classDoc.data();
// IMPLEMENTATION: Block Student Role from using Co-Teacher Code
if (userData.role !== 'teacher') { showModal(TPL.messageModal('Access Denied', 'Only users with a teacher account can join with this code.', 'red')); return; }
const isMember = classData.teacherId === currentUser.uid || (classData.teacherIds || []).includes(currentUser.uid);
if (isMember) { showModal(TPL.messageModal('Already Enrolled', `You are already a teacher in ${classData.name}.`, 'yellow')); return; }
// NEW: Send request and show confirmation modal
await requestCoTeacher(classDoc.id, ''); // Send request with empty comment
hideModal();
showModal(TPL.requestConfirmationModal(classDoc.id, classData.name));
} else { // Student join
const classDoc = studentSnap.docs[0];
const classData = classDoc.data();
const isMember = classData.teacherId === currentUser.uid || (classData.teacherIds || []).includes(currentUser.uid) || (classData.studentIds || []).includes(currentUser.uid);
if(isMember){ showModal(TPL.messageModal('Already Enrolled',`You are already a member of ${classData.name}.`,'yellow')); return; }
// IMPLEMENTATION: Block Teacher Role from using Student Code
if (userData.role === 'teacher') {
showModal(TPL.messageModal('Access Denied', `Users with a teacher account cannot join using a Student Code. Please use the Co-Teacher Code or ask the owner to invite you.`, 'red'));
return;
}
// Any user type can join as a student with the student code
await db.collection('classes').doc(classDoc.id).update({studentIds:FieldValue.arrayUnion(currentUser.uid)});
hideModal();
showModal(TPL.messageModal('Success',`Successfully joined class: ${classData.name} as a student!`,'green'));
}
}
// NEW: Logic to find a recyclable request slot
async function findRecyclableRequestSlot(classId) {
const recyclableSnap = await db.collection('classes').doc(classId).collection('coTeacherRequests')
.where('status', '==', 'recyclable')
.limit(1)
.get();
if (!recyclableSnap.empty) {
return recyclableSnap.docs[0].id;
}
return currentUser.uid; // Default to using the user's ID as the doc ID
}
// UPDATED: requestCoTeacher to use recyclable slot and make comment optional
async function requestCoTeacher(classId, comment) {
const docId = await findRecyclableRequestSlot(classId); // Find or use current user's ID
const requestData = {
requesterName: userData.username,
comment: comment, // This can now be an empty string
status: 'pending',
requestedAt: FieldValue.serverTimestamp(),
requesterEmail: currentUser.email, // Good to have for the teacher
requesterId: currentUser.uid // Store actual requester ID
};
await db.collection('classes').doc(classId).collection('coTeacherRequests').doc(docId).set(requestData);
hideModal();
showModal(TPL.messageModal('Request Sent', 'Your request to join as a co-teacher has been sent to the class owner.', 'green'));
}
// UPDATED: handleCoTeacherRequest to use full fields
async function handleCoTeacherRequest(classId, requestDocId, action) {
const requestRef = db.collection('classes').doc(classId).collection('coTeacherRequests').doc(requestDocId);
const requestDoc = await requestRef.get();
if (!requestDoc.exists) return; // Should not happen
const requesterId = requestDoc.data().requesterId; // Get the actual requester ID
if(action === 'accept'){
await db.collection('classes').doc(classId).update({ teacherIds: FieldValue.arrayUnion(requesterId) });
await requestRef.update({ status: 'accepted' });
} else if (action === 'deny') {
await requestRef.update({ status: 'denied' });
} else if (action === 'comment-edit' || action === 'comment-delete') {
showModal(TPL.messageModal('Feature Update', 'Commenting on requests is a planned feature! This button is currently for demonstration.', 'yellow'));
return; // Placeholder for future comment logic
}
// For accept/deny, hide the modal and re-render the main content
hideModal();
renderMainContent();
}
async function raiseHand(id,q){await db.collection('classes').doc(id).collection('raisedHands').doc(currentUser.uid).set({studentName:userData.username,studentPhotoURL:currentUser.photoURL||'',question:q||'',raisedAt:FieldValue.serverTimestamp()});hideModal();}
async function lowerHand(id,studentId=currentUser.uid){await db.collection('classes').doc(id).collection('raisedHands').doc(studentId).delete();}
async function lowerAllHands(id){const s=await db.collection('classes').doc(id).collection('raisedHands').get();const b=db.batch();s.docs.forEach(d=>b.delete(d.ref));await b.commit();}
// FIXED: toggleHandRaising to include immediate UI update
async function toggleHandRaising(id, status, buttonEl) {
// Immediate UI update (NEW)
if (buttonEl) {
buttonEl.classList.toggle('bg-yellow-100', !status);
buttonEl.classList.toggle('text-yellow-600', !status);
buttonEl.classList.toggle('hover:bg-yellow-200', !status);
buttonEl.classList.toggle('bg-gray-200', status);
buttonEl.classList.toggle('text-gray-600', status);
buttonEl.classList.toggle('hover:bg-gray-300', status);
const icon = buttonEl.querySelector('i');
if (icon) {
icon.classList.toggle('fa-hand', !status);
icon.classList.toggle('fa-hand-sparkles', status);
}
const tooltip = buttonEl.closest('.tooltip-container').querySelector('.tooltip-text');
if (tooltip) {
tooltip.textContent = !status ? 'Pause Raising' : 'Resume Raising';
}
}
// DB update
await db.collection('classes').doc(id).update({ handRaisingEnabled: !status });
// onSnapshot listener will handle the full re-render and UI changes eventually.
}
async function handleChangeClassName(id,name){const today=new Date().toISOString().split('T')[0];const key=`classNameChanges_${id}`;let changes;try{changes=JSON.parse(localStorage.getItem(key))||{};}catch(e){changes={};}if(changes.date!==today){changes={date:today,count:0};}if(changes.count>=3){showModal(TPL.messageModal('Limit Reached','You can only change the class name 3 times per day.','red'));return;}await db.collection('classes').doc(id).update({name});changes.count++;localStorage.setItem(key,JSON.stringify(changes));showModal(TPL.messageModal('Success','Class name updated!','green'));}
// FIXED: handleSaveSchedule now takes 24-hour time strings directly from the template logic
async function handleSaveSchedule(id,enable,disable){
await db.collection('classes').doc(id).update({
schedule:{enableAt:enable,disableAt:disable},
scheduleLastActionDate: ''
});
showModal(TPL.messageModal('Success','Schedule saved!','green'));
}
// FIXED: deleteSchedule now clears input boxes
async function deleteSchedule(id) {
await db.collection('classes').doc(id).update({ 'schedule.enableAt': '', 'schedule.disableAt': '' });
// NEW: Clear the text boxes
const enableInput = document.getElementById('enable-time-input');
const disableInput = document.getElementById('disable-time-input');
if (enableInput) {
enableInput.value = '';
enableInput.dataset.time24hr = '';
enableInput.dataset.digits = '';
const periodBtns = enableInput.closest('.schedule-time-input-container').querySelectorAll('.period-btn');
periodBtns.forEach(btn => btn.classList.remove('active'));
}
if (disableInput) {
disableInput.value = '';
disableInput.dataset.time24hr = '';
disableInput.dataset.digits = '';
const periodBtns = disableInput.closest('.schedule-time-input-container').querySelectorAll('.period-btn');
periodBtns.forEach(btn => btn.classList.remove('active'));
}
showModal(TPL.messageModal('Success', 'Schedule has been removed.', 'green'));
}
async function removeUserFromClass(id, userId) { const data = allLoadedClasses[id]; if ((data.teacherIds || []).includes(userId)) { await db.collection('classes').doc(id).update({ teacherIds: FieldValue.arrayRemove(userId) }); } else if ((data.studentIds || []).includes(userId)) { await db.collection('classes').doc(id).update({ studentIds: FieldValue.arrayRemove(userId) }); } await fetchRosterData(allLoadedClasses[id]); renderMainContent(); }
async function handleDeleteClass(id){const s=await db.collection('classes').doc(id).collection('raisedHands').get();const b=db.batch();s.docs.forEach(d=>b.delete(d.ref));b.delete(db.collection('classes').doc(id));await b.commit();hideModal();selectClass(null);}
let scheduleInterval = null;
function initializeScheduleChecker() {
if (scheduleInterval) clearInterval(scheduleInterval);
scheduleInterval = setInterval(() => {
const now = new Date();
const todayStr = now.toISOString().split('T')[0];
if (!userData || userData.role !== 'teacher') return;
for (const classId in allLoadedClasses) {
const cls = allLoadedClasses[classId];
if (cls.teacherId === userData.uid) { // Only the owner handles auto-disabling
if (cls.schedule?.disableAt) {
// Check for auto-disable logic (using DB handRaisingEnabled as the override state)
const effectiveStatus = getEffectiveHandRaisingStatus(cls, true);
// If scheduled time is over (effective status is disabled), and the teacher has not overridden it
// and the DB still says it's enabled (meaning it hasn't been auto-disabled today yet).
if (!effectiveStatus.enabled && !effectiveStatus.override && cls.handRaisingEnabled && cls.scheduleLastActionDate !== todayStr) {
console.log(`Auto-disabling for ${cls.name} due to schedule end.`);
// Set the DB to disabled and record the date to prevent further action today
db.collection('classes').doc(classId).update({ scheduleLastActionDate: todayStr, handRaisingEnabled: false });
lowerAllHands(classId); // Lower hands when auto-disabling
}
}
}
}
}, 60000); // Check every minute
}
// NEW: Request Recycler Logic
let recyclerInterval = null;
function initializeRequestRecycler() {
if (recyclerInterval) clearInterval(recyclerInterval);
recyclerInterval = setInterval(() => {
if (!userData || userData.role !== 'teacher') return;
const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
for (const classId in allLoadedClasses) {
const cls = allLoadedClasses[classId];
if (cls.teacherId === userData.uid) { // Only the owner recycles requests
recycleOldRequests(classId, twentyFourHoursAgo);
}
}
}, 5 * 60 * 1000); // Check every 5 minutes
}
async function recycleOldRequests(classId, cutoffDate) {
const oldRequestsSnap = await db.collection('classes').doc(classId).collection('coTeacherRequests')
.where('status', 'in', ['accepted', 'denied']) // Only recycle closed requests
.get();
const batch = db.batch();
let recycledCount = 0;
oldRequestsSnap.docs.forEach(doc => {
const data = doc.data();
// Check if the request is older than 1 day
if (data.requestedAt && data.requestedAt.toDate() < cutoffDate) {
const ref = doc.ref;
batch.update(ref, {
status: 'recyclable',
requesterName: null,
comment: null,
requestedAt: null,
requesterEmail: null,
requesterId: null
});
recycledCount++;
}
});
if (recycledCount > 0) {
await batch.commit();
console.log(`Recycled ${recycledCount} old co-teacher requests for class ${classId}.`);
}
}
let gapiLoaded=false,googleAuth=null;
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/classroom/v1/rest';
const SCOPES = 'https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.rosters.readonly';
// *** CRITICAL FIX: Ensure GAPI/OAuth initialization is robust ***
async function initializeGAPI(apiKey,clientId){
if(gapiLoaded) return Promise.resolve();
return new Promise((resolve,reject)=>{
const checkGAPI=()=>{
if(typeof gapi!=='undefined'&&gapi.load){
gapi.load('client:auth2',async()=>{ // Added 'auth2' for better token handling
try{
await gapi.client.init({apiKey,discoveryDocs:[DISCOVERY_DOC]});
// Check if Google accounts client is available
if(typeof google === 'undefined' || typeof google.accounts === 'undefined' || typeof google.accounts.oauth2 === 'undefined') {
throw new Error("Google Accounts Client library failed to load.");
}
googleAuth = google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: SCOPES,
callback: '' // Will be set in requestAccessToken
});
gapiLoaded=true;
resolve();
}catch(e){
reject(e);
}
});
} else {
setTimeout(checkGAPI,100);
}
};
checkGAPI();
});
}
function requestAccessToken(){
return new Promise((resolve,reject)=>{
try{
googleAuth.callback = async(res) => {
if(res.error) return reject(new Error(res.error));
// CRITICAL: Set the token immediately after receiving it
gapi.client.setToken({access_token:res.access_token});
try{
await listGoogleCourses();
resolve();
}catch(e){
reject(e);
}
};
// This line is what should trigger the pop-up/consent window
googleAuth.requestAccessToken();
}catch(e){
reject(e);
}
});
}
// *** END CRITICAL FIX ***
async function handleGoogleImportClick(){
showModal(TPL.googleImportModal());
const loadingEl=document.getElementById('g-import-loading');
const errorEl=document.getElementById('g-import-error');
loadingEl.classList.remove('hidden');
errorEl.classList.add('hidden');
try{
const secretsDoc=await db.collection('secrets').doc('wUTBTbjuNLueOFhgHXEE').get();
if(!secretsDoc.exists)throw new Error("Secrets document not found.");
const{GoogleClassroomAPIKey:apiKey,GoogleClientID:clientId}=secretsDoc.data();
if(!apiKey||!clientId)throw new Error("Missing API Key or Client ID in secrets document.");
await initializeGAPI(apiKey,clientId);
await requestAccessToken(); // This triggers the popup
}catch(e){
console.error('Google Classroom init error:',e);
loadingEl.classList.add('hidden');
errorEl.textContent=`Error initializing import: ${e.message}. Check browser console for details.`;
errorEl.classList.remove('hidden');
}
}
async function listGoogleCourses(){
const listEl=document.getElementById('g-import-list');
const loadingEl=document.getElementById('g-import-loading');
const errorEl=document.getElementById('g-import-error');
try{
loadingEl.textContent='Loading courses...';
const response=await gapi.client.classroom.courses.list({teacherId:'me',courseStates:'ACTIVE'});
loadingEl.classList.add('hidden');
const courses=response.result.courses||[];
const notifyClassesSnapshot=await db.collection('classes').where('teacherId','==',currentUser.uid).get();
const existingGoogleIds=new Set();
notifyClassesSnapshot.forEach(doc=>{const data=doc.data();if(data.googleCourseId)existingGoogleIds.add(data.googleCourseId);});
if(courses.length>0){
listEl.innerHTML=courses.map(course=>{const isImported=existingGoogleIds.has(course.id);
const buttonHtml=isImported?'<button disabled class="bg-gray-400 text-white px-3 py-1 rounded-md text-sm font-poppins">Imported</button>':`<button data-course-id="${course.id}" data-course-name="${escapeHtml(course.name)}" class="import-g-class-btn bg-blue-600 text-white px-3 py-1 rounded-md text-sm hover:bg-blue-700 btn-bubbly font-poppins">Import</button>`;
return`<li class="flex justify-between items-center p-3 bg-gray-50 rounded-lg"><div class="flex-1"><p class="font-bold text-gray-800">${escapeHtml(course.name)}</p><p class="text-xs text-gray-500 mt-1">${escapeHtml(course.section||'No section')}</p></div>${buttonHtml}</li>`;
}).join('');
document.querySelectorAll('.import-g-class-btn').forEach(button=>{button.addEventListener('click',()=>importGoogleClass(button.dataset.courseId,button.dataset.courseName));});
} else {
listEl.innerHTML='<p class="text-center text-gray-500 py-8">No active courses found in your Google Classroom that you are the primary teacher of.</p>';
}
}catch(e){
console.error('Error listing courses:',e);
loadingEl.classList.add('hidden');
let errorMessage='Failed to load courses.';
if(e.result&&e.result.error){errorMessage=e.result.error.message||errorMessage;}
else if(e.message){errorMessage=e.message;}
errorEl.textContent=`Error: ${errorMessage}`;
errorEl.classList.remove('hidden');
}
}
async function importGoogleClass(googleCourseId,googleCourseName){const importBtn=document.querySelector(`.import-g-class-btn[data-course-id="${googleCourseId}"]`);if(importBtn){importBtn.textContent='Importing...';importBtn.disabled=true;}try{const existingClass=await db.collection('classes').where('googleCourseId','==',googleCourseId).limit(1).get();if(!existingClass.empty){showModal(TPL.messageModal('Duplicate','This class has already been imported.','yellow'));if(importBtn){importBtn.textContent='Import';importBtn.disabled=false;}return;}const studentsResponse=await gapi.client.classroom.courses.students.list({courseId:googleCourseId});const students=studentsResponse.result.students||[];const studentEmails=students.map(s=>s.profile?.emailAddress).filter(Boolean);const existingStudentUids=[];const pendingEmails=[];if(studentEmails.length>0){const batchSize=10;for(let i=0;i<studentEmails.length;i+=batchSize){const batchEmails=studentEmails.slice(i,i+batchSize);const usersSnapshot=await db.collection('users').where('email','in',batchEmails).get();const existingEmailsBatch=new Set();usersSnapshot.forEach(doc=>{existingStudentUids.push(doc.id);existingEmailsBatch.add(doc.data().email);});batchEmails.forEach(email=>{if(!existingEmailsBatch.has(email)){pendingEmails.push(email);}});}}const classCode=Math.random().toString(36).substring(2,10).toUpperCase(); const coTeacherCode = 'T' + Math.random().toString(36).substring(2,9).toUpperCase(); await db.collection('classes').add({name:googleCourseName,teacherId:currentUser.uid,teacherIds:[],code:classCode,coTeacherCode,googleCourseId:googleCourseId,studentIds:existingStudentUids,pendingStudentEmails:pendingEmails,createdAt:FieldValue.serverTimestamp(),handRaisingEnabled:true,schedule:{enableAt:'',disableAt:''}, scheduleLastActionDate:''});hideModal();showModal(TPL.messageModal('Import Successful',`Class "${googleCourseName}" has been imported with ${existingStudentUids.length} existing students and ${pendingEmails.length} pending emails!`,'green'));}catch(e){console.error("Error importing Google Classroom:",e);let errorMessage='Failed to import class. Please ensure Google Classroom API is enabled for your account.';if(e.result&&e.result.error){errorMessage=e.result.error.message||errorMessage;}else if(e.message){errorMessage=e.message;}showModal(TPL.messageModal('Import Failed',errorMessage,'red'));if(importBtn){importBtn.textContent='Import';importBtn.disabled=false;}}}
document.body.addEventListener('click', async e => {
const target = e.target.closest('button, a, [role="button"]');
if (!target) return;
const userProfileBtn = document.getElementById('user-profile-btn'), userProfileMenu = document.getElementById('user-profile-menu');
if (target === userProfileBtn) userProfileMenu.classList.toggle('hidden');
else if (!target.closest('#user-profile-menu')) userProfileMenu.classList.add('hidden');
if(target.id === 'logout-btn') auth.signOut();
if (target.closest('#class-list button')) selectClass(target.closest('#class-list button').dataset.classId);
if(target.id === 'new-class-btn') showModal(TPL.newClassChoiceModal(userData));
if(target.id === 'join-class-btn-main') showModal(TPL.joinClassModal());
if(target.id === 'create-manual-btn') showModal(TPL.createClassModal());
if(target.id === 'import-gclass-btn') handleGoogleImportClick();
if(target.classList.contains('modal-cancel-btn') || e.target.id === 'modal-backdrop' || target.classList.contains('modal-close-btn')) hideModal();
if (target.id === 'raise-hand-action-btn') showModal(TPL.raiseHandModal(currentClassId));
if (target.id === 'lower-hand-action-btn') lowerHand(currentClassId);
// FIXED: Pass the button element to the function for immediate UI update
if (target.id === 'toggle-hand-raising-btn') toggleHandRaising(currentClassId, allLoadedClasses[currentClassId].handRaisingEnabled, target);
// NEW: Updated view tab logic
if(target.matches('.class-view-tab')) {
currentClassView = target.dataset.view;
renderMainContent();
}
if(target.id === 'delete-class-btn') { showModal(TPL.deleteClassConfirmModal(currentClassId, allLoadedClasses[currentClassId].name)); }
if(target.id === 'confirm-delete-class-btn') { handleDeleteClass(target.dataset.classId); }
if(target.matches('.remove-user-btn')) { removeUserFromClass(currentClassId, target.dataset.userId); }
// NEW: Updated co-teacher request button logic
if(target.matches('.request-action-btn')) {
const action = target.dataset.action;
const requesterId = target.dataset.requesterDocId; // The ID of the document in the subcollection
handleCoTeacherRequest(currentClassId, requesterId, action);
}
// NEW: Updated hand queue action button logic
if(target.matches('.queue-action-btn')) {
const action = target.dataset.action;
const studentId = target.dataset.studentId;
if (action === 'accept-hand' || action === 'deny-hand') {
lowerHand(currentClassId, studentId); // Both actions lower the hand
// Use setTimeout to allow lowerHand async call to start before showing modal
setTimeout(() => {
showModal(TPL.messageModal('Hand Lowered', `The student's hand was ${action === 'accept-hand' ? 'accepted and lowered' : 'denied and lowered'}.`, action === 'accept-hand' ? 'green' : 'red'));
}, 50);
} else if (action.startsWith('comment-')) {
showModal(TPL.messageModal('Feature Update', 'Commenting on raised hands is a planned feature! This button is currently for demonstration.', 'yellow'));
}
}
if(target.matches('.schedule-action-btn')) {
const action = target.dataset.action;
if (action === 'save') {
// Collect the data-time-24hr attributes which are set during the period-btn click/initial render
const enableTime24 = document.getElementById('enable-time-input').dataset.time24hr;
const disableTime24 = document.getElementById('disable-time-input').dataset.time24hr;
// Validate that we have 24hr times
if (disableTime24) { // Only require a disable time to activate the schedule
handleSaveSchedule(currentClassId, enableTime24, disableTime24);
} else {
showModal(TPL.messageModal('Error', 'The "Disable at" time is required to save a schedule.', 'red'));
}
} else if (action === 'clear') { deleteSchedule(currentClassId); }
}
if(target.matches('.copy-code-btn')) {
const code = target.dataset.classCode;
navigator.clipboard.writeText(code).then(() => {
const tooltip = target.querySelector('.tooltip-text');
if (tooltip) { tooltip.textContent = 'Copied!'; setTimeout(() => { tooltip.textContent = target.dataset.tooltipText; }, 2000); }
});
}
if (target.matches('.period-btn')) {
const container = target.closest('.period-selector');
container.querySelectorAll('.period-btn').forEach(btn => btn.classList.remove('active'));
target.classList.add('active');
// Update the associated input's 24-hour data attribute immediately
const inputId = container.id.replace('-period-selector', '-input');
const input = document.getElementById(inputId);
const time12hr = input.value;
const period = target.dataset.value;
// Function to convert 12hr time string to 24hr time string
const to24Hour = (time, period) => {
let [h, m] = time.split(':').map(Number);
if (period === 'PM' && h !== 12) h += 12;
if (period === 'AM' && h === 12) h = 0;
return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}`;
};
// Only calculate/set 24hr time if the input field actually has a value
if(time12hr){
input.dataset.time24hr = to24Hour(time12hr, period);
} else {
input.dataset.time24hr = '';
}
}
});
document.body.addEventListener('submit', async e => {
e.preventDefault();
if(e.target.id === 'create-class-form') { const name = e.target.querySelector('#new-class-name').value.trim(); if(name) createNewClass(name); }
if(e.target.id === 'join-class-form') { const code = e.target.querySelector('#class-code-input').value.trim().toUpperCase(); if(code) joinClass(code); }
if(e.target.id === 'raise-hand-form') { const q = e.target.querySelector('#hand-raise-question').value.trim(); raiseHand(e.target.dataset.classId, q); }
if(e.target.id === 'change-class-name-form') { const newName = e.target.querySelector('#class-name-input').value.trim(); if (newName && currentClassId) handleChangeClassName(currentClassId, newName); }
if(e.target.id === 'request-co-teacher-form') { const comment = e.target.querySelector('#co-teacher-request-comment').value.trim(); requestCoTeacher(e.target.dataset.classId, comment); }
});
const TPL = {
messageModal: (title, message, color = 'blue') => { const c = {'blue':{i:'fa-circle-info',b:'bg-blue-600',t:'text-blue-700',d:'border-blue-400'},'green':{i:'fa-circle-check',b:'bg-green-600',t:'text-green-700',d:'border-green-400'},'red':{i:'fa-triangle-exclamation',b:'bg-red-600',t:'text-red-700',d:'border-red-400'},'yellow':{i:'fa-exclamation',b:'bg-yellow-600',t:'text-yellow-700',d:'border-yellow-400'}}[color]||c['blue']; return `<div class="relative bg-white w-full max-w-sm p-6 rounded-xl shadow-2xl pointer-events-auto text-center border-t-4 ${c.d}"><div class="flex flex-col items-center justify-center"><i class="fa-solid ${c.i} fa-3x ${c.t}"></i><h3 class="mt-4 text-xl font-bold text-gray-800 font-poppins">${escapeHtml(title)}</h3><p class="mt-2 text-gray-600">${escapeHtml(message)}</p></div><div class="mt-6"><button type="button" class="modal-close-btn px-6 py-2 ${c.b} text-white rounded-lg hover:opacity-90 transition-opacity btn-bubbly">OK</button></div></div>`; },
emptyState: (user) => `<div class="h-full flex items-center justify-center text-center fade-enter-active"><div><svg class="w-12 h-12 mx-auto text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg><h2 class="mt-4 text-xl font-semibold font-poppins text-gray-700">Welcome, ${escapeHtml(user?.username||'')}!</h2><p class="mt-1 text-gray-500">Select a class or get started below.</p><div class="mt-6 flex flex-col items-center space-y-4">${user.role==='teacher'?`<button id="new-class-btn" class="bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-blue-700 flex items-center space-x-2 btn-bubbly"><i class="fa-solid fa-plus w-5 h-5"></i><span>New Class</span></button>`:''} <button id="join-class-btn-main" class="bg-green-500 text-white font-semibold py-2 px-4 rounded-lg hover:bg-green-600 btn-bubbly flex items-center space-x-2"><i class="fa-solid fa-user-plus w-5 h-5"></i><span>Join Class</span></button></div></div></div>`,
classView: (cls, user, isOwner, isCoTeacher, queue, pendingRequests, view, roster) => {
const isAnyTeacher = isOwner || isCoTeacher;
const nameChangesLeft = () => { const today=new Date().toISOString().split('T')[0]; const key=`classNameChanges_${cls.id}`; let changes; try { changes=JSON.parse(localStorage.getItem(key))||{}; } catch(e){changes={};} return (changes.date===today)?3-changes.count:3; };
// NEW: Calculate the effective status for teacher/student views
const effectiveStatus = getEffectiveHandRaisingStatus(cls, isOwner);
const dbStatus = cls.handRaisingEnabled === undefined ? true : cls.handRaisingEnabled; // Handle undefined case
const pendingRequestCount = pendingRequests.length;
// UPDATED: timePicker to handle empty values and use placeholder
const timePicker = (id, label, value) => {
const internalValue = value || '00:00';
const isValueEmpty = !value;
const [h24, m] = internalValue.split(':').map(Number);
const period = h24 >= 12 ? 'PM' : 'AM';
let h12 = h24 % 12; if (h12 === 0) h12 = 12;
const timeString = isValueEmpty ? '' : `${String(h12).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
const periodId = id.replace('-input', '-period-selector');
// If empty, the 24hr data attribute should also be empty
const time24hrData = isValueEmpty ? '' : `${String(h24).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
const periodActiveAM = isValueEmpty ? '' : (period === 'AM' ? 'active' : '');
const periodActivePM = isValueEmpty ? '' : (period === 'PM' ? 'active' : '');
return `<div><label class="block text-sm font-medium text-gray-600 mb-2">${label}</label><div class="schedule-time-input-container"><input type="text" id="${id}" value="${timeString}" class="app-input schedule-time-input" data-time-24hr="${time24hrData}" data-digits="${timeString.replace(':','')}" placeholder=" " inputmode="numeric"><div id="${periodId}" class="period-selector"><button type="button" data-value="AM" class="period-btn ${periodActiveAM}">AM</button><button type="button" data-value="PM" class="period-btn ${periodActivePM}">PM</button></div></div></div>`;
};
// Helper to generate a view button. If a view is active, it becomes the overview button.