-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
926 lines (778 loc) · 33.5 KB
/
script.js
File metadata and controls
926 lines (778 loc) · 33.5 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
// ===============================================================
// 1. CONFIGURAÇÃO E INICIALIZAÇÃO DO FIREBASE BACKCUP
// ===============================================================
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut, sendEmailVerification, sendPasswordResetEmail } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
import { getFirestore, collection, addDoc, query, where, doc, updateDoc, deleteDoc, onSnapshot, serverTimestamp, getDocs } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { firebaseConfig } from './firebase-config.js';
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
// ===============================================================
// 2. ELEMENTOS DA UI E ESTADO DA APLICAÇÃO
// ===============================================================
const appContainer = document.getElementById('app');
const togglePassword = document.getElementById('toggle-password');
const passwordInput = document.getElementById('password');
const authContainer = document.getElementById('auth-container');
const loginButton = document.getElementById('login-button');
const registerButton = document.getElementById('register-button');
const authFeedback = document.getElementById('auth-feedback');
const logoutButton = document.getElementById('logout-button');
const userEmailDisplay = document.getElementById('user-email');
const btnHamburger = document.getElementById('btn-hamburger');
const checkboxHamburger = document.getElementById('checkbox');
const sidebar = document.getElementById('sidebar');
const overlay = document.getElementById('overlay');
const btnCloseSidebar = document.getElementById('btn-close-sidebar');
const mainContent = document.getElementById('main-content');
const sidebarTitle = document.querySelector('.sidebar-title');
const sidebarTexts = document.querySelectorAll('.sidebar-text');
const pageHome = document.getElementById('page-home');
const pageLearned = document.getElementById('page-learned');
const navButtons = sidebar.querySelectorAll('button[data-page]');
const formAddWord = document.getElementById('form-add-word');
const btnShowForm = document.getElementById('btn-show-form');
const learnedWordsContainer = document.getElementById('learned-words-container');
const searchLearnedInput = document.getElementById('search-learned');
const clearSearchButton = document.getElementById('clear-search');
const sortLearnedSelect = document.getElementById('sort-learned');
const modalWordDetails = document.getElementById('modal-word-details');
const btnCloseModal = document.getElementById('btn-close-modal');
const modalWordTitle = document.getElementById('modal-word-title');
const modalWordContent = document.getElementById('modal-word-content');
const inputWord = document.getElementById('input-word');
const inputContext = document.getElementById('input-context');
const inputMeaning = document.getElementById('input-meaning');
const inputImage = document.getElementById('input-image');
const inputCategorySearch = document.getElementById('input-category-search');
const btnCreateCategory = document.getElementById('btn-create-category');
const categoryListbox = document.getElementById('category-listbox');
const btnDiscard = document.getElementById('btn-discard');
const modalCategory = document.getElementById('modal-category-created');
const btnCloseCategoryModal = document.getElementById('btn-close-category-modal');
const categoryCreatedMessage = document.getElementById('category-created-message');
const confirmModal = document.getElementById('modal-delete-confirm');
const btnConfirmDelete = document.getElementById('btn-confirm-delete');
const btnCancelDelete = document.getElementById('btn-cancel-delete');
const modalEditCategory = document.getElementById('modal-edit-category');
const btnCancelEditCategory = document.getElementById('btn-cancel-edit-category');
const btnSaveCategory = document.getElementById('btn-save-category');
const btnDeleteCategory = document.getElementById('btn-delete-category');
const inputEditCategoryName = document.getElementById('input-edit-category-name');
const profileToggle = document.getElementById('profile-toggle');
const profileMenu = document.getElementById('profile-menu');
const modalAlert = document.getElementById('modal-alert');
const alertTitle = document.getElementById('alert-title');
const alertMessage = document.getElementById('alert-message');
const btnCloseAlert = document.getElementById('btn-close-alert');
const dateFilterContainer = document.getElementById('date-filter-container');
const dateFilterInput = document.getElementById('date-filter-input');
const clearDateFilter = document.getElementById('clear-date-filter');
const wordsPerPage = 20;
let paginationState = {};
let words = [];
let categories = [];
let currentUser = null;
let isSidebarExpanded = window.innerWidth >= 768;
let unsubscribeFromWords = null;
let currentSort = "alphabetical";
let wordIdToDelete = null;
let currentCategoryToEdit = null;
let selectedDateFilter = null;
// ===============================================================
// 3. LÓGICA DE AUTENTICAÇÃO
// ===============================================================
onAuthStateChanged(auth, (user) => {
const verifyEmailContainer = document.getElementById('verify-email-container');
if (user) {
if (user.emailVerified) {
currentUser = user;
authContainer.classList.add('hidden');
verifyEmailContainer.classList.add('hidden');
appContainer.classList.remove('hidden');
userEmailDisplay.textContent = currentUser.email;
loadData();
corrigirPalavrasAntigasSemData();
} else {
currentUser = null;
authContainer.classList.add('hidden');
appContainer.classList.add('hidden');
verifyEmailContainer.classList.remove('hidden');
document.getElementById('verification-email-display').textContent = user.email;
}
} else {
currentUser = null;
if (unsubscribeFromWords) unsubscribeFromWords();
authContainer.classList.remove('hidden');
appContainer.classList.add('hidden');
verifyEmailContainer.classList.add('hidden');
words = [];
renderLearnedWords();
}
});
document.getElementById("login-form").addEventListener("submit", async (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
authFeedback.classList.add('hidden');
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (error) {
if (error.code === 'auth/invalid-login-credentials' || error.code === 'auth/user-not-found' || error.code === 'auth/wrong-password') {
authFeedback.textContent = "❌ Email ou senha inválidos.";
} else {
authFeedback.textContent = "Ocorreu um erro ao entrar.";
}
authFeedback.className = 'text-center mt-4 text-red-500';
}
});
document.getElementById('resend-verification-button').addEventListener('click', async () => {
const feedbackEl = document.getElementById('verify-feedback');
feedbackEl.textContent = 'Enviando...';
feedbackEl.className = 'text-center mt-4 h-5 text-gray-400';
try {
if (auth.currentUser) {
await sendEmailVerification(auth.currentUser);
feedbackEl.textContent = '✅ E-mail reenviado com sucesso!';
feedbackEl.className = 'text-center mt-4 h-5 text-green-500';
}
} catch (error) {
feedbackEl.textContent = '❌ Tente novamente em alguns instantes.';
feedbackEl.className = 'text-center mt-4 h-5 text-red-500';
}
setTimeout(() => { feedbackEl.textContent = ''; }, 5000);
});
document.getElementById('back-to-login-button').addEventListener('click', () => {
signOut(auth);
});
registerButton.addEventListener('click', async (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
authFeedback.className = 'text-center mt-4 hidden';
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
await sendEmailVerification(userCredential.user);
await signOut(auth);
authFeedback.textContent = "✅ Conta criada! Verifique seu e-mail para ativá-la.";
authFeedback.className = 'text-center mt-4 text-green-500';
} catch (error) {
if (error.code === 'auth/email-already-in-use') {
authFeedback.textContent = "Este email já está registrado. Tente entrar.";
} else if (error.code === 'auth/weak-password') {
authFeedback.textContent = "A senha precisa ter pelo menos 6 caracteres.";
} else {
authFeedback.textContent = "Ocorreu um erro ao criar a conta.";
}
authFeedback.className = 'text-center mt-4 text-red-500';
}
});
logoutButton.addEventListener('click', () => { signOut(auth); });
document.getElementById('forgot-password-button').addEventListener('click', async () => {
const emailInput = document.getElementById('email');
const email = emailInput.value;
const feedback = document.getElementById('auth-feedback');
if (!email) {
feedback.textContent = "Digite seu e-mail para redefinir a senha.";
feedback.className = 'text-center mt-4 text-yellow-400';
emailInput.focus();
return;
}
feedback.textContent = "Enviando link...";
feedback.className = 'text-center mt-4 text-gray-400';
try {
await sendPasswordResetEmail(auth, email);
feedback.textContent = "✅ Link enviado! Verifique sua caixa de e-mail (e spam).";
feedback.className = 'text-center mt-4 text-green-500';
} catch (error) {
if (error.code === 'auth/user-not-found') {
feedback.textContent = "❌ E-mail não encontrado.";
} else {
feedback.textContent = "Ocorreu um erro. Tente novamente.";
}
feedback.className = 'text-center mt-4 text-red-500';
}
});
// ===============================================================
// 4. LÓGICA DA BASE DE DADOS (FIRESTORE)
// ===============================================================
function loadData() {
if (!currentUser) return;
if (unsubscribeFromWords) unsubscribeFromWords();
let unsubscribeFromCategories;
if (unsubscribeFromCategories) unsubscribeFromCategories();
const wordsQuery = query(collection(db, "palavras"), where("userId", "==", currentUser.uid));
unsubscribeFromWords = onSnapshot(wordsQuery, (snapshot) => {
words = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
renderLearnedWords(searchLearnedInput.value);
});
const categoriesQuery = query(collection(db, "categories"), where("userId", "==", currentUser.uid));
unsubscribeFromCategories = onSnapshot(categoriesQuery, (snapshot) => {
categories = snapshot.docs.map(doc => doc.data().name).sort();
});
}
async function addWord(newWordObject) {
if (!currentUser) return;
await addDoc(collection(db, "palavras"), {
...newWordObject,
userId: currentUser.uid,
createdAt: serverTimestamp()
});
}
async function updateWord(wordId, updatedData) {
if (!currentUser) return;
const wordRef = doc(db, "palavras", wordId);
await updateDoc(wordRef, updatedData);
}
async function deleteWord(wordId) {
if (!currentUser) return;
await deleteDoc(doc(db, "palavras", wordId));
}
async function corrigirPalavrasAntigasSemData() {
if (!currentUser) return;
const palavrasRef = collection(db, "palavras");
const snapshot = await getDocs(query(palavrasRef, where("userId", "==", currentUser.uid)));
const updates = [];
snapshot.forEach(docSnap => {
const data = docSnap.data();
if (!data.createdAt) {
updates.push(updateDoc(doc(db, "palavras", docSnap.id), {
createdAt: serverTimestamp()
}));
}
});
if (updates.length > 0) {
await Promise.all(updates);
console.log(`✅ Corrigido: ${updates.length} palavras receberam createdAt.`);
} else {
console.log("✅ Nenhuma palavra sem createdAt foi encontrada.");
}
}
// ===============================================================
// 5. LÓGICA DA APLICAÇÃO E UI
// ===============================================================
function isDuplicate(list, newItemName, currentItemName = null) {
const normalizedNewName = newItemName.trim().toLowerCase();
const normalizedCurrentName = currentItemName ? currentItemName.trim().toLowerCase() : null;
return list.some(item => {
const normalizedItem = typeof item === 'string' ? item.toLowerCase() : item.word.toLowerCase();
return normalizedItem === normalizedNewName && normalizedItem !== normalizedCurrentName;
});
}
function renderCategorySuggestions(searchTerm) {
if (!searchTerm) {
categoryListbox.classList.add('hidden');
return;
}
const filteredCategories = categories.filter(cat =>
cat.toLowerCase().startsWith(searchTerm.toLowerCase())
);
if (filteredCategories.length === 0) {
categoryListbox.classList.add('hidden');
return;
}
categoryListbox.innerHTML = filteredCategories.map(cat => `
<li class="px-3 py-2 cursor-pointer hover:bg-[rgb(92,130,255)]" tabindex="0">
${cat}
</li>
`).join('');
categoryListbox.classList.remove('hidden');
}
inputCategorySearch.addEventListener('input', () => {
renderCategorySuggestions(inputCategorySearch.value);
});
categoryListbox.addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
inputCategorySearch.value = e.target.textContent.trim();
categoryListbox.classList.add('hidden');
}
});
window.addEventListener('click', (e) => {
if (!inputCategorySearch.contains(e.target) && !categoryListbox.contains(e.target)) {
categoryListbox.classList.add('hidden');
}
});
formAddWord.addEventListener('submit', async (e) => {
e.preventDefault();
const wordValue = inputWord.value.trim();
const meaningValue = inputMeaning.value.trim();
document.getElementById('word-error').classList.toggle('hidden', !!wordValue);
document.getElementById('meaning-error').classList.toggle('hidden', !!meaningValue);
if (!wordValue || !meaningValue) return;
if (isDuplicate(words, wordValue)) {
showAlert(`A palavra "${wordValue}" já existe no seu dicionário.`, "Palavra duplicada");
return;
}
const newWord = {
word: wordValue,
meaning: meaningValue,
context: inputContext.value.trim(),
image: inputImage.value.trim(),
category: inputCategorySearch.value.trim() || 'Sem Categoria',
};
try {
const categoryName = newWord.category;
if (categoryName !== 'Sem Categoria' && !isDuplicate(categories, categoryName)) {
await addDoc(collection(db, "categories"), {
name: categoryName,
userId: currentUser.uid
});
}
await addWord(newWord);
formAddWord.reset();
inputCategorySearch.value = '';
hideForm();
document.getElementById('modal-word-added').classList.remove('hidden');
} catch (error) {
console.error("Erro ao adicionar palavra: ", error);
showAlert("Ocorreu um erro ao salvar a palavra. Verifique sua conexão e tente novamente.");
}
});
document.getElementById('form-edit-word').addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target;
const wordId = form.querySelector('#edit-id').value;
const updatedData = {
word: form.querySelector('#edit-word').value.trim(),
meaning: form.querySelector('#edit-meaning').value.trim(),
context: form.querySelector('#edit-context').value.trim(),
image: form.querySelector('#edit-image').value.trim(),
category: form.querySelector('#edit-category').value.trim() || 'Sem Categoria',
};
if (!updatedData.word || !updatedData.meaning) {
showAlert("Palavra e significado são obrigatórios.");
return;
}
const originalWord = words.find(w => w.id === wordId);
if (originalWord && updatedData.word !== originalWord.word && isDuplicate(words, updatedData.word, originalWord.word)) {
showAlert(`A palavra "${updatedData.word}" já existe no seu dicionário.`, "Palavra duplicada");
return;
}
try {
const categoryName = updatedData.category;
if (categoryName !== 'Sem Categoria' && !isDuplicate(categories, categoryName)) {
await addDoc(collection(db, "categories"), {
name: categoryName,
userId: currentUser.uid
});
}
await updateWord(wordId, updatedData);
document.getElementById('modal-edit-word').classList.add('hidden');
} catch (error) {
console.error("Erro ao atualizar palavra: ", error);
showAlert("Ocorreu um erro ao salvar as alterações.");
}
});
function showAlert(message, title = "Atenção") {
alertTitle.textContent = title;
alertMessage.textContent = message;
modalAlert.classList.remove('hidden');
}
function hideForm() { formAddWord.classList.add('hidden'); btnShowForm.classList.remove('hidden'); }
function showForm() { formAddWord.classList.remove('hidden'); btnShowForm.classList.add('hidden'); }
btnShowForm.addEventListener('click', showForm);
btnDiscard.addEventListener('click', hideForm);
function updateSidebarState() {
const isDesktop = window.innerWidth >= 768;
mainContent.classList.remove('ml-20', 'ml-64');
sidebar.classList.remove('w-20', 'w-64', '-translate-x-full');
overlay.classList.add('hidden');
sidebarTitle.classList.add('hidden');
sidebarTexts.forEach(text => text.classList.add('hidden', 'opacity-0'));
if (isDesktop) {
if (isSidebarExpanded) {
sidebar.classList.add('w-64');
mainContent.classList.add('ml-64');
sidebarTitle.classList.remove('hidden');
sidebarTexts.forEach(text => text.classList.remove('hidden', 'opacity-0'));
} else {
sidebar.classList.add('w-20');
mainContent.classList.add('ml-20');
}
} else {
sidebar.classList.add('w-64');
sidebarTitle.classList.remove('hidden');
sidebarTexts.forEach(text => text.classList.remove('hidden', 'opacity-0'));
if (isSidebarExpanded) {
sidebar.classList.remove('-translate-x-full');
overlay.classList.remove('hidden');
} else {
sidebar.classList.add('-translate-x-full');
}
}
checkboxHamburger.checked = isSidebarExpanded;
}
function toggleSidebar() { isSidebarExpanded = !isSidebarExpanded; updateSidebarState(); }
function showPage(page) {
pageHome.classList.add('hidden');
pageLearned.classList.add('hidden');
if (page === 'home') pageHome.classList.remove('hidden');
if (page === 'learned') pageLearned.classList.remove('hidden');
navButtons.forEach(btn => {
const isSelected = btn.dataset.page === page;
btn.classList.toggle('bg-[rgb(92,130,255)]', isSelected);
btn.classList.toggle('text-white', isSelected);
btn.classList.toggle('text-custom-blue', !isSelected);
});
modalCategory.classList.add('hidden');
if (window.innerWidth < 768) {
isSidebarExpanded = false;
updateSidebarState();
}
}
btnHamburger.addEventListener('click', toggleSidebar);
btnCloseSidebar.addEventListener('click', toggleSidebar);
overlay.addEventListener('click', toggleSidebar);
window.addEventListener('resize', updateSidebarState);
navButtons.forEach(btn => { btn.addEventListener('click', () => showPage(btn.dataset.page)); });
function renderLearnedWords(searchTerm = "") {
if (!learnedWordsContainer) return;
let processedWords = [...words];
if (selectedDateFilter) {
const filterDate = new Date(selectedDateFilter + 'T00:00:00');
processedWords = processedWords.filter(word => {
if (!word.createdAt || !word.createdAt.seconds) return false;
const wordDate = new Date(word.createdAt.seconds * 1000);
return wordDate.getFullYear() === filterDate.getFullYear() &&
wordDate.getMonth() === filterDate.getMonth() &&
wordDate.getDate() === filterDate.getDate();
});
}
if (searchTerm) {
processedWords = processedWords.filter(word =>
word.word.toLowerCase().includes(searchTerm.toLowerCase()) ||
word.meaning?.toLowerCase().includes(searchTerm.toLowerCase()) ||
word.context?.toLowerCase().includes(searchTerm.toLowerCase())
);
}
if (currentSort === "date") {
processedWords.sort((a, b) => (b.createdAt?.seconds || 0) - (a.createdAt?.seconds || 0));
} else {
processedWords.sort((a, b) => a.word.localeCompare(b.word));
}
const grouped = processedWords.reduce((acc, w) => {
const cat = w.category || 'Sem Categoria';
if (!acc[cat]) { acc[cat] = []; }
acc[cat].push(w);
return acc;
}, {});
Object.keys(grouped).forEach(cat => {
if (paginationState[cat] === undefined) {
paginationState[cat] = 1;
}
});
let categoryOrder;
if (currentSort === 'alphabetical') {
categoryOrder = Object.keys(grouped).sort();
} else {
categoryOrder = [...new Set(processedWords.map(w => w.category || 'Sem Categoria'))];
}
if (processedWords.length === 0) {
learnedWordsContainer.innerHTML = `<p class="text-center text-gray-400">Nenhuma palavra encontrada para os filtros aplicados.</p>`;
return;
}
learnedWordsContainer.innerHTML = categoryOrder.map(cat => {
const wordsInCategory = grouped[cat];
const totalWords = wordsInCategory.length;
const currentPage = paginationState[cat] || 1;
const totalPages = Math.ceil(totalWords / wordsPerPage);
const startIndex = (currentPage - 1) * wordsPerPage;
const endIndex = startIndex + wordsPerPage;
const paginatedWords = wordsInCategory.slice(startIndex, endIndex);
let paginationControls = '';
if (totalPages > 1) {
paginationControls = `
<div class="flex justify-between items-center mt-3 text-sm">
<button
data-action="paginate"
data-category="${cat}"
data-direction="prev"
${currentPage === 1 ? 'disabled' : ''}
class="px-3 py-1 bg-gray-700 rounded hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
Anterior
</button>
<span class="text-gray-400">Página ${currentPage} de ${totalPages}</span>
<button
data-action="paginate"
data-category="${cat}"
data-direction="next"
${currentPage === totalPages ? 'disabled' : ''}
class="px-3 py-1 bg-gray-700 rounded hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
Próximo
</button>
</div>
`;
}
return `
<div class="space-y-3">
<h3 class="text-xl font-extrabold text-custom-blue flex items-center gap-2">
<span>${cat}</span>
<button class="text-sm text-gray-400 hover:text-white" data-action="edit-category" data-category="${cat}" title="Editar categoria">
<i class="fas fa-pen"></i>
</button>
</h3>
<ul class="space-y-1">
${paginatedWords.map(w => `
<li data-word-id="${w.id}" class="rounded-md px-3 py-2 hover:bg-[rgb(92,130,255)] flex justify-between items-center group">
<span data-action="details" class="flex-1 cursor-pointer">${w.word}</span>
<div class="flex items-center">
<button data-word-text="${w.word}" data-action="speak" class="p-2 text-gray-400 hover:text-white" title="Ouvir pronúncia">
<i class="fas fa-volume-up"></i>
</button>
<button data-word-id="${w.id}" data-action="edit" class="p-2 text-gray-400 hover:text-white" title="Editar palavra">
<i class="fas fa-pen"></i>
</button>
</div>
</li>
`).join('')}
</ul>
${paginationControls}
</div>
`;
}).join('');
}
function openModalWordDetails(wordId) {
const word = words.find(w => w.id === wordId);
if (!word) return;
modalWordTitle.innerHTML = `
<span class="mr-3">${word.word}</span>
<button id="btn-speak-word" title="Ouvir pronúncia" class="text-gray-400 hover:text-white focus:outline-none text-xl">
<i class="fas fa-volume-up"></i>
</button>
`;
modalWordContent.innerHTML = `
${word.image ? `<img src="${word.image}" alt="Imagem de ${word.word}" class="w-full max-h-60 object-cover rounded-md mb-4">` : ''}
<p><strong class="font-semibold text-custom-blue">Significado:</strong><br>${word.meaning.replace(/\n/g, '<br>')}</p>
${word.context ? `<p class="mt-2"><strong class="font-semibold text-custom-blue">Contexto/Exemplo:</strong><br>${word.context.replace(/\n/g, '<br>')}</p>` : ''}
<p class="mt-2 text-sm text-gray-400"><strong>Categoria:</strong> ${word.category || 'Nenhuma'}</p>
`;
const btnSpeak = document.getElementById('btn-speak-word');
btnSpeak.addEventListener('click', () => {
const utterance = new SpeechSynthesisUtterance(word.word);
utterance.lang = 'en-US';
utterance.rate = 0.6;
window.speechSynthesis.speak(utterance);
});
modalWordDetails.classList.remove('hidden');
}
function openEditModal(wordId) {
const word = words.find(w => w.id === wordId);
if (!word) return;
const modal = document.getElementById('modal-edit-word');
modal.querySelector('#edit-id').value = word.id;
modal.querySelector('#edit-word').value = word.word;
modal.querySelector('#edit-meaning').value = word.meaning;
modal.querySelector('#edit-context').value = word.context || '';
modal.querySelector('#edit-image').value = word.image || '';
modal.querySelector('#edit-category').value = word.category || '';
modal.classList.remove('hidden');
}
togglePassword.addEventListener('click', () => {
const isPassword = passwordInput.type === 'password';
passwordInput.type = isPassword ? 'text' : 'password';
togglePassword.innerHTML = `<i class="fas ${isPassword ? 'fa-eye-slash' : 'fa-eye'}"></i>`;
});
document.getElementById('btn-close-edit-modal').addEventListener('click', () => {
document.getElementById('modal-edit-word').classList.add('hidden');
});
document.getElementById('btn-delete-word').addEventListener('click', () => {
wordIdToDelete = document.getElementById('edit-id').value;
confirmModal.classList.remove('hidden');
});
btnCancelDelete.addEventListener('click', () => {
wordIdToDelete = null;
confirmModal.classList.add('hidden');
});
btnCloseAlert.addEventListener('click', () => {
modalAlert.classList.add('hidden');
});
document.getElementById('btn-cancel-edit').addEventListener('click', () => {
document.getElementById('modal-edit-word').classList.add('hidden');
});
btnCloseModal.addEventListener('click', () => {
modalWordDetails.classList.add('hidden');
});
document.getElementById('btn-close-word-added-modal').addEventListener('click', () => {
document.getElementById('modal-word-added').classList.add('hidden');
});
learnedWordsContainer.addEventListener('click', (e) => {
const target = e.target;
const actionTarget = target.closest('[data-action]');
const action = actionTarget?.dataset.action;
if (!action) return;
const wordId = target.closest('[data-word-id]')?.dataset.wordId;
const category = target.closest('[data-category]')?.dataset.category;
if (action === 'speak') {
const wordToSpeak = actionTarget.dataset.wordText;
const utterance = new SpeechSynthesisUtterance(wordToSpeak);
utterance.lang = 'en-US';
utterance.rate = 0.6;
window.speechSynthesis.speak(utterance);
}
else if (action === 'details') {
openModalWordDetails(wordId);
}
else if (action === 'edit') {
openEditModal(wordId);
}
else if (action === 'edit-category') {
currentCategoryToEdit = category;
inputEditCategoryName.value = currentCategoryToEdit;
modalEditCategory.classList.remove('hidden');
}
else if (action === 'paginate') {
const direction = actionTarget.dataset.direction;
const cat = actionTarget.dataset.category;
if (direction === 'next') {
paginationState[cat]++;
} else if (direction === 'prev') {
paginationState[cat]--;
}
renderLearnedWords(searchLearnedInput.value);
}
});
btnCancelEditCategory.addEventListener('click', () => {
modalEditCategory.classList.add('hidden');
currentCategoryToEdit = null;
});
btnCreateCategory.addEventListener('click', async () => {
const newCatName = inputCategorySearch.value.trim();
if (!newCatName) {
showAlert("Digite um nome de categoria válido.");
return;
}
if (isDuplicate(categories, newCatName)) {
showAlert(`A categoria "${newCatName}" já existe.`, "Nome duplicado");
return;
}
try {
await addDoc(collection(db, "categories"), {
name: newCatName,
userId: currentUser.uid
});
inputCategorySearch.value = "";
categoryListbox.classList.add('hidden');
categoryCreatedMessage.textContent = `A categoria "${newCatName}" foi criada com sucesso.`;
modalCategory.classList.remove('hidden');
} catch (error) {
console.error("Erro ao criar categoria:", error);
showAlert("Erro ao criar categoria. Tente novamente.");
}
});
btnCloseCategoryModal.addEventListener('click', () => {
modalCategory.classList.add('hidden');
});
btnSaveCategory.addEventListener('click', async () => {
const newName = inputEditCategoryName.value.trim();
const oldName = currentCategoryToEdit;
if (!newName || !oldName || newName === oldName) {
modalEditCategory.classList.add('hidden');
return;
}
const newCategoryAlreadyExists = isDuplicate(categories, newName);
try {
const wordsQuery = query(collection(db, "palavras"), where("userId", "==", currentUser.uid), where("category", "==", oldName));
const wordsSnapshot = await getDocs(wordsQuery);
const updatePromises = wordsSnapshot.docs.map(docSnap => updateDoc(docSnap.ref, { category: newName }));
await Promise.all(updatePromises);
const oldCategoryQuery = query(collection(db, "categories"), where("userId", "==", currentUser.uid), where("name", "==", oldName));
const oldCategorySnapshot = await getDocs(oldCategoryQuery);
const deletePromises = oldCategorySnapshot.docs.map(docSnap => deleteDoc(docSnap.ref));
await Promise.all(deletePromises);
if (!newCategoryAlreadyExists) {
await addDoc(collection(db, "categories"), { name: newName, userId: currentUser.uid });
}
showAlert(`Categoria "${oldName}" foi renomeada para "${newName}".`, "Sucesso!");
modalEditCategory.classList.add('hidden');
currentCategoryToEdit = null;
} catch (error) {
console.error("Erro ao renomear categoria:", error);
showAlert("Ocorreu um erro ao renomear a categoria.", "Erro");
}
});
btnDeleteCategory.addEventListener('click', () => {
modalEditCategory.classList.add('hidden');
confirmModal.classList.remove('hidden');
wordIdToDelete = '__CATEGORY__' + currentCategoryToEdit;
});
btnConfirmDelete.addEventListener('click', async () => {
if (!wordIdToDelete) return;
try {
if (wordIdToDelete.startsWith('__CATEGORY__')) {
const categoryName = wordIdToDelete.replace('__CATEGORY__', '');
const wordsQuery = query(collection(db, "palavras"), where("userId", "==", currentUser.uid), where("category", "==", categoryName));
const wordsSnapshot = await getDocs(wordsQuery);
const updatePromises = wordsSnapshot.docs.map(docSnap => updateDoc(docSnap.ref, { category: 'Sem Categoria' }));
await Promise.all(updatePromises);
const categoryQuery = query(collection(db, "categories"), where("userId", "==", currentUser.uid), where("name", "==", categoryName));
const categorySnapshot = await getDocs(categoryQuery);
const deletePromises = categorySnapshot.docs.map(docSnap => deleteDoc(docSnap.ref));
await Promise.all(deletePromises);
showAlert(`Categoria "${categoryName}" deletada.`, "Sucesso");
} else {
await deleteWord(wordIdToDelete);
}
} catch(error) {
console.error("Erro ao deletar:", error);
showAlert("Ocorreu um erro durante a exclusão.");
}
document.getElementById('modal-edit-word').classList.add('hidden');
confirmModal.classList.add('hidden');
wordIdToDelete = null;
});
clearSearchButton?.addEventListener('click', () => {
searchLearnedInput.value = "";
renderLearnedWords();
searchLearnedInput.focus();
});
sortLearnedSelect?.addEventListener('change', (e) => {
paginationState = {}; // Reinicia a paginação
const selection = e.target.value;
dateFilterContainer.classList.add('hidden');
selectedDateFilter = null;
if (selection === 'by-date') {
dateFilterContainer.classList.remove('hidden');
if (!dateFilterInput.value) {
const today = new Date().toISOString().split('T')[0];
dateFilterInput.value = today;
}
selectedDateFilter = dateFilterInput.value;
} else {
currentSort = selection;
}
renderLearnedWords(searchLearnedInput.value);
});
dateFilterInput?.addEventListener('input', (e) => {
selectedDateFilter = e.target.value;
renderLearnedWords(searchLearnedInput.value);
});
clearDateFilter?.addEventListener('click', () => {
dateFilterContainer.classList.add('hidden');
selectedDateFilter = null;
dateFilterInput.value = '';
sortLearnedSelect.value = 'alphabetical';
currentSort = 'alphabetical';
renderLearnedWords(searchLearnedInput.value);
});
searchLearnedInput?.addEventListener('input', (e) => {
renderLearnedWords(e.target.value);
});
profileToggle?.addEventListener('click', () => {
profileMenu.classList.toggle('hidden');
});
window.addEventListener('click', (e) => {
if (!profileMenu.contains(e.target) && !profileToggle.contains(e.target)) {
profileMenu.classList.add('hidden');
}
});
// ===============================================================
// 6. INICIALIZAÇÃO DA APLICAÇÃO
// ===============================================================
function initialize() {
updateSidebarState();
showPage('home');
}
initialize();