/**
 * Hero Slider
 *
 * @package ChaletMontagne
 * @since 1.0.0
 */

(function() {
    'use strict';

    class HeroSlider {
        constructor(element, options = {}) {
            this.slider = element;
            this.options = {
                speed: parseInt(options.speed) || 5000,
                transitionSpeed: parseInt(options.transitionSpeed) || 1000,
                transition: options.transition || 'fade',
                autoplay: options.autoplay !== false,
                pauseOnHover: options.pauseOnHover !== false,
                dots: options.dots !== false,
                arrows: options.arrows !== false,
                ...options
            };

            this.slides = [];
            this.currentIndex = 0;
            this.isPlaying = this.options.autoplay;
            this.isPaused = false;
            this.autoplayTimer = null;
            this.touchStartX = 0;
            this.touchEndX = 0;

            this.init();
        }

        init() {
            this.slides = this.slider.querySelectorAll('.hero-slide');

            if (this.slides.length <= 1) {
                // Single image, no slider needed
                if (this.slides.length === 1) {
                    this.slides[0].classList.add('active');
                }
                return;
            }

            // Set CSS variables
            this.slider.style.setProperty('--slider-speed', this.options.speed + 'ms');
            this.slider.style.setProperty('--slider-transition-speed', this.options.transitionSpeed + 'ms');

            // Add transition class
            this.slider.classList.add('transition-' + this.options.transition);

            // Initialize first slide
            this.slides[0].classList.add('active');

            // Create navigation
            if (this.options.arrows) {
                this.createArrows();
            }

            if (this.options.dots) {
                this.createDots();
            }

            // Event listeners
            this.bindEvents();

            // Start autoplay
            if (this.options.autoplay) {
                this.startAutoplay();
            }
        }

        createArrows() {
            const prevBtn = document.createElement('button');
            prevBtn.className = 'hero-slider-nav prev';
            prevBtn.setAttribute('aria-label', window.chaletMontagneData && chaletMontagneData.prevSlide || 'Previous slide');
            prevBtn.textContent = '<';

            const nextBtn = document.createElement('button');
            nextBtn.className = 'hero-slider-nav next';
            nextBtn.setAttribute('aria-label', window.chaletMontagneData && chaletMontagneData.nextSlide || 'Next slide');
            nextBtn.textContent = '>';

            prevBtn.addEventListener('click', () => this.prev());
            nextBtn.addEventListener('click', () => this.next());

            this.slider.appendChild(prevBtn);
            this.slider.appendChild(nextBtn);
        }

        createDots() {
            const dotsContainer = document.createElement('div');
            dotsContainer.className = 'hero-slider-dots';
            dotsContainer.setAttribute('role', 'tablist');

            this.slides.forEach((_, index) => {
                const dot = document.createElement('button');
                dot.className = 'hero-slider-dot' + (index === 0 ? ' active' : '');
                dot.setAttribute('role', 'tab');
                dot.setAttribute('aria-label', (window.chaletMontagneData && chaletMontagneData.goToSlide || 'Go to slide') + ' ' + (index + 1));
                dot.setAttribute('aria-selected', index === 0 ? 'true' : 'false');
                dot.addEventListener('click', () => this.goTo(index));
                dotsContainer.appendChild(dot);
            });

            this.slider.appendChild(dotsContainer);
            this.dots = dotsContainer.querySelectorAll('.hero-slider-dot');
        }

        bindEvents() {
            // Pause on hover
            if (this.options.pauseOnHover) {
                this.slider.addEventListener('mouseenter', () => this.pause());
                this.slider.addEventListener('mouseleave', () => this.resume());
            }

            // Touch events for swipe
            this.slider.addEventListener('touchstart', (e) => {
                this.touchStartX = e.changedTouches[0].screenX;
            }, { passive: true });

            this.slider.addEventListener('touchend', (e) => {
                this.touchEndX = e.changedTouches[0].screenX;
                this.handleSwipe();
            }, { passive: true });

            // Keyboard navigation
            this.slider.setAttribute('tabindex', '0');
            this.slider.addEventListener('keydown', (e) => {
                if (e.key === 'ArrowLeft') {
                    this.prev();
                } else if (e.key === 'ArrowRight') {
                    this.next();
                } else if (e.key === ' ') {
                    e.preventDefault();
                    this.togglePlay();
                }
            });

            // Visibility change - pause when tab is hidden
            document.addEventListener('visibilitychange', () => {
                if (document.hidden) {
                    this.pause();
                } else if (this.isPlaying) {
                    this.resume();
                }
            });
        }

        handleSwipe() {
            const threshold = 50;
            const diff = this.touchStartX - this.touchEndX;

            if (Math.abs(diff) > threshold) {
                if (diff > 0) {
                    this.next();
                } else {
                    this.prev();
                }
            }
        }

        goTo(index) {
            if (index === this.currentIndex) return;

            const prevIndex = this.currentIndex;
            this.currentIndex = index;

            // Handle slide transition
            if (this.options.transition === 'slide') {
                this.slides[prevIndex].classList.add('prev');
                this.slides[prevIndex].classList.remove('active');

                setTimeout(() => {
                    this.slides[prevIndex].classList.remove('prev');
                }, this.options.transitionSpeed);
            } else {
                this.slides[prevIndex].classList.remove('active');
            }

            this.slides[this.currentIndex].classList.add('active');

            // Update dots
            if (this.dots) {
                this.dots[prevIndex].classList.remove('active');
                this.dots[prevIndex].setAttribute('aria-selected', 'false');
                this.dots[this.currentIndex].classList.add('active');
                this.dots[this.currentIndex].setAttribute('aria-selected', 'true');
            }

            // Reset autoplay timer
            if (this.isPlaying && !this.isPaused) {
                this.startAutoplay();
            }
        }

        next() {
            const nextIndex = (this.currentIndex + 1) % this.slides.length;
            this.goTo(nextIndex);
        }

        prev() {
            const prevIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
            this.goTo(prevIndex);
        }

        startAutoplay() {
            this.stopAutoplay();
            this.autoplayTimer = setTimeout(() => {
                if (!this.isPaused) {
                    this.next();
                }
            }, this.options.speed);
        }

        stopAutoplay() {
            if (this.autoplayTimer) {
                clearTimeout(this.autoplayTimer);
                this.autoplayTimer = null;
            }
        }

        pause() {
            this.isPaused = true;
            this.slider.classList.add('paused');
            this.stopAutoplay();
        }

        resume() {
            if (this.isPlaying) {
                this.isPaused = false;
                this.slider.classList.remove('paused');
                this.startAutoplay();
            }
        }

        togglePlay() {
            if (this.isPaused) {
                this.resume();
            } else {
                this.pause();
            }
        }

        destroy() {
            this.stopAutoplay();
            // Remove added elements and event listeners
            const arrows = this.slider.querySelectorAll('.hero-slider-nav');
            arrows.forEach(arrow => arrow.remove());

            const dots = this.slider.querySelector('.hero-slider-dots');
            if (dots) dots.remove();
        }
    }

    // Initialize on DOM ready
    document.addEventListener('DOMContentLoaded', function() {
        const sliderElement = document.querySelector('.hero-slider');

        if (sliderElement && typeof chaletMontagneSlider !== 'undefined') {
            window.heroSlider = new HeroSlider(sliderElement, {
                speed: chaletMontagneSlider.speed,
                transitionSpeed: chaletMontagneSlider.transitionSpeed,
                transition: chaletMontagneSlider.transition,
                autoplay: chaletMontagneSlider.autoplay === '1',
                pauseOnHover: chaletMontagneSlider.pauseOnHover === '1',
                dots: chaletMontagneSlider.dots === '1',
                arrows: chaletMontagneSlider.arrows === '1'
            });
        }
    });

})();
