// SmartThink LMS - Main JavaScript File

// Global Variables
let currentRegion = 'usa';
let isWhatsAppOpen = false;

// DOM Content Loaded
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// Initialize Application
function initializeApp() {
    initializeRegionSelector();
    initializeWhatsAppWidget();
    initializeContactForm();
    initializeNewsletterForm();
    initializeSmoothScrolling();
    loadCourses();
    initializeAnimations();
    initializeMobileMenu();
}

// Region Selector
function initializeRegionSelector() {
    const regionButtons = document.querySelectorAll('.region-btn');
    
    regionButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Remove active class from all buttons
            regionButtons.forEach(btn => btn.classList.remove('active'));
            
            // Add active class to clicked button
            this.classList.add('active');
            
            // Update current region
            currentRegion = this.dataset.region;
            
            // Store in localStorage
            localStorage.setItem('selectedRegion', currentRegion);
            
            // Reload content based on region
            loadRegionContent(currentRegion);
            
            // Show notification
            showNotification(`Region changed to ${currentRegion.toUpperCase()}`, 'success');
        });
    });
    
    // Load saved region
    const savedRegion = localStorage.getItem('selectedRegion');
    if (savedRegion) {
        currentRegion = savedRegion;
        document.querySelector(`[data-region="${savedRegion}"]`).classList.add('active');
        loadRegionContent(currentRegion);
    }
}

// Load Region-Specific Content
function loadRegionContent(region) {
    // Update courses based on region
    loadCourses(region);
    
    // Update pricing display
    updatePricing(region);
    
    // Update contact information
    updateContactInfo(region);
}

// Load Courses
function loadCourses(region = 'usa') {
    const coursesContainer = document.getElementById('coursesContainer');
    if (!coursesContainer) return;
    
    // Sample course data - in real app, this would come from API
    const courses = {
        usa: [
            {
                id: 1,
                title: 'Digital Marketing Mastery',
                instructor: 'John Smith',
                duration: '8 weeks',
                level: 'Beginner',
                price: '$299',
                image: 'digital-marketing.jpg',
                badge: 'Popular'
            },
            {
                id: 2,
                title: 'Web Development Bootcamp',
                instructor: 'Sarah Johnson',
                duration: '12 weeks',
                level: 'Intermediate',
                price: '$499',
                image: 'web-development.jpg',
                badge: 'Bestseller'
            },
            {
                id: 3,
                title: 'Data Science Fundamentals',
                instructor: 'Dr. Michael Chen',
                duration: '10 weeks',
                level: 'Advanced',
                price: '$699',
                image: 'data-science.jpg',
                badge: 'New'
            },
            {
                id: 4,
                title: 'Business Analytics',
                instructor: 'Emily Davis',
                duration: '6 weeks',
                level: 'Intermediate',
                price: '$399',
                image: 'business-analytics.jpg',
                badge: 'Trending'
            }
        ],
        europe: [
            {
                id: 5,
                title: 'EU Business Compliance',
                instructor: 'Hans Mueller',
                duration: '4 weeks',
                level: 'Professional',
                price: 'â‚¬349',
                image: 'eu-compliance.jpg',
                badge: 'EU Focus'
            },
            {
                id: 6,
                title: 'Multilingual Digital Strategy',
                instructor: 'Sophie Martin',
                duration: '8 weeks',
                level: 'Advanced',
                price: 'â‚¬599',
                image: 'multilingual-strategy.jpg',
                badge: 'Premium'
            },
            {
                id: 7,
                title: 'European Market Entry',
                instructor: 'Jean-Luc Dubois',
                duration: '6 weeks',
                level: 'Intermediate',
                price: 'â‚¬449',
                image: 'market-entry.jpg',
                badge: 'Business'
            },
            {
                id: 8,
                title: 'GDPR Implementation',
                instructor: 'Maria Garcia',
                duration: '5 weeks',
                level: 'Professional',
                price: 'â‚¬399',
                image: 'gdpr.jpg',
                badge: 'Compliance'
            }
        ],
        africa: [
            {
                id: 9,
                title: 'African Business Strategy',
                instructor: 'Kwame Asante',
                duration: '8 weeks',
                level: 'Intermediate',
                price: 'â‚¦150,000',
                image: 'african-business.jpg',
                badge: 'Local Focus'
            },
            {
                id: 10,
                title: 'Mobile Money Integration',
                instructor: 'Fatima Al Hassan',
                duration: '6 weeks',
                level: 'Technical',
                price: 'â‚¦120,000',
                image: 'mobile-money.jpg',
                badge: 'Fintech'
            },
            {
                id: 11,
                title: 'Agricultural Technology',
                instructor: 'Dr. Samuel Okonkwo',
                duration: '10 weeks',
                level: 'Advanced',
                price: 'â‚¦200,000',
                image: 'agri-tech.jpg',
                badge: 'Innovation'
            },
            {
                id: 12,
                title: 'Renewable Energy Systems',
                instructor: 'Amina Mohamed',
                duration: '12 weeks',
                level: 'Professional',
                price: 'â‚¦250,000',
                image: 'renewable-energy.jpg',
                badge: 'Sustainability'
            }
        ]
    };
    
    const regionCourses = courses[region] || courses.usa;
    
    coursesContainer.innerHTML = '';
    
    regionCourses.forEach(course => {
        const courseCard = createCourseCard(course);
        coursesContainer.appendChild(courseCard);
    });
}

