import Foundation

struct AmplitudeSong: Codable {
    let name: String
    let artist: String
    let album: String
    let track: String
    let url: String
    let cover_art_url: String
}

struct AudioPlayerScript: HtmlProducer {

    let items: [AmplitudeSong]

    init(items: [AmplitudeSong]) {
        self.items = items
    }

    func populate(_ result: inout String) {
        result += "<script>window.onload = () => { "
        result += "Amplitude.init({ songs: "
        let songData = try! JSONEncoder().encode(items)
        result += String(data: songData, encoding: .utf8)!
        result += "}); }; " // Close Amplitude.init and window.onload
        result += "function playEntry(index) { Amplitude.playSongAtIndex(index) };"
        result += animatePlaylist
        result += "</script>"
    }

    private var animatePlaylist: String {
        """
        const el = document.getElementById('playlist-container')
        document.getElementsByClassName('show-playlist')[0].addEventListener('click', function(){
            el.classList.remove('slide-out-top');
            el.classList.add('slide-in-top');
            el.style.display = "block";
        });
        document.getElementsByClassName('close-playlist')[0].addEventListener('click', function(){
            el.classList.remove('slide-in-top');
            el.classList.add('slide-out-top');
            el.style.display = "none";
        });
        """
    }
}
