// Centralized function to handle liking/unliking and updating all elements const handleLikeClick = (trackId, folderPath, button) => { const isCurrentlyLiked = hasUserLiked(trackId); const isNewLikedStatus = !isCurrentlyLiked; // ACTION: Use the appropriate PHP file based on the desired status const actionFile = isNewLikedStatus ? 'like_track.php' : 'unlike_track.php'; // Perform the AJAX request fetch(folderPath + actionFile + '?track=' + encodeURIComponent(trackId)) .then(response => response.text()) .then(newCount => { recordUserLike(trackId, isNewLikedStatus); // 1. Update the Now Playing button state if (trackId === currentPlaylist[currentTrackIndex].getAttribute('data-full-src')) { if (isNewLikedStatus) { nowPlayingLikeButton.classList.add('liked-top'); nowPlayingLikeButton.textContent = '❤️ Liked'; } else { nowPlayingLikeButton.classList.remove('liked-top'); nowPlayingLikeButton.textContent = '♡ Like'; } } // 2. Update the main list button state const mainButton = document.querySelector(`.like-button[data-track-id="${trackId}"]`); if (mainButton) { if (isNewLikedStatus) { mainButton.classList.add('liked'); } else { mainButton.classList.remove('liked'); } } // 3. Update the like count display const likeCountSpan = document.querySelector(`[data-like-for="${trackId}"]`); if (likeCountSpan) { likeCountSpan.textContent = newCount; } }) .catch(error => console.error(`Error processing like/unlike request:`, error)); };