const audio = document.getElementById("audio");
const playBtn = document.getElementById("play");
const progress = document.getElementById("progress");
const current = document.getElementById("current");
const duration = document.getElementById("duration");
const rewind = document.getElementById("rewind");
const forward = document.getElementById("forward");

const modal = document.getElementById("audioPlayer");
const closeBtnMp3 = document.getElementById("closePlayer");
const dragHandle = document.getElementById("dragHandle");

const playlist = document.querySelector(".playlist");

let isPlaying = false;

// Play / Pause
playBtn.addEventListener("click", () => {
    if (isPlaying) {
        audio.pause();
        playBtn.innerHTML = '<img src="icons/play.svg" class="control-icon">';
    } else {
        audio.play();
        playBtn.innerHTML = '<img src="icons/pause.svg" class="control-icon" width="32" height="32">';
    }
    isPlaying = !isPlaying;
});

// Update duration
audio.addEventListener("loadedmetadata", () => {
    duration.textContent = formatTime(audio.duration);
});

// Update progress
audio.addEventListener("timeupdate", () => {
    progress.value = (audio.currentTime / audio.duration) * 100;
    current.textContent = formatTime(audio.currentTime);
});

// Seek
progress.addEventListener("input", () => {
    audio.currentTime = (progress.value / 100) * audio.duration;
});

// Rewind 10s
rewind.addEventListener("click", () => {
    audio.currentTime -= 10;
});

// Forward 10s
forward.addEventListener("click", () => {
    audio.currentTime += 10;
});

// Format time
function formatTime(time) {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
}

// Mostrar

document.addEventListener("click", (event) => {
    const openPlayer = event.target.closest(".openPlayer");

    if (openPlayer) {
        menuAudios.classList.remove('show');

        const title = openPlayer.getAttribute("data-title");
        const subtitle = openPlayer.getAttribute("data-subtitle");
        const path = openPlayer.getAttribute("data-path");
        const dataEncode = openPlayer.getAttribute('data-info');
        const listSong = JSON.parse(decodeURIComponent(dataEncode));

        playlist.innerHTML = '';

        for (const [clave, valor] of Object.entries(listSong)) {
            const realName = valor.replace(/\.[^/.]+$/, "");
            playlist.innerHTML += `<div class="track disabled option-track" data-path="${path}/${valor}">${realName}</div>`;
        }

        audio.src = `${path}/${listSong['Track 1']}`;

        document.getElementById("audioTitle").textContent = title;
        document.getElementById("audioSubtitle").textContent = subtitle;

        modal.classList.remove("hidden");
        menuRecursosExtras.classList.remove('show');
    }
});

playlist.addEventListener('click', (event) => {
    if (event.target.classList.contains('option-track')) {
        event.target.classList.remove('disabled');
        event.target.classList.add('active');

        //remover active de los demás
        const tracks = playlist.querySelectorAll('.track');
        tracks.forEach(track => {
            if (track !== event.target) {
                track.classList.remove('active');
                track.classList.add('disabled');
            }
        });

        const path = event.target.getAttribute('data-path');

        // antes de cambiar la canción, verificar si hay una canción sonando y pausarla
        if (isPlaying) {
            audio.pause();
            playBtn.innerHTML = '<img src="icons/play.svg" class="control-icon">';
            isPlaying = false;
        }

        audio.src = path;
        audio.play();
        playBtn.innerHTML = '<img src="icons/pause.svg" class="control-icon" width="32" height="32">';
        isPlaying = true;
    }
});

// Ocultar
closeBtnMp3.addEventListener("click", () => {
    // Pausar audio si está sonando y resetear el botón y estado
    if (isPlaying) {
        audio.pause();
        playBtn.innerHTML = '<img src="icons/play.svg" class="control-icon">';
        isPlaying = false;
        progress.value = 0;
        current.textContent = "0:00";
        audio.src = ""; // Limpiar fuente para liberar recursos
        duration.textContent = "0:00";

    }
    modal.classList.add("hidden");
});


let isDraggingMp3 = false;
let offsetXMp3 = 0;
let offsetYMp3 = 0;

dragHandle.addEventListener("mousedown", (e) => {
    isDraggingMp3 = true;
    offsetXMp3 = e.clientX - modal.offsetLeft;
    offsetY = e.clientY - modal.offsetTop;
    dragHandle.style.cursor = "grabbing";
});

document.addEventListener("mousemove", (e) => {
    if (!isDraggingMp3) return;

    modal.style.left = `${e.clientX - offsetXMp3}px`;
    modal.style.top = `${e.clientY - offsetY}px`;
});

document.addEventListener("mouseup", () => {
    isDraggingMp3 = false;
    dragHandle.style.cursor = "grab";
});