Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4166 lines (3633 loc) · 158 KB
/
Copy pathapp.js
File metadata and controls
4166 lines (3633 loc) · 158 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
// ============================================================
// SAWFISH APP STORE - APPLICATION JAVASCRIPT
// Full Logic for PWA, Navigation, Ratings, Reviews, Firestore
// Enhanced with Firebase Authentication, Profile Pictures, Search
// Author: Eric Zhu / Sawfish Developer Group
// Date: January 10, 2026
// ============================================================
// ============================================================
// VERSION CONFIGURATION
// ============================================================
const APP_VERSION = '2.8.0';
const VERSION_CHECK_URL = '/update/version.json';
// ============================================================
// FIREBASE CONFIGURATION
// ============================================================
const firebaseConfig = {
apiKey: "AIzaSyB5JaGq3ezv1ghif7ggRr8_jxuq7ZGw4Bo",
authDomain: "appstore-cb2fa.firebaseapp.com",
projectId: "appstore-cb2fa",
storageBucket: "appstore-cb2fa.firebasestorage.app",
messagingSenderId: "122307463006",
appId: "1:122307463006:web:25993ed888531908fbb1cf"
};
// Initialize Firebase
let db = null;
let auth = null;
let storage = null;
let app = null;
// Force Firebase initialization - NO LOCALSTORAGE FALLBACK FOR REVIEWS
function initializeFirebase() {
if (typeof firebase === 'undefined') {
console.error('Firebase SDK not loaded');
return false;
}
if (firebaseConfig.apiKey === "YOUR_API_KEY_HERE") {
console.error('Firebase config not properly set');
return false;
}
try {
app = firebase.initializeApp(firebaseConfig);
db = firebase.firestore();
auth = firebase.auth();
storage = firebase.storage();
// Configure Firestore settings for better reliability
db.settings({
experimentalForceLongPolling: false,
merge: true
});
console.log('Firebase initialized successfully');
console.log('Project ID:', firebaseConfig.projectId);
// Set up auth persistence
if (auth) {
auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
console.log('Auth persistence set to LOCAL');
})
.catch((error) => {
console.error('Error setting auth persistence:', error);
});
auth.onAuthStateChanged((user) => {
if (user) {
console.log('User signed in:', user.email);
UserAuth.currentUser = {
uid: user.uid,
email: user.email,
displayName: user.displayName || user.email.split('@')[0],
emailVerified: user.emailVerified
};
UserAuth.updateAuthUI();
} else {
console.log('User signed out');
}
});
}
return true;
} catch (error) {
console.error('Firebase initialization failed:', error);
return false;
}
}
// Initialize Firebase immediately
const firebaseInitialized = initializeFirebase();
if (!firebaseInitialized) {
console.error('CRITICAL: Firebase failed to initialize. Reviews will not work until Firebase is available.');
}
// ============================================================
// USER AUTHENTICATION SYSTEM
// ============================================================
const UserAuth = {
currentUser: null,
userProfile: null,
isDeveloperMode: false,
DEVELOPER_USERNAME: 'Developer',
DEVELOPER_PASSWORD: '120622',
init: function() {
this.loadUserSession();
this.setupAuthListeners();
this.updateAuthUI();
},
loadUserSession: function() {
try {
const storedUser = localStorage.getItem('sawfish_user');
const storedProfile = localStorage.getItem('sawfish_profile');
if (storedUser) {
this.currentUser = JSON.parse(storedUser);
}
if (storedProfile) {
this.userProfile = JSON.parse(storedProfile);
}
const devSession = sessionStorage.getItem('developer_logged_in');
this.isDeveloperMode = devSession === 'true';
} catch (error) {
console.error('Error loading session:', error);
}
},
saveUserSession: function() {
try {
if (this.currentUser) {
localStorage.setItem('sawfish_user', JSON.stringify(this.currentUser));
}
if (this.userProfile) {
localStorage.setItem('sawfish_profile', JSON.stringify(this.userProfile));
}
} catch (error) {
console.error('Error saving session:', error);
}
},
clearSession: function() {
this.currentUser = null;
this.userProfile = null;
this.isDeveloperMode = false;
localStorage.removeItem('sawfish_user');
localStorage.removeItem('sawfish_profile');
sessionStorage.removeItem('developer_logged_in');
},
setupAuthListeners: function() {
console.log('Setting up auth listeners...');
const loginForm = document.getElementById('login-form');
console.log('Login form found:', !!loginForm);
if (loginForm) {
loginForm.addEventListener('submit', (e) => this.handleLogin(e));
}
const signupForm = document.getElementById('signup-form');
console.log('Signup form found:', !!signupForm);
if (signupForm) {
signupForm.addEventListener('submit', (e) => this.handleSignup(e));
}
const resetForm = document.getElementById('reset-form');
console.log('Reset form found:', !!resetForm);
if (resetForm) {
resetForm.addEventListener('submit', (e) => this.handlePasswordReset(e));
}
const authTabs = document.querySelectorAll('.auth-tab');
authTabs.forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.authTab;
authTabs.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
document.getElementById('login-form').style.display = tab === 'login' ? 'block' : 'none';
document.getElementById('signup-form').style.display = tab === 'signup' ? 'block' : 'none';
document.getElementById('reset-form').style.display = tab === 'reset' ? 'block' : 'none';
const title = document.getElementById('auth-modal-title');
if (title) {
if (tab === 'login') title.textContent = 'Sign In';
else if (tab === 'signup') title.textContent = 'Create Account';
else if (tab === 'reset') title.textContent = 'Reset Password';
}
});
});
const userProfileBtn = document.getElementById('user-profile-button');
if (userProfileBtn) {
userProfileBtn.addEventListener('click', () => this.handleProfileButtonClick());
}
const logoutBtn = document.getElementById('profile-logout-btn');
if (logoutBtn) {
logoutBtn.addEventListener('click', () => this.handleLogout());
}
const profileSaveBtn = document.getElementById('profile-save-btn');
if (profileSaveBtn) {
profileSaveBtn.addEventListener('click', () => this.saveProfileChanges());
}
const profileCancelBtn = document.getElementById('profile-cancel-btn');
if (profileCancelBtn) {
profileCancelBtn.addEventListener('click', () => this.closeProfileModal());
}
const avatarUpload = document.getElementById('avatar-upload-input');
if (avatarUpload) {
avatarUpload.addEventListener('change', (e) => this.handleProfilePictureUpload(e));
}
const profileClose = document.getElementById('profile-close');
if (profileClose) {
profileClose.addEventListener('click', () => this.closeProfileModal());
}
const authCancel = document.getElementById('auth-cancel');
if (authCancel) {
authCancel.addEventListener('click', () => this.closeAuthModal());
}
const authModal = document.getElementById('auth-modal');
if (authModal) {
const backdrop = authModal.querySelector('.modal-backdrop');
if (backdrop) {
backdrop.addEventListener('click', () => this.closeAuthModal());
}
}
// User profile modal close button
const userProfileClose = document.getElementById('user-profile-modal-close');
if (userProfileClose) {
userProfileClose.addEventListener('click', () => this.closeUserProfileModal());
}
// User profile modal backdrop
const userProfileModal = document.getElementById('user-profile-modal');
if (userProfileModal) {
const backdrop = userProfileModal.querySelector('.modal-backdrop');
if (backdrop) {
backdrop.addEventListener('click', () => this.closeUserProfileModal());
}
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const authModal = document.getElementById('auth-modal');
if (authModal && !authModal.classList.contains('hidden')) {
this.closeAuthModal();
}
const userProfileModal = document.getElementById('user-profile-modal');
if (userProfileModal && !userProfileModal.classList.contains('hidden')) {
this.closeUserProfileModal();
}
}
});
},
handleProfileButtonClick: function() {
if (this.isLoggedIn()) {
this.openProfileModal();
} else {
this.openAuthModal();
}
},
openProfileModal: function() {
const modal = document.getElementById('profile-modal');
if (!modal) return;
const name = this.userProfile?.username || this.currentUser?.displayName || 'User';
const email = this.userProfile?.email || this.currentUser?.email || 'Not signed in';
const bio = this.userProfile?.bio || '';
const nameEl = document.getElementById('profile-display-name');
const emailEl = document.getElementById('profile-email');
const nameInput = document.getElementById('profile-name-input');
const bioInput = document.getElementById('profile-bio-input');
if (nameEl) nameEl.textContent = name;
if (emailEl) emailEl.textContent = email;
if (nameInput) nameInput.value = name;
if (bioInput) bioInput.value = bio;
this.updateProfileAvatar();
const statusBadge = document.getElementById('profile-status-badge');
if (statusBadge) {
if (this.isDeveloperMode) {
statusBadge.textContent = 'Developer';
statusBadge.classList.add('developer');
} else {
statusBadge.textContent = 'User';
statusBadge.classList.remove('developer');
}
}
modal.classList.remove('hidden');
modal.setAttribute('aria-hidden', 'false');
},
closeProfileModal: function() {
const modal = document.getElementById('profile-modal');
if (modal) {
modal.classList.add('hidden');
modal.setAttribute('aria-hidden', 'true');
}
},
closeUserProfileModal: function() {
const modal = document.getElementById('user-profile-modal');
if (modal) {
modal.classList.add('hidden');
modal.setAttribute('aria-hidden', 'true');
}
},
updateProfileAvatar: function() {
const avatarInitial = document.getElementById('profile-avatar-initial');
const avatarImg = document.getElementById('profile-avatar-img');
const previewInitial = document.getElementById('upload-preview-initial');
const previewImg = document.getElementById('upload-preview-img');
const name = this.userProfile?.username || this.currentUser?.displayName || 'User';
const initial = name.charAt(0).toUpperCase();
if (this.userProfile?.avatarUrl) {
if (avatarInitial) avatarInitial.style.display = 'none';
if (avatarImg) {
avatarImg.src = this.userProfile.avatarUrl;
avatarImg.style.display = 'block';
}
if (previewInitial) previewInitial.style.display = 'none';
if (previewImg) {
previewImg.src = this.userProfile.avatarUrl;
previewImg.style.display = 'block';
}
} else {
if (avatarInitial) {
avatarInitial.textContent = initial;
avatarInitial.style.display = 'flex';
}
if (avatarImg) avatarImg.style.display = 'none';
if (previewInitial) {
previewInitial.textContent = initial;
previewInitial.style.display = 'flex';
}
if (previewImg) previewImg.style.display = 'none';
}
},
saveProfileChanges: function() {
const nameInput = document.getElementById('profile-name-input');
const bioInput = document.getElementById('profile-bio-input');
const name = nameInput?.value.trim();
const bio = bioInput?.value.trim();
if (name) {
this.userProfile = this.userProfile || {};
this.userProfile.username = name;
this.userProfile.bio = bio || '';
if (this.currentUser) {
this.currentUser.displayName = name;
}
this.saveUserSession();
if (db && this.currentUser) {
db.collection('users').doc(this.currentUser.uid).set({
username: name,
bio: bio || ''
}, { merge: true })
.then(() => {
console.log('Profile saved to Firestore');
})
.catch((error) => {
console.error('Error saving profile to Firestore:', error);
});
}
if (!db && this.currentUser) {
const storedUsers = JSON.parse(localStorage.getItem('sawfish_users') || '{}');
const email = this.currentUser.email;
if (storedUsers[email]) {
storedUsers[email].username = name;
storedUsers[email].bio = bio || '';
localStorage.setItem('sawfish_users', JSON.stringify(storedUsers));
}
}
this.updateAuthUI();
this.updateProfileAvatar();
showNotification('Profile updated!');
this.closeProfileModal();
}
},
handleLogin: async function(event) {
event.preventDefault();
const emailInput = document.getElementById('login-email');
const passwordInput = document.getElementById('login-password');
const errorDiv = document.getElementById('auth-error');
const submitBtn = document.getElementById('login-submit');
const email = emailInput?.value.trim();
const password = passwordInput?.value;
if (!email || !password) {
this.showError(errorDiv, 'Please enter both email and password');
return;
}
submitBtn.disabled = true;
submitBtn.textContent = 'Signing in...';
try {
if (email === this.DEVELOPER_USERNAME && password === this.DEVELOPER_PASSWORD) {
this.isDeveloperMode = true;
sessionStorage.setItem('developer_logged_in', 'true');
this.currentUser = {
uid: 'developer',
email: null,
displayName: this.DEVELOPER_USERNAME,
isDeveloper: true
};
this.userProfile = {
username: this.DEVELOPER_USERNAME,
avatarUrl: null
};
this.saveUserSession();
this.closeAuthModal();
this.updateAuthUI();
DeveloperMode.isLoggedIn = true;
DeveloperMode.updateLoginButton();
updateDevOnlyElements();
Achievements.checkAchievements('be_a_dev');
showNotification('Developer mode activated');
return;
}
if (auth) {
const userCredential = await auth.signInWithEmailAndPassword(email, password);
const user = userCredential.user;
await this.getOrCreateUserProfile(user);
this.saveUserSession();
this.closeAuthModal();
this.updateAuthUI();
showNotification('Welcome back!');
} else {
const storedUsers = JSON.parse(localStorage.getItem('sawfish_users') || '{}');
if (storedUsers[email] && storedUsers[email].password === password) {
this.currentUser = {
uid: storedUsers[email].uid,
email: email,
displayName: storedUsers[email].username,
isDeveloper: false
};
this.userProfile = {
username: storedUsers[email].username,
email: email,
bio: storedUsers[email].bio || '',
achievements: storedUsers[email].achievements || [],
avatarUrl: storedUsers[email].avatarUrl || null
};
this.saveUserSession();
this.closeAuthModal();
this.updateAuthUI();
showNotification('Welcome back! (Offline mode)');
} else {
this.showError(errorDiv, 'Invalid email or password. In offline mode, please sign up first.');
}
}
} catch (error) {
console.error('Login error:', error);
let errorMessage = 'Login failed. Please try again.';
switch (error.code) {
case 'auth/user-not-found':
errorMessage = 'No account found with this email';
break;
case 'auth/wrong-password':
errorMessage = 'Incorrect password';
break;
case 'auth/invalid-email':
errorMessage = 'Invalid email address';
break;
case 'auth/user-disabled':
errorMessage = 'This account has been disabled';
break;
case 'auth/too-many-requests':
errorMessage = 'Too many failed attempts. Please try again later';
break;
}
this.showError(errorDiv, errorMessage);
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Sign In';
}
},
handleSignup: async function(event) {
event.preventDefault();
const nameInput = document.getElementById('signup-name');
const emailInput = document.getElementById('signup-email');
const passwordInput = document.getElementById('signup-password');
const confirmInput = document.getElementById('signup-confirm');
const errorDiv = document.getElementById('auth-error');
const submitBtn = document.getElementById('signup-submit');
const name = nameInput?.value.trim();
const email = emailInput?.value.trim();
const password = passwordInput?.value;
const confirm = confirmInput?.value;
if (!name || !email || !password || !confirm) {
this.showError(errorDiv, 'Please fill in all fields');
return;
}
if (password.length < 6) {
this.showError(errorDiv, 'Password must be at least 6 characters');
return;
}
if (password !== confirm) {
this.showError(errorDiv, 'Passwords do not match');
return;
}
submitBtn.disabled = true;
submitBtn.textContent = 'Creating account...';
try {
if (auth) {
const userCredential = await auth.createUserWithEmailAndPassword(email, password);
const user = userCredential.user;
await user.updateProfile({ displayName: name });
await user.sendEmailVerification();
this.userProfile = {
username: name,
email: email,
avatarUrl: null,
createdAt: new Date().toISOString(),
bio: '',
totalRatings: 0,
achievements: ['first_time']
};
await this.saveUserProfile(user.uid);
this.currentUser = {
uid: user.uid,
email: user.email,
displayName: name,
emailVerified: user.emailVerified,
isDeveloper: false
};
this.saveUserSession();
this.closeAuthModal();
this.updateAuthUI();
showNotification('Account created! Please check your email for verification.');
} else {
const storedUsers = JSON.parse(localStorage.getItem('sawfish_users') || '{}');
if (storedUsers[email]) {
this.showError(errorDiv, 'An account with this email already exists');
submitBtn.disabled = false;
submitBtn.textContent = 'Create Account';
return;
}
const uid = 'user_' + Date.now();
storedUsers[email] = {
uid: uid,
username: name,
email: email,
password: password,
createdAt: new Date().toISOString(),
achievements: ['first_time']
};
localStorage.setItem('sawfish_users', JSON.stringify(storedUsers));
this.currentUser = {
uid: uid,
email: email,
displayName: name,
isDeveloper: false
};
this.userProfile = {
username: name,
email: email,
achievements: ['first_time']
};
this.saveUserSession();
this.closeAuthModal();
this.updateAuthUI();
showNotification('Account created! (Offline mode)');
}
} catch (error) {
console.error('Signup error:', error);
let errorMessage = 'Signup failed. Please try again.';
switch (error.code) {
case 'auth/email-already-in-use':
errorMessage = 'An account with this email already exists';
break;
case 'auth/invalid-email':
errorMessage = 'Invalid email address';
break;
case 'auth/weak-password':
errorMessage = 'Password is too weak';
break;
}
this.showError(errorDiv, errorMessage);
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Create Account';
}
},
handlePasswordReset: async function(event) {
event.preventDefault();
const emailInput = document.getElementById('reset-email');
const errorDiv = document.getElementById('auth-error');
const successDiv = document.getElementById('auth-success');
const submitBtn = document.getElementById('reset-submit');
const email = emailInput?.value.trim();
if (!email) {
this.showError(errorDiv, 'Please enter your email address');
return;
}
submitBtn.disabled = true;
submitBtn.textContent = 'Sending...';
try {
if (auth) {
await auth.sendPasswordResetEmail(email);
successDiv.textContent = `Password reset email sent to ${email}`;
successDiv.classList.remove('hidden');
errorDiv.classList.add('hidden');
showNotification('Password reset email sent!');
} else {
this.showError(errorDiv, 'Authentication service unavailable');
}
} catch (error) {
console.error('Password reset error:', error);
let errorMessage = 'Failed to send reset email';
if (error.code === 'auth/user-not-found') {
errorMessage = 'No account found with this email';
}
this.showError(errorDiv, errorMessage);
successDiv.classList.add('hidden');
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Send Reset Link';
}
},
handleLogout: async function() {
try {
if (auth && this.currentUser && !this.isDeveloperMode) {
await auth.signOut();
}
this.clearSession();
this.closeProfileModal();
this.updateAuthUI();
if (DeveloperMode.isLoggedIn) {
DeveloperMode.isLoggedIn = false;
DeveloperMode.updateLoginButton();
updateDevOnlyElements();
}
showNotification('Logged out successfully');
switchTab('home');
} catch (error) {
console.error('Logout error:', error);
showNotification('Logout failed');
}
},
getOrCreateUserProfile: async function(user) {
if (!db) return;
try {
const doc = await db.collection('users').doc(user.uid).get();
if (doc.exists) {
this.userProfile = doc.data();
} else {
this.userProfile = {
username: user.displayName || user.email.split('@')[0],
email: user.email,
avatarUrl: null,
createdAt: new Date().toISOString(),
bio: '',
totalRatings: 0,
achievements: ['first_time']
};
await this.saveUserProfile(user.uid);
}
} catch (error) {
console.error('Error getting user profile:', error);
}
},
saveUserProfile: async function(uid) {
if (!db || !this.userProfile) return;
try {
await db.collection('users').doc(uid).set(this.userProfile, { merge: true });
} catch (error) {
console.error('Error saving user profile:', error);
}
},
handleProfilePictureUpload: async function(event) {
const file = event.target.files[0];
if (!file) return;
const previewInitial = document.getElementById('upload-preview-initial');
const previewImg = document.getElementById('upload-preview-img');
if (!this.currentUser) {
showNotification('Please log in to upload a profile picture');
return;
}
try {
const reader = new FileReader();
reader.onload = (e) => {
const base64Data = e.target.result;
this.userProfile = this.userProfile || {};
this.userProfile.avatarUrl = base64Data;
this.saveUserSession();
if (previewInitial) {
previewInitial.textContent = '';
previewInitial.style.display = 'none';
}
if (previewImg) {
previewImg.src = base64Data;
previewImg.style.display = 'block';
}
this.updateProfileAvatar();
const sidebarAvatar = document.getElementById('sidebar-avatar');
if (sidebarAvatar) {
sidebarAvatar.innerHTML = `<img src="${base64Data}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">`;
}
Achievements.checkAchievements('upload_avatar');
if (db && this.currentUser) {
db.collection('users').doc(this.currentUser.uid).set({
avatarUrl: base64Data
}, { merge: true })
.then(() => {
console.log('Profile picture saved to Firestore');
})
.catch((error) => {
console.error('Error saving profile picture to Firestore:', error);
});
}
// Also save to localStorage for offline mode
if (!db && this.currentUser && this.currentUser.email) {
const storedUsers = JSON.parse(localStorage.getItem('sawfish_users') || '{}');
if (storedUsers[this.currentUser.email]) {
storedUsers[this.currentUser.email].avatarUrl = base64Data;
localStorage.setItem('sawfish_users', JSON.stringify(storedUsers));
}
}
showNotification('Profile picture updated!');
};
reader.readAsDataURL(file);
} catch (error) {
console.error('Upload error:', error);
showNotification('Upload failed. Please try again.');
}
},
getDefaultAvatar: function() {
const username = this.userProfile?.username || 'User';
const initial = username.charAt(0).toUpperCase();
return `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="50" fill="#4da3ff"/><text x="50" y="50" text-anchor="middle" dy="0.35em" fill="white" font-size="50" font-family="sans-serif">${initial}</text></svg>`)}`;
},
showError: function(errorDiv, message) {
if (errorDiv) {
errorDiv.textContent = message;
errorDiv.classList.remove('hidden');
setTimeout(() => {
errorDiv.classList.add('hidden');
}, 5000);
}
},
openAuthModal: function() {
const modal = document.getElementById('auth-modal');
if (modal) {
modal.classList.remove('hidden');
modal.setAttribute('aria-hidden', 'false');
}
},
closeAuthModal: function() {
const modal = document.getElementById('auth-modal');
if (modal) {
modal.classList.add('hidden');
modal.setAttribute('aria-hidden', 'true');
const forms = modal.querySelectorAll('form');
forms.forEach(f => f.reset());
document.getElementById('login-form').style.display = 'block';
document.getElementById('signup-form').style.display = 'none';
document.getElementById('reset-form').style.display = 'none';
const errorDiv = document.getElementById('auth-error');
const successDiv = document.getElementById('auth-success');
if (errorDiv) errorDiv.classList.add('hidden');
if (successDiv) successDiv.classList.add('hidden');
const authTabs = document.querySelectorAll('.auth-tab');
authTabs.forEach((btn, index) => {
btn.classList.toggle('active', index === 0);
});
const title = document.getElementById('auth-modal-title');
if (title) title.textContent = 'Sign In';
}
},
updateAuthUI: function() {
const profileStatusText = document.getElementById('profile-status-text');
const sidebarAvatar = document.getElementById('sidebar-avatar');
if (this.currentUser) {
const name = this.userProfile?.username || this.currentUser.displayName || 'User';
if (profileStatusText) profileStatusText.textContent = name;
if (this.userProfile?.avatarUrl) {
if (sidebarAvatar) {
sidebarAvatar.innerHTML = `<img src="${this.userProfile.avatarUrl}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">`;
}
} else {
const initial = name.charAt(0).toUpperCase();
if (sidebarAvatar) {
sidebarAvatar.innerHTML = '';
sidebarAvatar.textContent = initial;
}
}
const userProfileBtn = document.getElementById('user-profile-button');
if (userProfileBtn) {
userProfileBtn.classList.add('logged-in');
}
} else {
if (profileStatusText) profileStatusText.textContent = 'Sign In';
if (sidebarAvatar) {
sidebarAvatar.innerHTML = '';
sidebarAvatar.textContent = '?';
}
const userProfileBtn = document.getElementById('user-profile-button');
if (userProfileBtn) {
userProfileBtn.classList.remove('logged-in');
}
}
},
isLoggedIn: function() {
return this.currentUser !== null;
},
canRate: function() {
return this.isLoggedIn() || this.isDeveloperMode;
},
getReviewUsername: function() {
if (this.isDeveloperMode) return 'Developer';
return this.userProfile?.username || this.currentUser?.displayName || 'Anonymous';
},
getReviewAvatar: function() {
if (this.isDeveloperMode) return null;
return this.userProfile?.avatarUrl;
},
openUserProfile: function(userId) {
this.loadUserProfileData(userId);
},
loadUserProfileData: async function(userId) {
const modal = document.getElementById('user-profile-modal');
if (!modal) return;
const nameEl = document.getElementById('user-profile-name');
const bioEl = document.getElementById('user-profile-bio');
const avatarEl = document.getElementById('user-profile-avatar');
const achievementsEl = document.getElementById('user-profile-achievements');
const statsEl = document.getElementById('user-profile-stats');
const memberSinceEl = document.getElementById('user-profile-member-since');
modal.classList.remove('hidden');
modal.setAttribute('aria-hidden', 'false');
try {
let userData;
let achievements = [];
let postCount = 0;
if (db) {
const userDoc = await db.collection('users').doc(userId).get();
if (userDoc.exists) {
userData = userDoc.data();
achievements = userData.achievements || [];
}
// Get post count
const postsSnapshot = await db.collection('sawfish_community_posts')
.where('author', '==', userData?.username || 'Unknown')
.get();
postCount = postsSnapshot.size;
} else {
const storedUsers = JSON.parse(localStorage.getItem('sawfish_users') || '{}');
for (const email in storedUsers) {
if (storedUsers[email].uid === userId) {
userData = storedUsers[email];
achievements = userData.achievements || [];
break;
}
}
// Get post count from localStorage
const posts = JSON.parse(localStorage.getItem('sawfish_community_posts') || '[]');
postCount = posts.filter(p => p.author === userData?.username).length;
}
// Update name
if (nameEl) {
nameEl.textContent = userData?.username || 'Unknown User';
}
// Update bio
if (bioEl) {
bioEl.textContent = userData?.bio || 'No bio yet';
bioEl.style.display = userData?.bio ? 'block' : 'none';
}
// Update avatar
if (avatarEl) {
const initial = (userData?.username || 'U').charAt(0).toUpperCase();
if (userData?.avatarUrl) {
avatarEl.innerHTML = `<img src="${userData.avatarUrl}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">`;
} else {
avatarEl.textContent = initial;
}
}