-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.min.js
More file actions
1625 lines (1380 loc) · 55.6 KB
/
app.min.js
File metadata and controls
1625 lines (1380 loc) · 55.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
class VideoApp {
constructor() {
this.currentVideoIndex = 0;
this.videos = [];
this.usernameSuffixes = [];
this.baseUrl = window.location.origin;
this.isUploading = false;
this.currentUsername = null;
this.likedVideos = new Set();
this.viewedVideos = new Set();
this.commentsLimit = 20;
this.searchInput = document.getElementById('searchInput');
this.searchButton = document.getElementById('searchButton');
this.trendingSearches = document.querySelector('.trending-searches');
this.trendingList = document.querySelector('.trending-list');
this.searchTimeout = null;
this.userSearches = new Map();
this.repliesLimit = 3;
this.isScrolling = false;
this.lastScrollTime = 0;
this.replyDepthLimit = 3; // Maximum depth for nested replies
this.expandedReplies = new Set(); // Track which comments have expanded replies
// DOM Elements
this.reelsContainer = document.getElementById('reelsContainer');
this.uploadModal = document.getElementById('uploadModal');
this.uploadForm = document.getElementById('uploadForm');
this.fileInput = document.getElementById('fileInput');
this.dropArea = document.getElementById('dropArea');
this.videoTemplate = document.getElementById('videoTemplate');
this.progressBar = document.querySelector('.progress-fill');
this.progressText = document.querySelector('.progress-text');
this.commentModal = document.getElementById('commentModal');
// Initialize the current user
this.initializeUser();
this.videoLikes = new Map();
this.videoComments = new Map();
this.setupSearch();
this.loadSearchStats();
// Ensure DOM elements exist before initialization
if (this.reelsContainer && this.uploadModal && this.uploadForm) {
this.init();
} else {
console.error('Required DOM elements not found');
}
}
async initializeUser() {
let username = localStorage.getItem('videoAppUsername');
let userId = localStorage.getItem('videoAppUserId');
if (!username || !userId) {
username = this.generateUsername();
userId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
try {
const response = await fetch('api.php?action=update_user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: userId,
username: username,
createdAt: new Date().toISOString()
})
});
if (!response.ok) throw new Error('Failed to create user');
const data = await response.json();
if (data.success) {
localStorage.setItem('videoAppUsername', username);
localStorage.setItem('videoAppUserId', userId);
}
} catch (error) {
console.error('Error creating user:', error);
}
}
this.currentUsername = username;
this.userId = userId;
}
async init() {
try {
await this.loadVideos();
this.setupUploadHandlers();
this.setupIntersectionObserver();
this.setupScrollHandlers();
this.setupModalHandlers();
this.setupCommentInteractions();
} catch (error) {
console.error('Initialization error:', error);
}
}
setupSearch() {
if (!this.searchInput || !this.searchButton) return;
this.searchInput.addEventListener('focus', () => {
this.trendingSearches.classList.add('active');
this.loadSearchStats();
});
document.addEventListener('click', (e) => {
if (!this.searchInput.contains(e.target) &&
!this.trendingSearches.contains(e.target)) {
this.trendingSearches.classList.remove('active');
}
});
this.searchInput.addEventListener('input', (e) => {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => {
this.performSearch(e.target.value);
}, 300);
});
this.searchButton.addEventListener('click', () => {
this.performSearch(this.searchInput.value);
});
this.searchInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.performSearch(this.searchInput.value);
}
});
}
async loadSearchStats() {
try {
const response = await fetch(`api.php?action=search_stats&userId=${encodeURIComponent(this.userId)}`);
const data = await response.json();
if (data.success) {
this.userSearches = new Map(Object.entries(data.userSearches));
this.updateTrendingSearches(data.trending);
}
} catch (error) {
console.error('Error loading search stats:', error);
}
}
async performSearch(query) {
try {
if (!query.trim()) {
await this.loadVideos();
return;
}
const response = await fetch(`api.php?action=search&query=${encodeURIComponent(query)}&userId=${encodeURIComponent(this.userId)}`);
const data = await response.json();
if (data.success) {
// Map the videos with additional data
this.videos = data.results.map(video => ({
...video,
username: video.username || this.generateUsername(),
shareUrl: this.createShareUrl(video.title, video.id),
likes: video.stats.likes || [],
views: video.stats.views || 0,
comments: []
}));
// Reload search stats to update trending
await this.loadSearchStats();
// Render the videos
if (this.reelsContainer) {
this.renderVideos();
}
// If no results found, show a message
if (this.videos.length === 0) {
this.showToast('No videos found', 'info');
}
}
} catch (error) {
console.error('Search error:', error);
this.showToast('Search failed', 'error');
}
}
updateTrendingSearches(trending) {
if (!this.trendingList) return;
this.trendingList.innerHTML = '';
// Create recent searches header
const recentHeader = document.createElement('div');
recentHeader.className = 'trending-section-header';
recentHeader.textContent = 'Your Recent Searches';
this.trendingList.appendChild(recentHeader);
// Add user's recent searches
const userSearches = Array.from(this.userSearches.values())
.sort((a, b) => new Date(b.lastSearched) - new Date(a.lastSearched))
.slice(0, 3);
userSearches.forEach(item => {
const searchItem = document.createElement('div');
searchItem.className = 'trending-item recent-search';
searchItem.innerHTML = `
<i class="fas fa-history"></i>
<span class="trend-query">${this.escapeHtml(item.query)}</span>
<span class="trend-count">${this.formatNumber(item.count)}x</span>
`;
searchItem.addEventListener('click', () => {
this.searchInput.value = item.query;
this.performSearch(item.query);
});
this.trendingList.appendChild(searchItem);
});
// Create trending header
const trendingHeader = document.createElement('div');
trendingHeader.className = 'trending-section-header';
trendingHeader.textContent = 'Trending Searches';
this.trendingList.appendChild(trendingHeader);
// Add trending searches
trending.forEach((item, index) => {
const trendingItem = document.createElement('div');
trendingItem.className = 'trending-item';
trendingItem.innerHTML = `
<span class="trend-number">#${index + 1}</span>
<span class="trend-query">${this.escapeHtml(item.query)}</span>
<span class="trend-count">${this.formatNumber(item.count)} searches</span>
`;
trendingItem.addEventListener('click', () => {
this.searchInput.value = item.query;
this.performSearch(item.query);
});
this.trendingList.appendChild(trendingItem);
});
}
generateUsername() {
const names = ['pixel', 'cosmic', 'neon', 'cyber', 'digital', 'nova', 'stellar', 'lunar', 'solar', 'echo'];
const randomName = names[Math.floor(Math.random() * names.length)];
let randomNum;
do {
randomNum = Math.floor(100000 + Math.random() * 900000);
} while (this.usernameSuffixes.includes(randomNum));
this.usernameSuffixes.push(randomNum);
return `${randomName}${randomNum}`;
}
createShareUrl(title, videoId) {
const sanitizedTitle = title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '');
return `${this.baseUrl}/watch/${sanitizedTitle}-${videoId}`; // <-- change the subfolder if you have if its not a root domain before /watch/ //
}
setupScrollHandlers() {
if (!this.reelsContainer) return;
let startY;
let currentY;
let touchStartTime;
let isMouseWheel = false;
this.reelsContainer.addEventListener('wheel', (e) => {
e.preventDefault();
if (isMouseWheel) return;
isMouseWheel = true;
const now = Date.now();
if (now - this.lastScrollTime < 500) {
isMouseWheel = false;
return;
}
this.lastScrollTime = now;
const direction = e.deltaY > 0 ? 1 : -1;
const currentIndex = Math.round(this.reelsContainer.scrollTop / window.innerHeight);
const targetIndex = Math.max(0, Math.min(currentIndex + direction, this.videos.length - 1));
this.smoothScrollToVideo(targetIndex);
setTimeout(() => {
isMouseWheel = false;
}, 500);
}, { passive: false });
this.reelsContainer.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
touchStartTime = Date.now();
this.isScrolling = true;
}, { passive: false });
this.reelsContainer.addEventListener('touchmove', (e) => {
if (!this.isScrolling) return;
currentY = e.touches[0].clientY;
e.preventDefault();
}, { passive: false });
this.reelsContainer.addEventListener('touchend', () => {
if (!this.isScrolling) return;
const touchEndTime = Date.now();
const touchDuration = touchEndTime - touchStartTime;
const diff = startY - currentY;
if (touchDuration < 300 && Math.abs(diff) > 50) {
const currentIndex = Math.round(this.reelsContainer.scrollTop / window.innerHeight);
const targetIndex = diff > 0 ?
Math.min(currentIndex + 1, this.videos.length - 1) :
Math.max(currentIndex - 1, 0);
this.smoothScrollToVideo(targetIndex);
}
this.isScrolling = false;
});
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
const now = Date.now();
if (now - this.lastScrollTime < 500) return;
this.lastScrollTime = now;
const currentIndex = Math.round(this.reelsContainer.scrollTop / window.innerHeight);
const targetIndex = e.key === 'ArrowDown' ?
Math.min(currentIndex + 1, this.videos.length - 1) :
Math.max(currentIndex - 1, 0);
this.smoothScrollToVideo(targetIndex);
}
});
}
smoothScrollToVideo(index) {
const targetY = index * window.innerHeight;
gsap.to(this.reelsContainer, {
scrollTop: targetY,
duration: 0.5,
ease: "power2.out",
onComplete: () => {
document.querySelectorAll('.video-player').forEach((video, idx) => {
if (idx === index) {
video.play().catch(() => {});
} else {
video.pause();
video.currentTime = 0;
}
});
}
});
}
setupModalHandlers() {
const openModalBtn = document.getElementById('openUploadModal');
const closeModalBtn = document.querySelector('.close-modal');
const modalOverlay = document.querySelector('.modal-overlay');
const commentModalClose = this.commentModal?.querySelector('.close-modal');
if (openModalBtn) {
openModalBtn.addEventListener('click', () => this.openModal());
}
if (closeModalBtn) {
closeModalBtn.addEventListener('click', () => this.closeModal());
}
if (modalOverlay) {
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay) this.closeModal();
});
}
if (commentModalClose) {
commentModalClose.addEventListener('click', () => this.closeCommentModal());
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (this.uploadModal?.classList.contains('active')) {
this.closeModal();
}
if (this.commentModal?.classList.contains('active')) {
this.closeCommentModal();
}
}
});
}
setupCommentInteractions() {
if (!this.commentModal) return;
const closeBtn = this.commentModal.querySelector('.close-modal');
closeBtn?.addEventListener('click', () => this.closeCommentModal());
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.commentModal.classList.contains('active')) {
this.closeCommentModal();
}
});
const commentForm = this.commentModal.querySelector('.comment-form');
commentForm?.addEventListener('submit', async (e) => {
e.preventDefault();
const textarea = commentForm.querySelector('textarea');
const comment = await this.handleComment(this.commentModal.dataset.videoId, textarea.value);
if (comment) {
textarea.value = '';
this.updateCommentsUI(this.commentModal.dataset.videoId);
}
});
}
setupIntersectionObserver() {
const options = {
root: null,
rootMargin: '0px',
threshold: 0.8
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const video = entry.target.querySelector('.video-player');
if (!video) return;
if (entry.isIntersecting) {
video.play().catch(err => console.log('Autoplay prevented'));
this.animateVideoEntry(entry.target);
this.handleVideoView(entry.target.dataset.videoId);
} else {
video.pause();
video.currentTime = 0;
}
});
}, options);
document.querySelectorAll('.reel').forEach(reel => observer.observe(reel));
}
async handleVideoView(videoId) {
if (this.viewedVideos.has(videoId)) return;
try {
const response = await fetch('api.php?action=update_views', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
videoId: videoId,
username: this.currentUsername,
userId: this.userId
})
});
const data = await response.json();
if (data.success) {
this.viewedVideos.add(videoId);
const video = this.videos.find(v => v.id === videoId);
if (video) {
video.views = data.stats.views;
this.updateVideoStats(videoId);
}
}
} catch (error) {
console.error('Error updating view count:', error);
}
}
updateVideoStats(videoId) {
const video = this.videos.find(v => v.id === videoId);
const statsElement = document.querySelector(`[data-video-id="${videoId}"] .video-stats`);
if (statsElement && video) {
statsElement.textContent = `@${video.username} • ${this.formatNumber(video.views)} views`;
}
}
closeCommentModal() {
if (!this.commentModal) return;
gsap.to(this.commentModal, {
x: '100%',
duration: 0.3,
ease: "power2.in",
onComplete: () => {
this.commentModal.classList.remove('active');
document.body.style.overflow = '';
}
});
}
findComment(commentId, comments) {
if (!Array.isArray(comments)) return null;
for (const comment of comments) {
if (comment.id === commentId) return comment;
// Search in replies
if (comment.replies && comment.replies.length > 0) {
const found = this.findComment(commentId, comment.replies);
if (found) return found;
}
}
return null;
}
countTotalComments(comments) {
if (!Array.isArray(comments)) return 0;
let total = 0;
const countNestedComments = (comment) => {
let count = 1; // Count the comment itself
if (Array.isArray(comment.replies)) {
comment.replies.forEach(reply => {
count += countNestedComments(reply); // Count each reply recursively
});
}
return count;
};
comments.forEach(comment => {
total += countNestedComments(comment);
});
return total;
}
animateVideoEntry(reel) {
const videoInfo = reel.querySelector('.video-info');
const videoActions = reel.querySelector('.video-actions');
gsap.fromTo([videoInfo, videoActions],
{ opacity: 0, y: 20 },
{
opacity: 1,
y: 0,
duration: 0.5,
stagger: 0.1,
ease: "power2.out"
}
);
}
async loadVideos() {
try {
// First ensure the maps are initialized
this.videoLikes = this.videoLikes || new Map();
this.videoComments = this.videoComments || new Map();
// Load videos
const response = await fetch('api.php?action=get_videos');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
if (!data.success) throw new Error('Failed to load videos');
// Load likes and comments
await this.loadLikesAndComments();
// Map the videos with additional data
this.videos = (data.videos || []).map(video => ({
...video,
username: video.username || this.generateUsername(),
shareUrl: this.createShareUrl(video.title, video.id),
likes: Array.from(this.videoLikes.get(video.id) || []),
comments: Array.from(this.videoComments.get(video.id) || []),
views: 0
}));
if (this.reelsContainer) {
this.renderVideos();
}
} catch (error) {
console.error('Error loading videos:', error);
this.videos = [];
this.showToast('Failed to load videos', 'error');
}
}
async loadLikesAndComments() {
try {
// Initialize Maps
this.videoLikes = new Map();
this.videoComments = new Map();
const [likesResponse, commentsResponse] = await Promise.all([
fetch('api.php?action=get_stats').then(res => res.json()).catch(() => ({ success: true, stats: {} })),
fetch('api.php?action=get_comments').then(res => res.json()).catch(() => ({ success: true, comments: {} }))
]);
// Handle stats/likes
if (likesResponse.stats) {
Object.entries(likesResponse.stats).forEach(([videoId, stats]) => {
if (stats && Array.isArray(stats.likes)) {
this.videoLikes.set(videoId, stats.likes);
} else {
this.videoLikes.set(videoId, []);
}
});
}
// Handle comments
if (commentsResponse.comments) {
Object.entries(commentsResponse.comments).forEach(([videoId, comments]) => {
this.videoComments.set(videoId, Array.isArray(comments) ? comments : []);
});
}
} catch (error) {
console.error('Error loading likes and comments:', error);
// Ensure Maps are initialized even if loading fails
this.videoLikes = new Map();
this.videoComments = new Map();
}
}
processComments(comments) {
if (!Array.isArray(comments)) return [];
const commentMap = new Map();
const topLevelComments = [];
comments.forEach(comment => {
comment.replies = comment.replies || [];
commentMap.set(comment.id, comment);
if (!comment.parentCommentId) {
topLevelComments.push(comment);
} else {
const parentComment = commentMap.get(comment.parentCommentId);
if (parentComment) {
parentComment.replies.push(comment);
}
}
});
return topLevelComments;
}
countTotalReplies(comment) {
let total = comment.replies.length;
comment.replies.forEach(reply => {
total += this.countTotalReplies(reply);
});
return total;
}
renderVideos() {
if (!this.reelsContainer) return;
gsap.to(this.reelsContainer, {
opacity: 0,
duration: 0.2,
onComplete: () => {
this.reelsContainer.innerHTML = '';
this.videos.forEach((video, index) => {
const reel = this.createVideoReel(video, index);
this.reelsContainer.appendChild(reel);
});
gsap.to(this.reelsContainer, {
opacity: 1,
duration: 0.2,
onComplete: () => {
this.setupIntersectionObserver();
}
});
}
});
}
createVideoReel(video, index) {
const reel = this.videoTemplate.content.cloneNode(true).querySelector('.reel');
const videoElement = reel.querySelector('.video-player');
const videoInfo = reel.querySelector('.video-info');
const title = videoInfo.querySelector('.video-title');
const stats = videoInfo.querySelector('.video-stats');
// Set video source
videoElement.src = video.url;
videoElement.loop = true;
videoElement.muted = true;
videoElement.setAttribute('playsinline', '');
// Set video info
if (title) title.textContent = video.title || 'Untitled';
if (stats) {
stats.textContent = `@${video.username || 'anonymous'} • ${this.formatNumber(video.views || 0)} views`;
}
// Set video ID for interactions
reel.setAttribute('data-video-id', video.id);
// Setup interactions
this.setupVideoInteractions(reel, video);
return reel;
}
setupVideoInteractions(reel, video) {
if (!reel || !video) return;
const videoElement = reel.querySelector('.video-player');
const likeBtn = reel.querySelector('.like-btn');
const shareBtn = reel.querySelector('.share-btn');
const commentBtn = reel.querySelector('.comment-btn');
const likeCount = likeBtn?.querySelector('.count');
const commentCount = commentBtn?.querySelector('.count');
// Set initial like count
if (likeCount) {
likeCount.textContent = this.formatNumber(video.likes.length);
if (video.likes.includes(this.currentUsername)) {
likeBtn.classList.add('liked');
}
}
// Set initial comment count (including all replies)
if (commentCount) {
const totalComments = video.comments.reduce((total, comment) => {
return total + 1 + this.countTotalReplies(comment);
}, 0);
commentCount.textContent = this.formatNumber(totalComments);
}
// Double tap to like
let lastTap = 0;
reel.addEventListener('touchstart', (e) => {
const currentTime = new Date().getTime();
const tapLength = currentTime - lastTap;
if (tapLength < 300 && tapLength > 0) {
this.handleLike(video.id);
this.showLikeAnimation(e.touches[0].clientX, e.touches[0].clientY);
}
lastTap = currentTime;
});
videoElement?.addEventListener('click', () => {
if (videoElement.paused) {
videoElement.play().catch(err => console.log('Playback prevented'));
} else {
videoElement.pause();
}
});
likeBtn?.addEventListener('click', (e) => {
e.stopPropagation();
this.handleLike(video.id);
});
shareBtn?.addEventListener('click', (e) => {
e.stopPropagation();
this.handleShare(video);
});
commentBtn?.addEventListener('click', (e) => {
e.stopPropagation();
this.openCommentModal(video.id);
});
}
async handleLike(videoId) {
if (!this.currentUsername) return;
const video = this.videos.find(v => v.id === videoId);
if (!video) return;
try {
const isLiked = video.likes.includes(this.currentUsername);
const response = await fetch('api.php?action=update_likes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
videoId: videoId,
username: this.currentUsername,
userId: this.userId,
action: isLiked ? 'unlike' : 'like'
})
});
const data = await response.json();
if (data.success) {
if (isLiked) {
video.likes = video.likes.filter(username => username !== this.currentUsername);
} else {
video.likes.push(this.currentUsername);
}
this.updateLikeUI(videoId);
}
} catch (error) {
console.error('Error updating like:', error);
this.showToast('Failed to update like', 'error');
}
}
updateLikeUI(videoId) {
const likeBtn = document.querySelector(`[data-video-id="${videoId}"] .like-btn`);
const likeCount = likeBtn?.querySelector('.count');
const video = this.videos.find(v => v.id === videoId);
if (likeBtn && video) {
const isLiked = video.likes.includes(this.currentUsername);
likeBtn.classList.toggle('liked', isLiked);
if (likeCount) {
likeCount.textContent = this.formatNumber(video.likes.length);
gsap.from(likeCount, {
scale: 1.2,
duration: 0.3,
ease: "back.out(1.7)"
});
}
}
}
showLikeAnimation(x, y) {
const heart = document.createElement('div');
heart.className = 'heart-animation';
heart.innerHTML = '❤️';
heart.style.left = `${x - 25}px`;
heart.style.top = `${y - 25}px`;
document.body.appendChild(heart);
gsap.to(heart, {
y: -100,
opacity: 0,
scale: 2,
duration: 1,
ease: "power2.out",
onComplete: () => heart.remove()
});
}
createTimelineComment(comment, depth = 0) {
const el = document.createElement('div');
el.className = 'comment-timeline-item';
el.dataset.commentId = comment.id;
el.dataset.depth = depth;
// Calculate total replies recursively
const totalReplies = this.calculateTotalReplies(comment);
const hasReplies = totalReplies > 0;
el.innerHTML = `
<div class="timeline-item">
<div class="comment-content">
${depth > 0 ? `<div class="reply-thread-line" style="background: ${this.generateThreadColor(depth)}"></div>` : ''}
<div class="comment-header">
<div class="user-info">
<div class="user-avatar" style="background: ${this.generateAvatarColor(comment.username)}">
${comment.username.charAt(0).toUpperCase()}
</div>
<div class="user-details">
<span class="comment-username">@${comment.username}</span>
<span class="comment-time">${this.formatTime(comment.timestamp)}</span>
${depth > 0 ? '<span class="reply-indicator">Reply</span>' : ''}
</div>
</div>
</div>
<div class="comment-text">${this.escapeHtml(comment.text || comment.comment)}</div>
<div class="comment-actions">
<button class="reply-btn">
<i class="fas fa-reply"></i>
${hasReplies ? `Reply (${this.formatNumber(totalReplies)})` : 'Reply'}
</button>
</div>
</div>
</div>
<div class="comment-replies"></div>
`;
// Add replies if they exist
const repliesContainer = el.querySelector('.comment-replies');
if (hasReplies && comment.replies) {
comment.replies.forEach(reply => {
repliesContainer.appendChild(this.createTimelineComment(reply, depth + 1));
});
}
// Setup reply button interaction
const replyBtn = el.querySelector('.reply-btn');
replyBtn.addEventListener('click', () => this.showReplyForm(comment.id, depth));
return el;
}
// Add this method to generate thread colors
generateThreadColor(depth) {
const colors = [
'#2196F3', // Material Blue
'#FF5252', // Coral Red
'#4CAF50', // Material Green
'#FF9800', // Material Orange
'#9C27B0', // Material Purple
'#00BCD4', // Cyan
'#F44336', // Material Red
'#8BC34A', // Light Green
'#673AB7', // Deep Purple
'#FF4081', // Pink
'#009688', // Teal
'#FFC107', // Amber
'#3F51B5', // Indigo
'#CDDC39', // Lime
'#795548' // Brown
];
return colors[depth % colors.length];
}
// Modify updateCommentsUI
updateCommentsUI(videoId) {
if (!this.commentModal) return;
const commentsList = this.commentModal.querySelector('.comments-list');
const video = this.videos.find(v => v.id === videoId);
if (!commentsList || !video) return;
commentsList.innerHTML = '';
if (video.comments) {
video.comments.forEach(comment => {
commentsList.appendChild(this.createTimelineComment(comment, 0));
});
}
}
calculateTotalReplies(comment) {
let total = 0;
if (comment.replies && Array.isArray(comment.replies)) {
total = comment.replies.length;
comment.replies.forEach(reply => {
total += this.calculateTotalReplies(reply);
});
}
return total;
}
generateAvatarColor(username) {
const colors = [
'linear-gradient(45deg, #FF6B6B, #FF8E8E)',
'linear-gradient(45deg, #4ECDC4, #6EE7DE)',
'linear-gradient(45deg, #45B7D1, #6AD5EE)',
'linear-gradient(45deg, #96C93D, #B5E555)',
'linear-gradient(45deg, #9B59B6, #B07CC6)',
'linear-gradient(45deg, #3498DB, #5DADE2)',
'linear-gradient(45deg, #FC913A, #FFB067)',
'linear-gradient(45deg, #2ECC71, #55D98D)'
];
// Generate a consistent index based on username
const index = username.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
return colors[index % colors.length];
}
createTimelineReply(reply) {
const el = document.createElement('div');
el.className = 'timeline-reply';
el.dataset.replyId = reply.id;
el.innerHTML = `
<div class="reply-content">
<div class="reply-header">
<div class="user-info">
<div class="user-avatar">${reply.username.charAt(0).toUpperCase()}</div>
<span class="reply-username">@${reply.username}</span>
</div>
<span class="reply-time">${this.formatTime(reply.timestamp)}</span>
</div>
<div class="reply-text">${this.escapeHtml(reply.text || reply.comment)}</div>
<div class="reply-actions">
<button class="reply-btn">
<i class="fas fa-reply"></i>
Reply
</button>
</div>
</div>
`;
const replyBtn = el.querySelector('.reply-btn');
replyBtn.addEventListener('click', () => {
this.showReplyForm(reply.id);
});
return el;
}
openCommentModal(videoId) {
if (!this.commentModal) return;
const video = this.videos.find(v => v.id === videoId);
if (!video) return;
this.commentModal.dataset.videoId = videoId;
const commentsList = this.commentModal.querySelector('.comments-list');
const commentForm = this.commentModal.querySelector('.comment-form');