// Global Dropdown and Theme Toggle JavaScript

// Testimonial Slider Variables
let currentSlide = 0;
let slides = [];
let indicators = [];
let totalSlides = 0;
let autoSlideInterval;

// Global Dropdown Functions
function toggleGlobalDropdown() {
    const dropdown = document.getElementById('globalDropdown');
    dropdown.classList.toggle('active');
    
    // Close dropdown when clicking outside
    document.addEventListener('click', function closeDropdown(e) {
        if (!dropdown.contains(e.target)) {
            dropdown.classList.remove('active');
            document.removeEventListener('click', closeDropdown);
        }
    });
}

function selectRegion(region, element) {
    // Remove active class from all options
    document.querySelectorAll('.region-option').forEach(option => {
        option.classList.remove('active');
    });
    
    // Add active class to selected option
    element.classList.add('active');
    
    // Update the dropdown button text
    const regionName = element.querySelector('.region-name').textContent;
    const regionFlag = element.querySelector('.region-flag').textContent;
    const toggle = document.querySelector('.global-dropdown-toggle span');
    toggle.textContent = `${regionFlag} ${regionName}`;
    
    // Close dropdown
    document.getElementById('globalDropdown').classList.remove('active');
    
    // Store preference in localStorage
    localStorage.setItem('selectedRegion', region);
    
    // You can add page reload or content update logic here
    console.log(`Region changed to: ${region}`);
}

// Theme Toggle Functions
function toggleTheme() {
    const body = document.body;
    const themeIcon = document.getElementById('themeIcon');
    
    if (body.classList.contains('light-theme')) {
        // Switch to dark theme
        body.classList.remove('light-theme');
        themeIcon.className = 'fas fa-moon';
        localStorage.setItem('theme', 'dark');
    } else {
        // Switch to light theme
        body.classList.add('light-theme');
        themeIcon.className = 'fas fa-sun';
        localStorage.setItem('theme', 'light');
    }
}

// Testimonial Slider Functions
function showSlide(index) {
    if (slides.length === 0) return;
    
    // Hide all slides
    slides.forEach(slide => slide.classList.remove('active'));
    indicators.forEach(indicator => indicator.classList.remove('active'));
    
    // Show current slide
    slides[index].classList.add('active');
    indicators[index].classList.add('active');
}

function changeSlide(direction) {
    currentSlide += direction;
    
    // Wrap around if we reach the ends
    if (currentSlide < 0) {
        currentSlide = totalSlides - 1;
    } else if (currentSlide >= totalSlides) {
        currentSlide = 0;
    }
    
    showSlide(currentSlide);
}

function goToSlide(index) {
    currentSlide = index;
    showSlide(currentSlide);
}

// Auto-advance slider
function startAutoSlide() {
    clearInterval(autoSlideInterval);
    autoSlideInterval = setInterval(() => {
        changeSlide(1);
    }, 5000); // Change slide every 5 seconds
}

// Statistics Counter Animation
function animateCounter() {
    const counters = document.querySelectorAll('.stat-number');
    const speed = 200; // Animation speed
    
    counters.forEach(counter => {
        const animate = () => {
            const target = +counter.getAttribute('data-target');
            const count = +counter.innerText.replace(/[^0-9]/g, '');
            const increment = target / speed;
            
            if (count < target) {
                counter.innerText = Math.ceil(count + increment);
                setTimeout(animate, 10);
            } else {
                // Add formatting for large numbers
                if (target >= 1000) {
                    counter.innerText = (target / 1000).toFixed(0) + 'K+';
                } else if (target >= 100) {
                    counter.innerText = target + '%';
                } else {
                    counter.innerText = target + '+';
                }
            }
        };
        
        animate();
    });
}

// Initialize theme on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize testimonial slider elements
    slides = document.querySelectorAll('.testimonial-slide');
    indicators = document.querySelectorAll('.indicator');
    totalSlides = slides.length;
    
    // Load saved theme
    const savedTheme = localStorage.getItem('theme');
    const themeIcon = document.getElementById('themeIcon');
    
    if (savedTheme === 'light') {
        document.body.classList.add('light-theme');
        themeIcon.className = 'fas fa-sun';
    } else {
        themeIcon.className = 'fas fa-moon';
    }
    
    // Load saved region
    const savedRegion = localStorage.getItem('selectedRegion');
    if (savedRegion) {
        // Update the dropdown button with saved region
        const regionOptions = {
            'usa': '🇺🇸 United States',
            'canada': '🇨🇦 Canada',
            'brazil': '🇧🇷 Brazil',
            'mexico': '🇲🇽 Mexico',
            'uk': '🇬🇧 United Kingdom',
            'france': '🇫🇷 France',
            'germany': '🇩🇪 Germany',
            'netherlands': '🇳🇱 Netherlands',
            'india': '🇮🇳 India',
            'australia': '🇦🇺 Australia',
            'singapore': '🇸🇬 Singapore',
            'japan': '🇯🇵 Japan',
            'uae': '🇦🇪 UAE',
            'southafrica': '🇿🇦 South Africa',
            'egypt': '🇪🇬 Egypt',
            'nigeria': '🇳🇬 Nigeria'
        };
        
        if (regionOptions[savedRegion]) {
            const toggle = document.querySelector('.global-dropdown-toggle span');
            toggle.textContent = regionOptions[savedRegion];
            
            // Update active state in dropdown
            document.querySelectorAll('.region-option').forEach(option => {
                option.classList.remove('active');
            });
            
            // Find and activate the saved region option
            const savedOption = document.querySelector(`[onclick="selectRegion('${savedRegion}', this)"]`);
            if (savedOption) {
                savedOption.classList.add('active');
            }
        }
    }
    
    // Initialize testimonial slider
    if (slides.length > 0) {
        showSlide(0); // Show first slide
        startAutoSlide(); // Start auto-advance
    }
    
    // Initialize statistics counter when stats section is in viewport
    const statsSection = document.querySelector('.stats-section');
    if (statsSection) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    animateCounter();
                    observer.unobserve(entry.target);
                }
            });
        });
        
        observer.observe(statsSection);
    }
});

