{% extends 'base_blank.html' %}
{% load i18n %}
{% load static %}

{% block extra_css %}
<style>
    body {
        margin: 0;
        background-color: black;
        overflow: hidden;
    }
    .slideshow-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .slide {
        position: absolute;
        width: 100%;
        height: 100%;
        opacity: 0;
        transition: all 0.5s ease-in-out;
        display: flex;
        align-items: center;
        justify-content: center;
        transform: scale(1) rotate(0deg);
        filter: blur(0px);
    }
    .slide.active {
        opacity: 1;
    }
    /* Transition Effects */
    .slide.fade-out {
        opacity: 0;
    }
    .slide.slide-out {
        transform: translateX(-100%);
    }
    .slide.scale-out {
        transform: scale(0.8);
        opacity: 0;
    }
    .slide.rotate-out {
        transform: rotate(-15deg);
        opacity: 0;
    }
    .slide.blur-out {
        filter: blur(10px);
        opacity: 0;
    }
    .slide img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
    }
    .image-description {
        position: absolute;
        bottom: 5rem;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.7);
        padding: 1rem;
        border-radius: 0.5rem;
        color: white;
        max-width: 80%;
        text-align: center;
    }
    .image-description p {
        margin: 0;
    }
    .controls {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 1rem;
        background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        gap: 0.5rem;
        opacity: 1;
        transition: opacity 0.5s ease-in-out;
        pointer-events: auto;
    }
    .controls[style*="opacity: 0"] {
        pointer-events: none;
    }
    .slideshow-container:hover .controls,
    .controls:focus-within {
        opacity: 1;
    }
    .control-button {
        background: rgba(255,255,255,0.1);
        border: none;
        color: white;
        padding: 0.5rem;
        border-radius: 0.375rem;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: background-color 0.2s;
        font-size: 0.9rem;
        min-width: 44px;
        min-height: 44px;
        justify-content: center;
    }
    .control-button:hover {
        background: rgba(255,255,255,0.2);
    }
    .control-group {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background: rgba(255,255,255,0.1);
        padding: 0.5rem;
        border-radius: 0.375rem;
    }
    .slider {
        -webkit-appearance: none;
        width: 100px;
        height: 4px;
        border-radius: 2px;
        background: rgba(255,255,255,0.2);
        outline: none;
    }
    .slider::-webkit-slider-thumb {
        -webkit-appearance: none;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: #3b82f6;
        cursor: pointer;
    }
    #intervalValue {
        color: white;
        min-width: 30px;
        font-size: 0.9rem;
    }
    .progress-circle {
        position: fixed;
        top: 1rem;
        right: 1rem;
        width: 24px;
        height: 24px;
        z-index: 50;
        opacity: 0.8;
        transition: opacity 0.3s;
    }
    .slideshow-container:hover .progress-circle {
        opacity: 1;
    }
    .progress-circle-bg {
        fill: none;
        stroke: rgba(255, 255, 255, 0.2);
        stroke-width: 2.5;
    }
    .progress-circle-path {
        fill: none;
        stroke: #3b82f6;
        stroke-width: 2.5;
        stroke-linecap: round;
        transform: rotate(-90deg);
        transform-origin: center;
    }
    .music-playlist {
        position: fixed;
        bottom: 5rem;
        left: 50%;
        transform: translateX(-50%);
        background-color: rgba(0, 0, 0, 0.9);
        padding: 1rem;
        border-radius: 0.5rem;
        display: none;
        width: 90%;
        max-width: 400px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
    }
    .settings-panel {
        position: fixed;
        bottom: 5rem;
        left: 50%;
        transform: translateX(-50%);
        background-color: rgba(0, 0, 0, 0.9);
        padding: 1rem;
        border-radius: 0.5rem;
        display: none;
        width: 90%;
        max-width: 400px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
    }
    .settings-content {
        max-height: 60vh;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    .settings-group {
        margin: 1rem 0;
        padding: 0.75rem;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 0.375rem;
    }
    .settings-group h4 {
        color: #fff;
        margin: 0 0 0.5rem 0;
        font-size: 0.9rem;
        font-weight: 500;
        opacity: 0.8;
    }
    .settings-item {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin: 0.5rem 0;
    }
    .settings-item .slider {
        flex: 1;
    }
    .settings-item span {
        color: white;
        min-width: 40px;
        font-size: 0.9rem;
    }
    .playlist-content {
        max-height: 60vh;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    .playlist-items {
        margin-top: 1rem;
    }
    .playlist-item {
        padding: 0.75rem;
        cursor: pointer;
        color: #fff;
        border-radius: 0.375rem;
        transition: background-color 0.2s;
        font-size: 1rem;
        min-height: 44px;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .playlist-item:hover {
        background-color: rgba(255, 255, 255, 0.1);
    }
    .playlist-item.active {
        background-color: rgba(59, 130, 246, 0.5);
        font-weight: 500;
    }
    .playlist-item input[type="checkbox"] {
        width: 18px;
        height: 18px;
        margin: 0;
    }
    .playlist-controls {
        display: flex;
        justify-content: center;
        margin-top: 1rem;
        padding-top: 1rem;
        border-top: 1px solid rgba(255, 255, 255, 0.1);
    }
    .playlist-controls button {
        background: rgba(59, 130, 246, 0.5);
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        cursor: pointer;
        transition: background-color 0.2s;
        font-size: 0.9rem;
    }
    .playlist-controls button:hover {
        background: rgba(59, 130, 246, 0.7);
    }
    .playlist-content h3 {
        color: #fff;
        margin: 0;
        font-size: 1.1rem;
        font-weight: 500;
        text-align: center;
    }
    .transition-options {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 0.5rem;
    }
    .transition-option {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 0.375rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    .transition-option:hover {
        background: rgba(255, 255, 255, 0.1);
    }
    .transition-option input[type="radio"] {
        width: 16px;
        height: 16px;
        margin: 0;
    }
    .transition-option label {
        color: white;
        font-size: 0.9rem;
        cursor: pointer;
    }
    
    @media (max-width: 768px) {
        .controls {
            padding: 0.75rem;
            gap: 0.25rem;
        }
        .control-button {
            padding: 0.5rem;
            font-size: 0.8rem;
        }
        .control-button span {
            display: none;
        }
        .control-button svg {
            width: 20px;
            height: 20px;
        }
        .music-playlist {
            bottom: 4rem;
        }
        #musicText {
            display: inline !important;
            font-size: 0.8rem;
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
    
    @media (max-width: 480px) {
        .music-playlist {
            width: 95%;
            max-height: 50vh;
        }
        .playlist-item {
            padding: 0.5rem;
            font-size: 0.9rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="slideshow-container">
    <div class="progress-circle">
        <svg viewBox="0 0 36 36">
            <circle class="progress-circle-bg"
                    cx="18" cy="18" r="16"/>
            <circle class="progress-circle-path"
                    cx="18" cy="18" r="16"
                    stroke-dasharray="100 100"
                    stroke-dashoffset="100"/>
        </svg>
    </div>

    {% for image in collection.images.all %}
    <div class="slide {% if forloop.first %}active{% endif %}" data-url="{{ image.get_url }}" data-id="{{ image.id }}">
        <img src="{{ image.get_url }}" alt="{{ image.title }}" loading="lazy">
        {% if image.description %}
        <div class="image-description">
            <p class="description-text">{{ image.description }}</p>
        </div>
        {% endif %}
    </div>
    {% endfor %}

    <div class="controls">
        <button class="control-button" onclick="togglePlayPause()" id="playPauseBtn">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" id="playPauseIcon">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6"/>
            </svg>
            <span id="playPauseText">{% trans "Pause" %}</span>
        </button>
        <button class="control-button" onclick="previousSlide()">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
            </svg>
            <span>{% trans "Previous" %}</span>
        </button>
        <button class="control-button" onclick="nextSlide()">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
            </svg>
            <span>{% trans "Next" %}</span>
        </button>
        <button class="control-button" onclick="toggleMusic()" id="musicBtn">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" id="musicIcon">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"/>
            </svg>
            <span id="musicText">{% trans "Mute" %}</span>
        </button>
        <button class="control-button" onclick="togglePlaylist()">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
            </svg>
            <span>{% trans "Playlist" %}</span>
        </button>
        <button class="control-button" onclick="toggleSettings()">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
            </svg>
            <span>{% trans "Settings" %}</span>
        </button>
        <button class="control-button" onclick="exitSlideshow()">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
            <span>{% trans "Exit" %}</span>
        </button>
    </div>
</div>

<div class="settings-panel">
    <div class="settings-content">
        <h3>{% trans "Slideshow Settings" %}</h3>
        <div class="settings-group">
            <h4>{% trans "Transition Interval" %}</h4>
            <div class="settings-item">
                <input type="range" class="slider" id="intervalSlider" min="2000" step="1000" max="15000" value="5000" oninput="updateInterval(this.value)">
                <span id="intervalValue">5s</span>
            </div>
        </div>
        <div class="settings-group">
            <h4>{% trans "Transition Effect" %}</h4>
            <div class="transition-options">
                <div class="transition-option">
                    <input type="radio" id="effect-fade" name="transition-effect" value="fade" checked>
                    <label for="effect-fade">Fade</label>
                </div>
                <div class="transition-option">
                    <input type="radio" id="effect-slide" name="transition-effect" value="slide">
                    <label for="effect-slide">Slide</label>
                </div>
                <div class="transition-option">
                    <input type="radio" id="effect-scale" name="transition-effect" value="scale">
                    <label for="effect-scale">Scale</label>
                </div>
                <div class="transition-option">
                    <input type="radio" id="effect-rotate" name="transition-effect" value="rotate">
                    <label for="effect-rotate">Rotate</label>
                </div>
                <div class="transition-option">
                    <input type="radio" id="effect-blur" name="transition-effect" value="blur">
                    <label for="effect-blur">Blur</label>
                </div>
            </div>
        </div>
        <div class="settings-group">
            <h4>{% trans "Description Display" %}</h4>
            <div class="settings-item">
                <input type="checkbox" id="showDescriptions" onchange="toggleDescriptions(this.checked)" checked>
                <label for="showDescriptions">{% trans "Show Image Descriptions" %}</label>
            </div>
        </div>
    </div>
</div>

<audio id="backgroundMusic">
    <source src="" type="audio/mpeg">
    Your browser does not support the audio element.
</audio>

<div class="music-playlist">
    <div class="playlist-content">
        <h3>{% trans "Music Playlist" %}</h3>
        <div class="playlist-items" id="playlistItems">
        </div>
        <div class="playlist-controls">
            <button onclick="updatePlaylist()">{% trans "Update" %}</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let playlist = [];
let selectedSongs = new Set();
let activePlaylist = [];
let currentSlide = 0;
let currentSongIndex = 0;
const slides = document.querySelectorAll('.slide');
const totalSlides = slides.length;
let slideInterval = null;
let progressInterval = null;
let isPlaying = true;
let INTERVAL_TIME = 5000; // 5 seconds, configurable through slider
const CONTROLS_HIDE_DELAY = 6000; // 6 seconds
let startTime = null;
let animationFrame = null;
let controlsTimeout = null;
let currentEffect = 'fade';
const backgroundMusic = document.getElementById('backgroundMusic');
let isMusicPlaying = true;

// Function to hide controls
function hideControls() {
    const controls = document.querySelector('.controls');
    controls.style.opacity = '0';
}

// Function to show controls
function showControls() {
    const controls = document.querySelector('.controls');
    controls.style.opacity = '1';
    
    // Reset the timeout
    if (controlsTimeout) {
        clearTimeout(controlsTimeout);
    }
    controlsTimeout = setTimeout(hideControls, CONTROLS_HIDE_DELAY);
}

// Add mousemove event listener to show controls
document.addEventListener('mousemove', showControls);

// Add keydown event listener to show controls
document.addEventListener('keydown', showControls);

async function fetchPlaylist() {
    try {
        const response = await fetch('{% url "api-music-list" %}');
        if (!response.ok) {
            throw new Error('Failed to fetch playlist');
        }
        const data = await response.json();
        if (!Array.isArray(data)) {
            throw new Error('Invalid playlist format');
        }
        playlist = data;
        if (playlist.length > 0) {
            // Select all songs by default
            selectedSongs = new Set(playlist.map((_, index) => index));
            // Set active playlist to all songs
            activePlaylist = [...playlist];
            populatePlaylist();
            loadSong(0);
            isMusicPlaying = true;
        } else {
            isMusicPlaying = false;
            updateMusicDisplay();
        }
    } catch (error) {
        console.error('Error fetching playlist:', error);
        playlist = [];
        selectedSongs = new Set();
        activePlaylist = [];
        isMusicPlaying = false;
        updateMusicDisplay();
    }
}

function loadSong(index) {
    if (!activePlaylist || activePlaylist.length === 0) {
        isMusicPlaying = false;
        updateMusicDisplay();
        return;
    }
    currentSongIndex = (index + activePlaylist.length) % activePlaylist.length;
    const song = activePlaylist[currentSongIndex];
    if (!song || !song.src) {
        console.error('Invalid song data:', song);
        return;
    }
    backgroundMusic.src = song.src;
    if (isMusicPlaying && isPlaying) {
        backgroundMusic.play().catch(error => {
            console.error('Error playing music:', error);
            isMusicPlaying = false;
            updateMusicDisplay();
        });
    }
    updateMusicDisplay();
    populatePlaylist();
}

function nextSong() {
    loadSong(currentSongIndex + 1);
}

function previousSong() {
    loadSong(currentSongIndex - 1);
}

function updateMusicDisplay() {
    const musicText = document.getElementById('musicText');
    if (!activePlaylist || activePlaylist.length === 0) {
        musicText.textContent = 'No music selected';
        return;
    }
    const currentSong = activePlaylist[currentSongIndex];
    musicText.textContent = isMusicPlaying ? `${currentSong.title} (Playing)` : `${currentSong.title} (Muted)`;
}

function toggleSongSelection(index) {
    if (selectedSongs.has(index)) {
        selectedSongs.delete(index);
    } else {
        selectedSongs.add(index);
    }
    populatePlaylist();
}

function updatePlaylist() {
    if (selectedSongs.size === 0) {
        activePlaylist = [];
        isMusicPlaying = false;
        updateMusicDisplay();
    } else {
        activePlaylist = Array.from(selectedSongs).map(index => playlist[index]);
        loadSong(0);
        isMusicPlaying = true;
    }
    togglePlaylist();
}

function populatePlaylist() {
    const playlistItems = document.getElementById('playlistItems');
    playlistItems.innerHTML = playlist.map((song, index) => `
        <div class="playlist-item ${activePlaylist.includes(song) ? 'active' : ''}" onclick="toggleSongSelection(${index})">
            <input type="checkbox" 
                   ${selectedSongs.has(index) ? 'checked' : ''} 
                   onchange="toggleSongSelection(${index})"
                   onclick="event.stopPropagation()">
            ${song.title}
            ${activePlaylist.includes(song) && activePlaylist[currentSongIndex] === song ? ' (Playing)' : ''}
        </div>
    `).join('');
}

// Add event listener for when a song ends
backgroundMusic.addEventListener('ended', () => {
    if (activePlaylist && activePlaylist.length > 0) {
        // Move to next song in playlist
        currentSongIndex = (currentSongIndex + 1) % activePlaylist.length;
        loadSong(currentSongIndex);
        if (isMusicPlaying && isPlaying) {
            backgroundMusic.play().catch(error => {
                console.error('Error playing next song:', error);
            });
        }
    }
});

function toggleMusic() {
    isMusicPlaying = !isMusicPlaying;
    const icon = document.getElementById('musicIcon');

    if (isMusicPlaying) {
        backgroundMusic.play();
        icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"/>';
    } else {
        backgroundMusic.pause();
        icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"/>';
    }
    updateMusicDisplay();
}

function togglePlaylist() {
    const playlistPanel = document.querySelector('.music-playlist');
    if (playlistPanel.style.display === 'none' || playlistPanel.style.display === '') {
        playlistPanel.style.display = 'block';
        document.querySelector('.settings-panel').style.display = 'none';
    } else {
        playlistPanel.style.display = 'none';
    }
}

function toggleSettings() {
    const settingsPanel = document.querySelector('.settings-panel');
    if (settingsPanel.style.display === 'none' || settingsPanel.style.display === '') {
        settingsPanel.style.display = 'block';
        document.querySelector('.music-playlist').style.display = 'none';
    } else {
        settingsPanel.style.display = 'none';
    }
}

function selectSong(index) {
    loadSong(index);
    togglePlaylist();
}

function showSlide(index) {
    const oldSlide = slides[currentSlide];
    currentSlide = (index + totalSlides) % totalSlides;
    const newSlide = slides[currentSlide];

    // Remove any existing transition classes
    oldSlide.classList.remove('active', 'fade-out', 'slide-out', 'scale-out', 'rotate-out', 'blur-out');
    newSlide.classList.remove('fade-out', 'slide-out', 'scale-out', 'rotate-out', 'blur-out');

    // Add the appropriate transition class
    oldSlide.classList.add(`${currentEffect}-out`);
    newSlide.classList.add('active');

    resetProgress();
}

function updateTransitionEffect(effect) {
    currentEffect = effect;
}

// Add event listeners for transition effects
document.addEventListener('DOMContentLoaded', async () => {
    await fetchPlaylist();
    startSlideshow();
    // Initialize interval value display
    document.getElementById('intervalValue').textContent = `${INTERVAL_TIME/1000}s`;
    // Enable descriptions by default
    document.getElementById('showDescriptions').checked = true;
    toggleDescriptions(true);

    // Add transition effect listeners
    document.querySelectorAll('input[name="transition-effect"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            updateTransitionEffect(e.target.value);
        });
    });
});

function nextSlide() {
    showSlide(currentSlide + 1);
}

function previousSlide() {
    showSlide(currentSlide - 1);
}

function togglePlayPause() {
    isPlaying = !isPlaying;
    const icon = document.getElementById('playPauseIcon');
    const text = document.getElementById('playPauseText');

    if (isPlaying) {
        startSlideshow();
        icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6"/>';
        text.textContent = '{% trans "Pause" %}';
        if (isMusicPlaying) backgroundMusic.play();
    } else {
        stopSlideshow();
        icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0110 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/>';
        text.textContent = '{% trans "Play" %}';
        backgroundMusic.pause();
    }
}

function startSlideshow() {
    stopSlideshow();
    startTime = Date.now();
    slideInterval = setInterval(nextSlide, INTERVAL_TIME);
    updateProgress();
    if (isMusicPlaying) backgroundMusic.play();
}

function stopSlideshow() {
    clearInterval(slideInterval);
    if (animationFrame) {
        cancelAnimationFrame(animationFrame);
        animationFrame = null;
    }
    startTime = null;
    backgroundMusic.pause();
}

function exitSlideshow() {
    window.location.href = '{% url "collection-detail" collection.pk %}';
}

function updateProgress() {
    if (!startTime || !isPlaying) return;

    const elapsed = Date.now() - startTime;
    const progress = Math.min(100, (elapsed / INTERVAL_TIME) * 100);

    const circle = document.querySelector('.progress-circle-path');

    // Calculate the circumference of the circle
    const radius = 16;
    const circumference = 2 * Math.PI * radius;

    // Calculate the dash offset based on progress
    const dashOffset = circumference * (1 - progress / 100);

    // Update the circle
    circle.style.strokeDasharray = `${circumference} ${circumference}`;
    circle.style.strokeDashoffset = dashOffset;

    // Request next frame
    animationFrame = requestAnimationFrame(updateProgress);
}

function resetProgress() {
    startTime = Date.now();
    if (animationFrame) {
        cancelAnimationFrame(animationFrame);
    }
    if (isPlaying) {
        updateProgress();
    }
}

function updateInterval(value) {
    INTERVAL_TIME = parseInt(value);
    document.getElementById('intervalValue').textContent = `${value / 1000}s`;
    if (isPlaying) {
        stopSlideshow();
        startSlideshow();
    }
}

// Keyboard controls
document.addEventListener('keydown', (e) => {
    switch(e.key) {
        case 'ArrowLeft':
            previousSlide();
            break;
        case 'ArrowRight':
            nextSlide();
            break;
        case ' ':
            togglePlayPause();
            break;
        case 'm':
            toggleMusic();
            break;
        case 'Escape':
            exitSlideshow();
            break;
        case '[':
            previousSong();
            break;
        case ']':
            nextSong();
            break;
        case 'p':
            togglePlaylist();
            break;
    }
});

function toggleDescriptions(show) {
    document.querySelectorAll('.image-description').forEach(desc => {
        if (desc.querySelector('.description-text').textContent.trim()) {
            desc.style.display = show ? 'block' : 'none';
        }
    });
}
</script>
{% endblock %}