// Create Course Card
function createCourseCard(course) {
    const card = document.createElement('div');
    card.className = 'col-md-6 col-lg-3';
    card.innerHTML = `
        <div class="course-card">
            <div class="course-image">
                <img src="../assets/images/courses/${course.image}" alt="${course.title}" onerror="this.src='../assets/images/course-placeholder.jpg'">
                <span class="course-badge">${course.badge}</span>
            </div>
            <div class="course-content">
                <h3 class="course-title">${course.title}</h3>
                <p class="course-instructor">by ${course.instructor}</p>
                <div class="course-meta">
                    <span><i class="fas fa-clock"></i> ${course.duration}</span>
                    <span><i class="fas fa-signal"></i> ${course.level}</span>
                </div>
                <div class="course-price">${course.price}</div>
                <button class="btn btn-primary w-100" onclick="enrollCourse(${course.id})">
                    Enroll Now
                </button>
            </div>
        </div>
    `;
    return card;
}

// Update Pricing
function updatePricing(region) {
    // This would update currency symbols and prices throughout the site
    const currencySymbols = {
        usa: '$',
        europe: 'â‚¬',
        africa: 'â‚¦'
    };
    
    // Update any price displays on the page
    document.querySelectorAll('[data-price]').forEach(element => {
        const basePrice = parseFloat(element.dataset.basePrice);
        const currency = currencySymbols[region];
        element.textContent = `${currency}${basePrice}`;
    });
}

// Update Contact Information
function updateContactInfo(region) {
    const contactInfo = {
        usa: {
            phone: '+1 (555) 123-4567',
            email: 'usa@SmartThink.com'
        },
        europe: {
            phone: '+44 20 7123 4567',
            email: 'europe@SmartThink.com'
        },
        africa: {
            phone: '+234 800 123 4567',
            email: 'africa@SmartThink.com'
        }
    };
    
    const info = contactInfo[region];
    
    // Update contact information on the page
    const phoneElements = document.querySelectorAll('[data-contact-phone]');
    const emailElements = document.querySelectorAll('[data-contact-email]');
    
    phoneElements.forEach(element => {
        element.textContent = info.phone;
    });
    
    emailElements.forEach(element => {
        element.textContent = info.email;
    });
}

// WhatsApp Widget
function initializeWhatsAppWidget() {
    const whatsappButton = document.querySelector('.whatsapp-button');
    const whatsappChat = document.querySelector('.whatsapp-chat');
    const sendMessageBtn = document.getElementById('sendMessage');
    const chatInput = document.getElementById('chatInput');
    
    if (whatsappButton && whatsappChat) {
        whatsappButton.addEventListener('click', function() {
            isWhatsAppOpen = !isWhatsAppOpen;
            whatsappChat.classList.toggle('active', isWhatsAppOpen);
            
            if (isWhatsAppOpen) {
                chatInput.focus();
            }
        });
    }
    
    if (sendMessageBtn && chatInput) {
        sendMessageBtn.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    }
    
    // Close chat when clicking outside
    document.addEventListener('click', function(e) {
        if (isWhatsAppOpen && !e.target.closest('.whatsapp-widget')) {
            isWhatsAppOpen = false;
            whatsappChat.classList.remove('active');
        }
    });
}

