
document.addEventListener('DOMContentLoaded', function() {
    const chatForm = document.getElementById('chat-form');
    const chatBox = document.getElementById('chat-box');
    const chatInput = document.getElementById('chat-input');
    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    chatForm.addEventListener('submit', function(event) {
        event.preventDefault();

        const userMessage = chatInput.value.trim();
        if (userMessage === '') {
            return;
        }

        // Add user message to chat box
        appendMessage(userMessage, 'user-message');
        chatInput.value = '';

        fetch(window.location.href, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: new URLSearchParams({
                'message': userMessage
            })
        })
        .then(response => response.json())
        .then(data => {
            // Add AI message to chat box
            appendMessage(data.ai_message, 'ai-message');

            // If a playlist is returned, display it
            if (data.playlist && data.playlist.length > 0) {
                displayPlaylist(data.playlist);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            appendMessage('Sorry, something went wrong.', 'ai-message');
        });
    });

    function appendMessage(message, className) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('chat-message', className);
        const p = document.createElement('p');
        p.textContent = message;
        messageElement.appendChild(p);
        chatBox.appendChild(messageElement);
        chatBox.scrollTop = chatBox.scrollHeight; // Scroll to bottom
    }

    function displayPlaylist(playlist) {
        let playlistContainer = document.querySelector('.playlist-container');
        if (!playlistContainer) {
            playlistContainer = document.createElement('div');
            playlistContainer.classList.add('playlist-container');
            
            const heroSection = document.querySelector('.hero-section');
            heroSection.appendChild(playlistContainer);
        }

        playlistContainer.innerHTML = ''; // Clear previous playlist

        const title = document.createElement('h2');
        title.classList.add('playlist-title');
        title.textContent = 'Your Playlist';
        playlistContainer.appendChild(title);

        const ul = document.createElement('ul');
        ul.classList.add('playlist');
        
        playlist.forEach(song => {
            const li = document.createElement('li');
            li.classList.add('playlist-item');
            if (song.video_id) {
                li.innerHTML = `<iframe width="100%" height="315" src="https://www.youtube.com/embed/${song.video_id}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
            } else {
                li.innerHTML = `<span class="song-title">${song.title}</span> - <span class="song-artist">${song.artist}</span> (Video not found)`;
            }
            ul.appendChild(li);
        });

        playlistContainer.appendChild(ul);
    }
});
