-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3929 lines (3446 loc) · 164 KB
/
Copy pathscript.js
File metadata and controls
3929 lines (3446 loc) · 164 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
// ===== FIREBASE — LAZY CORE LOADER (performance) =====
// Public browsing (PYQ list, search, filters, paper reading) needs no
// Firebase at all — that data comes from the Worker API. The Firebase SDKs
// are therefore NOT loaded via <script> tags anymore: this loader injects
// them lazily, during browser idle time / on first user interaction, and
// every authenticated feature awaits `ensureFirebase()` first. Anonymous
// visitors never pay the ~270 KB Firebase parse/compile cost.
const firebaseConfig = {
apiKey: "AIzaSyBRlsk-knQs-AMlaTFxlneBMTwlSfwyFaQ",
authDomain: "dsmnru-data.firebaseapp.com",
projectId: "dsmnru-data",
storageBucket: "dsmnru-data.firebasestorage.app",
messagingSenderId: "62250453477",
appId: "1:62250453477:web:087c07403e4fead220470c",
measurementId: "G-VL6V3T96YX"
};
const FIREBASE_CORE_SRCS = [
'https://www.gstatic.com/firebasejs/9.22.1/firebase-app-compat.js',
'https://www.gstatic.com/firebasejs/9.22.1/firebase-auth-compat.js'
];
const FIRESTORE_SRC = 'https://www.gstatic.com/firebasejs/9.22.1/firebase-firestore-compat.js';
function _loadExternalScript(src) {
return new Promise((resolve, reject) => {
const existing = document.querySelector('script[src="' + src + '"]');
if (existing) {
if (existing.dataset.loaded === 'true') return resolve();
existing.addEventListener('load', resolve);
existing.addEventListener('error', () => reject(new Error('Failed to load ' + src)));
return;
}
const script = document.createElement('script');
script.src = src;
script.async = true;
script.dataset.loaded = 'false';
script.onload = () => { script.dataset.loaded = 'true'; resolve(); };
script.onerror = () => reject(new Error('Failed to load ' + src));
document.head.appendChild(script);
});
}
let firebaseCorePromise = null;
let auth = null;
let authListenerInstalled = false;
// Loads firebase-app + firebase-auth and initializes the app. Resolves with
// the global `firebase` namespace. Safe to call repeatedly (cached).
function ensureFirebase() {
// Already available (lazy scripts finished, an inline tag provided it, or
// a test/mock environment pre-populated the global).
if (typeof firebase !== 'undefined' && firebase.initializeApp) {
if (!firebase.apps || !firebase.apps.length) {
try { firebase.initializeApp(firebaseConfig); } catch (e) { /* already initialized */ }
}
_setupAuthStateListener();
return Promise.resolve(firebase);
}
if (firebaseCorePromise) return firebaseCorePromise;
firebaseCorePromise = (async () => {
for (const src of FIREBASE_CORE_SRCS) {
// eslint-disable-next-line no-await-in-loop
await _loadExternalScript(src);
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
_setupAuthStateListener();
return firebase;
})().catch((err) => {
firebaseCorePromise = null;
throw err;
});
return firebaseCorePromise;
}
window.ensureFirebase = ensureFirebase;
// Firestore is a separate, even larger bundle — only loaded for an
// authenticated/write feature (profile, comments, uploads, view increments).
let db = null;
let firestoreLoadPromise = null;
function configureFirestore() {
if (!db && typeof firebase !== 'undefined' && firebase.firestore) {
db = firebase.firestore();
// Expose cross-script so lazily-loaded modules (paper.js) share the
// same Firestore instance after ensureFirestore() resolves.
window.db = db;
db.enablePersistence({ synchronizeTabs: true }).catch((error) => {
if (error.code !== 'failed-precondition' && error.code !== 'unimplemented') {
console.warn('Firestore persistence unavailable:', error.message);
}
});
}
return db;
}
function ensureFirestore() {
return ensureFirebase().then(() => {
if (configureFirestore()) return db;
if (firestoreLoadPromise) return firestoreLoadPromise;
firestoreLoadPromise = _loadExternalScript(FIRESTORE_SRC)
.then(() => {
if (configureFirestore()) return db;
throw new Error('Firestore did not initialize');
})
.catch((err) => {
firestoreLoadPromise = null;
throw err;
});
return firestoreLoadPromise;
});
}
window.ensureFirestore = ensureFirestore;
// Kick off the core SDK during idle time so a returning signed-in visitor's
// session is restored without waiting for a click, while staying completely
// off the first-paint critical path for anonymous visitors.
function _preloadFirebaseSoon() {
const start = () => { ensureFirebase().catch(() => { /* offline */ }); };
if (typeof window !== 'undefined' && window.requestIdleCallback) {
window.requestIdleCallback(start, { timeout: 3000 });
} else {
setTimeout(start, 1500);
}
}
// First interaction also triggers the load (login click, typing, touch, etc.).
['pointerdown', 'keydown', 'focusin'].forEach((evt) => {
window.addEventListener(evt, () => ensureFirebase().catch(() => {}), { once: true, passive: true });
});
// SweetAlert is only used after a login, profile, upload or feedback action.
// Keep the notification UI, but do not parse it for an anonymous archive visit.
let sweetAlertLoadPromise = null;
function ensureSweetAlert() {
if (window.Swal && typeof window.Swal.fire === 'function') return Promise.resolve(window.Swal);
if (sweetAlertLoadPromise) return sweetAlertLoadPromise;
sweetAlertLoadPromise = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/sweetalert2@11';
script.async = true;
script.onload = () => resolve(window.Swal);
script.onerror = () => reject(new Error('Unable to load notifications'));
document.head.appendChild(script);
});
return sweetAlertLoadPromise;
}
function showAlert(...args) {
return ensureSweetAlert().then(Swal => Swal.fire(...args));
}
// ===== API CONFIGURATION (Cloudflare Worker) =====
// Public data (PYQs, search, contributors, homepage) now comes from the
// Cloudflare Worker API — never from direct full-collection Firestore reads.
// The browser still talks to Firestore directly ONLY for user-scoped data:
// auth/profile, comments, feedback, uploads, and view increments.
//
// Set the Worker URL via window.DSMNRU_API_URL (see index.html/paper.html)
// or via a Netlify `_redirects` proxy of `/api/*` to the Worker.
//
// window.DSMNRU_API_URL is the Worker *origin* (no /api). Worker routes all
// live under `/api/...`, so we append `/api` here. Without that, search
// hits `/pyqs/search` which the Worker treats as GET /pyqs/:id ("search")
// instead of the search endpoint — the list can still work via a `/pyqs`
// alias while search/filter hang or 404 forever.
function resolveApiBaseUrl(raw) {
const configured = (raw == null ? '' : String(raw)).trim();
if (!configured) return '/api';
const base = configured.replace(/\/+$/, '');
return /\/api$/i.test(base) ? base : base + '/api';
}
const API_BASE_URL = resolveApiBaseUrl(
(typeof window !== 'undefined' && window.DSMNRU_API_URL) ? window.DSMNRU_API_URL : ''
);
function buildApiUrl(path, params) {
const cleanPath = path.charAt(0) === '/' ? path : '/' + path;
const filtered = {};
if (params) {
Object.keys(params).forEach(function(key) {
const value = params[key];
if (value !== undefined && value !== null && value !== '') {
filtered[key] = String(value);
}
});
}
const query = Object.keys(filtered).length ? ('?' + new URLSearchParams(filtered).toString()) : '';
return API_BASE_URL.replace(/\/+$/, '') + cleanPath + query;
}
if (typeof window !== 'undefined') {
window.resolveApiBaseUrl = resolveApiBaseUrl;
window.buildApiUrl = buildApiUrl;
window.DSMNRU_RESOLVED_API_BASE = API_BASE_URL;
}
async function apiGet(path, params, options) {
const url = buildApiUrl(path, params);
const opts = options || {};
const timeoutMs = typeof opts.timeoutMs === 'number' ? opts.timeoutMs : 20000;
const controller = new AbortController();
const onAbort = function() {
try { controller.abort(); } catch (e) { /* ignore */ }
};
if (opts.signal) {
if (opts.signal.aborted) {
const aborted = new Error('Search request was cancelled');
aborted.name = 'AbortError';
throw aborted;
}
opts.signal.addEventListener('abort', onAbort);
}
const timeoutId = setTimeout(onAbort, timeoutMs);
try {
const res = await fetch(url, {
headers: { 'Accept': 'application/json' },
signal: controller.signal
});
if (!res.ok) {
let detail = '';
try {
const errBody = await res.json();
if (errBody && errBody.error) detail = errBody.error;
} catch (parseErr) { /* ignore non-JSON error bodies */ }
console.error('API error', res.status, path, detail || '');
const error = new Error(detail || ('API error ' + res.status));
error.status = res.status;
throw error;
}
return await res.json();
} catch (err) {
if (err && err.name === 'AbortError') {
const aborted = new Error('Search request was cancelled');
aborted.name = 'AbortError';
throw aborted;
}
console.error('API request failed:', path, err && err.message);
throw err;
} finally {
clearTimeout(timeoutId);
if (opts.signal) {
opts.signal.removeEventListener('abort', onAbort);
}
}
}
// Paginated PYQ list from the Worker (page/limit/sort/filters)
async function fetchPyqsPage(page, limit, sort) {
return apiGet('/pyqs', { page: String(page), limit: String(limit), sort: sort || 'newest' });
}
// Server-side search over the Worker's KV-cached search index
async function searchPyqs(params, options) {
return apiGet('/pyqs/search', params, options);
}
// Single PYQ full document (includes file/server URLs)
async function fetchPyqById(id) {
return apiGet('/pyqs/' + encodeURIComponent(id));
}
// List/search responses include a collision-safe canonical slug. Keep the
// legacy detail URL as a fallback while an old Worker index is being upgraded.
function getPyqDetailsUrl(pyq) {
const slug = pyq && typeof pyq.slug === 'string' ? pyq.slug.trim() : '';
if (/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) {
return '/pyq/' + encodeURIComponent(slug);
}
return '/paper.html?id=' + encodeURIComponent((pyq && pyq.id) || '');
}
// Contributors list (KV-cached, long TTL)
async function fetchContributors() {
return apiGet('/contributors');
}
// Homepage summary: recent, trending, course counts, stats
async function fetchHomepage() {
return apiGet('/homepage');
}
// Aggregated stats
async function fetchStats() {
return apiGet('/stats');
}
// ===== CLIENT CACHE FOR API RESPONSES =====
// The Worker + Cloudflare KV/edge cache already serve most traffic with zero
// Firestore reads. This small session cache just avoids repeat API calls
// within a single page session. It never stores the full collection.
const API_SESSION_CACHE = {};
const API_SESSION_TTL_MS = 2 * 60 * 1000; // 2 minutes
function getApiSessionCache(key) {
const entry = API_SESSION_CACHE[key];
if (entry && Date.now() - entry.t < API_SESSION_TTL_MS) {
return entry.data;
}
return null;
}
function setApiSessionCache(key, data) {
try {
API_SESSION_CACHE[key] = { data, t: Date.now() };
// keep the in-memory map small
const keys = Object.keys(API_SESSION_CACHE);
if (keys.length > 50) {
delete API_SESSION_CACHE[keys[0]];
}
} catch (e) { /* ignore */ }
}
// Cached fetch of a PYQ page (used by browsing + Load More)
async function fetchPyqsPageCached(page, limit, sort) {
const key = 'pyqs:' + page + ':' + limit + ':' + (sort || 'newest');
const cached = getApiSessionCache(key);
if (cached) return cached;
const data = await fetchPyqsPage(page, limit, sort);
setApiSessionCache(key, data);
return data;
}
function clearPyqsCache() {
for (const key of Object.keys(API_SESSION_CACHE)) {
delete API_SESSION_CACHE[key];
}
}
// Courses loaded from local courses.json (used to populate course selects)
let coursesList = [];
let _coursesPromise = null;
// Single shared fetch of /courses.json — used both by the filter populator and
// by the homepage-section catalog builder, so the file is requested once per
// page load instead of twice (the second caller previously forced a
// cache:'no-store' re-download).
function loadCourses() {
if (_coursesPromise) return _coursesPromise;
_coursesPromise = fetch('/courses.json')
.then(res => {
if (!res.ok) throw new Error('Unable to load courses.json');
return res.json();
})
.then(data => Array.isArray(data && data.courses) ? data.courses : [])
.catch(err => {
console.warn('courses.json not loaded:', err.message);
return [];
});
return _coursesPromise;
}
// Fetch courses.json (single shared request — see loadCourses) and populate
// course filters/badge where the UI supports it.
function fetchCoursesJson() {
loadCourses()
.then(courses => {
if (courses.length) {
coursesList = courses;
try { populateCourseFilter(); } catch (e) { /* ignore */ }
}
});
}
// Populate the course select used for filtering on the homepage
function populateCourseFilter() {
const select = document.getElementById('filterCourse');
if (!select) return;
if (!coursesList || !coursesList.length) return;
// Clear all options and rebuild
select.innerHTML = '';
// Add "All Courses" option first
const allOption = document.createElement('option');
allOption.value = '';
allOption.textContent = 'All Courses';
select.appendChild(allOption);
// Add courses from courses.json
coursesList.forEach(course => {
const label = typeof course === 'string' ? course : (course.name || course.label || '');
if (!label) return;
const opt = document.createElement('option');
opt.value = label;
opt.textContent = label;
select.appendChild(opt);
});
}
// Kick off load on script initialization (ensure DOM is ready)
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fetchCoursesJson);
} else {
fetchCoursesJson();
}
// ===== USER AUTHENTICATION & PROFILE MANAGEMENT =====
// Global user state
let currentUser = null;
let searchGateVisible = false;
function isGoogleUser(user) {
if (!user || !Array.isArray(user.providerData)) return false;
return user.providerData.some(provider => provider && provider.providerId === 'google.com');
}
function requiresEmailVerification(user) {
return !!user && !isGoogleUser(user) && !user.emailVerified;
}
async function ensureUserDocumentSynced(user) {
if (!user) return;
await ensureFirestore();
const googleAccount = isGoogleUser(user);
const userRef = db.collection('users').doc(user.uid);
const existingDoc = await userRef.get();
const existingData = existingDoc.exists ? existingDoc.data() : {};
await userRef.set({
uid: user.uid,
email: user.email || existingData.email || '',
name: existingData.name || existingData.signupName || user.displayName || 'User',
signupName: existingData.signupName || existingData.name || user.displayName || 'User',
signupEmail: existingData.signupEmail || existingData.email || user.email || '',
signupCourse: existingData.signupCourse || existingData.course || '',
course: existingData.course || existingData.signupCourse || '',
phone: existingData.phone || '',
role: existingData.role || 'user',
emailVerified: !!user.emailVerified || googleAccount,
createdAt: existingData.createdAt || firebase.firestore.FieldValue.serverTimestamp()
}, { merge: true });
}
async function sendSubscriberToMakeOnce(uid, name, email, source) {
if (!uid || !email) return false;
await ensureFirestore();
const userRef = db.collection('users').doc(uid);
const shouldSend = await db.runTransaction(async transaction => {
const snapshot = await transaction.get(userRef);
const data = snapshot.exists ? snapshot.data() : {};
if (data.makeSubscriberSynced === true || data.makeSubscriberSyncInProgress === true) {
return false;
}
transaction.set(userRef, {
makeSubscriberSyncInProgress: true,
makeSubscriberSyncSource: source || 'unknown',
makeSubscriberSyncRequestedAt: firebase.firestore.FieldValue.serverTimestamp()
}, { merge: true });
return true;
});
if (!shouldSend) {
return false;
}
try {
await sendSubscriberToMake(name, email);
await userRef.set({
makeSubscriberSynced: true,
makeSubscriberSyncInProgress: false,
makeSubscriberSyncedAt: firebase.firestore.FieldValue.serverTimestamp(),
makeSubscriberSyncError: ''
}, { merge: true });
return true;
} catch (error) {
await userRef.set({
makeSubscriberSynced: false,
makeSubscriberSyncInProgress: false,
makeSubscriberSyncError: error?.message || 'Webhook request failed',
makeSubscriberSyncFailedAt: firebase.firestore.FieldValue.serverTimestamp()
}, { merge: true });
throw error;
}
}
// Update UI based on auth state
function updateUploadAccessUI() {
const uploadSection = document.querySelector('.upload-section');
const uploadOverlay = document.getElementById('uploadFormLockOverlay');
const uploadForm = document.getElementById('userUploadForm');
prefillUploadEmail();
if (!uploadSection || !uploadOverlay || !uploadForm) return;
const formControls = uploadForm.querySelectorAll('input, button');
uploadSection.classList.remove('upload-locked');
uploadOverlay.style.display = 'none';
formControls.forEach(control => {
control.disabled = false;
});
}
// Monitor auth state changes (registered lazily once the Auth SDK exists).
function _setupAuthStateListener() {
if (authListenerInstalled || typeof firebase === 'undefined' || !firebase.auth) return;
auth = firebase.auth();
if (!auth) return;
authListenerInstalled = true;
auth.onAuthStateChanged(_handleAuthStateChanged);
}
async function _handleAuthStateChanged(user) {
currentUser = user;
updateUserUI();
updateUploadAccessUI();
updatePyqFilterUI();
// handle verification block overlay
if (!user) {
hideVerificationBlock();
} else if (requiresEmailVerification(user)) {
// will be confirmed after reload
}
if (user) {
// Load Firestore only for an authenticated visitor before profile sync.
try { await ensureFirestore(); } catch (error) { console.warn('Firestore unavailable:', error.message); }
// Check if email is verified
user.reload()
.then(async () => {
await ensureUserDocumentSynced(user);
if (requiresEmailVerification(user)) {
showEmailVerificationPrompt();
} else {
hideVerificationBlock();
loadUserProfile();
checkAndShowProfileCompletionReminder();
const searchInput = document.getElementById('searchInput');
if (searchInput && searchInput.value.trim()) {
performSearch();
}
}
})
.catch(error => {
console.error('Error syncing auth user with Firestore profile:', error);
if (user && requiresEmailVerification(user)) showEmailVerificationPrompt();
});
} else {
hideVerificationBlock();
}
}
// Update UI based on auth state
function updateUserUI() {
const loggedOutMenu = document.getElementById('userLoggedOutMenu');
const loggedInMenu = document.getElementById('userLoggedInMenu');
const profileBtn = document.getElementById('profileBtn');
const userDisplayName = document.getElementById('userDisplayName');
if (currentUser) {
loggedOutMenu.style.display = 'none';
loggedInMenu.style.display = 'block';
userDisplayName.textContent = currentUser.displayName || currentUser.email.split('@')[0];
document.getElementById('userNameDisplay').textContent = currentUser.displayName || 'User';
document.getElementById('userEmailDisplay').textContent = currentUser.email;
// Show verification badge if email not verified
const verificationBadge = document.getElementById('emailVerificationBadge');
if (verificationBadge) {
if (requiresEmailVerification(currentUser)) {
verificationBadge.style.display = 'inline-block';
} else {
verificationBadge.style.display = 'none';
}
}
} else {
loggedOutMenu.style.display = 'block';
loggedInMenu.style.display = 'none';
userDisplayName.textContent = 'Login';
}
}
// Profile dropdown toggle
function toggleProfileDropdown() {
const profileButton = document.getElementById('profileBtn');
const dropdown = document.getElementById('profileDropdown');
const isOpen = dropdown.style.display === 'none';
dropdown.style.display = isOpen ? 'block' : 'none';
if (profileButton) profileButton.setAttribute('aria-expanded', String(isOpen));
}
// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
const profileSection = document.querySelector('.user-profile-section');
if (!profileSection.contains(event.target)) {
const dropdown = document.getElementById('profileDropdown');
if (dropdown) dropdown.style.display = 'none';
const profileButton = document.getElementById('profileBtn');
if (profileButton) profileButton.setAttribute('aria-expanded', 'false');
}
});
// ===== LOGIN FUNCTIONS =====
async function openLoginModal() {
await ensureFirebase();
document.getElementById('profileDropdown').style.display = 'none';
const modal = new bootstrap.Modal(document.getElementById('loginModal'));
modal.show();
}
function closeLoginModal() {
const modal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
if (modal) modal.hide();
}
async function signInWithGoogle(providerEntryPoint) {
try {
await ensureFirebase();
const provider = new firebase.auth.GoogleAuthProvider();
const result = await auth.signInWithPopup(provider);
await result.user.reload();
await ensureUserDocumentSynced(result.user);
// --- NEW CODE: SEND GOOGLE SIGNUPS TO MAKE.COM ---
// Firebase tells us if this is their first time ever logging in
const isNewUser = result.additionalUserInfo?.isNewUser || providerEntryPoint === 'signup';
if (isNewUser) {
const displayName = result.user.displayName || result.user.email.split('@')[0] || 'User';
await sendSubscriberToMakeOnce(result.user.uid, displayName, result.user.email, 'google-signup');
}
// -------------------------------------------------
const loginModal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
if (loginModal) loginModal.hide();
const signupModal = bootstrap.Modal.getInstance(document.getElementById('signupModal'));
if (signupModal) signupModal.hide();
document.getElementById('loginForm').reset();
document.getElementById('signupForm').reset();
showAlert({
title: 'Signed in with Google',
text: providerEntryPoint === 'signup' ? 'Your Google account was created and signed in.' : 'You are now signed in with your Google account.',
icon: 'success'
});
// Ensure filter UI updates immediately after sign in
try { updatePyqFilterUI(); populateCourseFilter(); } catch (e) { /* ignore */ }
} catch (error) {
const message = error.code === 'auth/popup-closed-by-user'
? 'Google sign-in was cancelled.'
: error.message;
const errorDiv = providerEntryPoint === 'signup'
? document.getElementById('signupError')
: document.getElementById('loginError');
if (errorDiv) {
errorDiv.textContent = message;
errorDiv.style.display = 'block';
} else {
showAlert('Error', message, 'error');
}
}
}
document.getElementById('loginForm').addEventListener('submit', async function(e) {
e.preventDefault();
await ensureFirebase();
const email = document.getElementById('loginEmail').value;
const password = document.getElementById('loginPassword').value;
const errorDiv = document.getElementById('loginError');
try {
errorDiv.style.display = 'none';
const result = await auth.signInWithEmailAndPassword(email, password);
await result.user.reload();
closeLoginModal();
document.getElementById('loginForm').reset();
if (!requiresEmailVerification(result.user)) {
showAlert('Success', 'Logged in successfully!', 'success');
try { updatePyqFilterUI(); populateCourseFilter(); } catch (e) {}
} else {
showAlert({
title: 'Welcome Back!',
html: '<p>Your email is not verified yet.</p><p>Please verify your email to unlock all features.</p>',
icon: 'info'
});
showEmailVerificationPrompt();
}
} catch (error) {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
}
});
// Function to send new users to the beehiiv/Make.com mailing list
async function sendSubscriberToMake(name, email) {
const webhookUrl = "https://hook.us2.make.com/sc9ldu43pg3hnq48y9d6s6fds6j48bqk";
try {
const response = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name, email: email })
});
if (!response.ok) {
throw new Error(`Make.com webhook returned ${response.status}`);
}
console.log('Subscriber sent to Make.com successfully!');
} catch (err) {
console.error('Make.com webhook failed:', err);
throw err;
}
}
// ===== SIGNUP FUNCTIONS =====
async function openSignupModal() {
await ensureFirebase();
document.getElementById('profileDropdown').style.display = 'none';
const modal = new bootstrap.Modal(document.getElementById('signupModal'));
modal.show();
}
function closeSearchGateModal() {
const modalElement = document.getElementById('searchGateModal');
const modal = bootstrap.Modal.getInstance(modalElement) || bootstrap.Modal.getOrCreateInstance(modalElement);
modal.hide();
searchGateVisible = false;
}
function openSearchGateModal() {
if (searchGateVisible) return;
const modalElement = document.getElementById('searchGateModal');
const modal = bootstrap.Modal.getOrCreateInstance(modalElement, {
backdrop: 'static',
keyboard: false
});
searchGateVisible = true;
modal.show();
}
const searchGateModalElement = document.getElementById('searchGateModal');
if (searchGateModalElement) {
searchGateModalElement.addEventListener('shown.bs.modal', function() {
const backdrop = document.querySelector('.modal-backdrop:last-of-type');
if (backdrop) {
backdrop.classList.add('search-gate-backdrop');
}
});
searchGateModalElement.addEventListener('hidden.bs.modal', function() {
searchGateVisible = false;
document.querySelectorAll('.modal-backdrop.search-gate-backdrop').forEach(backdrop => {
backdrop.classList.remove('search-gate-backdrop');
});
});
}
function continueBrowsingWithoutSearch() {
closeSearchGateModal();
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.value = '';
}
performSearch();
}
function closeSignupModal() {
const modal = bootstrap.Modal.getInstance(document.getElementById('signupModal'));
if (modal) modal.hide();
}
document.getElementById('signupForm').addEventListener('submit', async function(e) {
e.preventDefault();
await ensureFirebase();
// 1. Lock the submit button to prevent double-clicks
const submitBtn = e.target.querySelector('button[type="submit"]');
const originalBtnText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Creating...';
const email = document.getElementById('signupEmail').value.trim();
const password = document.getElementById('signupPassword').value;
const confirmPassword = document.getElementById('signupConfirmPassword').value;
const errorDiv = document.getElementById('signupError');
if (!email || !password || !confirmPassword) {
errorDiv.textContent = 'Email, password, and password confirmation are required.';
errorDiv.style.display = 'block';
resetButton();
return;
}
if (password !== confirmPassword) {
errorDiv.textContent = 'Passwords do not match';
errorDiv.style.display = 'block';
resetButton();
return;
}
try {
errorDiv.style.display = 'none';
const userCredential = await auth.createUserWithEmailAndPassword(email, password);
const user = userCredential.user;
const displayName = email.split('@')[0] || 'User';
// Update user profile
await user.updateProfile({ displayName });
// Send verification email only for non-Google password accounts
if (!isGoogleUser(user)) {
await user.sendEmailVerification();
}
// Create user document in Firestore
await ensureFirestore();
await db.collection('users').doc(user.uid).set({
uid: user.uid,
email: email,
signupEmail: email,
name: displayName,
signupName: displayName,
course: '',
signupCourse: '',
emailVerified: isGoogleUser(user) ? true : false,
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
phone: '',
preferences: {},
role: 'user'
}, { merge: true });
// 2. Safely call the webhook ONLY after Firestore succeeds
await sendSubscriberToMakeOnce(user.uid, displayName, email, 'email-signup');
closeSignupModal();
document.getElementById('signupForm').reset();
// Show success message with verification instruction
showAlert({
title: 'Account Created!',
html: isGoogleUser(user)
? '<p>Google account created successfully.</p><p>You can use the app immediately. No email verification is needed.</p>'
: `<p>Account created successfully!</p><p>A verification email has been sent to <strong>${email}</strong>.</p><p>Please check your email and click the verification link to activate your account.</p><p>You can add your name, course, and phone number later from your profile.</p>`,
icon: 'success',
confirmButtonText: 'OK'
});
// Update filter UI immediately for newly created users
try { updatePyqFilterUI(); populateCourseFilter(); } catch (e) {}
} catch (error) {
errorDiv.textContent = error.message;
errorDiv.style.display = 'block';
} finally {
// Always unlock the button when finished
resetButton();
}
function resetButton() {
submitBtn.disabled = false;
submitBtn.innerHTML = originalBtnText;
}
});
// ===== PROFILE FUNCTIONS =====
async function openProfileModal() {
await ensureFirebase();
document.getElementById('profileDropdown').style.display = 'none';
if (currentUser) {
loadUserProfile();
const modal = new bootstrap.Modal(document.getElementById('profileModal'));
modal.show();
}
}
async function loadUserProfile() {
if (!currentUser) return;
await ensureFirestore();
try {
await ensureUserDocumentSynced(currentUser);
const userDoc = await db.collection('users').doc(currentUser.uid).get();
if (userDoc.exists) {
const userData = userDoc.data();
const nameValue = userData.name || userData.signupName || currentUser.displayName || '';
const emailValue = userData.email || userData.signupEmail || currentUser.email || '';
const courseValue = userData.course || userData.signupCourse || '';
const phoneValue = userData.phone || '';
document.getElementById('profileName').value = nameValue;
document.getElementById('profileEmail').value = emailValue;
document.getElementById('profileCourse').value = courseValue;
document.getElementById('profilePhone').value = phoneValue;
document.getElementById('profileEmail').readOnly = true;
if (userData.createdAt) {
const date = new Date(userData.createdAt.toDate()).toLocaleDateString();
document.getElementById('profileCreatedDate').textContent = date;
}
} else {
document.getElementById('profileName').value = currentUser.displayName || 'User';
document.getElementById('profileEmail').value = currentUser.email || '';
document.getElementById('profileCourse').value = '';
document.getElementById('profilePhone').value = '';
}
} catch (error) {
console.error('Error loading profile:', error);
}
// Points are independent of the profile document — a contribution can be
// rewarded before an account exists, so they live in `reward_accounts`.
loadProfileRewards();
}
// ===== PYQ CONTRIBUTION POINTS (read-only for students) =====
function rewardTimestampValue(value) {
if (!value) return 0;
if (typeof value.toDate === 'function') {
const date = value.toDate();
return Number.isFinite(date.getTime()) ? date.getTime() : 0;
}
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function rewardTypeLabel(type) {
if (window.DSMNRUPoints && type === window.DSMNRUPoints.PYQ_UPLOAD_REWARD_TYPE) return 'PYQ Contribution';
return String(type || 'Reward');
}
async function loadProfileRewards() {
// Only index.html renders the points card — skip the reads elsewhere.
if (!document.getElementById('profilePointsCard')) return;
const valueEl = document.getElementById('profilePointsValue');
const historyEl = document.getElementById('profilePointsHistory');
const helpers = window.DSMNRUPoints;
if (!helpers || !currentUser || !currentUser.email) {
if (valueEl) valueEl.textContent = '0';
if (historyEl) {
historyEl.innerHTML = '<div class="pyq-points-empty">Sign in with the email you used to contribute to see your points.</div>';
}
return;
}
const email = helpers.normalizeRewardEmail(currentUser.email);
const accountKey = helpers.rewardAccountKey(email);
if (valueEl) valueEl.textContent = '…';
if (historyEl) historyEl.innerHTML = '<div class="pyq-points-empty">Loading…</div>';
try {
await ensureFirestore();
const accountRef = db.collection('reward_accounts').doc(accountKey);
const accountSnap = await accountRef.get();
let points = 0;
if (accountSnap.exists) {
const account = accountSnap.data() || {};
points = Number(account.points) || 0;
// Points earned before this email had an account are linked to the
// signed-in user on first visit. Rules only allow the `uid` field
// to change here — the balance can never be touched by a client.
if (account.uid !== currentUser.uid) {
await accountRef.update({ uid: currentUser.uid }).catch(err => {
console.warn('Could not link reward account to this user:', err.message);
});
}
}
if (valueEl) valueEl.textContent = String(points);
// Equality-only query → no composite index required. Sorted client-side.
const txSnap = await db.collection('point_transactions')
.where('email', '==', email)
.limit(20)
.get();
const entries = txSnap.docs
.map(doc => ({ id: doc.id, ...doc.data() }))
.sort((a, b) => rewardTimestampValue(b.createdAt) - rewardTimestampValue(a.createdAt));
if (!entries.length) {
if (historyEl) {
historyEl.innerHTML = '<div class="pyq-points-empty">No contributions yet — upload a PYQ to earn 10 points.</div>';
}
return;
}
if (historyEl) {
historyEl.innerHTML = entries.map(entry => {
const amount = Number(entry.amount) || 0;
const ts = rewardTimestampValue(entry.createdAt);
const dateLabel = ts ? new Date(ts).toLocaleDateString() : '';
return ''
+ '<div class="pyq-points-entry">'
+ `<span class="pyq-points-entry-amount">+${escapeUploadText(amount)}</span>`