<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Audio Player</title>
    <style>
        body {
            background: #475c35;
            color: #FFFFFF;
            font-family: monospace;
            margin: 0;
            padding: 20px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden; /* Prevent scrolling on the entire page */
        }

        #editor {
            text-shadow: 3px 4px 10px #000000;
            font-weight: 1000;
            letter-spacing: 1px;
            outline: none;
            border: none;
            background: #475c35;
            color: #FFFFFF;
            font-family: monospace;
            resize: none;
            font-size: 1em;
            width: 100%;
            height: 150px;
        }

        #output {
            background: #3a4a2b;
            border: 1px solid #5a7143;
            padding: 10px;
            margin-top: 10px;
            height: 20px;
            overflow-y: auto;
            color: lightblue;
            font-family: 'Roboto', 'Arial', sans-serif;
            font-weight: bold;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
            stroke: rgba(255, 255, 255, 0.8);
            stroke-width: 1px;
            -webkit-text-stroke: 1px rgba(0, 0, 0, 0.8);
            font-size: 18px;
        }

        #playlist, #queue {
            list-style-type: none;
            padding: 0;
            margin: 0;
            height: 150px; /* Fixed height for scrolling */
            overflow-y: auto;
            border: 2px solid black;
            font-family: 'Roboto', 'Arial', sans-serif;
            font-weight: bold;
            font-size: 18px;
            color: #ffffff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
            stroke: rgba(255, 255, 255, 0.8);
            stroke-width: 1px;
            -webkit-text-stroke: 1px rgba(0, 0, 0, 0.8);
        }

        #playlist li, #queue li {
            cursor: pointer;
            padding: 5px;
            border-bottom: 1px solid #5a7143;
        }

        #playlist li:hover, #queue li:hover {
            background: #5a7143;
        }

        #player-controls {
            border: 2px solid black;
            background: #3a4a2b;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 10px;
        }

        #player-controls button {
            background: #5a7143;
            color: #FFFFFF;
            border: 2px solid black;
            padding: 5px 10px;
            cursor: pointer;
        }

        #player-controls button:hover {
            background: #333;
            opacity: 0.8;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5),
                        0 2px 10px rgba(255, 255, 255, 0.2);
            transform: translateY(2px);
        }

        #progress-bar {
            width: 100%;
            height: 10px;
            background: #3a4a2b;
            margin-top: 10px;
        }

        #progress {
            width: 0;
            height: 100%;
            background: #ffffff;
            opacity: 0.5;
        }

        input[type="range"] {
            width: 180px;
            height: 10px;
            -webkit-appearance: none;
            appearance: none;
            background: linear-gradient(to left, #5a7143 var(--value, 0%), #5a7143 var(--value, 0%)) no-repeat;
            background-color: green;
            border-radius: 5px;
            overflow: hidden;
            cursor: pointer;
        }

        input[type="range"]::-webkit-slider-thumb {
            width: 20px;
            height: 20px;
            border-radius: 30%;
            background-color: green;
            -webkit-appearance: none;
            appearance: none;
            margin-top: -5px;
            border: 2px solid black;
        }

        .boost {
            background-color: orange !important;
        }

        .boost::-webkit-slider-thumb {
            background-color: orange !important;
        }

        #sliders {
            display: flex;
            gap: 10px;
        }

        #playlistManager, #queue {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #3a4a2b;
            padding: 10px;
            border: 1px solid #5a7143;
            width: 200px;
            max-height: 400px;
            overflow-y: auto;
            z-index: 1000;
        }

        #playlistManager {
            display: none; /* Initially hidden */
        }

        #togglePlaylist {
            position: absolute;
            top: 12px;
            right: 14px;
            background: linear-gradient(45deg, #1a7f2e, #5a7143);
            border: 2px solid black;
            color: white;
            padding: 10px 20px;
            cursor: pointer;
            transition: background 0.4s, transform 0.4s;
            z-index: 1100; /* Above other elements */
            width: 19px;
            height: 18px;
            border-radius: %50;
        }

        #togglePlaylist:hover {
            background: linear-gradient(45deg, #2b9848, #6b8243);
            transform: scale(.9);
        }

        #togglePlaylist:active {
            transform: scale(0.9);
        }

        #contextMenu {
            position: absolute;
            display: none;
            background: #3a4a2b;
            box-shadow: 0 0 10px white;
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
        }

        #contextMenu ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        #contextMenu li {
            padding: 5px;
            cursor: pointer;
            color: white;
        }

        #contextMenu li:hover {
            background-color: #5a7143;
        }

        #tagEditor {
            display: none;
            position: fixed;
            background: #3a4a2b;
            padding: 20px;
            border-radius: 10px;
            z-index: 1000;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        #tagEditor input {
            display: block;
            margin-bottom: 10px;
            width: 100%;
        }

        #tagEditor button {
            margin-top: 10px;
        }

        #equalizer {
            display: none;
            position: absolute;
            background: #3a4a2b;
            padding: 20px;
            border-radius: 10px;
            z-index: 1000;
            top: 200px; /* Position above output */
            left: 10px; /* Position to the left of the queue/playlist */
            width: 180px;
        }

        #equalizer label {
            display: block;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <textarea id="editor" spellcheck="false" autofocus></textarea>
    <div id="output"></div>
    <div id="player-controls">
        <button id="prev">Previous</button>
        <button id="play">Play</button>
        <button id="pause">Pause</button>
        <button id="stop">Stop</button>
        <button id="next">Next</button>
        <span id="current-time">0:00</span> ⧸ <span id="duration">0:00</span>
        <div id="sliders">
            <input type="range" id="volume" min="0" max="2" step="0.01" value="1">
            <input type="range" id="speed" min="0.5" max="2" step="0.1" value="1">
        </div>
    </div>
    <div id="progress-bar"><div id="progress"></div></div>
    <h8 style="opacity: 0;">1</h8>
    <ul id="playlist"></ul>
    <audio id="audio-player"></audio>

    <div id="queue">
        <h3>Queue</h3>
        <ul id="queueList"></ul>
    </div>

    <div id="playlistManager">
        <h3>Playlists</h3>
        <ul id="playlists"></ul>
    </div>

    <button id="togglePlaylist" onclick="togglePlaylistManager()">
    </button>

    <div id="contextMenu">
        <ul id="contextMenuList">
            <li onclick="createNewPlaylist()">Create new playlist</li>
            <li onclick="addCurrentSongToPlaylist()">Add current song to playlist</li>
            <li onclick="playAllSongsContaining()">Play all songs containing...</li>
        </ul>
    </div>

    <div id="tagEditor">
        <h3>Edit Tags</h3>
        <label>Choose new album art / picture</label>
        <input type="text" placeholder="Type upload and hit enter" id="uploadImage">
        <label>Title</label><input type="text" id="title">
        <label>Artist</label><input type="text" id="artist">
        <label>Album</label><input type="text" id="album">
        <label>Track Number</label><input type="text" id="trackNumber">
        <label>Genre</label><input type="text" id="genre">
        <label>Comments</label><input type="text" id="comments">
        <label>Year</label><input type="text" id="year">
        <button onclick="saveTags()">Save</button>
    </div>

    <div id="equalizer">
        <h3>Equalizer</h3>
        <label>Bass</label><input type="range" id="bass" min="-10" max="10" value="0">
        <label>Mids</label><input type="range" id="mids" min="-10" max="10" value="0">
        <label>Treble</label><input type="range" id="treble" min="-10" max="10" value="0">
    </div>

    <script>


    const editor = document.getElementById('editor');
    const output = document.getElementById('output');
    const playlist = document.getElementById('playlist');
    const audioPlayer = document.getElementById('audio-player');
    const playButton = document.getElementById('play');
    const pauseButton = document.getElementById('pause');
    const stopButton = document.getElementById('stop');
    const prevButton = document.getElementById('prev');
    const nextButton = document.getElementById('next');
    const volumeControl = document.getElementById('volume');
    const progressBar = document.getElementById('progress');
    const currentTimeSpan = document.getElementById('current-time');
    const durationSpan = document.getElementById('duration');
    const speedControl = document.getElementById('speed');
    const queueList = document.getElementById('queueList');
    const playlistManager = document.getElementById('playlistManager');
    const contextMenu = document.getElementById('contextMenu');
    const tagEditor = document.getElementById('tagEditor');
    const equalizer = document.getElementById('equalizer');
    const contextMenuList = document.getElementById('contextMenuList');

    let songs = [];
    let currentSongIndex = 0;
    let songCodes = {};
    let isFirstSong = true;
    let isVolumeFocused = true;
    let fastForwardInterval;
    let rewindInterval;
    let queue = [];
    let playlists = {};
    let nextSongIndex = null; // For tracking the loaded song
    let isLooping = false; // Track loop status
    let savedVolume = volumeControl.value; // For mute/unmute functionality

    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const track = audioContext.createMediaElementSource(audioPlayer);
    const gainNode = audioContext.createGain();
    track.connect(gainNode).connect(audioContext.destination);

    volumeControl.addEventListener('input', handleVolumeChange);
    speedControl.addEventListener('input', handleSpeedChange);

    function handleVolumeChange() {
        updateVolume();
    }

    function handleSpeedChange() {
        updateSpeed();
    }

    function updateVolume() {
        const value = parseFloat(volumeControl.value);
        gainNode.gain.value = value;
        if (value > 1) {
            volumeControl.classList.add('boost');
        } else {
            volumeControl.classList.remove('boost');
        }
        volumeControl.style.backgroundSize = `${(value / 2) * 100}% 100%`;
    }

    function updateSpeed() {
        const value = parseFloat(speedControl.value);
        audioPlayer.playbackRate = value;
        speedControl.style.backgroundSize = `${((value - 0.5) / 1.5) * 100}% 100%`;
    }

    document.addEventListener('keydown', function(event) {
        const focusedElement = document.activeElement;
        if (event.altKey && event.key.toLowerCase() === 't') {
            toggleSliderFocus();
        }
        if (focusedElement === volumeControl || (focusedElement !== speedControl && event.key === 'ArrowUp') || (focusedElement !== speedControl && event.key === 'ArrowDown')) {
            if (event.key === 'ArrowUp') {
                changeVolume(0.1);
            } else if (event.key === 'ArrowDown') {
                changeVolume(-0.1);
            }
        }
        if (event.key === 'ArrowRight') {
            if (!fastForwardInterval) {
                fastForwardInterval = setInterval(() => fastForward(1), 100);
            }
        } else if (event.key === 'ArrowLeft') {
            if (!rewindInterval) {
                rewindInterval = setInterval(() => rewind(1), 100);
            }
        }
    });

    document.addEventListener('keyup', function(event) {
        if (event.key === 'ArrowRight' && fastForwardInterval) {
            clearInterval(fastForwardInterval);
            fastForwardInterval = null;
        }
        if (event.key === 'ArrowLeft' && rewindInterval) {
            clearInterval(rewindInterval);
            rewindInterval = null;
        }
    });

    function toggleSliderFocus() {
        if (isVolumeFocused) {
            speedControl.focus();
        } else {
            volumeControl.focus();
        }
        isVolumeFocused = !isVolumeFocused;
    }

    function changeVolume(delta) {
        let newVolume = Math.max(0, Math.min(2, parseFloat(volumeControl.value) + delta));
        volumeControl.value = newVolume;
        updateVolume();
    }

    editor.addEventListener('keydown', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            const command = editor.value.trim();
            executeCommand(command);
            editor.value = '';
        }
    });

    function executeCommand(command) {
        if (command.toLowerCase() === 'load all') {
            loadAllSongs();
        } else if (command.toLowerCase() === 'play') {
            if (nextSongIndex !== null) {
                playLoadedSong();
            } else {
                resumeSong();
            }
        } else if (command.toLowerCase() === 'pause') {
            pauseSong();
        } else if (command.toLowerCase() === 'stop') {
            stopSong();
        } else if (command.toLowerCase() === 'next') {
            playNextSong();
        } else if (command.toLowerCase() === 'previous') {
            playPreviousSong();
        } else if (command.toLowerCase() === 'resume') {
            resumeSong();
        } else if (command.toLowerCase().startsWith('set time:')) {
            setTime(command.substring(9).trim());
        } else if (command.toLowerCase().startsWith('load ')) {
            loadSongByCode(command.substring(5).trim());
        } else if (command.toLowerCase() === 'reset') {
            displayResetOptions();
        } else if (command.toLowerCase() === 'reset all') {
            resetAll();
        } else if (command.toLowerCase() === 'reset audio') {
            resetAudio();
        } else if (command.toLowerCase() === 'reset sliders') {
            resetSliders();
        } else if (command.toLowerCase() === 'reset volume slider') {
            resetVolumeSlider();
        } else if (command.toLowerCase() === 'reset speed slider') {
            resetSpeedSlider();
        } else if (command.toLowerCase() === 'reset time') {
            resetTime();
        } else if (command.toLowerCase() === 'add to queue') {
            addToQueue();
        } else if (command.toLowerCase() === 'add to playlist') {
            addToPlaylist();
        } else if (command.toLowerCase() === 'edit tags') {
            showTagEditor();
        } else if (command.toLowerCase() === 'equalizer') {
            showEqualizer();
        } else if (command.toLowerCase() === 'close equalizer') {
            closeEqualizer();
        } else if (command.toLowerCase() === 'mute') {
            mute();
        } else if (command.toLowerCase() === 'unmute') {
            unmute();
        } else if (command.toLowerCase().startsWith('loop')) {
            handleLoopCommand(command.toLowerCase());
        } else if (command.toLowerCase() === 'close player') {
            window.close();
        } else {
            filterSongs(command);
        }
    }

    function displayResetOptions() {
        output.textContent = 'Available Reset Commands: reset all, reset audio, reset sliders, reset volume slider, reset speed slider, reset time.';
    }

    function resetAll() {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
        audioPlayer.src = '';
        songs = [];
        songCodes = {};
        playlist.innerHTML = '';
        output.textContent = 'All settings and playlists have been reset. Please upload a new folder to start over.';
        resetSliders();
        setTimeout(() => {
            output.textContent = '';
        }, 3000);
    }

    function resetAudio() {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
        output.textContent = 'Audio reset to the beginning.';
    }

    function resetSliders() {
        resetVolumeSlider();
        resetSpeedSlider();
        output.textContent = 'Both sliders have been reset to default values.';
    }

    function resetVolumeSlider() {
        volumeControl.value = 1;
        updateVolume();
        output.textContent = 'Volume slider reset to default value.';
    }

    function resetSpeedSlider() {
        speedControl.value = 1;
        updateSpeed();
        output.textContent = 'Speed slider reset to default value.';
    }

    function resetTime() {
        audioPlayer.currentTime = 0;
        output.textContent = 'Current song time reset to the beginning.';
    }

    function loadAllSongs() {
        const input = document.createElement('input');
        input.type = 'file';
        input.webkitdirectory = true;
        input.multiple = true;
        input.accept = '.mp3,.ogg';
        input.onchange = function(event) {
            songs = Array.from(event.target.files).filter(file => 
                file.name.endsWith('.mp3') || file.name.endsWith('.ogg')
            );
            assignRandomCodes();
            updatePlaylist();
            output.textContent = `Loaded ${songs.length} audio files.`;
        };
        input.click();
    }

    function assignRandomCodes() {
        songCodes = {};
        const usedCodes = new Set();
        songs.forEach(song => {
            let code;
            do {
                code = Math.floor(1000 + Math.random() * 9000).toString();
            } while (usedCodes.has(code));
            usedCodes.add(code);
            songCodes[song.name] = code;
        });
    }

    function updatePlaylist() {
        playlist.innerHTML = '';
        songs.forEach((song, index) => {
            const li = document.createElement('li');
            li.textContent = `${songCodes[song.name]} - ${song.name}`;
            li.onclick = () => {
                currentSongIndex = index;
                playSong();
            };
            li.addEventListener('contextmenu', function(event) {
                event.preventDefault();
                showContextMenuForSong(event, song);
            });
            playlist.appendChild(li);
        });
    }

    function filterSongs(query) {
        const filteredSongs = songs.filter(song => 
            song.name.toLowerCase().includes(query.toLowerCase()) ||
            songCodes[song.name].includes(query)
        );
        playlist.innerHTML = '';
        filteredSongs.forEach((song, index) => {
            const li = document.createElement('li');
            li.textContent = `${songCodes[song.name]} - ${song.name}`;
            li.onclick = () => {
                currentSongIndex = songs.indexOf(song);
                playSong();
            };
            playlist.appendChild(li);
        });
        output.textContent = `Found ${filteredSongs.length} songs matching "${query}".`;
    }

    function playSong() {
        if (songs.length === 0) return;
        const song = songs[currentSongIndex];
        if (song.path) {
            fetch(song.path)
                .then(response => response.blob())
                .then(blob => {
                    audioPlayer.src = URL.createObjectURL(blob);
                    audioPlayer.play();
                    audioContext.resume();
                    output.textContent = `Now playing: ${songCodes[song.name]} - ${song.name}`;
                })
                .catch(error => {
                    console.error('Error loading audio file:', error);
                    output.textContent = `Error playing: ${songCodes[song.name]} - ${song.name}`;
                });
        } else {
            audioPlayer.src = URL.createObjectURL(song);
            audioPlayer.play();
            audioContext.resume();
            output.textContent = `Now playing: ${songCodes[song.name]} - ${song.name}`;
        }
        if (isFirstSong) {
            volumeControl.value = 0.1;
            gainNode.gain.value = 0.1;
            isFirstSong = false;
        }
        updateVolume();
    }

    function playLoadedSong() {
        currentSongIndex = nextSongIndex;
        nextSongIndex = null;
        playSong();
    }

    function resumeSong() {
        if (audioPlayer.paused && audioPlayer.src) {
            audioPlayer.play();
            output.textContent = `Resumed: ${songCodes[songs[currentSongIndex].name]} - ${songs[currentSongIndex].name}`;
        } else if (!audioPlayer.src && songs.length > 0) {
            playSong();
        } else {
            output.textContent = 'No song to resume.';
        }
    }

    function pauseSong() {
        audioPlayer.pause();
        output.textContent = 'Paused';
    }

    function stopSong() {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
        output.textContent = 'Stopped';
    }

    function playNextSong() {
        if (queue.length > 0) {
            currentSongIndex = songs.indexOf(queue.shift());
            updateQueueDisplay();
        } else {
            currentSongIndex = (currentSongIndex + 1) % songs.length;
        }
        playSong();
    }

    function playPreviousSong() {
        currentSongIndex = (currentSongIndex - 1 + songs.length) % songs.length;
        playSong();
    }

    function fastForward(seconds) {
        audioPlayer.currentTime = Math.min(audioPlayer.currentTime + seconds, audioPlayer.duration);
    }

    function rewind(seconds) {
        audioPlayer.currentTime = Math.max(audioPlayer.currentTime - seconds, 0);
    }

    function setTime(timeString) {
        const [minutes, seconds] = timeString.split(':').map(Number);
        if (!isNaN(minutes) && !isNaN(seconds)) {
            const totalSeconds = minutes * 60 + seconds;
            if (totalSeconds >= 0 && totalSeconds <= audioPlayer.duration) {
                audioPlayer.currentTime = totalSeconds;
                output.textContent = `Time set to ${timeString}`;
            } else {
                output.textContent = 'Invalid time. Please enter a valid time within the song duration.';
            }
        } else {
            output.textContent = 'Invalid time format. Please use "Set time: m:ss" format.';
        }
    }

    function loadSongByCode(code) {
        const song = songs.find(s => songCodes[s.name] === code);
        if (song) {
            nextSongIndex = songs.indexOf(song);
            output.textContent = `Loaded: ${songCodes[song.name]} - ${song.name}`;
        } else {
            output.textContent = `No song found with code ${code}`;
        }
    }

    function addToQueue() {
        if (nextSongIndex !== null) {
            queue.push(songs[nextSongIndex]);
            animateQueueAddition(songs[nextSongIndex]);
            nextSongIndex = null; // Reset after adding
        } else if (audioPlayer.src) {
            queue.push(songs[currentSongIndex]);
            animateQueueAddition(songs[currentSongIndex]);
        } else {
            output.textContent = 'Search: Add to queue';
        }
    }

    function animateQueueAddition(song) {
        output.textContent = `Added to queue: ${songCodes[song.name]} - ${song.name}`;
        output.style.transition = 'opacity 0.5s';
        output.style.opacity = 0;
        setTimeout(() => {
            const li = document.createElement('li');
            li.textContent = `${songCodes[song.name]} - ${song.name}`;
            queueList.appendChild(li);
            output.style.opacity = 1;
        }, 500);
    }

    function updateQueueDisplay() {
        queueList.innerHTML = '';
        queue.forEach(song => {
            const li = document.createElement('li');
            li.textContent = `${songCodes[song.name]} - ${song.name}`;
            queueList.appendChild(li);
        });
    }

    function togglePlaylistManager() {
        if (playlistManager.style.display === 'none') {
            playlistManager.style.display = 'block';
        } else {
            playlistManager.style.display = 'none';
        }
    }

    function addToPlaylist() {
        output.textContent = 'What playlist would you like to add it to?';
    }

    function showTagEditor() {
        tagEditor.style.display = 'block';
    }

    function saveTags() {
        // Logic to save tags and allow for file download
        tagEditor.style.display = 'none';
    }

    function showEqualizer() {
        equalizer.style.display = 'block';
    }

    function closeEqualizer() {
        equalizer.style.display = 'none';
    }

    function mute() {
        savedVolume = volumeControl.value;
        volumeControl.value = 0;
        updateVolume();
        output.textContent = 'Muted';
    }

    function unmute() {
        volumeControl.value = savedVolume;
        updateVolume();
        output.textContent = 'Unmuted';
    }

    function handleLoopCommand(command) {
        if (command === 'loop single') {
            audioPlayer.loop = true;
            output.textContent = 'Looping current song';
        } else if (command === 'loop queue') {
            loopQueue();
        } else if (command === 'loop playlist') {
            loopPlaylist();
        } else if (command === 'loop all') {
            loopAll();
        } else {
            audioPlayer.loop = false;
            output.textContent = 'Looping disabled';
        }
    }

    function loopQueue() {
        // Implement logic to loop the queue
    }

    function loopPlaylist() {
        // Implement logic to loop the playlist
    }

    function loopAll() {
        // Implement logic to loop all songs
    }

    function createNewPlaylist() {
        const playlistName = prompt('Enter playlist name:');
        if (playlistName && !playlists[playlistName]) {
            playlists[playlistName] = [];
            updatePlaylistManager();
            output.textContent = `Created playlist: ${playlistName}`;
        } else {
            output.textContent = 'Playlist already exists or invalid name.';
        }
    }

    function updatePlaylistManager() {
        const playlistsElement = document.getElementById('playlists');
        playlistsElement.innerHTML = '';
        for (const [name, songs] of Object.entries(playlists)) {
            const li = document.createElement('li');
            li.textContent = name;
            li.onclick = () => selectPlaylist(name);
            playlistsElement.appendChild(li);
        }
    }

    function selectPlaylist(name) {
        output.textContent = `Selected playlist: ${name}`;
        // Implement playlist selection logic
    }

    function addCurrentSongToPlaylist() {
        const playlistName = prompt('Enter playlist name to add the current song:');
        if (playlistName && playlists[playlistName]) {
            const currentSong = songs[currentSongIndex];
            playlists[playlistName].push(currentSong);
            output.textContent = `Added ${currentSong.name} to ${playlistName}`;
        } else {
            output.textContent = 'Playlist does not exist.';
        }
    }

    function playAllSongsContaining() {
        const keyword = prompt('Enter keyword to play all songs containing it:');
        const matchingSongs = songs.filter(song => song.name.includes(keyword));
        if (matchingSongs.length > 0) {
            queue = matchingSongs;
            playNextSong();
            output.textContent = `Playing all songs containing "${keyword}"`;
        } else {
            output.textContent = `No songs found containing "${keyword}"`;
        }
    }

    function showContextMenuForSong(event, song) {
        contextMenuList.innerHTML = `
            <li onclick="addToQueue('${song.name}')">Add to queue</li>
        `;
        contextMenu.style.left = `${event.pageX}px`;
        contextMenu.style.top = `${event.pageY}px`;
        contextMenu.style.display = 'block';
    }

    document.addEventListener('click', function() {
        contextMenu.style.display = 'none';
    });

    playButton.onclick = playSong;
    pauseButton.onclick = pauseSong;
    stopButton.onclick = stopSong;
    prevButton.onclick = playPreviousSong;
    nextButton.onclick = playNextSong;

    audioPlayer.ontimeupdate = function() {
        const percent = (audioPlayer.currentTime / audioPlayer.duration) * 100;
        progressBar.style.width = `${percent}%`;
        currentTimeSpan.textContent = formatTime(audioPlayer.currentTime);
    };

    audioPlayer.onloadedmetadata = function() {
        durationSpan.textContent = formatTime(audioPlayer.duration);
    };

    audioPlayer.onended = playNextSong;

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    document.addEventListener('keydown', function(event) {
        if (event.ctrlKey && event.shiftKey && event.altKey) {
            if (event.key === 'S') {
                event.preventDefault();
                savePlaylist();
            } else if (event.key === 'O') {
                event.preventDefault();
                loadPlaylist();
            }
        }
    });

    function savePlaylist() {
        const playlistData = songs.map(song => ({
            name: song.name,
            path: song.webkitRelativePath || song.path
        }));
        const blob = new Blob([JSON.stringify(playlistData)], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'playlist.json';
        a.click();
    }

    function loadPlaylist() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.onchange = function(event) {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function(e) {
                const playlistData = JSON.parse(e.target.result);
                songs = playlistData.map(songData => {
                    const song = new File([], songData.name, { type: songData.name.endsWith('.mp3') ? 'audio/mpeg' : 'audio/ogg' });
                    song.path = songData.path;
                    return song;
                });
                assignRandomCodes();
                updatePlaylist();
                output.textContent = `Loaded playlist with ${songs.length} audio files.`;
            };
            reader.readAsText(file);
        };
        input.click();
    }

    let inactivityTimer;
    const inactivityDuration = 2000;

    function resetInactivityTimer() {
        clearTimeout(inactivityTimer);
        inactivityTimer = setTimeout(() => {
            editor.focus();
        }, inactivityDuration);
    }

    document.addEventListener('mousemove', resetInactivityTimer);
    document.addEventListener('keydown', resetInactivityTimer);

    resetInactivityTimer();
    </script>
</body>
</html>