// Send WhatsApp Message
function sendMessage() {
    const chatInput = document.getElementById('chatInput');
    const chatMessages = document.getElementById('chatMessages');
    
    if (!chatInput || !chatMessages) return;
    
    const message = chatInput.value.trim();
    if (!message) return;
    
    // Add user message
    const userMessage = document.createElement('div');
    userMessage.className = 'message user';
    userMessage.textContent = message;
    chatMessages.appendChild(userMessage);
    
    // Clear input
    chatInput.value = '';
    
    // Scroll to bottom
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    // Simulate bot response
    setTimeout(() => {
        const botMessage = document.createElement('div');
        botMessage.className = 'message bot';
        botMessage.textContent = getBotResponse(message);
        chatMessages.appendChild(botMessage);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }, 1000);
}

// Get Bot Response
function getBotResponse(message) {
    const responses = [
        "Thank you for your message! Our support team will get back to you soon.",
        "I understand you need help. Let me connect you with our support team.",
        "Great question! You can find more information in our courses section.",
        "I'm here to help! Could you please provide more details about your inquiry?",
        "Thank you for contacting SmartThink! How can I assist you today?"
    ];
    
    return responses[Math.floor(Math.random() * responses.length)];
}

// Contact Form
function initializeContactForm() {
    const contactForm = document.getElementById('contactForm');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Get form data
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            // Validate form
            if (!validateContactForm(data)) {
                return;
            }
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
            submitBtn.disabled = true;
            
            // Simulate API call
            setTimeout(() => {
                showNotification('Message sent successfully! We will get back to you soon.', 'success');
                this.reset();
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }, 2000);
        });
    }
}

// Validate Contact Form
function validateContactForm(data) {
    const requiredFields = ['name', 'email', 'subject', 'message'];
    
    for (const field of requiredFields) {
        if (!data[field] || data[field].trim() === '') {
            showNotification(`Please fill in the ${field} field.`, 'error');
            return false;
        }
    }
    
    // Validate email
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(data.email)) {
        showNotification('Please enter a valid email address.', 'error');
        return false;
    }
    
    return true;
}

// Newsletter Form
function initializeNewsletterForm() {
    const newsletterForms = document.querySelectorAll('.newsletter-form');
    
    newsletterForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const email = this.querySelector('input[type="email"]').value;
            
            if (!email || !isValidEmail(email)) {
                showNotification('Please enter a valid email address.', 'error');
                return;
            }
            
            // Show loading state
            const submitBtn = this.querySelector('button');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = 'Subscribing...';
            submitBtn.disabled = true;
            
            // Simulate API call
            setTimeout(() => {
                showNotification('Successfully subscribed to our newsletter!', 'success');
                this.reset();
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }, 1500);
        });
    });
}

// Capgemini Header - Mobile Menu & Dropdowns
function initializeMobileMenu() {
    // Mobile toggle already wired via inline onclick on .navbar-toggler for Cap header; we just handle dropdown expand/collapse on mobile.
    const dropdownItems = document.querySelectorAll('.cap-nav-item.has-dropdown > .cap-nav-link');

    dropdownItems.forEach(link => {
        link.addEventListener('click', function(e) {
            const parentItem = this.parentElement;
            const isMobile = window.innerWidth <= 991.98;

            if (isMobile) {
                // Prevent navigation when toggling dropdown on mobile
                e.preventDefault();

                const isOpen = parentItem.classList.contains('open');

                // Close any other open dropdowns
                document.querySelectorAll('.cap-nav-item.has-dropdown.open').forEach(item => {
                    if (item !== parentItem) {
                        item.classList.remove('open');
                    }
                });

                // Toggle current
                parentItem.classList.toggle('open', !isOpen);
            }
        });
    });
}

// Smooth Scrolling
function initializeSmoothScrolling() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
                
                // Update active nav link
                document.querySelectorAll('.nav-link').forEach(link => {
                    link.classList.remove('active');
                });
                this.classList.add('active');
            }
        });
    });
}

// Initialize Animations
function initializeAnimations() {
    // Intersection Observer for fade-in animations
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in-up');
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);
    
    // Observe elements
    document.querySelectorAll('.feature-card, .course-card, .service-card').forEach(el => {
        observer.observe(el);
    });
}

