-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.js
More file actions
1890 lines (1573 loc) · 69.6 KB
/
Copy pathdata.js
File metadata and controls
1890 lines (1573 loc) · 69.6 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
// ==================== АНИМАЦИИ И ЭФФЕКТЫ ====================
// Создание частиц фона
function createParticles() {
const particlesContainer = document.getElementById('particles');
if (!particlesContainer) return;
const particleCount = window.innerWidth < 768 ? 15 : 30;
for (let i = 0; i < particleCount; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
const size = Math.random() * 60 + 20;
particle.style.width = `${size}px`;
particle.style.height = `${size}px`;
particle.style.left = `${Math.random() * 100}%`;
particle.style.top = `${Math.random() * 100}%`;
particle.style.background = `linear-gradient(135deg,
rgba(${Math.random() * 100 + 100}, ${Math.random() * 100 + 58}, ${Math.random() * 200 + 100}, 0.1),
rgba(${Math.random() * 100 + 58}, ${Math.random() * 100 + 100}, ${Math.random() * 200 + 100}, 0.05)
)`;
particle.style.animationDuration = `${Math.random() * 15 + 25}s`;
particle.style.animationDelay = `${Math.random() * 5}s`;
particlesContainer.appendChild(particle);
}
}
// Показать уведомление
function showNotification(message, type = 'info') {
const notification = document.getElementById('notification');
const notificationText = notification.querySelector('.notification-text');
const notificationIcon = notification.querySelector('.notification-icon');
notificationText.textContent = message;
notification.className = `notification ${type}`;
// Иконка в зависимости от типа
switch(type) {
case 'success':
notificationIcon.innerHTML = '✅';
break;
case 'warning':
notificationIcon.innerHTML = '⚠️';
break;
case 'danger':
notificationIcon.innerHTML = '❌';
break;
default:
notificationIcon.innerHTML = '💡';
}
notification.classList.add('show');
// Автоматическое скрытие
setTimeout(() => {
notification.classList.remove('show');
}, 5000);
}
// Показать лоадер
function showLoader() {
document.getElementById('loader').classList.add('show');
}
// Скрыть лоадер
function hideLoader() {
document.getElementById('loader').classList.remove('show');
}
// Анимация элементов при скролле
function initScrollAnimations() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animated');
}
});
}, {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
});
// Наблюдаем за карточками
document.querySelectorAll('.card').forEach(card => {
observer.observe(card);
});
// Наблюдаем за элементами статистики
document.querySelectorAll('.stat-card').forEach(stat => {
observer.observe(stat);
});
}
// ==================== УТИЛИТЫ ЧЕЛЛЕНДЖЕЙ ====================
function filterChallenges(challenges) {
if (currentFilter === 'all') {
return challenges;
} else if (currentFilter === 'active') {
return challenges.filter(c => c.isActive);
} else if (currentFilter === 'completed') {
return challenges.filter(c => !c.isActive && c.completedAsSuccess);
} else if (currentFilter === 'failed') {
return challenges.filter(c => !c.isActive && !c.completedAsSuccess);
}
return challenges;
}
function getCompletionDate(challenge) {
if (!challenge.history || challenge.history.length === 0) {
return new Date(challenge.createdAt);
}
const lastEntry = challenge.history[challenge.history.length - 1];
return new Date(lastEntry.timestamp);
}
function getCurrentGroupChallenge() {
const userData = getCurrentUserData();
if (!userData) return null;
// Вернуть данные общего челленджа если они есть
return userData.groupChallenge || null;
}
// ==================== ОТОБРАЖЕНИЕ ====================
function showInsufficientFundsModal(requiredAmount, purpose = 'создания челленджа') {
const currentBalance = getUserBalance();
const missingAmount = requiredAmount - currentBalance;
document.getElementById('insufficient-funds-text').textContent =
`Недостаточно средств для ${purpose}`;
document.getElementById('current-balance-display').textContent = currentBalance;
document.getElementById('required-amount-display').textContent = requiredAmount;
document.getElementById('missing-amount-display').textContent = missingAmount;
const modal = document.getElementById('insufficient-funds-modal');
modal.classList.remove('hidden');
modal.classList.remove('closing');
void modal.offsetWidth;
}
function hideInsufficientFundsModal() {
const modal = document.getElementById('insufficient-funds-modal');
modal.classList.add('closing');
setTimeout(() => {
modal.classList.add('hidden');
}, 400);
}
function showDeleteModal(index) {
const challenge = allChallenges[index];
if (!challenge) return;
const isOver = isOver12Hours(challenge);
const remainingTime = getRemainingTime(challenge);
let text = '';
if (isOver) {
text = `Уверены ли вы, что хотите прекратить и убрать данный челлендж? Срок на удаление истёк.`;
} else {
text = `Уверены ли вы, что хотите прекратить и убрать данный челлендж? У вас осталось ${formatTime(remainingTime)}.`;
}
document.getElementById('delete-modal-text').textContent = text;
const modal = document.getElementById('delete-modal');
modal.classList.remove('hidden');
modal.classList.remove('closing');
void modal.offsetWidth;
}
function hideDeleteModal() {
const modal = document.getElementById('delete-modal');
modal.classList.add('closing');
setTimeout(() => {
modal.classList.add('hidden');
}, 400);
}
function showHelpModal() {
const modal = document.getElementById('help-modal');
modal.classList.remove('hidden');
modal.classList.remove('closing');
void modal.offsetWidth;
}
function hideHelpModal() {
const modal = document.getElementById('help-modal');
modal.classList.add('closing');
setTimeout(() => {
modal.classList.add('hidden');
}, 400);
}
function showChangeLoginModal() {
const userData = getCurrentUserData();
if (!userData) return;
const canChange = canChangeLogin();
const timeRemaining = getTimeUntilLoginChange();
let html = '';
if (canChange) {
html = `
<p>Ваш текущий логин: <strong>@${userData.username}</strong></p>
<p>Вы можете изменить логин один раз в 2 недели.</p>
<div class="change-login-container">
<h3><i class="fas fa-edit"></i> Новый логин</h3>
<p style="margin-bottom: 15px;">Логин может содержать только буквы, цифры и символ подчеркивания. Минимум 3 символа.</p>
<label for="new-username-input">Новый логин:</label>
<input type="text" id="new-username-input" placeholder="Новый логин" value="${userData.username}">
<div class="change-login-note">
<i class="fas fa-info-circle"></i> После изменения логина следующее изменение будет доступно через 2 недели.
</div>
</div>
`;
} else {
const formattedTime = formatTimeRemaining(timeRemaining);
html = `
<div class="change-login-warning">
<i class="fas fa-exclamation-triangle"></i>
<p>Вы недавно меняли логин. Следующее изменение будет доступно через <strong>${formattedTime}</strong>.</p>
<p>Ваш текущий логин: <strong>@${userData.username}</strong></p>
</div>
`;
}
document.getElementById('change-login-content').innerHTML = html;
const modal = document.getElementById('change-login-modal');
modal.classList.remove('hidden');
modal.classList.remove('closing');
// Триггер рефлоу для запуска анимации
void modal.offsetWidth;
}
function hideChangeLoginModal() {
const modal = document.getElementById('change-login-modal');
modal.classList.add('closing');
setTimeout(() => {
modal.classList.add('hidden');
}, 400);
}
function showJoinGroupChallengeModal() {
const modal = document.getElementById('join-group-challenge-modal');
modal.classList.remove('hidden');
modal.classList.remove('closing');
void modal.offsetWidth;
}
function hideJoinGroupChallengeModal() {
const modal = document.getElementById('join-group-challenge-modal');
modal.classList.add('closing');
setTimeout(() => {
modal.classList.add('hidden');
}, 400);
}
function showScreen(screenName) {
// Скрываем все экраны
const screens = ['start', 'profile', 'create', 'active', 'challenges', 'group-challenge', 'result'];
screens.forEach(screen => {
const element = document.getElementById(`screen-${screen}`);
if (element) {
element.classList.add('hidden');
}
});
// Показываем нужный экран
const targetScreen = document.getElementById(`screen-${screenName}`);
if (targetScreen) {
targetScreen.classList.remove('hidden');
}
// Особые действия для определенных экранов
if (screenName === 'challenges') {
currentFilter = 'all';
currentPage = 1;
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.filter === 'all') {
btn.classList.add('active');
}
});
renderChallengesList();
} else if (screenName === 'profile') {
loadProfileData();
} else if (screenName === 'group-challenge') {
renderGroupChallenge();
}
}
// ==================== РЕНДЕРИНГ ====================
function initFilters() {
const filterButtons = document.querySelectorAll('.filter-btn');
filterButtons.forEach(btn => {
btn.addEventListener('click', () => {
filterButtons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = btn.dataset.filter;
currentPage = 1;
const monthInfo = document.getElementById('current-month-info');
if (currentFilter === 'completed' || currentFilter === 'failed') {
const current = getCurrentMonthYear();
const monthName = getMonthName(current.month);
monthInfo.innerHTML = `<i class="fas fa-calendar-alt"></i> Показаны челленджи за ${monthName} ${current.year} года`;
monthInfo.classList.remove('hidden');
} else {
monthInfo.classList.add('hidden');
}
renderChallengesList();
});
});
}
function renderChallengesList() {
const userData = getCurrentUserData();
if (!userData || !userData.challenges) {
allChallenges = [];
} else {
allChallenges = [...userData.challenges].sort((a, b) =>
new Date(b.createdAt) - new Date(a.createdAt)
);
}
let filtered = filterChallenges(allChallenges);
// Удаляем неактивные челленджи старше 28 дней
const now = new Date();
filtered = filtered.filter(challenge => {
if (challenge.isActive) return true;
const completionDate = getCompletionDate(challenge);
const daysSinceCompletion = (now - completionDate) / (24 * 60 * 60 * 1000);
return daysSinceCompletion <= 28;
});
// Обновляем allChallenges, удаляя старые
allChallenges = allChallenges.filter(challenge => {
if (challenge.isActive) return true;
const completionDate = getCompletionDate(challenge);
const daysSinceCompletion = (now - completionDate) / (24 * 60 * 60 * 1000);
return daysSinceCompletion <= 28;
});
// Сохраняем обновленный список
if (userData) {
userData.challenges = allChallenges;
saveCurrentUserData(userData);
}
const totalChallenges = filtered.length;
totalPages = Math.ceil(totalChallenges / CHALLENGES_PER_PAGE);
if (totalPages > MAX_PAGES) {
totalPages = MAX_PAGES;
}
const start = (currentPage - 1) * CHALLENGES_PER_PAGE;
const end = start + CHALLENGES_PER_PAGE;
const paginated = filtered.slice(start, end);
const challengesList = document.getElementById('challenges-list');
if (paginated.length === 0) {
challengesList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">
${currentFilter === 'all' ? '<i class="fas fa-clipboard-list"></i>' :
currentFilter === 'active' ? '<i class="fas fa-fire"></i>' :
currentFilter === 'completed' ? '<i class="fas fa-trophy"></i>' :
'<i class="fas fa-skull"></i>'}
</div>
<p>${currentFilter === 'all' ? 'Пока нет челленджей' :
currentFilter === 'active' ? 'Нет активных челленджей' :
currentFilter === 'completed' ? 'Нет выполненных челленджей за текущий месяц' :
'Нет срывов за текущий месяц'}</p>
${currentFilter === 'all' ? '<p style="font-size: 14px; margin-top: 8px;">Создайте свой первый челлендж!</p>' : ''}
</div>
`;
document.getElementById('pagination').classList.add('hidden');
document.getElementById('page-info').classList.add('hidden');
return;
}
let html = '';
paginated.forEach((challenge, index) => {
const actualIndex = allChallenges.findIndex(c => c.id === challenge.id);
const isActive = challenge.isActive;
const isOver = isOver12Hours(challenge);
const remainingTime = getRemainingTime(challenge);
let status = '';
let statusClass = '';
let statusBadge = '';
if (isActive) {
status = 'В процессе';
statusClass = 'active';
statusBadge = '<span class="status-badge active"><i class="fas fa-fire"></i> В процессе</span>';
} else {
// ИЗМЕНЕНО: Упрощенная логика определения статуса
if (challenge.completedAsSuccess === true) {
status = 'Выполнен';
statusClass = 'completed-success';
statusBadge = '<span class="status-badge completed"><i class="fas fa-trophy"></i> Выполнен</span>';
} else {
status = 'Срыв';
statusClass = 'completed-failure';
statusBadge = '<span class="status-badge failed"><i class="fas fa-skull"></i> Срыв</span>';
}
}
let progressPercent = 0;
if (isActive) {
const totalMarked = challenge.totalCompleted + challenge.totalSkipped;
progressPercent = Math.round((totalMarked / 7) * 100);
} else {
progressPercent = 100;
}
const exerciseInfo = EXERCISE_INFO[challenge.exercise] || EXERCISE_INFO['Отжимания'];
const habitText = `${challenge.exercise}: ${challenge.sets} подход(ов) по ${challenge.reps} раз, ${challenge.daysPerWeek} раз(а) в неделю`;
html += `
<div class="challenge-item ${statusClass}" data-index="${actualIndex}">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px;">
<div>
<h3 style="margin: 0 0 5px 0; font-size: 1.3rem;">${challenge.exercise}</h3>
${statusBadge}
</div>
<div style="text-align: right;">
<div style="font-weight: 700; font-size: 1.2rem; color: var(--primary);">${challenge.bet} ₽</div>
<div style="font-size: 0.9rem; color: var(--gray-500); margin-top: 5px;">${new Date(challenge.createdAt).toLocaleDateString('ru-RU')}</div>
</div>
</div>
<p style="margin: 10px 0; color: var(--gray-600);">${habitText}</p>
<div style="display: flex; justify-content: space-between; margin: 10px 0; font-size: 0.9rem;">
<div><i class="fas fa-check" style="color: var(--success);"></i> Выполнено: ${challenge.totalCompleted || 0}</div>
<div><i class="fas fa-times" style="color: var(--danger);"></i> Пропущено: ${challenge.totalSkipped || 0}</div>
</div>
<div class="progress" style="margin: 15px 0; height: 8px;">
<div class="progress-bar" style="width: ${progressPercent}%"></div>
</div>
<div style="display: flex; justify-content: space-between; margin-top: 15px;">
<div>
${isActive ? `<span style="font-weight: 600; color: var(--warning);"><i class="fas fa-clock"></i> ${isOver ? 'Срок истёк' : formatTime(remainingTime)}</span>` : ''}
</div>
<div style="display: flex; gap: 5px;">
${isActive && !isOver ? `<button class="delete-btn" data-index="${actualIndex}" title="Удалить челлендж"><i class="fas fa-trash"></i></button>` : ''}
</div>
</div>
</div>
`;
});
challengesList.innerHTML = html;
// Добавляем обработчики событий
challengesList.querySelectorAll('.challenge-item').forEach(item => {
item.addEventListener('click', (e) => {
if (!e.target.closest('.delete-btn')) {
const index = parseInt(item.dataset.index);
currentHabitIndex = index;
loadActiveHabit();
showScreen('active');
}
});
});
challengesList.querySelectorAll('.delete-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const index = parseInt(btn.dataset.index);
challengeToDeleteIndex = index;
showDeleteModal(index);
});
});
// Показываем пагинацию, если нужно
const pagination = document.getElementById('pagination');
const pageInfo = document.getElementById('page-info');
if (totalPages > 1) {
renderPagination();
pagination.classList.remove('hidden');
pageInfo.classList.remove('hidden');
pageInfo.textContent = `Страница ${currentPage} из ${totalPages}`;
} else {
pagination.classList.add('hidden');
pageInfo.classList.add('hidden');
}
}
function renderPagination() {
const pagination = document.getElementById('pagination');
let html = '';
// Кнопка "Назад"
html += `
<button class="page-btn ${currentPage === 1 ? 'disabled' : ''}" id="prev-page">
<i class="fas fa-chevron-left"></i>
</button>
`;
// Кнопки страниц
const maxVisible = 5;
let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
let endPage = Math.min(totalPages, startPage + maxVisible - 1);
if (endPage - startPage + 1 < maxVisible) {
startPage = Math.max(1, endPage - maxVisible + 1);
}
if (startPage > 1) {
html += `<button class="page-btn ${currentPage === 1 ? 'active' : ''}" data-page="1">1</button>`;
if (startPage > 2) {
html += `<span class="page-btn disabled">...</span>`;
}
}
for (let i = startPage; i <= endPage; i++) {
html += `<button class="page-btn ${currentPage === i ? 'active' : ''}" data-page="${i}">${i}</button>`;
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) {
html += `<span class="page-btn disabled">...</span>`;
}
html += `<button class="page-btn ${currentPage === totalPages ? 'active' : ''}" data-page="${totalPages}">${totalPages}</button>`;
}
// Кнопка "Вперед"
html += `
<button class="page-btn ${currentPage === totalPages ? 'disabled' : ''}" id="next-page">
<i class="fas fa-chevron-right"></i>
</button>
`;
pagination.innerHTML = html;
// Добавляем обработчики событий
pagination.querySelectorAll('.page-btn[data-page]').forEach(btn => {
btn.addEventListener('click', () => {
currentPage = parseInt(btn.dataset.page);
renderChallengesList();
});
});
document.getElementById('prev-page').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
renderChallengesList();
}
});
document.getElementById('next-page').addEventListener('click', () => {
if (currentPage < totalPages) {
currentPage++;
renderChallengesList();
}
});
}
async function renderGroupChallenge() {
if (window.USE_API && window.fetchGroupChallengeCurrent) {
await window.fetchGroupChallengeCurrent();
}
const currentGroupChallenge = getCurrentGroupChallenge();
if (!currentGroupChallenge) return;
const userData = getCurrentUserData();
const isParticipant = isUserInGroupChallenge();
const userParticipantData = getUserGroupChallengeData();
const participants = getAllGroupChallengeParticipants();
const totalPrize = calculateTotalPrize();
const remainingTime = getGroupChallengeRemainingTime();
const isFull = isGroupChallengeFull();
// Отображение нескольких челленджей
let challengeText = currentGroupChallenge.title;
if (currentGroupChallenge.challenges && currentGroupChallenge.challenges.length > 1) {
challengeText = '<div style="text-align: left; margin-bottom: 15px;">';
currentGroupChallenge.challenges.forEach((challenge, index) => {
challengeText += `<div><i class="fas fa-chevron-right" style="margin-right: 8px; color: var(--warning);"></i>${challenge.title}</div>`;
});
challengeText += '</div>';
}
document.getElementById('group-challenge-title').innerHTML = challengeText;
// Отображение максимальных пропусков
let maxSkipsText = '';
if (currentGroupChallenge.challenges && currentGroupChallenge.challenges.length > 0) {
const maxSkips = Math.min(...currentGroupChallenge.challenges.map(c => c.maxSkips));
maxSkipsText = maxSkips;
} else {
maxSkipsText = currentGroupChallenge.maxSkips || 3;
}
document.getElementById('group-max-skips').textContent = maxSkipsText;
document.getElementById('group-challenge-timer').textContent = formatGroupChallengeTime(remainingTime);
document.getElementById('group-prize-amount').textContent = `${totalPrize} ₽`;
document.getElementById('participant-count').textContent = `${participants.length}/${GROUP_CHALLENGE_MAX_PARTICIPANTS}`;
const alreadyJoinedDiv = document.getElementById('group-challenge-already-joined');
if (isParticipant) {
alreadyJoinedDiv.classList.remove('hidden');
} else {
alreadyJoinedDiv.classList.add('hidden');
}
const limitReachedDiv = document.getElementById('group-challenge-limit-reached');
if (isFull && !isParticipant) {
limitReachedDiv.classList.remove('hidden');
} else {
limitReachedDiv.classList.add('hidden');
}
const joinBtn = document.getElementById('btn-join-group-challenge');
if (isParticipant || isFull || !currentGroupChallenge.isActive) {
joinBtn.disabled = true;
if (isParticipant) {
joinBtn.innerHTML = '<i class="fas fa-check"></i> Вы уже участвуете';
} else if (isFull) {
joinBtn.innerHTML = '<i class="fas fa-ban"></i> Достигнут лимит участников';
} else {
joinBtn.innerHTML = '<i class="fas fa-clock"></i> Челлендж завершён';
}
} else {
joinBtn.disabled = false;
joinBtn.innerHTML = '<i class="fas fa-wallet"></i> Присоединиться за 500 ₽';
}
const userProgressDiv = document.getElementById('user-group-progress');
if (isParticipant && userParticipantData) {
userProgressDiv.classList.remove('hidden');
const totalMarked = (userParticipantData.daysDone || 0) + (userParticipantData.daysSkipped || 0);
const progressPercent = Math.round((totalMarked / 7) * 100);
document.getElementById('user-group-days-done').textContent = userParticipantData.daysDone || 0;
document.getElementById('user-group-skips').textContent = userParticipantData.daysSkipped || 0;
document.getElementById('user-group-max-skips').textContent = maxSkipsText;
document.getElementById('user-group-progress-bar').style.width = `${progressPercent}%`;
const skipWarning = document.getElementById('user-group-skip-warning');
if (userParticipantData.daysSkipped >= maxSkipsText) {
skipWarning.style.display = 'block';
} else {
skipWarning.style.display = 'none';
}
renderGroupChallengeHistory(userParticipantData.history || []);
} else {
userProgressDiv.classList.add('hidden');
}
renderGroupChallengeParticipants(participants);
let totalDaysDone = 0;
let activeParticipants = participants.filter(p => p.isActive);
if (activeParticipants.length > 0) {
activeParticipants.forEach(p => {
totalDaysDone += p.daysDone;
});
const avgDaysDone = Math.round(totalDaysDone / activeParticipants.length);
document.getElementById('group-days-done').textContent = avgDaysDone;
document.getElementById('group-progress-bar').style.width = `${Math.round((avgDaysDone / 7) * 100)}%`;
} else {
document.getElementById('group-days-done').textContent = '0';
document.getElementById('group-progress-bar').style.width = '0%';
}
}
function renderGroupChallengeParticipants(participants) {
const participantsContainer = document.getElementById('group-challenge-participants');
if (participants.length === 0) {
participantsContainer.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon"><i class="fas fa-users"></i></div>
<p>Пока нет участников</p>
<p style="font-size: 14px; margin-top: 8px;">Будьте первым!</p>
</div>
`;
return;
}
let html = '';
const sortedParticipants = [...participants].sort((a, b) => {
return new Date(a.joinedAt || 0) - new Date(b.joinedAt || 0);
});
sortedParticipants.forEach((participant, index) => {
const totalDays = participant.daysDone + participant.daysSkipped;
const isActive = participant.isActive;
const isCurrentUser = participant.email === getCurrentUser();
let participantClass = '';
let statusText = '';
let statusIcon = '';
if (!isActive) {
participantClass = 'failed';
statusText = 'Срыв';
statusIcon = '<i class="fas fa-skull"></i>';
} else if (totalDays >= 7 && participant.daysSkipped <= getCurrentGroupChallenge().challenges?.[0]?.maxSkips || getCurrentGroupChallenge().maxSkips) {
participantClass = 'success';
statusText = 'Завершён';
statusIcon = '<i class="fas fa-check"></i>';
} else {
statusText = `${participant.daysDone}/7 дней`;
statusIcon = '<i class="fas fa-fire"></i>';
}
html += `
<div class="group-challenge-participant ${participantClass}">
<div>
<div class="group-challenge-participant-name">
${isCurrentUser ? '<i class="fas fa-user"></i> ' : ''}${participant.username}
${isCurrentUser ? '<span style="font-size: 12px; color: var(--gray-500); margin-left: 5px;">(Вы)</span>' : ''}
</div>
<div style="font-size: 13px; color: var(--gray-600); margin-top: 5px;">${statusIcon} ${statusText}</div>
</div>
<div class="group-challenge-participant-stats">
<div><i class="fas fa-check" style="color: var(--success);"></i> ${participant.daysDone}</div>
<div><i class="fas fa-times" style="color: var(--danger);"></i> ${participant.daysSkipped}</div>
</div>
</div>
`;
});
participantsContainer.innerHTML = html;
}
function renderGroupChallengeHistory(history) {
const historyList = document.getElementById('group-history-list');
if (!history || history.length === 0) {
historyList.innerHTML = '<p style="text-align: center; color: var(--gray-500); padding: 20px;">История пока пуста</p>';
return;
}
let html = '';
const sortedHistory = [...history].sort((a, b) => new Date(b.date) - new Date(a.date));
sortedHistory.forEach(entry => {
let statusText = '';
let statusClass = '';
let statusIcon = '';
if (entry.status === 'completed') {
statusText = 'Выполнено';
statusClass = 'status-success';
statusIcon = '<i class="fas fa-check"></i>';
} else if (entry.status === 'skipped') {
statusText = 'Пропущено';
statusClass = 'status-skipped';
statusIcon = '<i class="fas fa-times"></i>';
}
const date = new Date(entry.date);
const formattedDate = date.toLocaleDateString('ru-RU', {
day: '2-digit',
month: '2-digit',
weekday: 'short'
});
html += `
<div class="history-item">
<div class="history-date">${formattedDate}</div>
<div class="history-status ${statusClass.replace('status-', '')}">
${statusIcon} ${statusText}
</div>
</div>
`;
});
historyList.innerHTML = html;
}
// ==================== ЛОГИКА ПРИЛОЖЕНИЯ ====================
function loadUserData() {
const userData = getCurrentUserData();
if (!userData) return;
// Загружаем аватар
if (userData.avatar) {
const avatarImage = document.getElementById('avatar-image');
const avatarPlaceholder = document.getElementById('avatar-placeholder');
avatarImage.src = userData.avatar;
avatarImage.classList.remove('hidden');
avatarPlaceholder.classList.add('hidden');
}
// Загружаем логин
updateLoginDisplay();
// Обновляем баланс
updateBalanceDisplay();
// Загружаем челленджи
allChallenges = userData.challenges || [];
// Загружаем общий челлендж
currentGroupChallenge = getCurrentGroupChallenge();
}
function updateUserDisplayData() {
loadUserData();
}
function updateBalanceDisplay() {
const balance = getUserBalance();
const balanceAmount = document.getElementById('balance-amount');
const profileBalance = document.getElementById('profile-balance-amount');
if (balanceAmount) {
balanceAmount.textContent = balance;
}
if (profileBalance) {
profileBalance.textContent = balance;
}
}
function updateLoginDisplay() {
const userData = getCurrentUserData();
if (!userData) return;
const loginDisplay = document.getElementById('user-login-display');
const profileEmailDisplay = document.getElementById('profile-user-email-display');
if (loginDisplay) {
loginDisplay.innerHTML = `
@${userData.username}
<button class="edit-login-btn" id="edit-login-btn" title="Изменить логин">
<i class="fas fa-edit"></i>
</button>
`;
// Добавляем обработчик для кнопки изменения логина
const editLoginBtn = document.getElementById('edit-login-btn');
if (editLoginBtn) {
editLoginBtn.addEventListener('click', (e) => {
e.stopPropagation();
showChangeLoginModal();
});
}
}
if (profileEmailDisplay) {
profileEmailDisplay.textContent = userData.email;
}
}
function loadProfileData() {
const userData = getCurrentUserData();
if (!userData) return;
// Обновляем статистику
const stats = calculateUserStats(userData);
document.getElementById('total-challenges').textContent = stats.total;
document.getElementById('completed-challenges').textContent = stats.completed;
document.getElementById('failed-challenges').textContent = stats.failed;
document.getElementById('active-challenges').textContent = stats.active;
document.getElementById('total-days').textContent = stats.totalCompletedDays + stats.totalSkippedDays;
document.getElementById('success-rate').textContent = stats.successRate + '%';
document.getElementById('total-completed-days').textContent = stats.totalCompletedDays;
document.getElementById('total-skipped-days').textContent = stats.totalSkippedDays;
document.getElementById('total-bets').textContent = stats.totalBets;
document.getElementById('average-bet').textContent = stats.total > 0 ? Math.round(stats.totalBets / stats.total) : 0;
// Обновляем баланс в профиле
document.getElementById('profile-balance-amount').textContent = userData.balance || 0;
// Обновляем отображение логина
updateLoginDisplay();
}
function calculateUserStats(userData) {
const challenges = userData.challenges || [];
const stats = {
total: challenges.length,
completed: 0,
failed: 0,
active: 0,
totalCompletedDays: 0,
totalSkippedDays: 0,
totalBets: 0,
successRate: 0
};
challenges.forEach(challenge => {
if (challenge.isActive) {
stats.active++;
} else {
if (challenge.completedAsSuccess) {
stats.completed++;
} else {
stats.failed++;
}
}
stats.totalCompletedDays += challenge.totalCompleted || 0;
stats.totalSkippedDays += challenge.totalSkipped || 0;
stats.totalBets += challenge.bet || 0;
});
if (stats.total > 0) {
stats.successRate = Math.round((stats.completed / (stats.completed + stats.failed)) * 100) || 0;
}
return stats;
}
function loadActiveHabit() {
if (currentHabitIndex === -1 || !allChallenges[currentHabitIndex]) {
showScreen('start');
return;
}
const habit = allChallenges[currentHabitIndex];
document.getElementById('active-habit-title').textContent = `${habit.exercise}: ${habit.sets} подход(ов) по ${habit.reps} раз, ${habit.daysPerWeek} раз(а) в неделю`;
document.getElementById('active-bet').textContent = habit.bet;
document.getElementById('active-mode').textContent = habit.mode === 'charity' ? 'На благотворительность' : 'В общий котёл (розыгрыш)';
const daysDone = habit.totalCompleted || 0;
const daysSkipped = habit.totalSkipped || 0;
const maxSkips = habit.maxSkips || 4;
document.getElementById('days-done').textContent = daysDone;
document.getElementById('days-total').textContent = 7;
document.getElementById('skip-current').textContent = daysSkipped;
document.getElementById('skip-max').textContent = maxSkips;
const totalMarked = daysDone + daysSkipped;
const progressPercent = Math.round((totalMarked / 7) * 100);
document.getElementById('progress-bar').style.width = `${progressPercent}%`;
// Обновляем индикатор пропусков
const skipIndicator = document.getElementById('skip-indicator');
const skipWarning = document.getElementById('skip-warning');
const skipLimitReachedWarning = document.getElementById('skip-limit-reached-warning');
if (daysSkipped >= maxSkips) {
skipIndicator.classList.add('limit-reached');
skipWarning.style.display = 'block';
skipLimitReachedWarning.style.display = 'block';
} else {
skipIndicator.classList.remove('limit-reached');
skipWarning.style.display = 'none';
skipLimitReachedWarning.style.display = 'none';
}
// Загружаем историю
renderHistory(habit.history || []);
}
function renderHistory(history) {
const historyList = document.getElementById('history-list');
if (!history || history.length === 0) {
historyList.innerHTML = '<p style="text-align: center; color: var(--gray-500); padding: 20px;">История пока пуста</p>';
return;
}
let html = '';
const sortedHistory = [...history].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
sortedHistory.forEach(entry => {
let statusText = '';