-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
2327 lines (2059 loc) · 104 KB
/
main.js
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
//consts
const CLIENT_ID = '52055e9524af40dcac80249b98ddb7db';
const CLIENT_SECRET = '71e2042b2b614c2cb035672ac98ed69c';
const modeToggle = document.getElementById('mode-toggle');
let accessToken = '';
let audioPlayer = new Audio();
let currentPlaylist = [];
let currentTrackIndex = 0;
modeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
updateModeIcon();
});
//modal-advanced
const expandBtn = document.getElementById("expandBtn");
const maximizeBtn = document.getElementById("maximizeBtn");
const minimizeBtn = document.getElementById("minimizeBtn");
const modalContent = document.querySelector(".modal-content");
const header = document.querySelector(".header");
const resizeHandles = document.querySelectorAll(".resize-handle");
let isExpanded = false;
let isMaximized = false;
let originalSize = { width: modalContent.style.width, height: modalContent.style.height };
let isDragging = false;
let startX, startY, startLeft, startTop, startWidth, startHeight;
let currentResizeHandle;
// Expand button functionality
expandBtn.onclick = function() {
if (!isExpanded) {
originalSize = { width: modalContent.style.width, height: modalContent.style.height };
modalContent.style.width = "90%";
modalContent.style.height = "90%";
isExpanded = true;
} else {
modalContent.style.width = originalSize.width;
modalContent.style.height = originalSize.height;
isExpanded = false;
}
}
// Maximize button functionality
maximizeBtn.onclick = function() {
if (!isMaximized) {
originalSize = { width: modalContent.style.width, height: modalContent.style.height };
modalContent.style.width = "100%";
modalContent.style.height = "100%";
modalContent.style.top = "0";
modalContent.style.left = "0";
modalContent.style.transform = "none";
isMaximized = true;
} else {
modalContent.style.width = originalSize.width;
modalContent.style.height = originalSize.height;
modalContent.style.top = "50%";
modalContent.style.left = "50%";
modalContent.style.transform = "translate(-50%, -50%)";
isMaximized = false;
}
}
// Minimize button functionality
minimizeBtn.onclick = function() {
modal.style.display = "none";
}
// Dragging functionality
header.onmousedown = function(e) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
startLeft = modalContent.offsetLeft;
startTop = modalContent.offsetTop;
}
// Resizing functionality
resizeHandles.forEach(handle => {
handle.addEventListener('mousedown', (e) => {
isResizing = true;
currentResizeHandle = handle;
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(modalContent).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(modalContent).height, 10);
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
e.preventDefault();
});
});
function resize(e) {
if (isResizing) {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
if (currentResizeHandle.classList.contains('bottom-right')) {
modalContent.style.width = `${startWidth + dx}px`;
modalContent.style.height = `${startHeight + dy}px`;
} else if (currentResizeHandle.classList.contains('bottom-left')) {
modalContent.style.width = `${startWidth - dx}px`;
modalContent.style.height = `${startHeight + dy}px`;
modalContent.style.left = `${startLeft + dx}px`;
} else if (currentResizeHandle.classList.contains('top-right')) {
modalContent.style.width = `${startWidth + dx}px`;
modalContent.style.height = `${startHeight - dy}px`;
modalContent.style.top = `${startTop + dy}px`;
} else if (currentResizeHandle.classList.contains('top-left')) {
modalContent.style.width = `${startWidth - dx}px`;
modalContent.style.height = `${startHeight - dy}px`;
modalContent.style.top = `${startTop + dy}px`;
modalContent.style.left = `${startLeft + dx}px`;
}
}
}
function stopResize() {
isResizing = false;
document.removeEventListener('mousemove', resize);
}
document.onmousemove = function(e) {
if (isDragging) {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
modalContent.style.left = startLeft + dx + "px";
modalContent.style.top = startTop + dy + "px";
}
}
document.onmouseup = function() {
isDragging = false;
}
//Spotiy fetch
async function getAccessToken() {
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(CLIENT_ID + ':' + CLIENT_SECRET)
},
body: 'grant_type=client_credentials'
});
const data = await response.json();
accessToken = data.access_token;
}
async function fetchSpotifyData(endpoint) {
if (!accessToken) {
await getAccessToken();
}
const response = await fetch(`https://api.spotify.com/v1/${endpoint}`, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
return await response.json();
}
//playlist-content
async function displayFeaturedPlaylists() {
const data = await fetchSpotifyData('browse/featured-playlists');
const playlists = data.playlists.items;
let html = '<h2>Featured Playlists</h2><div class="grid">';
playlists.forEach(playlist => {
html += `
<div class="grid-item" data-type="playlist" data-id="${playlist.id}">
<img src="${playlist.images[0].url}" alt="${playlist.name}">
<p>${playlist.name}</p>
</div>
`;
});
html += '</div>';
document.getElementById('content').innerHTML = html;
addGridItemListeners();
}
async function displayNewReleases() {
const data = await fetchSpotifyData('browse/new-releases');
const albums = data.albums.items;
let html = '<h2>New Releases</h2><div class="grid">';
albums.forEach(album => {
html += `
<div class="grid-item" data-type="album" data-id="${album.id}">
<img src="${album.images[0].url}" alt="${album.name}">
<p>${album.name}</p>
<p>${album.artists[0].name}</p>
</div>
`;
});
html += '</div>';
document.getElementById('content').innerHTML = html;
addGridItemListeners();
}
async function displayCategories() {
const data = await fetchSpotifyData('browse/categories');
const categories = data.categories.items;
let html = '<h2>Categories</h2><div class="grid">';
categories.forEach(category => {
html += `
<div class="grid-item" data-type="category" data-id="${category.id}">
<img src="${category.icons[0].url}" alt="${category.name}">
<p>${category.name}</p>
</div>
`;
});
html += '</div>';
document.getElementById('content').innerHTML = html;
addGridItemListeners();
}
async function displayPlaylistTracks(playlistId) {
const data = await fetchSpotifyData(`playlists/${playlistId}/tracks`);
displayTracks(data.items.map(item => item.track));
}
async function displayAlbumTracks(albumId) {
const data = await fetchSpotifyData(`albums/${albumId}/tracks`);
displayTracks(data.items);
}
async function displayCategoryPlaylists(categoryId) {
const data = await fetchSpotifyData(`browse/categories/${categoryId}/playlists`);
const playlists = data.playlists.items;
let html = '<h2>Category Playlists</h2><div class="grid">';
playlists.forEach(playlist => {
html += `
<div class="grid-item" data-type="playlist" data-id="${playlist.id}">
<img src="${playlist.images[0].url}" alt="${playlist.name}">
<p>${playlist.name}</p>
</div>
`;
});
html += '</div>';
document.getElementById('content').innerHTML = html;
addGridItemListeners();
}
//shearch artist and play song list
async function searchSpotify() {
const query = document.getElementById('searchInput').value;
if (query) {
const data = await fetchSpotifyData(`search?q=${encodeURIComponent(query)}&type=artist,track`);
displaySearchResults(data);
}
}
//displayArtists
function displaySearchResults(data) {
let html = '<h2>Search Results</h2>';
if (data.artists && data.artists.items.length > 0) {
html += '<h3>Artists</h3><div class="artists-container">';
data.artists.items.forEach(artist => {
html += createArtistCardHTML(artist);
});
html += '</div>';
}
if (data.tracks && data.tracks.items.length > 0) {
html += '<h3>Songs</h3><div class="tracks-container">';
data.tracks.items.forEach((track, index) => {
html += createTrackHTML(track, index);
});
html += '</div>';
currentPlaylist = data.tracks.items;
}
document.getElementById('content').innerHTML = html;
}
//creat card Artist
function createArtistCardHTML(artist) {
const formattedFollowers = formatNumber(artist.followers.total);
const backgroundImage = artist.images[0]?.url || 'https://via.placeholder.com/400';
return `
<div class="artist-card">
<img src="${backgroundImage}" alt="${artist.name}" class="artist-image">
<div class="artist-info">
<h3>${artist.name}</h3>
<p>${formattedFollowers} Followers</p>
<p>Popularity: ${artist.popularity}</p>
<button onclick="displayArtistDetails('${artist.id}')" class="artist-button">View details</button>
<a href="spotify:artist:${artist.id}" class="spotify-link">Open in Spotify</a>
</div>
</div>
`;
}
//format Numbrr
function formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num;
}
//display Artist tracks
async function displayArtistDetails(artistId) {
const artist = await fetchSpotifyData(`artists/${artistId}`);
const topTracks = await fetchSpotifyData(`artists/${artistId}/top-tracks?market=US`);
const relatedArtists = await fetchSpotifyData(`artists/${artistId}/related-artists`);
currentPlaylist = topTracks?.tracks || [];
// Function to determine verification status and badge
const getVerificationBadge = (artist) => {
if (artist?.verified) {
return '<span class="verified-badge" title="Verified Artist">✓</span>';
} else if (artist?.reel) {
return '<span class="reel-badge" title="Spotify Reel Artist">⭐</span>';
}
return '';
};
// Calculate monthly listeners (example calculation)
const monthlyListeners = Math.floor(artist?.followers?.total * 0.4);
let html = `
<div class="artist-profile" style="background-image: url('${artist?.images[0]?.url || 'https://via.placeholder.com/1000'}');">
<div class="artist-info">
<div class="artist-header">
<h2>
${artist?.name || 'Unknown Artist'}
${getVerificationBadge(artist)}
</h2>
<div class="artist-stats">
<div class="stat">
<span class="stat-value">${formatNumber(artist?.followers?.total || 0)}</span>
<span class="stat-label">Followers</span>
</div>
<div class="stat">
<span class="stat-value">${formatNumber(monthlyListeners)}</span>
<span class="stat-label">Monthly Listeners</span>
</div>
<div class="stat">
<span class="stat-value">${artist?.popularity || 'N/A'}</span>
<span class="stat-label">Popularity Score</span>
</div>
</div>
</div>
<div class="artist-details">
<p class="genres">
<strong>Genres:</strong> ${artist?.genres?.join(', ') || 'No genres available'}
</p>
${artist?.external_urls?.spotify ?
`<div class="social-links">
<a href="${artist.external_urls.spotify}" class="spotify-link" target="_blank">
<i class="fab fa-spotify"></i> Open in Spotify
</a>
</div>` : ''
}
</div>
</div>
</div>
<h3>Top Tracks</h3>
<div class="tracks-container">
`;
if (topTracks && topTracks.tracks) {
topTracks.tracks.forEach((track, index) => {
html += createTrackHTML(track, index);
});
} else {
html += '<p>No top tracks available for this artist.</p>';
}
html += '</div>';
html += '<div id="videoContainer" class="video-container"></div>';
html += '<h3>Gallery</h3><div id="imageGallery" class="image-gallery"></div>';
if (relatedArtists && relatedArtists.artists) {
html += '<h3>Similar Artists</h3><div class="related-artists">';
relatedArtists.artists.slice(0, 10).forEach(relatedArtist => {
html += `
<div class="related-artist-card">
<img src="${relatedArtist.images[0]?.url || 'https://via.placeholder.com/100'}"
alt="${relatedArtist.name}">
<div class="related-artist-info">
<p>${relatedArtist.name} ${getVerificationBadge(relatedArtist)}</p>
<span class="popularity">Popularity: ${relatedArtist.popularity}%</span>
<button onclick="displayArtistDetails('${relatedArtist.id}')">View Artist</button>
</div>
</div>
`;
});
html += '</div>';
} else {
html += '<p>No similar artists found.</p>';
}
document.getElementById('content').innerHTML = html;
fetchArtistVideos(artist?.name);
fetchArtistImages(artist?.id);
}
// Add this CSS to your stylesheet
const style = `
<style>
.verified-badge {
display: inline-block;
background-color: #1DB954;
color: white;
width: 20px;
height: 20px;
border-radius: 50%;
text-align: center;
line-height: 20px;
font-size: 12px;
margin-left: 5px;
vertical-align: middle;
}
.reel-badge {
display: inline-block;
background-color: #FFD700;
color: white;
width: 20px;
height: 20px;
border-radius: 50%;
text-align: center;
line-height: 20px;
font-size: 12px;
margin-left: 5px;
vertical-align: middle;
}
.artist-header {
display: flex;
flex-direction: column;
gap: 15px;
}
.artist-stats {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.stat {
display: flex;
flex-direction: column;
align-items: center;
}
.stat-value {
font-size: 1.2em;
font-weight: bold;
}
.stat-label {
font-size: 0.9em;
color: #888;
}
.artist-details {
margin-top: 20px;
}
.social-links {
margin-top: 15px;
}
.related-artist-card {
position: relative;
overflow: hidden;
border-radius: 8px;
transition: transform 0.3s ease;
}
.related-artist-card:hover {
transform: translateY(-5px);
}
.related-artist-info {
padding: 10px;
background: rgba(0, 0, 0, 0.7);
}
.popularity {
font-size: 0.8em;
color: #888;
}
</style>
`;
// Add the style to the document head
document.head.insertAdjacentHTML('beforeend', style);
//creat Track html
function createTrackHTML(track, index) {
return `
<div class="track-item">
<img src="${track.album.images[0].url}" alt="${track.name}">
<div class="track-info">
<p>${track.name}</p>
<p>${track.artists[0].name}</p>
</div>
<div class="track-controls">
<button class="like-btn ${track.liked ? 'active' : ''}" onclick="toggleLike('${track.id}')">
<i class="fas fa-heart"></i>
</button>
<button onclick="playTrack(${index})" class="play-button">
<i class="fas fa-play"></i>
</button>
<button onclick="addToPersonalPlaylist(currentPlaylist[${index}])" class="add-button">
<i class="fas fa-plus"></i>
</button>
<a href="spotify:track:${track.id}" class="spotify-link">
<i class="fab fa-spotify"></i>
</a>
</div>
</div>
`;
}
//artist Videos
async function fetchArtistVideos(artistName) {
// هنا يجب استخدام YouTube API لجلب الفيديوهات الفعلية
const videoContainer = document.getElementById('videoContainer');
videoContainer.innerHTML = '<h3>Arist Videos</h3><div class="video-gallery"></div>';
const videoGallery = videoContainer.querySelector('.video-gallery');
try {
const response = await fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(artistName)}&type=video&key=AIzaSyDULbpO4E6_GML55UQVVjIEkR3oicW3820`);
const data = await response.json();
data.items.forEach(item => {
videoGallery.innerHTML += `
<div class="video-item">
<iframe width="280" height="157" src="https://www.youtube.com/embed/${item.id.videoId}" frameborder="0" allowfullscreen></iframe>
<p>${item.snippet.title}</p>
</div>
`;
});
} catch (error) {
console.error('Error fetching videos:', error);
videoGallery.innerHTML = '<p>An error occurred while processing your request</p>';
}
}
//gallery
async function fetchArtistImages(artistId) {
const data = await fetchSpotifyData(`artists/${artistId}`);
const imageGallery = document.getElementById('imageGallery');
if (data.images && data.images.length > 0) {
data.images.forEach(image => {
imageGallery.innerHTML += `
<div class="gallery-item">
<img src="${image.url}" alt="${data.name}" onclick="openImageModal('${image.url}')">
</div>
`;
});
} else {
imageGallery.innerHTML = '<p>No images available</p>';
}
}
//tabs function
function initTabs() {
const tabButtons = document.querySelectorAll('.tab-button');
const tabPanes = document.querySelectorAll('.tab-pane');
tabButtons.forEach(button => {
button.addEventListener('click', () => {
const tabId = button.getAttribute('data-tab');
// Deactivate all tabs
tabButtons.forEach(btn => btn.classList.remove('active'));
tabPanes.forEach(pane => pane.classList.remove('active'));
// Activate the clicked tab
button.classList.add('active');
document.getElementById(tabId).classList.add('active');
// Update content for the active tab
if (tabId === 'playlistStats') {
updatePlaylistStats();
} else if (tabId === 'recentAdditions') {
updateRecentAdditions();
} else if (tabId === 'playlistItems') {
updatePlaylistItems();
}
});
});
}
//Modal image function
function openImageModal(imageUrl) {
const modal = document.createElement('div');
modal.className = 'image-modal';
modal.innerHTML = `
<span class="close-modal">×</span>
<img src="${imageUrl}" alt="صورة مكبرة">
`;
document.body.appendChild(modal);
modal.querySelector('.close-modal').onclick = () => modal.remove();
}
//save PersonalPLaylist
function savePersonalPlaylist() {
localStorage.setItem('personalPlaylist', JSON.stringify(personalPlaylist));
}
//liste of music
let personalPlaylist = JSON.parse(localStorage.getItem('personalPlaylist')) || [];
// فتح الـ modal
function openPlaylistModal() {
document.getElementById("playlistModal").style.display = "block";
renderPersonalPlaylist(); // عرض قائمة التشغيل عند الفتح
initTabs();
updatePlaylistItems();
}
// إغلاق الـ modal
function closePlaylistModal() {
document.getElementById("playlistModal").style.display = "none";
}
//Updates remove & like
function removeFromPersonalPlaylist(trackId) {
personalPlaylist = personalPlaylist.filter(track => track.id !== trackId);
savePersonalPlaylist();
renderPersonalPlaylist();
updatePlaylistStats(); // Add this line
}
function toggleLike(trackId) {
const track = personalPlaylist.find(t => t.id === trackId);
if (track) {
track.liked = !track.liked;
savePersonalPlaylist();
renderPersonalPlaylist();
updatePlaylistStats(); // Add this line
}
}
//render-personal-list
function renderPersonalPlaylist() {
const playlistItems = document.getElementById('playlistItems');
playlistItems.innerHTML = '';
personalPlaylist.forEach((track, index) => {
const item = document.createElement('div');
item.className = 'playlist-item';
item.innerHTML = `
<img src="${track.image}" alt="${track.name}">
<div class="playlist-item-info">
<p>${track.name}</p>
<p>${track.artist}</p>
</div>
<div class="playlist-item-actions">
<button onclick="playTrack(${index}, true)" style="font-size: 18px; border: none; outlin: none;
background-color: transparent; cursor: pointer; color: black;"><i class="fas fa-play" style="font-size: 18px;"></i></button>
<button class="like-btn ${track.liked ? 'active' : ''}" onclick="toggleLike('${track.id}')">
<i class="fas fa-heart"></i>
</button>
<button class="remove-btn" onclick="removeFromPersonalPlaylist('${track.id}')">
<i class="fas fa-trash"></i>
</button>
</div>
`;
playlistItems.appendChild(item);
});
}
//State playliste
function updatePlaylistStats() {
const totalTracks = personalPlaylist.length;
const likedTracks = personalPlaylist.filter(track => track.liked).length;
// Genre statistics
const genreCounts = {};
personalPlaylist.forEach(track => {
genreCounts[track.genre] = (genreCounts[track.genre] || 0) + 1;
});
const genreChart = new Chart(document.getElementById('genreChart'), {
type: 'pie',
data: {
labels: Object.keys(genreCounts),
datasets: [{
data: Object.values(genreCounts),
backgroundColor: [
'#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'
]
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Genre Distribution'
}
}
});
// 2. نسبة الأغاني المفضلة
const likedChart = new Chart(document.getElementById('likedChart'), {
type: 'doughnut',
data: {
labels: ['Liked', 'Not Liked'],
datasets: [{
data: [likedTracks, totalTracks - likedTracks],
backgroundColor: ['#FF6384', '#36A2EB']
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Liked vs Not Liked Tracks'
}
}
});
// 3. أكثر الفنانين تكرارًا
const artistCounts = {};
personalPlaylist.forEach(track => {
if (!artistCounts[track.artist]) {
artistCounts[track.artist] = { count: 1, imageUrl: track.image };
} else {
artistCounts[track.artist].count++;
// Update imageUrl if it's not set
if (!artistCounts[track.artist].imageUrl) {
artistCounts[track.artist].imageUrl = track.image;
}
}
});
const sortedArtists = Object.entries(artistCounts)
.sort((a, b) => b[1].count - a[1].count)
.slice(0, 8);
const topArtistsElement = document.getElementById('topArtists');
topArtistsElement.innerHTML = '<h3>Top 8 Artists</h3>';
sortedArtists.forEach(([artist, { count, imageUrl }]) => {
topArtistsElement.innerHTML += `
<div class="artist-container">
<div class="top-art">
<img src="${imageUrl || 'https://via.placeholder.com/50'}" alt="${artist}" class="artist-img">
<p class="artist-info">${artist}: ${count} track${count > 1 ? 's' : ''}</p>
</div>
</div>
<style>
.artist-container {
display: inline-block;
flex-wrap: nowrap;
overflow-x: hidden;
gap: 10px;
padding: 15px;
}
.top-art {
flex: 0 0 auto;
width: 200px;
display: flex;
align-items: center;
padding: 15px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
border-radius: 15px;
font-size: 14px;
background-color: var(--hover-bg1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.artist-img {
width: 50px; /* Adjust size as needed */
height: 50px;
border-radius: 50%; /* Makes the image circular */
float: left;
margin-right: 8px;
shape-outside; circle(50%);
object-fit: cover;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); /* Optional shadow */
}
.artist-info {
font-size: 14px;
max-widht: 100px;
font-weight: bold;
color: var(--text-color);
}
</style>
`;
});
// Total playlist duration
const totalDuration = personalPlaylist.reduce((sum, track) => sum + (track.duration_ms || 0), 0);
const hours = Math.floor(totalDuration / 3600000);
const minutes = Math.floor((totalDuration % 3600000) / 60000);
const durationElement = document.getElementById('playlistDuration');
durationElement.innerHTML = `<h3>Total Playlist Duration</h3>
<p>${hours} hours ${minutes} minutes</p>`;
// Average track length
if (totalTracks > 0) {
const avgDuration = totalDuration / totalTracks;
const avgMinutes = Math.floor(avgDuration / 60000);
const avgSeconds = Math.floor((avgDuration % 60000) / 1000);
durationElement.innerHTML += `<p>Average Track Length: ${avgMinutes}:${avgSeconds.toString().padStart(2, '0')}</p>`;
}
// Latest additions
const recentAdditions = [...personalPlaylist]
.sort((a, b) => new Date(b.dateAdded) - new Date(a.dateAdded))
.slice(0, 12);
const recentElement = document.getElementById('recentAdditions');
recentElement.innerHTML = '<h3>Recent Additions</h3>';
recentAdditions.forEach(track => {
recentElement.innerHTML += `
<div class="recent-tracks-container">
<div class="recent-track">
<img src="${track.image}" alt="${track.name}" class="recent-track-img">
<div class="recent-track-info">
<p class="track-name">${track.name}</p>
<p class="track-artist">${track.artist}</p>
</div>
</div>
</div>
<style>
.recent-tracks-container {
display: inline-block;
flex-wrap: nowrap;
overflow-x: auto;
gap: 20px;
padding: 20px 0;
}
.recent-track {
flex: 0 0 auto;
width: 300px;
display: flex;
align-items: center;
padding: 15px;
margin-left: 10px;
box-shadow: 0 1rem 2rem rgba(92, 92, 92, 0.1);
border-radius: 15px;
background-color: var(--hover-bg3);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.recent-track:hover {
transform: translateY(-5px);
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}
.recent-track-img {
width: 100px;
height: 100px;
object-fit: cover;
border-radius: 12px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.recent-track:hover .recent-track-img {
transform: scale(1.05);
}
.recent-track-info {
flex-grow: 1;
margin-left: 15px;
color: var(--text-color);
background-color: transparent;
}
.recent-track-info p{
max-width: 150px;
background-color: transparent;
}
.track-name {
font-size: 16px;
font-weight: bold;
margin: 0 0 5px 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background-color: transparent;
}
.track-artist {
font-size: 14px;
opacity: 0.8;
margin: 0;
white-space: nowrap;
overflow: hidden;
background-color:transparent;
text-overflow: ellipsis;
}
@media (max-width: 768px) {
.recent-track {
width: 250px;
}
.recent-track-img {
width: 80px;
height: 80px;
}
}
</style>
`;
});
}
// تحديث البيانات الإحصائية
function updateTrackStats(track) {
// تحديث تاريخ الإضافة عند إضافة أغنية جديدة
track.dateAdded = new Date().toISOString();
// إضافة معلومات النوع الموسيقي (يمكن تحديثها من API إذا كان متاحًا)
track.genre = track.genre || 'Unknown';
// تحديث مدة الأغنية (يمكن الحصول عليها من API)
track.duration_ms = track.duration_ms || 180000; // افتراضيًا 3 دقائق
}
//add tracks to personalPlaylist
function addToPersonalPlaylist(track) {
const existingTrack = personalPlaylist.find(t => t.id === track.id);
if (!existingTrack) {
const newTrack = {
id: track.id,
name: track.name,
artist: track.artists[0].name,
image: track.album?.images[0]?.url || 'https://via.placeholder.com/50',
preview_url: track.preview_url,
liked: false,
genre: track.genre || 'Unknown',
duration_ms: track.duration_ms || 180000,
dateAdded: new Date().toISOString()
};
personalPlaylist.push(newTrack);
savePersonalPlaylist();
renderPersonalPlaylist();
updatePlaylistStats(); // Make sure this is called here
}
}
function addToPersonalPlaylist(track) {
const existingTrack = personalPlaylist.find(t => t.id === track.id);
if (!existingTrack) {
const newTrack = {
id: track.id,
name: track.name,
artist: track.artists[0].name,
image: track.album?.images[0]?.url || 'https://via.placeholder.com/50',
preview_url: track.preview_url,
liked: false,
genre: track.genre || 'Unknown',
duration_ms: track.duration_ms || 180000,
dateAdded: new Date().toISOString()
};
personalPlaylist.push(newTrack);
savePersonalPlaylist();
renderPersonalPlaylist();
updatePlaylistStats(); // Make sure this is called here
}
}
// Add this to your initialization code
window.addEventListener('load', () => {
personalPlaylist = JSON.parse(localStorage.getItem('personalPlaylist')) || [];
renderPersonalPlaylist();
updatePlaylistStats();