// Close dropdowns on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.getElementById('globalDropdown').classList.remove('active');
    }
});

// Pause auto-slide on hover
const sliderWrapper = document.querySelector('.testimonials-slider-wrapper');
if (sliderWrapper) {
    sliderWrapper.addEventListener('mouseenter', () => {
        clearInterval(autoSlideInterval);
    });
    
    sliderWrapper.addEventListener('mouseleave', () => {
        startAutoSlide();
    });
}

// Hero Slider functionality
let currentHeroSlide = 0;
const heroSlides = document.querySelectorAll('.hero-slide');
const heroSlider = document.getElementById('heroSlider');
const heroIndicators = document.querySelectorAll('.hero-slider-indicators .indicator');

function showHeroSlide(index) {
    // Hide all slides
    heroSlides.forEach(slide => slide.classList.remove('active'));
    heroIndicators.forEach(indicator => indicator.classList.remove('active'));
    
    // Show current slide
    heroSlides[index].classList.add('active');
    heroIndicators[index].classList.add('active');
    
    // Move slider
    const offset = -index * 100;
    heroSlider.style.transform = `translateX(${offset}%)`;
    
    currentHeroSlide = index;
}

function changeHeroSlide(direction) {
    const totalSlides = heroSlides.length;
    let newSlide = currentHeroSlide + direction;
    
    if (newSlide < 0) {
        newSlide = totalSlides - 1;
    } else if (newSlide >= totalSlides) {
        newSlide = 0;
    }
    
    showHeroSlide(newSlide);
}

function goToHeroSlide(index) {
    showHeroSlide(index);
}

// Auto-advance hero slider
let heroSliderInterval;

function startHeroAutoSlide() {
    heroSliderInterval = setInterval(() => {
        changeHeroSlide(1);
    }, 5000); // Change slide every 5 seconds
}

function stopHeroAutoSlide() {
    clearInterval(heroSliderInterval);
}

// Initialize hero slider
document.addEventListener('DOMContentLoaded', function() {
    if (heroSlides.length > 0) {
        showHeroSlide(0);
        startHeroAutoSlide();
        
        // Pause on hover
        const heroSliderWrapper = document.querySelector('.hero-slider-wrapper');
        if (heroSliderWrapper) {
            heroSliderWrapper.addEventListener('mouseenter', stopHeroAutoSlide);
            heroSliderWrapper.addEventListener('mouseleave', startHeroAutoSlide);
        }
    }
});

// Multi-Card Slider functionality
let currentMultiCardSlide = 0;
const multiCardSlider = document.getElementById('multiCardSlider');
const multiCards = document.querySelectorAll('.slider-card');
const totalMultiCards = multiCards.length;

function changeMultiCardSlide(direction) {
    const cardWidth = 350; // Base card width
    const gap = 32; // Gap between cards
    const slideWidth = cardWidth + gap;
    
    currentMultiCardSlide += direction;
    
    // Calculate maximum slides based on visible cards
    const maxSlides = Math.max(0, totalMultiCards - 3); // Show 3 cards at once
    const maxSlideIndex = maxSlides;
    
    if (currentMultiCardSlide < 0) {
        currentMultiCardSlide = 0;
    } else if (currentMultiCardSlide > maxSlideIndex) {
        currentMultiCardSlide = maxSlideIndex;
    }
    
    const offset = -currentMultiCardSlide * slideWidth;
    multiCardSlider.style.transform = `translateX(${offset}px)`;
}

// Auto-advance multi-card slider
let multiCardInterval;

function startMultiCardAutoSlide() {
    multiCardInterval = setInterval(() => {
        changeMultiCardSlide(1);
    }, 4000); // Change slide every 4 seconds
}

function stopMultiCardAutoSlide() {
    clearInterval(multiCardInterval);
}

// Initialize multi-card slider
document.addEventListener('DOMContentLoaded', function() {
    if (multiCards.length > 0) {
        startMultiCardAutoSlide();
        
        // Pause on hover
        const multiSliderWrapper = document.querySelector('.multi-card-slider-wrapper');
        if (multiSliderWrapper) {
            multiSliderWrapper.addEventListener('mouseenter', stopMultiCardAutoSlide);
            multiSliderWrapper.addEventListener('mouseleave', startMultiCardAutoSlide);
        }
    }
});

// Hero background + card slider (synchronized)
let currentHeroBgSlide = 0;
const heroBgSlides = document.querySelectorAll('.hero-bg-slide');
const heroCardSlides = document.querySelectorAll('.hero-card-slide');

function showHeroBgSlide(index) {
    if (!heroBgSlides.length) return;
    heroBgSlides.forEach((slide, i) => {
        slide.classList.toggle('active', i === index);
    });
    // Sync hero card content
    if (heroCardSlides.length) {
        heroCardSlides.forEach((slide, i) => {
            slide.classList.toggle('active', i === index);
        });
    }
    currentHeroBgSlide = index;
}

function startHeroBgAutoSlide() {
    if (heroBgSlides.length <= 1) return;
    setInterval(() => {
        const nextIndex = (currentHeroBgSlide + 1) % heroBgSlides.length;
        showHeroBgSlide(nextIndex);
    }, 6000); // Change background + card every 6 seconds
}

document.addEventListener('DOMContentLoaded', function() {
    if (heroBgSlides.length > 0) {
        showHeroBgSlide(0);
        startHeroBgAutoSlide();
    }
});
