// 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 (use plain region name only)
    const regionName = element.querySelector('.region-name').textContent;
    const toggle = document.querySelector('.global-dropdown-toggle span');
    toggle.textContent = 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}`);
}

// Capgemini Header Dropdowns (desktop behaviour)
function initializeCapNavDropdowns() {
    const dropdownParents = document.querySelectorAll('.cap-nav-item.has-dropdown');
    if (!dropdownParents.length) return;

    dropdownParents.forEach(parent => {
        parent.addEventListener('mouseenter', () => {
            if (window.innerWidth < 992) return;
            dropdownParents.forEach(p => p.classList.remove('open'));
            parent.classList.add('open');
        });

        parent.addEventListener('mouseleave', () => {
            if (window.innerWidth < 992) return;
            parent.classList.remove('open');
        });
    });

    // Close dropdowns when clicking outside header on desktop
    document.addEventListener('click', (e) => {
        if (window.innerWidth < 992) return;
        if (!e.target.closest('.cap-header')) {
            dropdownParents.forEach(p => p.classList.remove('open'));
        }
    });
}

// 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 (plain names, no emojis)
        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);
    }

    // Initialize Capgemini header dropdowns (Services / Training)
    initializeCapNavDropdowns();
});

// 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;
const multiCardWrapper = document.querySelector('.multi-card-slider-wrapper');

function getVisibleCardsCount(cardWidth) {
    if (!multiCardWrapper || !cardWidth) return 1;
    const wrapperWidth = multiCardWrapper.getBoundingClientRect().width;
    return Math.max(1, Math.floor(wrapperWidth / cardWidth));
}

function changeMultiCardSlide(direction) {
    if (!multiCardSlider || !multiCards.length) return;

    const firstCard = multiCards[0];
    const cardRect = firstCard.getBoundingClientRect();
    const baseWidth = cardRect.width;
    const gap = 32;
    const slideWidth = baseWidth + gap;

    currentMultiCardSlide += direction;

    const visibleCards = getVisibleCardsCount(baseWidth);
    const maxSlides = Math.max(0, totalMultiCards - visibleCards);

    if (currentMultiCardSlide < 0) {
        currentMultiCardSlide = 0;
    } else if (currentMultiCardSlide > maxSlides) {
        currentMultiCardSlide = 0;
    }

    const offset = -currentMultiCardSlide * slideWidth;
    multiCardSlider.style.transform = `translateX(${offset}px)`;
}

// Expose for inline onclick handlers
window.changeMultiCardSlide = changeMultiCardSlide;

// 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();
        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');
const heroCardIndicators = document.querySelectorAll('.hero-card-indicator');

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);
        });
        if (heroCardIndicators.length) {
            heroCardIndicators.forEach((ind, i) => {
                ind.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();
    }
});

// Mobile navigation toggle
const navToggler = document.querySelector('.navbar-toggler');
const capNav = document.querySelector('.cap-nav');
if (navToggler && capNav) {
    navToggler.addEventListener('click', function () {
        capNav.classList.toggle('open');
    });
}

// Scroll behavior: header shrink, scroll-spy, reveal-on-scroll, course filters
document.addEventListener('DOMContentLoaded', function () {
    const header = document.querySelector('.cap-header');
    const sectionLinks = document.querySelectorAll('.cap-nav-link[data-section-target]');
    const scrollSpySections = document.querySelectorAll('[data-scroll-spy="true"]');
    const revealSections = document.querySelectorAll('.reveal-on-scroll');
    const filters = document.querySelectorAll('.course-filter');
    const courseCards = document.querySelectorAll('.slider-card');

    function handleScroll() {
        const scrollY = window.scrollY || window.pageYOffset;
        if (header) {
            if (scrollY > 40) {
                header.classList.add('scrolled');
            } else {
                header.classList.remove('scrolled');
            }
        }

        if (scrollSpySections.length && sectionLinks.length) {
            scrollSpySections.forEach(section => {
                const rect = section.getBoundingClientRect();
                if (rect.top <= 120 && rect.bottom >= 120) {
                    const id = '#' + section.id;
                    sectionLinks.forEach(link => {
                        const target = link.getAttribute('data-section-target');
                        link.classList.toggle('active', target === id);
                    });
                }
            });
        }
    }

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();

    // Reveal-on-scroll via IntersectionObserver
    if ('IntersectionObserver' in window && revealSections.length) {
        const revealObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('visible');
                    revealObserver.unobserve(entry.target);
                }
            });
        }, { threshold: 0.15 });

        revealSections.forEach(section => revealObserver.observe(section));
    } else {
        revealSections.forEach(section => section.classList.add('visible'));
    }

    // Course filter chips
    if (filters.length && courseCards.length) {
        filters.forEach(filter => {
            filter.addEventListener('click', function () {
                const category = this.getAttribute('data-category');
                filters.forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');

                courseCards.forEach(card => {
                    const cardCategory = card.getAttribute('data-category') || 'all';
                    if (category === 'all' || category === cardCategory) {
                        card.style.display = '';
                    } else {
                        card.style.display = 'none';
                    }
                });
            });
        });
    }

    // Course Quick View Modal
    const quickViewButtons = document.querySelectorAll('.course-quickview-btn');
    const courseModalEl = document.getElementById('courseQuickViewModal');

    if (quickViewButtons.length && courseModalEl && window.bootstrap && bootstrap.Modal) {
        const modalInstance = new bootstrap.Modal(courseModalEl);
        const titleEl = courseModalEl.querySelector('.course-modal-title');
        const descEl = courseModalEl.querySelector('.course-modal-description');
        const imageEl = courseModalEl.querySelector('.course-modal-image');
        const badgeEl = courseModalEl.querySelector('.course-modal-badge');
        const durationValueEl = courseModalEl.querySelector('.course-modal-duration .value');
        const levelValueEl = courseModalEl.querySelector('.course-modal-level .value');
        const priceEl = courseModalEl.querySelector('.course-modal-price');

        quickViewButtons.forEach(btn => {
            btn.addEventListener('click', function () {
                const sliderCard = this.closest('.slider-card');
                if (!sliderCard) return;

                const title = sliderCard.getAttribute('data-title') || '';
                const description = sliderCard.getAttribute('data-description') || '';
                const duration = sliderCard.getAttribute('data-duration') || '';
                const level = sliderCard.getAttribute('data-level') || '';
                const price = sliderCard.getAttribute('data-price') || '';
                const image = sliderCard.getAttribute('data-image') || '';
                const badge = sliderCard.getAttribute('data-badge') || '';

                if (titleEl) titleEl.textContent = title;
                if (descEl) descEl.textContent = description;
                if (durationValueEl) durationValueEl.textContent = ' ' + duration;
                if (levelValueEl) levelValueEl.textContent = ' ' + level;
                if (priceEl) priceEl.textContent = price;
                if (imageEl && image) {
                    imageEl.src = image;
                    imageEl.alt = title || 'Course image';
                }
                if (badgeEl) {
                    badgeEl.textContent = badge;
                    badgeEl.style.display = badge ? 'inline-block' : 'none';
                }

                modalInstance.show();
            });
        });
    }
});
