const playBtn = document.getElementById('play-btn');
const volumeSlider = document.getElementById('volume');
const songName = document.getElementById('song-name');
const nextSong = document.getElementById('next-song');
const cover = document.getElementById('cover');
const progressBar = document.getElementById('progress-bar');
const elapsedTime = document.getElementById('elapsed-time');
const totalDuration = document.getElementById('total-duration');
const background = document.getElementById('background');

const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
const audio = new Audio('https://radiopoder.kevinparejo.com:8000/radio.mp3');
audio.loop = true; // Asegura que la transmisión sea continua (en bucle)
let isPlaying = true;

const apiUrl = 'https://radiopoder.kevinparejo.com/api/nowplaying/radio_poder';

let currentSongStart = 0;
let currentSongDuration = 0;

async function fetchSongInfo() {
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();

        const currentSong = data.now_playing.song;
        const nextSongInfo = data.playing_next ? data.playing_next.song : { text: 'No disponible' };

        const isLive = data.live.is_live; // Verifica si está en vivo

        if (isLive) {
            // Si está en vivo, actualizar con datos de la transmisión
            const streamerName = data.live.streamer_name || 'En vivo';
            const liveSongTitle = currentSong.title || 'Transmisión en vivo';

            // Verificar si existe el cover del streamer
            const liveCover = data.live.art || 'https://via.placeholder.com/150'; // Usar el cover del streamer o un placeholder

            // Mostrar "Live"
            document.getElementById('live-indicator').style.display = 'block'; // Muestra el cuadro "Live"

            // Actualizar la UI con la información del streamer y su cover
            songName.textContent = streamerName; // Mostrar nombre del streamer
            document.getElementById('artist-name').textContent = liveSongTitle; // Mostrar título de la canción en vivo
            nextSong.textContent = '';
            cover.style.backgroundImage = `url(${liveCover})`; // Mostrar cover del streaming
            background.style.backgroundImage = `url(${liveCover})`;

            // Ocultar barra de progreso y tiempos
            progressBar.style.width = '0%';
            progressBar.style.display = 'none';
            elapsedTime.style.display = 'none';
            totalDuration.style.display = 'none';

            // Reproducir el stream en vivo si no está activo
            if (audio.src !== 'https://radiopoder.kevinparejo.com:8000/radio.mp3') {
                audio.src = 'https://radiopoder.kevinparejo.com:8000/radio.mp3';
                audio.play();
            }

            return; // Salir para no actualizar la barra de progreso
        }

        // Si no está en vivo, ocultar el cuadro "Live"
        document.getElementById('live-indicator').style.display = 'none';

        // Si no está en vivo, actualizar la información de la canción
        currentSongStart = data.now_playing.played_at;
        currentSongDuration = data.now_playing.duration;

        songName.textContent = `${currentSong.title}`;
        nextSong.textContent = `Siguiente: ${nextSongInfo.title}`;
        document.getElementById('artist-name').textContent = currentSong.artist || 'Artista desconocido';
        cover.style.backgroundImage = `url(${currentSong.art || 'https://via.placeholder.com/150'})`; // Usar el cover de la canción actual
        background.style.backgroundImage = `url(${currentSong.art || 'https://via.placeholder.com/150'})`;

        // Mostrar duración total de la canción
        totalDuration.textContent = formatTime(currentSongDuration);

        // Mostrar barra de progreso y tiempos si no está en vivo
        progressBar.style.display = 'block';
        elapsedTime.style.display = 'block';
        totalDuration.style.display = 'block';
    } catch (error) {
        songName.textContent = 'Error al cargar información';
        nextSong.textContent = 'Intenta más tarde';
    }
}



function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
}

function updateProgress() {
    if (currentSongDuration > 0 && progressBar.style.display !== 'none') {
        const now = Math.floor(Date.now() / 1000);
        const elapsed = now - currentSongStart;

        if (elapsed <= currentSongDuration) {
            elapsedTime.textContent = formatTime(elapsed);
            const progress = (elapsed / currentSongDuration) * 100;
            progressBar.style.width = `${progress}%`;
        } else {
            elapsedTime.textContent = formatTime(currentSongDuration);
            progressBar.style.width = '100%';
        }
    }
}

// Actualizar la información de la canción cada 10 segundos
setInterval(fetchSongInfo, 10000);
fetchSongInfo();

// Actualizar progreso cada segundo
setInterval(updateProgress, 1000);

