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]

    private let encoder = JSONEncoder()

    init(items: [AmplitudeSong]) {
        self.items = items
        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    }

    func populate(_ result: inout String) {
        result += "<script>\nwindow.onload = () => { "
        result += "Amplitude.init({ songs: "
        let songData = try! encoder.encode(items)
        result += String(data: songData, encoding: .utf8)!
        result += "}); };\n" // Close Amplitude.init and window.onload
        result += "function playEntry(index) { Amplitude.playSongAtIndex(index) };"
        result += animatePlaylist
        result += "\n</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";
        });
        """
    }
}
