document.addEventListener('DOMContentLoaded', function() {
    // Initialize Bootstrap tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Initialize Bootstrap popovers
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });
    
    // Smooth scrolling for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            
            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            });
        });
    });
    
    // Initialize product carousel if it exists
    const productCarousel = document.querySelector('#productCarousel');
    if (productCarousel) {
        new bootstrap.Carousel(productCarousel, {
            interval: 3000,
            pause: 'hover'
        });
    }
    
    // Back to top button and navbar scroll effect
    const backToTopButton = document.getElementById('back-to-top');
    const navbar = document.querySelector('.navbar');
    
    if (backToTopButton) {
        window.onscroll = function() {
            // Back to top button visibility
            if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
                backToTopButton.style.display = 'block';
            } else {
                backToTopButton.style.display = 'none';
            }
            
            // Shrink logo on scroll
            if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
                if (navbar) navbar.classList.add('scrolled');
            } else {
                if (navbar) navbar.classList.remove('scrolled');
            }
        };
        
        backToTopButton.addEventListener('click', function() {
            window.scrollTo({top: 0, behavior: 'smooth'});
        });
    }
    
    // Animate about stats numbers on scroll
    const animateStats = () => {
        const statElements = document.querySelectorAll('.about-stat-number');
        
        if (statElements.length) {
            const options = {
                threshold: 0.5
            };
            
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const element = entry.target;
                        const countTo = parseInt(element.getAttribute('data-count')) || parseInt(element.textContent);
                        let count = 0;
                        const duration = 2000; // 2 seconds
                        const interval = Math.floor(duration / countTo);
                        
                        const timer = setInterval(() => {
                            count++;
                            element.textContent = count + '+';
                            
                            if (count >= countTo) {
                                clearInterval(timer);
                                element.textContent = countTo + '+';
                            }
                        }, interval);
                        
                        observer.unobserve(element);
                    }
                });
            }, options);
            
            statElements.forEach(element => {
                observer.observe(element);
            });
        }
    };
    
    // Reveal image captions on about page
    const setupImageCaptions = () => {
        const imageContainers = document.querySelectorAll('.about-image-container');
        
        if (imageContainers.length) {
            imageContainers.forEach(container => {
                const caption = container.querySelector('.about-image-caption');
                if (caption) {
                    // On desktop devices, use hover
                    container.addEventListener('mouseenter', () => {
                        caption.style.transform = 'translateY(0)';
                    });
                    
                    container.addEventListener('mouseleave', () => {
                        caption.style.transform = 'translateY(100%)';
                    });
                    
                    // On mobile devices, show caption on scroll into view
                    const observer = new IntersectionObserver((entries) => {
                        entries.forEach(entry => {
                            if (entry.isIntersecting) {
                                setTimeout(() => {
                                    caption.style.transform = 'translateY(0)';
                                }, 300);
                                observer.unobserve(container);
                            }
                        });
                    }, { threshold: 0.6 });
                    
                    observer.observe(container);
                }
            });
        }
    };
    
    // Add hover effects to values cards
    const setupValuesCards = () => {
        const valuesCards = document.querySelectorAll('.values-card');
        
        if (valuesCards.length) {
            valuesCards.forEach((card, index) => {
                // Add delay to staggered animation
                setTimeout(() => {
                    card.classList.add('animate-in');
                }, index * 150);
                
                // Add hover effects
                card.addEventListener('mouseenter', () => {
                    const icon = card.querySelector('.values-card-icon i');
                    if (icon) {
                        icon.classList.add('fa-beat');
                    }
                });
                
                card.addEventListener('mouseleave', () => {
                    const icon = card.querySelector('.values-card-icon i');
                    if (icon) {
                        icon.classList.remove('fa-beat');
                    }
                });
            });
        }
    };
    
    // Add animation to mission and vision cards
    const setupMissionVisionCards = () => {
        const cards = document.querySelectorAll('.mission-vision-card');
        
        if (cards.length) {
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animate-in');
                        observer.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.2 });
            
            cards.forEach(card => {
                observer.observe(card);
            });
        }
    };
    
    // Motor animation for homepage hero image
    const setupMotorAnimation = () => {
        const heroImage = document.querySelector('.hero-image img');
        if (heroImage) {
            // Add pulsing effect
            heroImage.addEventListener('mouseenter', () => {
                heroImage.style.animation = 'engineRevving 1.5s ease-in-out infinite';
            });
            
            heroImage.addEventListener('mouseleave', () => {
                heroImage.style.animation = 'enginePulse 3s ease-in-out infinite';
            });
        }
    };
    
    // Google Maps initialization for contact page
    const mapContainer = document.getElementById('map');
    if (mapContainer) {
        // The map will be initialized in the contact page when Google Maps API is loaded
        // This script tag with async defer is already included in the contact.html
    }
    
    // Form validation for contact form
    const contactForm = document.querySelector('.contact-form form');
    if (contactForm) {
        contactForm.addEventListener('submit', function(event) {
            if (!contactForm.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            
            contactForm.classList.add('was-validated');
        });
    }
    
    // Run animations for About page
    animateStats();
    setupImageCaptions();
    setupValuesCards();
    setupMissionVisionCards();
    setupMotorAnimation();
});

// Function to initialize Google Maps
function initMap() {
    const mapElement = document.getElementById('map');
    if (mapElement) {
        // GMPL address coordinates - Coordonnées exactes de GMPL à Dakar
        // Extraites du lien Google Maps: https://maps.app.goo.gl/ZTJhi3FrtA9FzsUp9
        const gmplLocation = { lat: 14.7177, lng: -17.3858 };
        
        const map = new google.maps.Map(mapElement, {
            zoom: 16,
            center: gmplLocation,
        });
        
        const marker = new google.maps.Marker({
            position: gmplLocation,
            map: map,
            title: 'GMPL - General Motors Poids Lourds'
        });
        
        const infoWindow = new google.maps.InfoWindow({
            content: `
                <div style="max-width: 250px;">
                    <strong>GMPL - General Motors Poids Lourds</strong><br>
                    Km 12, route de Rufisque<br>
                    Dakar, Sénégal<br>
                    <a href="tel:+221771252929" class="text-primary">+221 77 125 29 29</a><br>
                    <a href="tel:+221770496217" class="text-primary">+221 77 049 62 17</a><br>
                    <a href="tel:+221760115353" class="text-primary">+221 76 011 53 53</a><br>
                    <a href="tel:+221775223636" class="text-primary">+221 77 522 36 36</a><br>
                    <a href="https://maps.app.goo.gl/ZTJhi3FrtA9FzsUp9" target="_blank" class="text-primary mt-2 d-inline-block">
                        <small>Voir sur Google Maps</small>
                    </a>
                </div>
            `
        });
        
        marker.addListener('click', () => {
            infoWindow.open(map, marker);
        });
        
        // Open info window by default
        infoWindow.open(map, marker);
    }
}
