document.addEventListener('DOMContentLoaded', () => {
    // Select the main elements of the slider
    const container = document.querySelector('.slider-container');
    const wrapper = container.querySelector('.slider-wrapper');
    const slides = container.querySelectorAll('.slide');
    const prevButton = container.querySelector('.slider-prev');
    const nextButton = container.querySelector('.slider-next');

    let currentIndex = 0;
    let slideInterval; // Variable to store the automatic slide timer

    // This function updates the slider's position
    function updateSlider_old() {
        const slideWidth = slides[0].clientWidth; // Recalculates the width on every update
        wrapper.style.transform = `translateX(${-currentIndex * slideWidth}px)`;
    }

    function updateSlider() {
        const slideWidth = slides[0].clientWidth;
        const newPosition = -currentIndex * slideWidth;
        wrapper.style.transform = `translateX(${Math.floor(newPosition)}px)`;
    }
    // Moves to the next slide, looping back to the start if needed
    function goToNextSlide() {
        currentIndex = (currentIndex < slides.length - 1) ? currentIndex + 1 : 0;
        updateSlider();
    }

    // Starts the automatic slide show
    function startSlideShow() {
        // Sets a timer to call goToNextSlide() every 5 seconds
        slideInterval = setInterval(goToNextSlide, 5000);
    }

    // Stops the automatic slide show
    function stopSlideShow() {
        clearInterval(slideInterval);
    }

    // Event listener for the previous button
    prevButton.addEventListener('click', () => {
        currentIndex = (currentIndex > 0) ? currentIndex - 1 : slides.length - 1;
        updateSlider();
    });

    // Event listener for the next button
    nextButton.addEventListener('click', () => {
        goToNextSlide();
    });

    // Event listeners to pause the automatic slide show when the mouse hovers over the slider
    container.addEventListener('mouseenter', stopSlideShow);
    container.addEventListener('mouseleave', startSlideShow);

    // Start the slide show when the page loads
    startSlideShow();

    // Recalculates the slider position when the window is resized
    window.addEventListener('resize', updateSlider);
});
