-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile.js
More file actions
1469 lines (1248 loc) · 55.8 KB
/
Copy pathprofile.js
File metadata and controls
1469 lines (1248 loc) · 55.8 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
// profile.js - Handles User Profile, Auth, and Team Builder
window.rarityOrder = {
mythic: 0,
legendary: 1,
epic: 2,
rare: 3,
uncommon: 4,
common: 5
};
let currentUserProfile = null;
let currentTeam = Array(5).fill(null);
let editingSlot = -1;
let supabaseClient = null;
let isAuthChecking = true;
function initSupabase() {
if (typeof supabase !== 'undefined' && CONFIG.SUPABASE_URL && CONFIG.SUPABASE_KEY) {
try {
supabaseClient = supabase.createClient(CONFIG.SUPABASE_URL, CONFIG.SUPABASE_KEY);
console.log('Supabase client initialized');
checkAuthState();
} catch (e) {
console.error('Failed to initialize Supabase:', e);
}
}
}
async function checkAuthState() {
if (!supabaseClient) {
isAuthChecking = false;
return;
}
const { data: { session } } = await supabaseClient.auth.getSession();
if (session?.user) {
// Fetch and cache profile immediately on startup
const profile = await getProfile();
if (profile) {
currentUserProfile = profile;
fetchTeam(profile.id); // Also pre-fetch team
restoreDataFromCloud(); // Try to restore if local is empty
}
}
updateAuthUI(session?.user);
isAuthChecking = false;
}
function updateAuthUI(user) {
// Target the button container specifically, NOT the first div in header-container
// The header structure is: <div class="header-container"> <div>Logo+Title</div> <div id="controlsContainer">Buttons</div> </div>
// We need to find the SECOND div.
const header = document.querySelector('.header-container');
if (!header) return;
// The second child div holds the buttons
let container = header.children[1];
if (!container) return;
const existingAuthBtn = document.getElementById('authBtn');
if (existingAuthBtn) existingAuthBtn.remove();
const authBtn = document.createElement('button');
authBtn.id = 'authBtn';
authBtn.style.marginLeft = '8px';
if (user) {
authBtn.className = 'dark-mode-toggle';
// Use avatar_seed from profile if available, else user.id
const seed = (currentUserProfile && currentUserProfile.avatar_seed) ? currentUserProfile.avatar_seed : user.id;
authBtn.innerHTML = `
<img src="https://api.dicebear.com/7.x/bottts/svg?seed=${seed}" style="width:16px;height:16px;margin-right:4px;vertical-align:middle;border-radius:50%;">
${t('tabProfile')}
`;
authBtn.title = `Logged in as ${user.email}`;
authBtn.onclick = () => switchTab('profile'); // Use global switchTab
} else {
authBtn.className = 'google-btn';
authBtn.innerHTML = `
<svg width="14" height="14" viewBox="0 0 24 24" style="margin-right:6px;vertical-align:middle;">
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
</svg>Sign in
`;
authBtn.title = 'Login with Google';
authBtn.onclick = loginWithGoogle;
}
container.appendChild(authBtn);
}
async function loginWithGoogle() {
if (!supabaseClient) return;
const redirectURL = chrome.identity.getRedirectURL();
const authUrl = `${CONFIG.SUPABASE_URL}/auth/v1/authorize?provider=google&redirect_to=${encodeURIComponent(redirectURL)}`;
console.log("Launching Manual WebAuthFlow:", authUrl);
chrome.identity.launchWebAuthFlow({
url: authUrl,
interactive: true
}, async (redirectUrl) => {
console.log("WebAuthFlow callback url:", redirectUrl);
if (chrome.runtime.lastError || !redirectUrl) {
console.error('Auth flow failed:', chrome.runtime.lastError ? JSON.stringify(chrome.runtime.lastError) : 'No redirect URL');
return;
}
// Parse the session from the URL
const url = new URL(redirectUrl);
const params = new URLSearchParams(url.hash.substring(1)); // remove #
const access_token = params.get('access_token');
const refresh_token = params.get('refresh_token');
console.log("Tokens received:", { access_token: !!access_token, refresh_token: !!refresh_token });
if (access_token && refresh_token) {
const { error } = await supabaseClient.auth.setSession({
access_token,
refresh_token
});
if (error) {
console.error("Supabase setSession error:", error);
} else {
console.log("Session set successfully");
checkAuthState();
}
} else {
console.error("Missing tokens in redirect URL");
}
});
}
async function getProfile() {
if (!supabaseClient) return null;
const { data: { user } } = await supabaseClient.auth.getUser();
if (!user) return null;
const { data, error } = await supabaseClient
.from('profiles')
.select('*')
.eq('id', user.id)
.single();
if (error && error.code === 'PGRST116') { // Not found
// Create new profile
const newProfile = {
id: user.id,
username: 'Trainer ' + user.id.slice(0, 4),
avatar_id: 1,
rating: 1000,
wins: 0,
losses: 0,
total_words: 0
};
const { error: insertError } = await supabaseClient.from('profiles').insert([newProfile]);
if (insertError) {
console.error('Error creating profile:', insertError);
return null;
}
return newProfile;
}
return data;
}
async function showProfile(isOverlay = true) {
// If called directly (legacy or overlay mode), we might want to manually hide things,
// but if called via switchTab, switchTab already hides things.
// However, switchTab calls showProfile.
// Let's rely on switchTab to handle visibility of other containers.
// We just ensure profileContainer is visible.
const container = document.getElementById('profileContainer');
// Just in case we are in overlay mode or direct call:
// But strictly, switchTab handles hiding.
// We should NOT hide everything here if we assume switchTab did it.
// But for safety, let's keep it or refactor.
// Refactor: Rely on switchTab logic primarily.
// If we want to force "Tab Mode", we assume container visibility is handled.
// But let's check if we need to fetch data.
// NOTE: switchTab logic in popup.js sets display='none' for others.
// So here we just set display='block'.
container.style.display = 'block';
// Show loading only if empty? Or always refresh?
if (!container.innerHTML.includes('profile-avatar')) {
container.innerHTML = `<p>${t('profileLoading')}</p>`;
}
const profile = await getProfile();
if (!profile) {
container.innerHTML = `<p>${t('profileError')}</p>`; // Removed back button since it's a tab now
return;
}
currentUserProfile = profile;
// Sync local word count
chrome.storage.local.get(['wordDex', 'achievements', 'streakData', 'sitesExplored', 'badges'], async (data) => {
const count = Object.keys(data.wordDex || {}).length;
if (profile && count !== profile.total_words) {
await supabaseClient.from('profiles').update({ total_words: count }).eq('id', profile.id);
profile.total_words = count;
}
// Auto-backup whenever profile is opened
backupDataToCloud(data);
renderProfileUI(profile);
});
}
async function backupDataToCloud(data = null) {
if (!currentUserProfile || !supabaseClient) return;
// If data not provided, fetch it
if (!data) {
data = await new Promise(resolve => {
chrome.storage.local.get(['wordDex', 'achievements', 'streakData', 'sitesExplored', 'badges'], resolve);
});
}
const { error } = await supabaseClient
.from('profiles')
.update({ data: data })
.eq('id', currentUserProfile.id);
if (error) {
console.error('Backup failed:', error);
} else {
console.log('Backup successful');
const btn = document.getElementById('forceBackupBtn');
if (btn) {
const originalText = btn.textContent;
btn.textContent = t('profileSaved') || "Saved!";
setTimeout(() => { btn.textContent = originalText; }, 2000);
}
}
}
async function restoreDataFromCloud() {
if (!currentUserProfile || !supabaseClient) return;
// Check if local data is empty (only wordDex matters for "freshness")
const local = await new Promise(resolve => chrome.storage.local.get(['wordDex'], resolve));
if (local.wordDex && Object.keys(local.wordDex).length > 0) {
console.log('Local data exists, skipping auto-restore');
return;
}
console.log('Local data empty, attempting restore from cloud...');
// Fetch profile data
const { data, error } = await supabaseClient
.from('profiles')
.select('data')
.eq('id', currentUserProfile.id)
.single();
if (error || !data || !data.data) {
console.log('No backup found or error:', error);
return;
}
// Restore
const backup = data.data;
await new Promise(resolve => chrome.storage.local.set(backup, resolve));
console.log('Data restored from cloud');
}
function closeProfile() {
switchTab('dex');
}
function renderProfileUI(profile) {
const container = document.getElementById('profileContainer');
// Tab State
let activeTab = 'overview'; // 'overview' or 'friends'
const render = () => {
const avatarUrl = `https://api.dicebear.com/7.x/bottts/svg?seed=${profile.avatar_seed || profile.id}`;
container.innerHTML = `
<div style="display:flex; gap:10px; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:10px;">
<button class="profile-tab-btn ${activeTab === 'overview' ? 'active' : ''}" id="tabOverview">${t('profileOverview')}</button>
<button class="profile-tab-btn ${activeTab === 'friends' ? 'active' : ''}" id="tabFriends">${t('profileFriends')}</button>
<button class="profile-tab-btn ${activeTab === 'history' ? 'active' : ''}" id="tabHistory">History</button>
</div>
<!-- Overview Tab -->
<div id="viewOverview" style="display:${activeTab === 'overview' ? 'block' : 'none'}">
<img src="${avatarUrl}" class="profile-avatar" alt="Avatar">
<div style="margin-top:-10px; margin-bottom:10px;">
<span style="font-size:10px; color:#666; background:#f0f0f0; padding:2px 8px; border-radius:10px; border:1px solid #e0e0e0;">${profile.title || t('Rookie Trainer')}</span>
${getFeaturedBadgeHtml(profile.featured_badge)}
<button id="btnCustomize" style="font-size:10px; background:none; border:none; cursor:pointer; text-decoration:underline; color:#666; margin-left:4px;">${t('editProfile')}</button>
</div>
<input type="text" class="profile-name-input" value="${escapeHtml(profile.username)}" maxlength="15" spellcheck="false">
<div class="profile-stats">
<div class="stat-item">
<span class="stat-value">${profile.rating}</span>
<span class="stat-label">${t('profileRating')}</span>
</div>
<div class="stat-item">
<span class="stat-value" style="color:#a1ff96">${profile.wins}</span>
<span class="stat-label">${t('profileWins')}</span>
</div>
<div class="stat-item">
<span class="stat-value" style="color:#ff6969">${profile.losses}</span>
<span class="stat-label">${t('profileLosses')}</span>
</div>
</div>
<div class="profile-stats">
<div class="stat-item">
<span class="stat-value">${profile.total_words}</span>
<span class="stat-label">${t('profileWords')}</span>
</div>
</div>
<div style="text-align:center; margin-top:10px;">
<button id="forceBackupBtn" style="font-size:11px; padding:4px 8px; background:#f0f0f0; border:1px solid #ccc; border-radius:4px; cursor:pointer;">
☁️ ${t('forceBackup') || 'Backup Data'}
</button>
</div>
<!-- Team Section -->
<div class="team-section">
<strong style="font-size:14px; display:block;">${t('profileTeam')}</strong>
<span id="teamPower" style="font-size:11px; color:#666;">Power: 0</span>
<div id="teamUI" class="team-container"></div>
<button id="saveTeamBtn" class="save-team-btn" style="display:none;">${t('profileSave')}</button>
</div>
</div>
<!-- Friends Tab -->
<div id="viewFriends" style="display:${activeTab === 'friends' ? 'block' : 'none'}">
<div class="friend-add-row">
<input type="text" id="friendSearchInput" placeholder="${t('friendPlaceholder')}" style="flex:1; padding:8px; border:1px solid #ccc; border-radius:4px;">
<button id="addFriendBtn" style="padding:8px 12px; background:#000; color:#fff; border:none; border-radius:4px; cursor:pointer;">${t('friendAdd')}</button>
</div>
<div id="friendList" class="friend-list">
<p style="color:#666; font-size:12px; margin-top:20px;">${t('profileLoading')}</p>
</div>
</div>
<!-- History Tab -->
<div id="viewHistory" style="display:${activeTab === 'history' ? 'block' : 'none'}">
<div id="historyList" class="friend-list">
<p style="color:#666; font-size:12px; margin-top:20px;">Loading history...</p>
</div>
</div>
<button class="back-btn">${t('profileBack')}</button>
`;
// Event Listeners
container.querySelector('.back-btn').onclick = closeProfile;
// Tabs
container.querySelector('#tabOverview').onclick = () => { activeTab = 'overview'; render(); };
container.querySelector('#tabFriends').onclick = () => { activeTab = 'friends'; render(); fetchFriends(); };
container.querySelector('#tabHistory').onclick = () => { activeTab = 'history'; render(); fetchHistory(); };
if (activeTab === 'overview') {
container.querySelector('#btnCustomize').onclick = openCustomize;
container.querySelector('#saveTeamBtn').onclick = saveTeam;
const nameInput = container.querySelector('.profile-name-input');
nameInput.onchange = async (e) => {
const newName = e.target.value.trim();
if (newName) {
await supabaseClient.from('profiles').update({ username: newName }).eq('id', profile.id);
}
};
if (profile.featured_badge) {
// Defer rendering slightly to ensure DOM insertion is complete
setTimeout(() => renderFeaturedBadge(profile.featured_badge), 0);
}
container.querySelector('#forceBackupBtn').onclick = () => backupDataToCloud();
fetchTeam(profile.id);
} else {
container.querySelector('#addFriendBtn').onclick = () => addFriend();
}
};
render();
}
async function fetchFriends() {
const list = document.getElementById('friendList');
if (!list || !supabaseClient || !currentUserProfile) return;
// Fetch friendships where user is sender OR receiver
const { data, error } = await supabaseClient
.from('friendships')
.select('*')
.or(`user_id.eq.${currentUserProfile.id},friend_id.eq.${currentUserProfile.id}`);
if (error) {
console.error('Error fetching friends:', error);
list.innerHTML = `<p style="color:red">Error fetching friends: ${error.message}</p>`;
return;
}
list.innerHTML = '';
if (data.length === 0) {
list.innerHTML = `<p style="color:#999; font-style:italic; margin-top:20px;">No friends yet. Add someone!</p>`;
return;
}
// Separate requests and friends
const friends = [];
const requests = []; // Received
const pending = []; // Sent
// We need to fetch profile details for the *other* person
const otherIds = data.map(f => f.user_id === currentUserProfile.id ? f.friend_id : f.user_id);
const { data: profiles } = await supabaseClient
.from('profiles')
.select('id, username, rating, avatar_seed')
.in('id', otherIds);
const profileMap = {};
if (profiles) profiles.forEach(p => profileMap[p.id] = p);
data.forEach(f => {
const isSender = f.user_id === currentUserProfile.id;
const otherId = isSender ? f.friend_id : f.user_id;
const otherProfile = profileMap[otherId] || { username: 'Unknown', id: otherId };
if (f.status === 'accepted') {
friends.push({ ...f, other: otherProfile });
} else if (f.status === 'pending') {
if (isSender) pending.push({ ...f, other: otherProfile });
else requests.push({ ...f, other: otherProfile });
}
});
// Render Requests
if (requests.length > 0) {
const reqHeader = document.createElement('div');
reqHeader.innerHTML = `<strong>${t('friendRequests')}</strong>`;
reqHeader.style.marginBottom = '8px';
reqHeader.style.textAlign = 'left';
list.appendChild(reqHeader);
requests.forEach(req => {
const el = document.createElement('div');
el.className = 'friend-item request';
el.innerHTML = `
<div style="display:flex; align-items:center; gap:8px;">
<img src="https://api.dicebear.com/7.x/bottts/svg?seed=${req.other.avatar_seed || req.other.id}" style="width:24px; height:24px; border-radius:50%;">
<span>${escapeHtml(req.other.username)}</span>
</div>
<div>
<button class="accept-btn">✔</button>
<button class="reject-btn">✕</button>
</div>
`;
el.querySelector('.accept-btn').onclick = () => respondFriend(req.id, true);
el.querySelector('.reject-btn').onclick = () => respondFriend(req.id, false);
list.appendChild(el);
});
list.appendChild(document.createElement('hr'));
}
// Render Friends
friends.forEach(f => {
const el = document.createElement('div');
el.className = 'friend-item';
el.innerHTML = `
<div style="display:flex; align-items:center; gap:8px;">
<img src="https://api.dicebear.com/7.x/bottts/svg?seed=${f.other.avatar_seed || f.other.id}" style="width:32px; height:32px; border-radius:50%; border:1px solid #ccc;">
<div style="text-align:left;">
<div style="font-weight:bold; font-size:12px;">${escapeHtml(f.other.username)}</div>
<div style="font-size:10px; color:#666;">${t('profileRating')}: ${f.other.rating || 0}</div>
</div>
</div>
<button class="challenge-btn">${t('battleChallenge')}</button>
`;
el.querySelector('.challenge-btn').onclick = () => {
// Switch to Battle tab first
switchTab('battle');
// Wait slightly for UI to switch then start
setTimeout(() => {
startFriendBattle(f.other.id);
}, 100);
};
list.appendChild(el);
});
// Render Pending
if (pending.length > 0) {
const penHeader = document.createElement('div');
penHeader.innerHTML = `<br><strong>${t('friendPending')}</strong>`;
penHeader.style.fontSize = '11px';
penHeader.style.color = '#999';
penHeader.style.textAlign = 'left';
list.appendChild(penHeader);
pending.forEach(p => {
const el = document.createElement('div');
el.className = 'friend-item pending';
el.innerHTML = `
<span style="color:#999;">${escapeHtml(p.other.username)}</span>
<span style="font-size:10px; color:#999;">${t('friendWaiting')}</span>
`;
list.appendChild(el);
});
}
}
async function fetchHistory() {
const list = document.getElementById('historyList');
if (!list || !supabaseClient || !currentUserProfile) return;
const { data, error } = await supabaseClient
.from('battle_history')
.select('*')
.eq('user_id', currentUserProfile.id)
.order('created_at', { ascending: false })
.limit(20);
if (error) {
console.error('Error fetching history:', error);
list.innerHTML = `<p style="color:red">Error: ${error.message}</p>`;
return;
}
if (data.length === 0) {
list.innerHTML = `<p style="color:#999; font-style:italic; margin-top:20px;">No battles recorded yet.</p>`;
return;
}
list.innerHTML = '';
data.forEach(match => {
const el = document.createElement('div');
el.className = 'friend-item'; // Reuse styling
const resultColor = match.result === 'win' ? '#4caf50' : '#ff4444';
const resultText = match.result === 'win' ? 'WIN' : 'LOSS';
const sign = match.rating_change >= 0 ? '+' : '';
// Render mini team icons
let teamHtml = '';
if (match.player_team && Array.isArray(match.player_team)) {
teamHtml = `<div style="display:flex; gap:2px; margin-top:4px;">`;
match.player_team.forEach(unit => {
if(unit) {
const rarityColor = rarityScale[unit.rarity] || '#ccc';
teamHtml += `<div style="width:8px; height:8px; background:${rarityColor}; border-radius:50%;" title="${unit.word}"></div>`;
}
});
teamHtml += `</div>`;
}
const date = new Date(match.created_at).toLocaleDateString();
el.innerHTML = `
<div style="display:flex; align-items:center; gap:10px; width:100%;">
<img src="https://api.dicebear.com/7.x/bottts/svg?seed=${match.opponent_avatar || match.opponent_name}" style="width:32px; height:32px; border-radius:50%; border:1px solid #ccc;">
<div style="flex:1;">
<div style="display:flex; justify-content:space-between;">
<span style="font-weight:bold; font-size:12px;">vs ${escapeHtml(match.opponent_name)}</span>
<span style="font-weight:bold; font-size:11px; color:${resultColor}">${resultText}</span>
</div>
<div style="display:flex; justify-content:space-between; align-items:center;">
${teamHtml}
<span style="font-size:10px; color:#666;">${sign}${match.rating_change} (${date})</span>
</div>
</div>
</div>
`;
list.appendChild(el);
});
}
async function addFriend() {
const input = document.getElementById('friendSearchInput');
const username = input.value.trim();
if (!username) return;
// Find user by username
const { data: users, error } = await supabaseClient
.from('profiles')
.select('id')
.eq('username', username)
.limit(1);
if (!users || users.length === 0) {
alert(t('friendNotFound'));
return;
}
const targetId = users[0].id;
if (targetId === currentUserProfile.id) {
alert(t('friendSelf'));
return;
}
// Check existing
const { data: existing } = await supabaseClient
.from('friendships')
.select('*')
.or(`and(user_id.eq.${currentUserProfile.id},friend_id.eq.${targetId}),and(user_id.eq.${targetId},friend_id.eq.${currentUserProfile.id})`);
if (existing && existing.length > 0) {
alert(t('friendExists'));
return;
}
// Insert
const { error: insertError } = await supabaseClient
.from('friendships')
.insert({ user_id: currentUserProfile.id, friend_id: targetId, status: 'pending' });
if (insertError) {
console.error('Error adding friend:', insertError);
alert(`${t('requestError')}: ${insertError.message}`);
} else {
alert(t('requestSent'));
input.value = '';
fetchFriends();
}
}
async function respondFriend(friendshipId, accept) {
if (accept) {
await supabaseClient.from('friendships').update({ status: 'accepted' }).eq('id', friendshipId);
} else {
await supabaseClient.from('friendships').delete().eq('id', friendshipId);
}
fetchFriends();
}
function getFeaturedBadgeHtml(featuredBadgeId) {
return `<div id="featuredBadgeDisplay" style="margin-top:4px; min-height:20px;"></div>`;
}
async function renderFeaturedBadge(featuredBadgeId) {
const container = document.getElementById('featuredBadgeDisplay');
if (!container) {
console.warn("Featured Badge Container not found");
return;
}
if (!featuredBadgeId) {
container.innerHTML = '';
return;
}
chrome.storage.local.get(['badges'], (data) => {
const badges = data.badges || { main: [], hidden: [] };
const allBadges = [...badges.main, ...badges.hidden];
console.log("Searching for badge:", featuredBadgeId);
// Match by type (since id might not be unique/present on all legacy badges)
const badge = allBadges.find(b => b.type === featuredBadgeId || b.name === featuredBadgeId);
if (badge) {
let badgeName = badge.name;
if (badge.nameKey) badgeName = t(badge.nameKey);
// Handle hidden badge translation logic duplicate
else if (badge.type === 'firstMythic') badgeName = t('firstMythic');
else if (badge.type === 'meta') badgeName = t('meta');
else if (badge.type === 'huh') badgeName = t('huh');
else if (badge.type === 'rarityKiller') badgeName = t(`${badge.rarity}Killer`);
// Check if rarityScale is available (it should be global from animations.js)
const scale = window.rarityScale || { common: '#ccc' }; // Fallback
let color = scale[badge.rarity] || '#cccccc';
if (badge.type === 'meta') color = '#000000';
else if (badge.type === 'huh') color = 'linear-gradient(45deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #4b0082, #9400d3)';
// Render a mini hexagon or pill
container.innerHTML = `
<div style="display:inline-flex; align-items:center; gap:6px; background:#f9f9f9; padding:4px 8px; border-radius:12px; border:1px solid #e0e0e0; font-size:10px;">
<div style="width:14px; height:16px; background:${color}; clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);"></div>
<span style="font-weight:bold; color:#555;">${badgeName}</span>
</div>
`;
} else {
console.warn("Badge not found in storage:", featuredBadgeId);
container.innerHTML = `<span style="font-size:10px; color:red;">Badge not found</span>`;
}
});
}
// Customization
const UNLOCKABLES = {
titles: [
{ id: 'Rookie Trainer', req: 'Default' },
{ id: 'Word Collector', req: 'Collect 10 words', check: (p, a, s) => p.total_words >= 10 },
{ id: 'Mythic Hunter', req: 'Catch a Mythic', check: (p, a, s) => a.mythic > 0 },
{ id: 'Streak Master', req: '7 Day Streak', check: (p, a, s) => s.longestStreak >= 7 },
{ id: 'Battler', req: 'Win 5 Battles', check: (p, a, s) => p.wins >= 5 },
{ id: 'Legendary Hero', req: 'Catch 5 Legendaries', check: (p, a, s) => a.legendary >= 5 }
],
avatars: [
{ id: 'default', req: 'Default' },
{ id: 'pixel', req: 'Collect 50 words', check: (p, a, s) => p.total_words >= 50 },
{ id: 'bot', req: 'Win 10 Battles', check: (p, a, s) => p.wins >= 10 },
{ id: 'smile', req: 'Catch an Epic', check: (p, a, s) => a.epic > 0 }
]
};
function openCustomize(settings = null) {
const modal = document.getElementById('customizeModal');
const titleList = document.getElementById('titleList');
const avatarList = document.getElementById('avatarList');
modal.style.display = 'flex';
// Local state management for modal
// If settings passed, use them (re-render). Else clone current profile.
const profileState = settings || {
title: currentUserProfile.title,
avatar_seed: currentUserProfile.avatar_seed,
featured_badge: currentUserProfile.featured_badge
};
// Update Modal Title if needed
modal.querySelector('h3').textContent = t('editProfile');
modal.querySelectorAll('h4')[0].textContent = t('custTitle');
// Insert Badge Section Header if not present
if (!document.getElementById('badgeSectionHeader')) {
const badgeHeader = document.createElement('h4');
badgeHeader.id = 'badgeSectionHeader';
badgeHeader.style.margin = '15px 0 5px';
badgeHeader.textContent = "Featured Badge";
const badgeList = document.createElement('div');
badgeList.id = 'badgeList';
badgeList.className = 'tag-list';
// Insert after titleList
titleList.parentNode.insertBefore(badgeHeader, titleList.nextSibling);
titleList.parentNode.insertBefore(badgeList, badgeHeader.nextSibling);
}
modal.querySelectorAll('h4')[1].textContent = t('custAvatar');
chrome.storage.local.get(['achievements', 'streakData', 'badges'], (data) => {
const achievements = data.achievements || {};
const streakData = data.streakData || {};
const badges = data.badges || { main: [], hidden: [] };
// Check unlock status against ACTUAL profile stats, not the temp state
// But we use profileState for selection highlighting
const actualProfile = currentUserProfile;
titleList.innerHTML = '';
UNLOCKABLES.titles.forEach(item => {
const unlocked = !item.check || item.check(actualProfile, achievements, streakData);
const el = document.createElement('div');
el.className = `title-option ${unlocked ? '' : 'locked-item'} ${profileState.title === item.id ? 'selected' : ''}`;
el.textContent = item.id;
el.title = item.req;
if (unlocked) {
el.onclick = () => {
profileState.title = item.id;
openCustomize(profileState);
};
}
titleList.appendChild(el);
});
// Render Badges
const badgeList = document.getElementById('badgeList');
if (badgeList) {
badgeList.innerHTML = '';
// "None" option
const noneEl = document.createElement('div');
noneEl.className = `title-option ${!profileState.featured_badge ? 'selected' : ''}`;
noneEl.textContent = "None";
noneEl.onclick = () => {
profileState.featured_badge = null;
openCustomize(profileState);
};
badgeList.appendChild(noneEl);
const allBadges = [...badges.main, ...badges.hidden];
allBadges.forEach(badge => {
// Use type as ID if available, else name
const badgeId = badge.type || badge.name;
if (!badgeId) return;
// Translate name
let badgeName = badge.name;
if (badge.nameKey) badgeName = t(badge.nameKey);
else if (badge.type === 'firstMythic') badgeName = t('firstMythic');
else if (badge.type === 'meta') badgeName = t('meta');
else if (badge.type === 'huh') badgeName = t('huh');
else if (badge.type === 'rarityKiller') badgeName = t(`${badge.rarity}Killer`);
const el = document.createElement('div');
el.className = `title-option ${profileState.featured_badge === badgeId ? 'selected' : ''}`;
// Add color indicator?
let color = rarityScale[badge.rarity] || '#ccc';
if (badge.type === 'meta') color = '#000';
el.innerHTML = `<span style="display:inline-block;width:8px;height:8px;background:${color};border-radius:50%;margin-right:4px;"></span>${badgeName}`;
el.onclick = () => {
profileState.featured_badge = badgeId;
openCustomize(profileState);
};
badgeList.appendChild(el);
});
}
avatarList.innerHTML = '';
UNLOCKABLES.avatars.forEach(item => {
const unlocked = !item.check || item.check(actualProfile, achievements, streakData);
const seed = item.id === 'default' ? actualProfile.id : `${actualProfile.id}_${item.id}`;
const el = document.createElement('img');
el.src = `https://api.dicebear.com/7.x/bottts/svg?seed=${seed}`;
el.className = `avatar-option ${unlocked ? '' : 'locked-item'} ${profileState.avatar_seed === seed ? 'selected' : ''}`;
el.title = item.req;
if (unlocked) {
el.onclick = () => {
profileState.avatar_seed = seed;
openCustomize(profileState);
};
}
avatarList.appendChild(el);
});
});
document.getElementById('closeCustomize').onclick = () => {
modal.style.display = 'none';
showProfile(); // Reverts changes if not saved
};
// Bind Save Button
const saveBtn = document.getElementById('saveCustomizeBtn');
if(saveBtn) {
saveBtn.onclick = () => {
saveProfileChanges(profileState);
};
}
}
async function saveProfileChanges(newSettings) {
if (!currentUserProfile || !supabaseClient) return;
const saveBtn = document.getElementById('saveCustomizeBtn');
if(saveBtn) {
saveBtn.textContent = t('profileSaving') || "Saving...";
saveBtn.disabled = true;
}
// Update local state
currentUserProfile.title = newSettings.title;
currentUserProfile.avatar_seed = newSettings.avatar_seed;
currentUserProfile.featured_badge = newSettings.featured_badge;
// Update DB
await updateProfileCosmetics();
if(saveBtn) {
saveBtn.textContent = "Saved!";
setTimeout(() => {
saveBtn.textContent = "Save Changes";
saveBtn.disabled = false;
document.getElementById('customizeModal').style.display = 'none';
// Force re-render of profile UI to show changes
renderProfileUI(currentUserProfile);
}, 800);
}
}
async function updateProfileCosmetics() {
if (!currentUserProfile || !supabaseClient) return;
const { error } = await supabaseClient.from('profiles').update({
title: currentUserProfile.title,
avatar_seed: currentUserProfile.avatar_seed,
featured_badge: currentUserProfile.featured_badge
}).eq('id', currentUserProfile.id);
if(error) console.error("Error updating profile cosmetics:", JSON.stringify(error, null, 2));
// Update Auth UI avatar immediately
const { data: { user } } = await supabaseClient.auth.getUser();
if(user) updateAuthUI(user);
}
// Team Logic
const TEAM_CAPACITY = 7; // Cost Limit (Deployment Points)
const MAX_TEAM_SLOTS = 5; // Max number of units
// Combo Definitions (Handled via global check or mirrored)
// If profile.js loads first, it defines it. If battle.js loads first, it defines it.
if (typeof window.COMBOS === 'undefined') {
window.COMBOS = [
{
name: "The Quintuplets",
words: ["who", "what", "where", "when", "why"],
desc: "Resurrects first fallen unit with 1 HP (50% chance)",
color: "#FFD700" // Gold
},
{
name: "Liberator",
words: ["we", "the", "people"],
desc: "Grants +20% Attack to all team members",
color: "#00BFFF" // Deep Sky Blue
},
{
name: "Time Traveler",
words: ["time", "travel", "past", "future"],
desc: "+15% Speed to all team members",
color: "#FF69B4" // Hot Pink
},
{
name: "Nature's Wrath",
words: ["fire", "water", "earth", "wind"],
desc: "Deal 10% extra elemental damage on every hit",
color: "#32CD32" // Lime Green
},
{
name: "Binary Code",
words: ["zero", "one", "code"],
desc: "+10% Crit Chance for digital constructs",
color: "#00FF00" // Electric Green
}
];
}
// Local alias for convenience in this file
const COMBOS = window.COMBOS;
const COST_TABLE = {
mythic: 3,
legendary: 3,
epic: 2,
rare: 2,
uncommon: 1,
common: 1,
god: 3
};
function getWordCost(rarity) {
return COST_TABLE[rarity] || 1;
}
function calculateTeamCost(team) {
return team.reduce((acc, member) => {
if (!member) return acc;
return acc + getWordCost(member.rarity);
}, 0);
}
// NOTE: We now allow up to 7 slots, but the "Cost" limit (TEAM_CAPACITY) is what constrains power.
// TEAM_CAPACITY is set to 7 (e.g. 7 commons, or 2 mythics + 1 common).
// This creates a strategic tradeoff between "More Units" vs "Stronger Units".
function calculateStat(wordData, type) {
if (!wordData) return 0;
const len = wordData.word.length;
const rarity = wordData.rarity;
// Base multipliers
const rarityMult = { common: 1, uncommon: 1.2, rare: 1.5, epic: 2, legendary: 3, mythic: 5, god: 10 };
const rVal = rarityMult[rarity] || 1;
switch(type) {
case 'hp': return Math.floor(len * 10 * rVal);
case 'atk': return Math.floor((rVal * 20));
case 'speed': return Math.floor(100 / len);
default: return 0;
}
}
function calculatePower(wordData) {
if(!wordData) return 0;
return calculateStat(wordData, 'hp') + calculateStat(wordData, 'atk') + calculateStat(wordData, 'speed');
}
const VALID_TYPES = ['noun', 'verb', 'adjective', 'adverb', 'pronoun', 'preposition', 'conjunction', 'interjection'];