/* eslint-disable */

import { onPageLoadComplete } from '@nimius/event-utility';


const customAudioPlayer = () => {
    const audioPlayers = document.querySelectorAll(".c-audio-player__player");
    audioPlayers.forEach(audioPlayer => {
        let lastButtonPressed = null;
        const audio = audioPlayer.querySelector("audio");
        
        function getTimeCodeFromNum(num) {
            let seconds = parseInt(num);
            let minutes = parseInt(seconds / 60);
            seconds -= minutes * 60;
    
            return `${minutes}:${String(seconds).padStart(2, '0')}`;
        }

        // wait for metadata to be loaded before setting the total length
        audio.addEventListener('loadedmetadata', () => {
            const totalLength = getTimeCodeFromNum(audio.duration);
            const lengthElement = audioPlayer.querySelector(".time .length");
            lengthElement.textContent = totalLength;
        });
    
        const timeline = audioPlayer.querySelector(".timeline");
        timeline.addEventListener("click", e => {
            const timelineWidth = window.getComputedStyle(timeline).width;
            const timeToSeek = e.offsetX / parseInt(timelineWidth) * audio.duration;
            audio.currentTime = timeToSeek;
        }, false);
    
        const volumeSlider = audioPlayer.querySelector(".controls .volume-slider");
        volumeSlider.addEventListener('click', e => {
            const sliderWidth = window.getComputedStyle(volumeSlider).width;
            const newVolume = e.offsetX / parseInt(sliderWidth);
            audio.volume = newVolume;
            audioPlayer.querySelector(".controls .volume-percentage").style.width = newVolume * 100 + '%';
        }, false);
    
        setInterval(() => {
            const progressBar = audioPlayer.querySelector(".progress");
            progressBar.style.width = audio.currentTime / audio.duration * 100 + "%";
            audioPlayer.querySelector(".time .current").textContent = getTimeCodeFromNum(audio.currentTime);
        }, 500);
    
        const playBtn = audioPlayer.querySelector(".controls .toggle-play");
        playBtn.addEventListener("click", () => {
            if (audio.paused) {
                playBtn.classList.remove("play");
                playBtn.classList.add("pause");
                audio.play();
            } else {
                playBtn.classList.remove("pause");
                playBtn.classList.add("play");
                audio.pause();
            }
            lastButtonPressed = 'playPause';
        }, false);
    
        audioPlayer.querySelector(".volume-button").addEventListener("click", () => {
            lastButtonPressed = 'muteUnmute';
            toggleMute();
        });
    
        const rewindBtn = audioPlayer.querySelector(".controls .rewind");
        const forwardBtn = audioPlayer.querySelector(".controls .forward");
    
        rewindBtn.addEventListener("click", () => {
            audio.currentTime = Math.max(0, audio.currentTime - 15);
            lastButtonPressed = 'rewind';
        });
    
        forwardBtn.addEventListener("click", () => {
            audio.currentTime = Math.min(audio.duration, audio.currentTime + 15);
            lastButtonPressed = 'forward';
        });
    
        function toggleMute() {
            audio.muted = !audio.muted;
            const volumeButton = audioPlayer.querySelector(".volume-button");
            const unmuteIcon = volumeButton.querySelector(".unmute-icon");
            const muteIcon = volumeButton.querySelector(".mute-icon");            
            if (audio.muted) {
                unmuteIcon.style.display = "none";
                muteIcon.style.display = "block";
            } else {
                unmuteIcon.style.display = "block";
                muteIcon.style.display = "none";
            }
            lastButtonPressed = 'muteUnmute';
        }

        function togglePlayPause() {
            if (audio.paused) {
                playBtn.classList.remove("play");
                playBtn.classList.add("pause");
                audio.play();
            } else {
                playBtn.classList.remove("pause");
                playBtn.classList.add("play");
                audio.pause();
            }
            lastButtonPressed = 'playPause';
        }
      
        function rewind() {
            audio.currentTime = Math.max(0, audio.currentTime - 15);
            lastButtonPressed = 'rewind';
        }
  
        function forward() {
            audio.currentTime = Math.min(audio.duration, audio.currentTime + 15);
            lastButtonPressed = 'forward';
        }

        audioPlayer.addEventListener("keydown", event => {
            if (event.keyCode === 32) {
                event.preventDefault();
                switch (lastButtonPressed) {
                case 'playPause':
                    togglePlayPause();
                    break;
                case 'muteUnmute':
                    toggleMute();
                    break;
                case 'rewind':
                    rewind();
                    break;
                case 'forward':
                    forward();
                    break;
                default:
                    break;
                }
            }
        });
        audioPlayer.setAttribute("tabindex", "0");
    });
};

onPageLoadComplete(() => {
    customAudioPlayer();
});
