/**
 * Enhanced Header Image Slider
 */

class HeaderSlider {
    constructor(options = {}) {
        this.slideSelector = options.slideSelector || '.header-img';
        this.interval = options.interval || 2500;
        this.currentSlideIndex = 0;
        this.slides = [];
        this.timerId = null;
        this.isRunning = false;
        
        this.init();
    }
    
    /**
     * Initialize the slider with enhanced error handling
     */
    init() {
        this.slides = document.querySelectorAll(this.slideSelector);
        
        if (this.slides.length === 0) {
            return;
        }
        
        // Wait for DOM to be fully ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.setupSlides();
                this.start();
                this.setupEventListeners();
            });
        } else {
            // DOM already loaded
            setTimeout(() => {
                this.setupSlides();
                this.start();
                this.setupEventListeners();
            }, 100); // Small delay to ensure proper initialization
        }
        
        if (this.slides.length === 1) {
            // If only one slide, just show it and don't start slider
            this.slides[0].style.opacity = '1';
            return;
        }
    }
    
    /**
     * Setup initial slide states - natural height approach
     */
    setupSlides() {
        this.slides.forEach((slide, index) => {
            slide.setAttribute('data-slide-index', index);
            
            if (index === 0) {
                // First slide establishes natural height
                slide.style.position = 'relative';
                slide.style.width = '100%';
                slide.style.height = 'auto';
                slide.style.opacity = '1';
                slide.style.zIndex = '2';
            } else {
                // Other slides positioned absolutely
                slide.style.position = 'absolute';
                slide.style.top = '0';
                slide.style.left = '0';
                slide.style.width = '100%';
                slide.style.height = '100%';
                slide.style.objectFit = 'cover';
                slide.style.objectPosition = 'center';
                slide.style.opacity = '0';
                slide.style.zIndex = '2';
            }
            
            slide.style.transition = 'opacity 0.5s ease-in-out';
            
            // Add error handling for broken images
            slide.addEventListener('error', () => {
                slide.style.opacity = '0';
            });
        });
        
        // First slide is already visible
        this.currentSlideIndex = 0;
        
        // Preload all images
        this.preloadImages();
    }
    
    /**
     * Preload all slider images for smoother transitions
     */
    preloadImages() {
        this.slides.forEach(slide => {
            if (slide.src && !slide.complete) {
                const img = new Image();
                img.src = slide.src;
            }
        });
    }
    
    /**
     * Show specific slide by index - natural height transitions
     */
    showSlide(index) {
        if (index < 0 || index >= this.slides.length) {
            return;
        }
        
        // If it's the same slide, don't do anything
        if (index === this.currentSlideIndex) {
            return;
        }
        
        const currentSlide = this.slides[this.currentSlideIndex];
        const nextSlide = this.slides[index];
        
        // Handle transition to/from first slide (relative positioned)
        if (this.currentSlideIndex === 0) {
            // From first slide to others
            currentSlide.style.opacity = '0';
            setTimeout(() => {
                nextSlide.style.opacity = '1';
                this.currentSlideIndex = index;
            }, 300);
        } else if (index === 0) {
            // From other slides to first slide
            currentSlide.style.opacity = '0';
            setTimeout(() => {
                nextSlide.style.opacity = '1';
                this.currentSlideIndex = index;
            }, 300);
        } else {
            // Between non-first slides
            currentSlide.style.opacity = '0';
            setTimeout(() => {
                nextSlide.style.opacity = '1';
                this.currentSlideIndex = index;
            }, 300);
        }
    }
    
    /**
     * Move to next slide
     */
    nextSlide() {
        const nextIndex = (this.currentSlideIndex + 1) % this.slides.length;
        this.showSlide(nextIndex);
    }
    
    /**
     * Move to previous slide
     */
    prevSlide() {
        const prevIndex = this.currentSlideIndex === 0 
            ? this.slides.length - 1 
            : this.currentSlideIndex - 1;
        this.showSlide(prevIndex);
    }
    
    /**
     * Start the automatic slider
     */
    start() {
        if (this.isRunning || this.slides.length <= 1) {
            return;
        }
        
        this.isRunning = true;
        this.timerId = setInterval(() => {
            this.nextSlide();
        }, this.interval);
    }
    
    /**
     * Stop the automatic slider
     */
    stop() {
        if (this.timerId) {
            clearInterval(this.timerId);
            this.timerId = null;
            this.isRunning = false;
        }
    }
    
    /**
     * Restart the slider
     */
    restart() {
        this.stop();
        this.start();
    }
    
    /**
     * Set up event listeners for pause on hover and page visibility
     */
    setupEventListeners() {
        const headerContainer = document.querySelector('.header');
        
        if (headerContainer) {
            // Pause on hover
            headerContainer.addEventListener('mouseenter', () => {
                this.stop();
            });
            
            headerContainer.addEventListener('mouseleave', () => {
                this.start();
            });
        }
        
        // Pause when page is not visible (performance optimization)
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.stop();
            } else {
                this.start();
            }
        });
        
        // Handle window focus/blur
        window.addEventListener('focus', () => {
            this.start();
        });
        
        window.addEventListener('blur', () => {
            this.stop();
        });
    }
    
    /**
     * Destroy the slider and clean up
     */
    destroy() {
        this.stop();
        
        // Remove event listeners would go here if we stored references
        // Reset slides to original state
        this.slides.forEach(slide => {
            slide.style.display = '';
            slide.style.transition = '';
            slide.removeAttribute('data-slide-index');
        });
    }
    
    /**
     * Get current slide information
     */
    getCurrentSlide() {
        return {
            index: this.currentSlideIndex,
            element: this.slides[this.currentSlideIndex],
            total: this.slides.length
        };
    }
    
    /**
     * Update slider interval
     */
    setInterval(newInterval) {
        this.interval = newInterval;
        if (this.isRunning) {
            this.restart();
        }
    }
}

// Initialize slider when DOM is ready
let headerSlider;

function initHeaderSlider() {
    headerSlider = new HeaderSlider({
        slideSelector: '.header-img',
        interval: 2500 // 2.5 seconds
    });
}

// Auto-initialize when DOM is loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initHeaderSlider);
} else {
    // DOM is already loaded
    initHeaderSlider();
}

// Export for global access if needed
window.HeaderSlider = HeaderSlider;
window.headerSlider = headerSlider;
