document.addEventListener('DOMContentLoaded', () => {
// Initialize animations
const animatedElements = document.querySelectorAll('.fade-in, .slide-up');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate');
observer.unobserve(entry.target);
}
});
}, {
threshold: 0.1
});
animatedElements.forEach(el => observer.observe(el));
// Load playlist
fetch('/api/playlist')
.then(response => response.json())
.then(data => renderPlaylist(data));
// Search functionality
document.getElementById('search-btn').addEventListener('click', () => {
const query = document.getElementById('search-input').value.trim();
if (query) {
fetch('/api/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query })
})
.then(response => response.json())
.then(data => renderSearchResults(data));
}
});
// Playlist item click handler
document.getElementById('playlist-grid').addEventListener('click', (e) => {
if (e.target.classList.contains('remove-btn') || e.target.closest('.remove-btn')) {
const card = e.target.closest('.music-card');
const id = parseInt(card.dataset.id);
removeFromPlaylist(id);
}
});
// Search result click handler
document.getElementById('search-grid').addEventListener('click', (e) => {
const card = e.target.closest('.music-card');
if (!card) return;
if (e.target.classList.contains('remove-btn') || e.target.closest('.remove-btn')) {
card.remove();
} else {
const id = parseInt(card.dataset.id);
addToPlaylist(id);
card.classList.add('selected');
setTimeout(() => card.classList.remove('selected'), 1000);
}
});
});
function renderPlaylist(songs) {
const grid = document.getElementById('playlist-grid');
grid.innerHTML = '';
songs.forEach(song => {
const card = createMusicCard(song, true);
grid.appendChild(card);
});
}
function renderSearchResults(songs) {
const grid = document.getElementById('search-grid');
grid.innerHTML = '';
songs.forEach(song => {
const card = createMusicCard(song, false);
grid.appendChild(card);
});
}
function createMusicCard(song, isPlaylist) {
const card = document.createElement('div');
card.className = `music-card ${song.downloaded ? 'downloaded' : 'not-downloaded'}`;
card.dataset.id = song.id;
card.innerHTML = `
${song.duration}