// Mobile Menu
function initializeMobileMenu() {
    const navbarToggler = document.querySelector('.navbar-toggler');
    const navbarCollapse = document.querySelector('.navbar-collapse');
    
    if (navbarToggler && navbarCollapse) {
        navbarToggler.addEventListener('click', function() {
            navbarCollapse.classList.toggle('show');
        });
        
        // Close menu when clicking outside
        document.addEventListener('click', function(e) {
            if (!navbarToggler.contains(e.target) && !navbarCollapse.contains(e.target)) {
                navbarCollapse.classList.remove('show');
            }
        });
        
        // Close menu when clicking on nav links
        navbarCollapse.querySelectorAll('.nav-link').forEach(link => {
            link.addEventListener('click', function() {
                navbarCollapse.classList.remove('show');
            });
        });
    }
}

// Enroll in Course
function enrollCourse(courseId) {
    // Check if user is logged in
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    
    if (!isLoggedIn) {
        showNotification('Please login to enroll in courses.', 'info');
        setTimeout(() => {
            window.location.href = '../lms/login.php';
        }, 2000);
        return;
    }
    
    // Show enrollment modal or redirect
    showNotification(`Enrolling in course ${courseId}...`, 'info');
    
    // Simulate enrollment process
    setTimeout(() => {
        showNotification('Successfully enrolled in the course!', 'success');
    }, 1500);
}

// Utility Functions
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function showNotification(message, type = 'info') {
    // Remove existing notifications
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // Add styles
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 300px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    `;
    
    // Set background color based on type
    const colors = {
        success: '#10b981',
        error: '#ef4444',
        info: '#3b82f6',
        warning: '#f59e0b'
    };
    notification.style.backgroundColor = colors[type] || colors.info;
    
    // Add to DOM
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // Remove after 3 seconds
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// Geo-location Detection
function detectUserLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                // In a real app, you would send this to your backend
                // to determine the user's region based on coordinates
                console.log('Location detected:', position.coords);
            },
            function(error) {
                console.log('Geolocation error:', error);
                // Fallback to IP-based detection
                detectLocationByIP();
            }
        );
    } else {
        detectLocationByIP();
    }
}

// IP-based Location Detection (Fallback)
function detectLocationByIP() {
    // In a real app, you would use a geolocation API service
    // For demo purposes, we'll use a simple approach
    fetch('https://ipapi.co/json/')
        .then(response => response.json())
        .then(data => {
            console.log('IP-based location:', data);
            // Determine region based on country
            const region = determineRegionFromCountry(data.country);
            if (region && region !== currentRegion) {
                showNotification(`We detected you're in ${data.country_name}. Switched to ${region.toUpperCase()} region.`, 'info');
                currentRegion = region;
                document.querySelector(`[data-region="${region}"]`).click();
            }
        })
        .catch(error => {
            console.log('IP detection failed:', error);
        });
}

// Determine Region from Country
function determineRegionFromCountry(country) {
    const regionMapping = {
        // USA
        'US': 'usa',
        'CA': 'usa',
        'MX': 'usa',
        
        // Europe
        'GB': 'europe',
        'DE': 'europe',
        'FR': 'europe',
        'IT': 'europe',
        'ES': 'europe',
        'NL': 'europe',
        'BE': 'europe',
        'AT': 'europe',
        'CH': 'europe',
        'SE': 'europe',
        'NO': 'europe',
        'DK': 'europe',
        'FI': 'europe',
        'PL': 'europe',
        'CZ': 'europe',
        'HU': 'europe',
        'GR': 'europe',
        'PT': 'europe',
        'IE': 'europe',
        
        // Africa
        'NG': 'africa',
        'ZA': 'africa',
        'KE': 'africa',
        'GH': 'africa',
        'EG': 'africa',
        'MA': 'africa',
        'TN': 'africa',
        'DZ': 'africa',
        'ET': 'africa',
        'TZ': 'africa',
        'UG': 'africa',
        'ZW': 'africa',
        'BW': 'africa',
        'MW': 'africa',
        'ZM': 'africa',
        'AO': 'africa',
        'MZ': 'africa'
    };
    
    return regionMapping[country] || null;
}

// Initialize geo-location on page load
setTimeout(detectUserLocation, 2000);

// Export functions for global access
window.SmartThink = {
    enrollCourse,
    showNotification,
    loadCourses,
    detectUserLocation
};