playBtn.onclick = function () {
    if (isPlaying) {
        // Silenciar el reproductor sin pausar la transmisión
        audio.muted = true;
        playBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
        isPlaying = false;
    } else {
        // Volver a activar el audio y reanudar la transmisión sin afectar la secuencia
        audio.muted = false;

        // Asegurarnos de que el audio comience a sonar al darle play
        if (audio.paused) {
            audio.play();
        }

        playBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
        isPlaying = true;
    }
};


// Establecer volumen inicial al 20%
audio.volume = 0.2;  // Volumen al 20%
volumeSlider.value = 0.2;  // Sincroniza el valor del control deslizante

// Ajustar volumen
const volumeContainer = document.getElementById('volume-container');
const volumeIcon = document.getElementById('volume-icon');
let hideTimeout;

// Mostrar la barra al pasar el mouse
volumeContainer.onmouseenter = function () {
    clearTimeout(hideTimeout); // Cancelar cualquier ocultamiento pendiente
    volumeContainer.classList.add('show-volume'); // Mantener visible
};

// Ocultar la barra con retraso al salir del contenedor
volumeContainer.onmouseleave = function () {
    hideTimeout = setTimeout(() => {
        volumeContainer.classList.remove('show-volume'); // Ocultar después del retraso
    }, 500); // 500 ms de retraso
};



// Lógica de mute/desmute
let isMuted = false;
let previousVolume = audio.volume; // Guardar el volumen previo al mute

volumeIcon.onclick = function () {
    if (isMobile) {
        // En dispositivos móviles, mostrar la barra de volumen
        volumeSlider.style.display = 'block'; // Mostrar la barra
        volumeContainer.classList.add('show-volume'); // Mantener visible la barra de volumen
    } else {
        // En otros dispositivos, manejar el mute
        if (isMuted) {
            // Restaurar el volumen previo
            audio.volume = previousVolume;
            volumeSlider.value = previousVolume;
            volumeIcon.innerHTML = '<i class="fa-solid fa-volume-low"></i>'; // Cambiar icono a volumen activo
            isMuted = false;
        } else {
            // Guardar el volumen actual y mutear
            previousVolume = audio.volume;
            audio.volume = 0;
            volumeSlider.value = 0;
            volumeIcon.innerHTML = '<i class="fa-solid fa-volume-xmark"></i>'; // Cambiar icono a mute
            isMuted = true;
        }
    }
};

// Ajustar volumen
volumeSlider.oninput = function () {
    audio.volume = volumeSlider.value;
    previousVolume = volumeSlider.value; // Actualizar volumen previo
    volumeIcon.innerHTML = volumeSlider.value > 0 ? '<i class="fa-solid fa-volume-low"></i>' : '<i class="fa-solid fa-volume-xmark"></i>'; // Cambiar icono según el volumen
};


//TUTORIAL PARA REPRODUCIR.
document.addEventListener('DOMContentLoaded', () => {
    const playButton = document.getElementById('play-btn');
        try {
        audio.play().then(() => {
            console.log('Reproducción automática iniciada.');
        }).catch(error => {
            console.warn('La reproducción automática fue bloqueada por el navegador. Espera interacción del usuario.', error);
        });
    } catch (error) {
        console.error('Error al intentar reproducir el audio automáticamente:', error);
    }

    // Crear contenedor y elementos destacados
    const highlightContainer = document.createElement('div');
    highlightContainer.className = 'highlight';

    const highlightCircle = document.createElement('div');
    highlightCircle.className = 'highlight-circle';

    const highlightMessage = document.createElement('div');
    highlightMessage.className = 'highlight-message';
    highlightMessage.textContent = 'Pausar';

    // Envolver el botón Play con el contenedor
    playButton.parentNode.insertBefore(highlightContainer, playButton);
    highlightContainer.appendChild(playButton);
    highlightContainer.appendChild(highlightCircle);
    highlightContainer.appendChild(highlightMessage);

    // Función para eliminar el mensaje y el trazado
    const removeHighlight = () => {
        if (highlightContainer.contains(highlightCircle)) {
            highlightContainer.removeChild(highlightCircle);
        }
        if (highlightContainer.contains(highlightMessage)) {
            highlightContainer.removeChild(highlightMessage);
        }
    };

    // Configurar un temporizador para eliminar después de 1 minuto (60,000 ms)
    const timeout = setTimeout(removeHighlight, 20000);

    // Remover el mensaje y el trazado al hacer doble clic en el botón
    playButton.addEventListener('dblclick', () => {
        clearTimeout(timeout); // Cancelar el temporizador
        removeHighlight(); // Eliminar inmediatamente
    });
});
