-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2492 lines (2246 loc) · 113 KB
/
Copy pathscript.js
File metadata and controls
2492 lines (2246 loc) · 113 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
/* ═══════════════════════════════════════════════
WellSpace v2 - script.js
Full application logic
═══════════════════════════════════════════════ */
// ─────────────────────────────────────────────
// CONSTANTS
// ─────────────────────────────────────────────
// ─────────────────────────────────────────────
// XSS PREVENTION - escape any user-supplied text before it goes into
// innerHTML. Use this on every field a student/teacher typed themselves
// (names, class subjects, task/goal text, journal entries, banner
// messages, responsibilities, etc). Never needed for values you fully
// control (hardcoded strings, computed dates, enum labels like mood names).
// ─────────────────────────────────────────────
function escapeHtml(str){
if(str === null || str === undefined) return '';
return String(str)
.replace(/&/g,'&')
.replace(/</g,'<')
.replace(/>/g,'>')
.replace(/"/g,'"')
.replace(/'/g,''');
}
const NEGATIVE_MOODS = ['Sad','Frustrated','Tired','Confused'];
const MOOD_CFG = {
Happy: {icon:'😊', msg:"You're radiating good energy today! Keep it up 🌟"},
Energized: {icon:'⚡', msg:"Amazing - channel that energy into something great!"},
Sad: {icon:'😢', msg:"It's okay to feel sad. Be kind to yourself today 💙"},
Frustrated:{icon:'😤', msg:"Take a breath. This feeling is temporary. You've got this 💪"},
Tired: {icon:'😴', msg:"Rest is productive too. Small breaks help a lot 🌙"},
Confused: {icon:'🤔', msg:"Confusion is the beginning of learning. Ask for help!"},
};
const DAYS = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
const PROVINCES = ['Ontario','British Columbia','Alberta','Quebec','Nova Scotia','New Brunswick','Manitoba','Saskatchewan','PEI','Newfoundland & Labrador','Northwest Territories','Nunavut','Yukon'];
// Helpline data by province
const HELPLINES = {
Ontario: {
phone:[
{name:"Kids Help Phone",desc:"Free support for young people (24/7, confidential)",url:"https://www.kidshelpphone.ca",contact:"📞 1-800-668-6868 | Text CONNECT to 686868"},
{name:"Good2Talk",desc:"Counselling & referrals for post-secondary students",url:"https://www.good2talk.ca",contact:"📞 1-866-925-5454 | Online chat 24/7"},
{name:"ConnexOntario",desc:"Mental health, addiction & crisis services info/referral",url:"https://www.connexontario.ca",contact:"📞 1-866-531-2600"},
{name:"One Stop Talk",desc:"Free therapy sessions for youth ages 6-18",url:"https://onestoptalk.ca",contact:"📞 1-855-416-8255"},
{name:"Canada Suicide Prevention Service",desc:"English/French, 24/7",url:"https://www.crisisservicescanada.ca",contact:"📞 1-833-456-4566"},
{name:"Hope for Wellness Help Line",desc:"24/7 counselling for Indigenous Peoples",url:"https://hopeforwellness.ca/home.html",contact:"📞 1-855-242-3310"},
],
online:[
{name:"Youth Wellness Hubs Ontario",desc:"In-person supports ages 12-25",url:"https://youthhubs.ca/en/"},
{name:"Ontario Mental Health Support Directory",desc:"Government directory of local supports",url:"https://www.ontario.ca/page/find-mental-health-support"},
{name:"School Mental Health Ontario - Helpline Hub",desc:"Crisis & wellness info for students",url:"https://smho-smso.ca/students/helpline-hub/"},
{name:"Be There",desc:"Tips on supporting friends & yourself",url:"https://bethere.org/Home"},
{name:"Mind Your Mind",desc:"Youth mental health tools & info",url:"https://mindyourmind.ca"},
]
},
"British Columbia":{
phone:[
{name:"Kids Help Phone",url:"https://www.kidshelpphone.ca",contact:"📞 1-800-668-6868 | Text CONNECT to 686868",desc:"24/7 free support"},
{name:"BC Crisis Line",url:"https://www.crisiscentre.bc.ca",contact:"📞 1-866-661-3311",desc:"24/7 emotional support"},
{name:"YouthSpace BC",url:"https://www.youthspace.ca",contact:"Text 778-783-0177",desc:"Youth crisis chat & text"},
],
online:[
{name:"Here2Talk BC",desc:"Free counselling for post-secondary students",url:"https://here2talk.ca"},
{name:"BC Mental Health & Substance Use",desc:"Provincial resources & directory",url:"https://www.bcmhsus.ca"},
]
},
Alberta:{
phone:[
{name:"Kids Help Phone",url:"https://www.kidshelpphone.ca",contact:"📞 1-800-668-6868",desc:"24/7 free support"},
{name:"Distress Centre Calgary",url:"https://www.distresscentre.com",contact:"📞 403-266-HELP (4357)",desc:"24/7 crisis & mental health"},
{name:"211 Alberta",url:"https://ab.211.ca",contact:"📞 2-1-1",desc:"Connect to social & mental health services"},
],
online:[
{name:"Alberta Health Services-Mental Health",desc:"Provincial mental health services",url:"https://www.albertahealthservices.ca/findhealth/service.aspx?id=6810&serviceAtFacilityID=1047652"},
]
},
default:{
phone:[
{name:"Kids Help Phone",desc:"Free support for young people across Canada (24/7)",url:"https://www.kidshelpphone.ca",contact:"📞 1-800-668-6868 | Text CONNECT to 686868"},
{name:"Canada Suicide Prevention Service",desc:"English/French, 24/7",url:"https://www.crisisservicescanada.ca",contact:"📞 1-833-456-4566"},
{name:"Hope for Wellness Help Line",desc:"24/7 counselling for Indigenous Peoples",url:"https://hopeforwellness.ca",contact:"📞 1-855-242-3310"},
],
online:[
{name:"Be There",desc:"Supporting yourself and friends",url:"https://bethere.org/Home"},
]
}
};
// ─────────────────────────────────────────────
// STATE
// ─────────────────────────────────────────────
let CU = null;
let authRole = null;
let pendingMoodSel = null;
let periodOrder = [];
// ─────────────────────────────────────────────
// FIREBASE CONFIG
// ─────────────────────────────────────────────
const FB_CFG = {
apiKey: "AIzaSyCpUsu0Y2zbd7PH6a8b-NP6B7yEB7UL9Go",
authDomain: "wellspace-71c0c.firebaseapp.com",
projectId: "wellspace-71c0c",
};
let fbDb = null;
let fbAuth = null;
function initFirebase(){
try {
if(!firebase.apps.length) firebase.initializeApp(FB_CFG);
fbDb = firebase.firestore();
fbAuth = firebase.auth();
} catch(e){ fbDb = null; fbAuth = null; }
}
// ─────────────────────────────────────────────
// GLOBAL SAFETY NET - catches anything that slips
// past a local try/catch, plus offline/online state
// ─────────────────────────────────────────────
window.addEventListener('error', function(e){
console.error('Uncaught error:', e.error || e.message);
toast('⚠️ Something went wrong. Try refreshing the page.');
});
window.addEventListener('unhandledrejection', function(e){
console.error('Unhandled promise rejection:', e.reason);
toast('⚠️ Something went wrong. Try refreshing the page.');
});
window.addEventListener('offline', function(){
toast('📡 You\'re offline — changes will save once you\'re back online.');
});
window.addEventListener('online', function(){
toast('✅ Back online.');
});
// ─────────────────────────────────────────────
// FIRESTORE HELPERS - per-user + shared
// ─────────────────────────────────────────────
// Save a key to the current user's private Firestore doc
async function fsSet(key, value){
if(!fbDb || !fbAuth?.currentUser) return;
try {
await fbDb.collection('users').doc(fbAuth.currentUser.uid)
.set({ [key]: JSON.stringify(value) }, { merge: true });
} catch(e){
console.error('fsSet failed for key', key, e);
toast('⚠️ Could not save - check your connection and try again.');
}
}
// Read a key from the current user's private Firestore doc
async function fsGet(key, def=null){
if(!fbDb || !fbAuth?.currentUser) return def;
try {
const doc = await fbDb.collection('users').doc(fbAuth.currentUser.uid).get();
if(!doc.exists) return def;
const val = doc.data()[key];
return val ? JSON.parse(val) : def;
} catch(e){ return def; }
}
// Save to shared collection (class codes, classes list - readable by all authenticated users)
async function fsSetShared(key, value){
if(!fbDb) return;
try {
await fbDb.collection('shared').doc('data')
.set({ [key]: JSON.stringify(value) }, { merge: true });
} catch(e){
console.error('fsSetShared failed for key', key, e);
toast('⚠️ Could not save - check your connection and try again.');
}
}
// Read from shared collection
async function fsGetShared(key, def=null){
if(!fbDb) return def;
try {
const doc = await fbDb.collection('shared').doc('data').get();
if(!doc.exists) return def;
const val = doc.data()?.[key];
return val ? JSON.parse(val) : def;
} catch(e){ return def; }
}
// ─────────────────────────────────────────────
// JOURNALS - dedicated owner-only collection.
// Journals used to be embedded as a field inside /users/{uid} alongside
// moods/goals/wellness. That doc's read rule grants access to any teacher
// whose uid is in the student's teacherUids, so once a student joined a
// class, their journal entries were reachable by that teacher via direct
// Firestore access - even though the UI itself never surfaced them. The
// security rules already define /journals/{uid} as owner-only with no
// exceptions; these helpers actually route writes/reads there so that
// rule is the one doing the work.
// ─────────────────────────────────────────────
async function fsSetJournal(uid, journals){
if(!fbDb || !uid) return;
try {
await fbDb.collection('journals').doc(uid).set({ entries: JSON.stringify(journals) }, { merge: true });
} catch(e){
console.error('fsSetJournal failed', e);
toast('⚠️ Could not save your journal - check your connection and try again.');
}
}
async function fsGetJournal(uid){
if(!fbDb || !uid) return [];
try {
const doc = await fbDb.collection('journals').doc(uid).get();
if(!doc.exists) return [];
return JSON.parse(doc.data().entries || '[]');
} catch(e){ return []; }
}
// ─────────────────────────────────────────────
// LOCAL CACHE - fast reads, Firestore is source of truth
// ─────────────────────────────────────────────
const cache = {};
function cSet(k, v){ cache[k] = v; }
function cGet(k, def=null){ return k in cache ? cache[k] : def; }
// Keys that are shared across all users (classes, class codes)
const SHARED_KEYS = ['classes'];
// Keys that belong to all users but need to be read by teachers (moods, wellness, goals, responsibilities)
// These are stored per-user but teachers read their students' docs
const CROSS_KEYS = ['moods','goals','wellness','responsibilities','journals','messages'];
// Keys private to one user
const PRIVATE_KEYS= ['students','teachers'];
// ─────────────────────────────────────────────
// UNIFIED S - same API as before, now Firestore-backed
// ─────────────────────────────────────────────
const S = {
get(k, def=null){
// Return from cache first for speed
return cGet(k, def);
},
set(k, v){
cSet(k, v);
// Persist to correct Firestore location
if(k === 'journals'){
// Journals are private-by-rule and live in their own collection -
// see fsSetJournal for why this can't just fall through to fsSet().
if(fbAuth?.currentUser) fsSetJournal(fbAuth.currentUser.uid, v);
} else if(SHARED_KEYS.includes(k)){
fsSetShared(k, v);
} else {
fsSet(k, v);
}
},
};
// Shortcuts - same as original
const gs = ()=> S.get('students',[]);
const gt = ()=> S.get('teachers',[]);
const gc = ()=> S.get('classes',[]);
const gm = ()=> S.get('moods',[]);
const ggo = ()=> S.get('goals',[]);
const gw = ()=> S.get('wellness',[]);
const gmsg= ()=> S.get('messages',[]);
const gj = ()=> S.get('journals',[]);
// ─────────────────────────────────────────────
// LOAD USER DATA FROM FIRESTORE INTO CACHE
// (single, de-duplicated version - also loads profile + per-doc classes)
// ─────────────────────────────────────────────
async function loadUserData(){
if(!fbDb || !fbAuth?.currentUser) return;
try {
// Load user's private data from /users/{uid}
const userDoc = await fbDb.collection('users').doc(fbAuth.currentUser.uid).get();
if(userDoc.exists){
const data = userDoc.data();
Object.entries(data).forEach(([k,v])=>{
try{ cSet(k, JSON.parse(v)); }catch{}
});
// MIGRATION: journals used to be stored inline in this doc, which a
// linked teacher could technically read directly from Firestore even
// though the UI never showed them. Move any old entries into the
// owner-only /journals/{uid} collection and scrub them out of here.
if(data.journals){
try{
const oldJournals = JSON.parse(data.journals);
const existingJournals = await fsGetJournal(fbAuth.currentUser.uid);
const merged = [...existingJournals, ...oldJournals];
await fsSetJournal(fbAuth.currentUser.uid, merged);
await fbDb.collection('users').doc(fbAuth.currentUser.uid)
.update({ journals: firebase.firestore.FieldValue.delete() });
} catch(e){ console.error('journal migration failed', e); }
}
}
// Load journals from their dedicated owner-only collection (source of
// truth going forward - never from /users/{uid}).
const journals = await fsGetJournal(fbAuth.currentUser.uid);
cSet('journals', journals);
// ALSO load profile data (classIds, name, etc.) from /profiles/{uid}
const profileDoc = await fbDb.collection('profiles').doc(fbAuth.currentUser.uid).get();
if(profileDoc.exists){
const pdata = profileDoc.data();
if(CU){
if(pdata.classIds) CU.classIds = pdata.classIds;
if(pdata.name) CU.name = pdata.name;
if(pdata.grade) CU.grade = pdata.grade;
if(pdata.periodOrder) CU.periodOrder = pdata.periodOrder;
}
}
// Load shared data (classes) - legacy blob, for backwards compatibility
const sharedDoc = await fbDb.collection('shared').doc('data').get();
if(sharedDoc.exists){
const data = sharedDoc.data();
['classes'].forEach(k=>{
if(data[k]){ try{ cSet(k, JSON.parse(data[k])); }catch{} }
});
}
// Load from new per-doc classes collection (this is the source of truth going forward)
const classes = await fsGetAllClasses();
if(classes.length) cSet('classes', classes);
} catch(e){ console.error('loadUserData error', e); }
}
// ─────────────────────────────────────────────
// STUDENT-TEACHER LINK - store uid mapping
// ─────────────────────────────────────────────
// When a user signs up we store their profile in /profiles/{uid}
// So teachers can look up student uids to read their data
async function saveProfile(uid, profile){
if(!fbDb) return;
try {
await fbDb.collection('profiles').doc(uid).set(profile, { merge: true });
} catch(e){
console.error('saveProfile failed', e);
toast('⚠️ Could not save your profile - check your connection and try again.');
}
}
async function getProfile(uid){
if(!fbDb) return null;
try {
const doc = await fbDb.collection('profiles').doc(uid).get();
return doc.exists ? doc.data() : null;
} catch(e){ return null; }
}
// ─────────────────────────────────────────────
// TEACHER LINK BACKFILL - some student profiles may be missing
// teacherUids because they joined a class (either via joinClass() or
// via the signup-with-code flow) before teacherUids tracking existed,
// or through a code path that never set it. Security rules require
// teacherUids to grant a teacher read access to a student's data, so
// this repairs any student profile that's missing a link for a class
// they're already in. Safe to call on every login - it's a no-op once
// a profile is caught up, and joinClass() already sets this correctly
// for brand-new joins going forward.
// ─────────────────────────────────────────────
async function ensureTeacherLinks(){
if(!CU || CU.role !== 'student' || !fbAuth?.currentUser) return;
if(!CU.classIds?.length) return;
const classes = gc().length ? gc() : await fsGetAllClasses();
const existingTeacherUids = new Set(CU.teacherUids || []);
let changed = false;
CU.classIds.forEach(classId=>{
const cls = classes.find(c=>c.id===classId);
const teacherUid = cls?.teacherUid || cls?.teacherId;
if(teacherUid && !existingTeacherUids.has(teacherUid)){
existingTeacherUids.add(teacherUid);
changed = true;
}
});
if(changed){
CU.teacherUids = [...existingTeacherUids];
try {
await fbDb.collection('profiles').doc(fbAuth.currentUser.uid)
.set({ teacherUids: CU.teacherUids }, { merge: true });
} catch(e){ console.error('ensureTeacherLinks failed', e); }
}
}
// Get all student profiles for this teacher.
//
// FIX: this used to query `.where('classIds','array-contains-any', chunk)`
// and rely on the /profiles read rule (which checks `teacherUids`, not
// `classIds`) to gate access. Firestore rejects an entire list query if
// the security rule can't be validated purely from the query's own where
// clauses - since the rule checked a field the query didn't filter on,
// every call came back `permission-denied` for the WHOLE query. The old
// catch block only toasted on `failed-precondition` (missing index), so
// this specific failure was silent: students joined classes fine, but
// teachers never saw them or any of their shared data, with no visible
// error anywhere.
//
// Querying directly on `teacherUids array-contains teacherUid` matches
// the rule exactly, so Firestore can validate the query and actually
// return results. This also removes the old 10-item chunking, which was
// only needed for `array-contains-any`'s limit - plain `array-contains`
// has no such cap.
async function getStudentUids(teacherUid){
if(!fbDb || !teacherUid) return [];
try {
const snap = await fbDb.collection('profiles')
.where('role','==','student')
.where('teacherUids','array-contains', teacherUid)
.get();
return snap.docs.map(d => ({ uid: d.id, ...d.data() }));
} catch(e){
console.error('getStudentUids error', e);
if(e.code === 'failed-precondition' || /index/i.test(e.message||'')){
toast('⚠️ Missing Firestore index for student lookup — check the browser console for a link to create it.');
} else if(e.code === 'permission-denied'){
toast('⚠️ Could not load students — permission denied. Check that student profiles have teacherUids set.');
} else {
toast('⚠️ Could not load students — check the browser console for details.');
}
}
return [];
}
// Load a single student's full data doc (used by the teacher dashboard)
async function loadStudentData(uid){
if(!fbDb) return {};
try {
const doc = await fbDb.collection('users').doc(uid).get();
if(!doc.exists) return {};
const raw = doc.data();
const parsed = {};
Object.entries(raw).forEach(([k,v])=>{
try{ parsed[k] = JSON.parse(v); }catch{ parsed[k] = v; }
});
// Ensure a 'students' entry always exists, built from the profile if missing,
// so the teacher dashboard can always render a row for this student.
if(!parsed.students){
const profile = await getProfile(uid);
if(profile){
parsed.students = [{
id: profile.localId || uid,
name: profile.name,
email: profile.email,
grade: profile.grade,
classIds: profile.classIds || [],
periodOrder: profile.periodOrder || [],
joined: profile.joined,
}];
}
}
return parsed;
} catch(e){ console.error('loadStudentData error', e); return {}; }
}
// Merge an array of records into another array by a unique key (studentId + extra fields),
// replacing any existing record for that student/date/type combo so re-fetches don't duplicate.
function mergeInto(target, incoming, keyField){
incoming.forEach(item=>{
const idx = target.findIndex(t => t.id && item.id && t.id === item.id);
if(idx >= 0) target[idx] = item;
else target.push(item);
});
}
// ─────────────────────────────────────────────
// VALIDATION
// ─────────────────────────────────────────────
function validEmail(e){
return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e.trim());
}
function validPw(p){
return p.length>=8 && /[A-Z]/.test(p) && /[0-9]/.test(p) && /[!@#$%^&*(),.?":{}|<>]/.test(p);
}
function checkPwStrength(v){
const rules = {
'r-len': v.length>=8,
'r-upper': /[A-Z]/.test(v),
'r-num': /[0-9]/.test(v),
'r-special':/[!@#$%^&*(),.?":{}|<>]/.test(v),
};
let score = Object.values(rules).filter(Boolean).length;
const fill = document.getElementById('pw-strength-fill');
const colors = ['','#ef4444','#f59e0b','#3b82f6','#22c55e'];
if(fill){ fill.style.width=(score*25)+'%'; fill.style.background=colors[score]||''; }
Object.entries(rules).forEach(([id,ok])=>{
const el=document.getElementById(id);
if(el){ el.classList.toggle('ok',ok); }
});
}
function togglePw(id,btn){
const inp=document.getElementById(id);
if(!inp)return;
if(inp.type==='password'){ inp.type='text'; btn.textContent='🙈'; }
else{ inp.type='password'; btn.textContent='👁'; }
}
// ─────────────────────────────────────────────
// SCREEN NAVIGATION
// ─────────────────────────────────────────────
function showScreen(id){
document.querySelectorAll('.screen').forEach(s=>{
s.classList.remove('active','fade');
s.style.display='none';
s.style.flexDirection='';
});
const el=document.getElementById(id);
if(!el)return;
el.style.display='flex';
if(id==='screen-student'||id==='screen-teacher') el.style.flexDirection='column';
el.classList.add('active','fade');
}
function gotoAuth(role){
authRole=role;
const brand=document.getElementById('auth-brand-label');
brand.textContent = role==='student' ? '🎒 Student Login' : '📋 Teacher Login';
document.getElementById('su-student-fields').classList.toggle('hidden', role!=='student');
document.getElementById('su-teacher-fields').classList.toggle('hidden', role!=='teacher');
authTab('login');
showScreen('screen-auth');
}
function authTab(tab){
document.getElementById('form-login').classList.toggle('hidden', tab!=='login');
document.getElementById('form-signup').classList.toggle('hidden', tab!=='signup');
document.getElementById('atab-login').classList.toggle('active', tab==='login');
document.getElementById('atab-signup').classList.toggle('active', tab!=='login');
}
// ─────────────────────────────────────────────
// COOKIE CONSENT - synced to the account, not just the browser
// So the consent question only ever gets asked once per account,
// even if the student logs in on a different device later.
// ─────────────────────────────────────────────
async function saveCookieConsentToAccount(accepted){
if(!fbAuth?.currentUser) return; // not logged in yet, localStorage handles it for now
try {
await fbDb.collection('profiles').doc(fbAuth.currentUser.uid).set(
{ cookieConsent: accepted, cookieConsentDate: today() },
{ merge: true }
);
} catch(e){ console.error('saveCookieConsentToAccount failed', e); }
}
window.saveCookieConsentToAccount = saveCookieConsentToAccount;
async function syncCookieConsentAfterLogin(uid){
try {
const profile = await getProfile(uid);
const banner = document.getElementById('cookie-banner');
if(profile && typeof profile.cookieConsent === 'boolean'){
// Account already answered before (maybe on another device) - use that,
// don't ask again.
localStorage.setItem('wellspace_cookie_consent', profile.cookieConsent ? 'accepted' : 'declined');
if(banner) banner.classList.add('hidden');
if(profile.cookieConsent && typeof loadGoogleAnalytics==='function') loadGoogleAnalytics();
} else {
// Account has no answer yet. If this browser already answered
// (e.g. they chose on the entry screen before logging in), save
// that answer to the account now so it's remembered going forward.
const local = localStorage.getItem('wellspace_cookie_consent');
if(local === 'accepted' || local === 'declined'){
await saveCookieConsentToAccount(local === 'accepted');
}
}
} catch(e){ console.error('syncCookieConsentAfterLogin failed', e); }
}
// ─────────────────────────────────────────────
// AUTH - LOGIN (Firebase Auth)
// ─────────────────────────────────────────────
async function doLogin(){
const email = document.getElementById('login-email').value.trim().toLowerCase();
const pass = document.getElementById('login-pass').value;
const errEl = document.getElementById('login-err');
if(!email||!pass) return showErr(errEl,'Please enter your email and password.');
if(!validEmail(email)) return showErr(errEl,'Please enter a valid email address.');
try {
showErr(errEl,''); // clear error
const cred = await fbAuth.signInWithEmailAndPassword(email, pass);
const uid = cred.user.uid;
// Load profile
const profile = await getProfile(uid);
if(!profile) return showErr(errEl,'Account not found. Please sign up.');
// Check role matches
if(profile.role !== authRole) return showErr(errEl, `This is a ${profile.role} account. Please use the ${profile.role} login.`);
CU = { ...profile, id: profile.localId || uid, uid };
await loadUserData();
await ensureTeacherLinks();
syncCookieConsentAfterLogin(uid);
toast(`Welcome back, ${CU.name}! 👋`);
if(authRole==='student') loadStudentDash();
else { await loadTeacherStudents(); loadTeacherDash(); }
} catch(e){
if(e.code==='auth/wrong-password'||e.code==='auth/user-not-found'||e.code==='auth/invalid-credential'){
showErr(errEl,'Email or password incorrect. Check your details.');
} else {
showErr(errEl,'Login failed. Please try again.');
}
}
}
// ─────────────────────────────────────────────
// AUTH - SIGNUP (Firebase Auth)
// ─────────────────────────────────────────────
async function doSignup(){
const name = document.getElementById('su-name').value.trim();
const email = document.getElementById('su-email').value.trim().toLowerCase();
const pass = document.getElementById('su-pass').value;
const privacyOk = document.getElementById('su-privacy').checked;
const errEl = document.getElementById('signup-err');
if(!name||!email||!pass) return showErr(errEl,'Please fill in all required fields.');
if(!validEmail(email)) return showErr(errEl,'Please enter a valid email address.');
if(!validPw(pass)) return showErr(errEl,'Password must be 8+ chars with uppercase, number & special character.');
if(!privacyOk) return showErr(errEl,'Please accept the privacy policy to continue.');
try {
if(authRole==='student'){
const grade = document.getElementById('su-grade').value;
const code = document.getElementById('su-code').value.trim().toUpperCase();
if(!grade) return showErr(errEl,'Please select your grade.');
// Look up class code in the per-doc classes collection (source of truth)
const classes = await fsGetAllClasses();
cSet('classes', classes);
let classIds = [];
if(code){
const cls = classes.find(c=>c.code===code);
if(!cls) return showErr(errEl,`Class code "${code}" not found. Ask your teacher for the correct code.`);
classIds = [cls.id];
}
// Create Firebase Auth account
const cred = await fbAuth.createUserWithEmailAndPassword(email, pass);
const uid = cred.user.uid;
const localId = 's'+uid8();
const profile = { role:'student', name, email, grade, classIds, periodOrder:[], joined:today(), localId, uid };
// Save profile to shared profiles collection (this is what teachers query)
await saveProfile(uid, profile);
// Save student list entry to user's own doc
const studentEntry = { id:localId, name, email, grade, classIds, periodOrder:[], joined:today() };
cSet('students', [studentEntry]);
await fsSet('students', [studentEntry]);
CU = { ...profile, id: localId };
await loadUserData();
await ensureTeacherLinks();
toast(`Account created! Welcome, ${name} 🎉`);
loadStudentDash();
} else {
const province = document.getElementById('su-province').value;
const school = document.getElementById('su-school').value.trim();
if(!province) return showErr(errEl,'Please select your province.');
const cred = await fbAuth.createUserWithEmailAndPassword(email, pass);
const uid = cred.user.uid;
const localId = 't'+uid8();
const profile = { role:'teacher', name, email, province, school, socialWorker:null, joined:today(), localId, uid };
await saveProfile(uid, profile);
const teacherEntry = { id:localId, name, email, province, school, socialWorker:null, joined:today() };
cSet('teachers', [teacherEntry]);
await fsSet('teachers', [teacherEntry]);
CU = { ...profile, id: localId };
await loadUserData();
toast(`Account created! Welcome, ${name} 📋`);
loadTeacherDash();
}
} catch(e){
if(e.code==='auth/email-already-in-use'){
showErr(errEl,'An account with this email already exists.');
} else {
showErr(errEl,'Could not create account. Please try again.');
console.error(e);
}
}
}
function logout(){
CU=null; authRole=null;
pendingMoodSel=null;
Object.keys(cache).forEach(k=>delete cache[k]);
invalidateTeacherCache();
if(fbAuth) fbAuth.signOut().catch(()=>{});
showScreen('screen-entry');
}
// ─────────────────────────────────────────────
// TEACHER - load students across Firestore docs
// Cached for 60s so the dashboard doesn't re-read everything on every click.
// ─────────────────────────────────────────────
let _teacherStudentCache = null;
let _teacherStudentCacheTime = 0;
const TEACHER_CACHE_TTL = 60 * 1000; // 60 seconds
async function loadTeacherStudents(){
const now = Date.now();
// Serve from cache if fresh
if (_teacherStudentCache && (now - _teacherStudentCacheTime) < TEACHER_CACHE_TTL) {
Object.entries(_teacherStudentCache).forEach(([k, v]) => cSet(k, v));
return;
}
const myClasses = gc().filter(c => c.teacherId === CU.id);
const myClassIds = myClasses.map(c => c.id);
if (!myClassIds.length) {
// No classes yet - clear any stale student data and bail
cSet('students', []);
return;
}
try {
// FIX: query on the teacher's uid (matches the /profiles security rule)
// instead of passing classIds into getStudentUids - see comment on
// getStudentUids for why the old classIds-based query was silently
// returning permission-denied for the whole query.
const studentProfiles = await getStudentUids(CU.uid);
const allStudents = [];
const allMoods = cGet('moods', []);
const allGoals = cGet('goals', []);
const allWellness = cGet('wellness', []);
const allResps = cGet('responsibilities', []);
for (const sp of studentProfiles) {
const data = await loadStudentData(sp.uid);
if (data.students) {
// Only add students who are actually in one of this teacher's classes
const myStudents = data.students.filter(s =>
s.classIds && s.classIds.some(id => myClassIds.includes(id))
);
allStudents.push(...myStudents);
}
if (data.moods) mergeInto(allMoods, data.moods, 'studentId');
if (data.goals) mergeInto(allGoals, data.goals, 'studentId');
if (data.wellness) mergeInto(allWellness, data.wellness, 'studentId');
if (data.responsibilities) mergeInto(allResps, data.responsibilities, 'studentId');
}
cSet('students', allStudents);
cSet('moods', allMoods);
cSet('goals', allGoals);
cSet('wellness', allWellness);
cSet('responsibilities', allResps);
_teacherStudentCache = {
students: allStudents,
moods: [...allMoods],
goals: [...allGoals],
wellness: [...allWellness],
responsibilities: [...allResps],
};
_teacherStudentCacheTime = now;
} catch (e) { console.error('loadTeacherStudents error', e); }
}
// Call this after any action that changes student/class data, so the next
// dashboard read pulls fresh data instead of serving the 60s cache.
function invalidateTeacherCache(){
_teacherStudentCache = null;
_teacherStudentCacheTime = 0;
}
// ─────────────────────────────────────────────
// STUDENT DASHBOARD
// ─────────────────────────────────────────────
function loadStudentDash(){
showScreen('screen-student');
const el=document.getElementById('screen-student');
el.style.display='flex'; el.classList.add('active');
const h=new Date().getHours();
const gr=h<12?'Good morning':h<17?'Good afternoon':'Good evening';
document.getElementById('s-greet').textContent=`${gr}, ${CU.name}! 👋`;
document.getElementById('s-date').textContent=new Date().toLocaleDateString('en-CA',{weekday:'long',month:'long',day:'numeric'});
document.getElementById('s-av').textContent=CU.name[0].toUpperCase();
updateStudentNav();
sSection('home');
}
function hasClasses(){
return CU.classIds && CU.classIds.length > 0;
}
function updateStudentNav(){
const navItems = document.querySelectorAll('#s-sidebar .sn');
if(navItems[8]) navItems[8].style.display = '';
}
function sSection(name){
document.querySelectorAll('#s-sidebar .sn').forEach(n=>n.classList.remove('active'));
const navMap=['home','mood','goals','calendar','stats','wellness','help','classes','profile'];
const idx=navMap.indexOf(name);
const navItems=document.querySelectorAll('#s-sidebar .sn');
if(navItems[idx]) navItems[idx].classList.add('active');
document.querySelectorAll('#s-main .dsec').forEach(s=>s.classList.remove('active'));
const sec=document.getElementById('s-sec-'+name);
if(sec) sec.classList.add('active');
if(name==='home') renderHome();
if(name==='mood') renderMoodCheck();
if(name==='goals') renderGoalsSection();
if(name==='calendar') renderCalendar();
if(name==='stats') renderStats();
if(name==='wellness') renderWellnessSection();
if(name==='help') renderHelpSection();
if(name==='classes') renderClassesSection();
if(name==='profile') renderStudentProfile();
}
// HOME
function renderHome(){
const hour=new Date().getHours();
const bannerEl=document.getElementById('s-home-banner');
const msgs=[
[5,11,"Morning, {n}! 🌅 Start your day with intention."],
[11,14,"Hey {n}! 🌤 It's the middle of the day - how are you feeling?"],
[14,18,"Afternoon, {n}! 📚 Great time to focus on your most important tasks."],
[18,21,"Evening, {n}! 🌙 Wind down your work and get ready for tomorrow."],
[21,24,"Late night, {n}! 😴 Remember - sleep is the best productivity tool."],
[0,5,"Very late, {n}! 🌙 You need rest. Your goals will be here tomorrow."],
];
const [, , msg] = msgs.find(([s,e])=>hour>=s&&hour<e)||msgs[0];
bannerEl.innerHTML=`<strong>${msg.replace('{n}',escapeHtml(CU.name))}</strong><p>${new Date().toLocaleDateString('en-CA',{weekday:'long',month:'long',day:'numeric',year:'numeric'})}</p>`;
const goals=ggo().filter(g=>g.studentId===CU.id&&!g.done).slice(0,4);
const todayDay=new Date().toLocaleDateString('en-CA',{weekday:'long'});
const todayGoals=goals.filter(g=>g.day===todayDay);
const prevEl=document.getElementById('s-home-goals-preview');
if(todayGoals.length>0){
prevEl.innerHTML=`
<div class="sub-hdr" style="margin-top:0">Today's Tasks (${todayDay})</div>
${todayGoals.map(g=>`
<div class="goal-row" style="margin-bottom:8px">
<div class="gcheck ${g.done?'checked':''}" role="button" tabindex="0" aria-pressed="${g.done?'true':'false'}" aria-label="Mark ${escapeHtml(g.task)} as ${g.done?'not done':'done'}" onclick="quickToggleGoal('${g.id}');" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();quickToggleGoal('${g.id}');}">${g.done?'✓':''}</div>
<div class="ginfo"><h5>${escapeHtml(g.task)}</h5><span class="gmeta">🕐 ${escapeHtml(g.time)} · ${escapeHtml(g.duration)}</span></div>
<span class="gtype-badge gtype-${g.type||'study'}">${typeLabel(g.type)}</span>
</div>
`).join('')}
`;
} else {
prevEl.innerHTML=`<div class="ai-nudge" style="margin-top:16px"><div class="ai-nudge-icon">🎯</div><div><strong>No tasks for today yet</strong><p>Head to Goals to plan your day!</p></div></div>`;
}
}
// MOOD CHECK
function renderMoodCheck(){
const myClasses = gc().filter(c => CU.classIds && CU.classIds.includes(c.id));
const todayMoods = gm().filter(m => m.studentId === CU.id && m.date === today());
const container = document.getElementById('s-mood-list');
const hasTeacher = hasClasses();
const items = [
...(hasTeacher ? myClasses.map(c => ({id:c.id, label:c.subject, time:`${c.startTime} - ${c.endTime}`, isClass:true})) : []),
{id:'general', label:'How are you feeling today?', time:'', isClass:false},
];
const sub = document.querySelector('#s-sec-mood .sec-hdr p');
if(sub) sub.textContent = hasTeacher ? 'How are you feeling in each period today?' : 'Check in with yourself - just for you 🌱';
container.innerHTML = items.map(item => {
const existing = todayMoods.find(m => m.classId === item.id);
const shareButtons = hasTeacher
? `<button class="btn-green" onclick="saveMood(true)">Share with Teacher</button>
<button class="btn-outline" onclick="saveMood(false)">Keep Private</button>`
: `<button class="btn-green" onclick="saveMood(false)">Save</button>`;
return `
<div class="mood-card">
<div class="mood-card-hdr">
<h4>${item.isClass ? '📚 ' : ''}${escapeHtml(item.label)}</h4>
${item.time ? `<span class="cls-time">${escapeHtml(item.time)}</span>` : ''}
</div>
<div class="mood-btns">
${Object.keys(MOOD_CFG).map(mood=>`
<button class="mood-btn ${existing?.mood===mood?'sel':''}" data-m="${mood}"
onclick="selectMood('${item.id}','${escQ(item.label)}','${mood}')">
${MOOD_CFG[mood].icon} ${mood}
</button>
`).join('')}
</div>
${existing ? `<div class="mood-done">✓ Mood logged${hasTeacher && existing.shared ? ' · Shared with teacher' : ' · Private'}</div>` : ''}
</div>
<div id="mood-support-popup-${item.id}" class="support-popup hidden">
<div class="sp-inner">
<div id="sp-icon-${item.id}" class="sp-icon"></div>
<p id="sp-msg-${item.id}"></p>
<div class="sp-actions">${shareButtons}</div>
</div>
</div>
`;
}).join('');
}
function escQ(s){ return s.replace(/'/g,"\\'"); }
function selectMood(classId, classLabel, mood){
document.querySelectorAll('.support-popup').forEach(p => p.classList.add('hidden'));
pendingMoodSel = {classId, classLabel, mood};
const cfg = MOOD_CFG[mood];
const popup = document.getElementById(`mood-support-popup-${classId}`);
const iconEl = document.getElementById(`sp-icon-${classId}`);
const msgEl = document.getElementById(`sp-msg-${classId}`);
if(popup && iconEl && msgEl){
iconEl.textContent = cfg.icon;
msgEl.textContent = cfg.msg;
popup.classList.remove('hidden');
}
if(NEGATIVE_MOODS.includes(mood)){
if(!S.get('sw_dismissed_' + CU.id)){
setTimeout(() => showSWPopup(mood), 1500);
}
}
}
function saveMood(shared){
if(!pendingMoodSel) return;
const moods = gm().filter(m => !(m.studentId===CU.id && m.classId===pendingMoodSel.classId && m.date===today()));
moods.push({studentId:CU.id, classId:pendingMoodSel.classId, classLabel:pendingMoodSel.classLabel, mood:pendingMoodSel.mood, date:today(), shared});
S.set('moods', moods);
pendingMoodSel = null;
document.querySelectorAll('.support-popup').forEach(p => p.classList.add('hidden'));
toast('Mood saved! ' + (shared && hasClasses() ? 'Shared with teacher.' : 'Saved privately.'));
renderMoodCheck();
}
function showSWPopup(mood){
if(sessionStorage.getItem('sw_popup_shown')) return;
let swInfo = null;
if(hasClasses()){
const myClasses = gc().filter(c => CU.classIds && CU.classIds.includes(c.id));
if(myClasses.length > 0){
const teacher = gt().find(t => t.id === myClasses[0].teacherId);
if(teacher?.socialWorker) swInfo = teacher.socialWorker;
}
}
const contactEl = document.getElementById('sw-contact-display');
if(swInfo){
contactEl.innerHTML = `
<div class="sw-contact-box">
<strong>Your School Social Worker</strong>
<div>${escapeHtml(swInfo.name)}</div>
<div><a href="mailto:${escapeHtml(swInfo.email)}">${escapeHtml(swInfo.email)}</a></div>
<p style="font-size:.78rem;color:var(--muted);margin-top:6px">They won't be notified automatically - this is just their contact info.</p>
</div>`;
} else {
contactEl.innerHTML = `<div class="sw-contact-box"><strong>💙 Help is available</strong><p style="font-size:.88rem;margin-top:4px">Head to Help & Crisis for 24/7 support lines.</p></div>`;
}
document.getElementById('sw-popup').classList.remove('hidden');
sessionStorage.setItem('sw_popup_shown', '1');
}
function dismissSWPopup(dontShowAgain){
closeModal('sw-popup');
if(dontShowAgain){
S.set('sw_dismissed_' + CU.id, true);
toast("Got it - we won't show this again 👍");
}
}
// GOALS
function renderGoalsSection(){
const myClasses = gc().filter(c => CU.classIds && CU.classIds.includes(c.id));
const sel = document.getElementById('goal-cls-sel');
if(hasClasses()){
sel.style.display = '';
sel.innerHTML = `<option value="">All Tasks</option>` + myClasses.map(c=>`<option value="${c.id}">${escapeHtml(c.subject)}</option>`).join('');
} else {
sel.style.display = 'none';
}
renderGoals();
}