// SmartThink LMS - Modern Interactions & Micro-Animations

// Global Variables
let scrollProgress = 0;
let isScrolling = false;
let mousePosition = { x: 0, y: 0 };
let currentTheme = 'light';

// DOM Content Loaded
document.addEventListener('DOMContentLoaded', function() {
    initializeModernInteractions();
    initializeScrollEffects();
    initializeMouseTracking();
    initializeThemeSystem();
    initializeAdvancedAnimations();
    initializePerformanceOptimizations();
});

// Initialize Modern Interactions
function initializeModernInteractions() {
    // Enhanced scroll progress
    updateScrollProgress();
    
    // Smooth scroll behavior
    initializeSmoothScrolling();
    
    // Dynamic header effects
    initializeHeaderEffects();
    
    // Enhanced hover effects
    initializeHoverEffects();
    
    // Loading animations
    initializeLoadingAnimations();
    
    // Notification system
    initializeNotificationSystem();
    
    // Enhanced form interactions
    initializeFormInteractions();
    
    // Parallax effects
    initializeParallaxEffects();
    
    // Hero image slider
    initializeHeroSlider();
}

// Scroll Progress Bar
function updateScrollProgress() {
    const progressBar = document.getElementById('scrollProgress');
    if (!progressBar) return;
    
    window.addEventListener('scroll', () => {
        const windowHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrolled = (window.scrollY / windowHeight) * 100;
        progressBar.style.width = scrolled + '%';
        
        // Add glow effect at certain scroll positions
        if (scrolled > 25 && scrolled < 75) {
            progressBar.style.boxShadow = '0 0 10px rgba(99, 102, 241, 0.5)';
        } else {
            progressBar.style.boxShadow = 'none';
        }
    });
}

// Enhanced Header Effects
function initializeHeaderEffects() {
    const header = document.querySelector('.modern-header');
    if (!header) return;
    
    let lastScrollY = window.scrollY;
    let ticking = false;
    
    function updateHeader() {
        const currentScrollY = window.scrollY;
        
        // Add/remove scrolled class
        if (currentScrollY > 100) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
        
        // Hide/show on scroll
        if (currentScrollY > lastScrollY && currentScrollY > 300) {
            header.style.transform = 'translateY(-100%)';
        } else {
            header.style.transform = 'translateY(0)';
        }
        
        lastScrollY = currentScrollY;
        ticking = false;
    }
    
    window.addEventListener('scroll', () => {
        if (!ticking) {
            requestAnimationFrame(updateHeader);
            ticking = true;
        }
    });
}

// Enhanced Hover Effects
function initializeHoverEffects() {
    // Card hover effects with mouse tracking
    const cards = document.querySelectorAll('.service-card-modern, .team-card');
    
    cards.forEach(card => {
        card.addEventListener('mouseenter', function(e) {
            this.style.transform = 'translateY(-8px) scale(1.02)';
        });
        
        card.addEventListener('mousemove', function(e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            
            const rotateX = (y - centerY) / 10;
            const rotateY = (centerX - x) / 10;
            
            this.style.transform = `translateY(-8px) perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) perspective(1000px) rotateX(0) rotateY(0)';
        });
    });
    
    // Button hover effects
    const buttons = document.querySelectorAll('.btn');
    
    buttons.forEach(button => {
        button.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
}

// Loading Animations
function initializeLoadingAnimations() {
    // Animate elements on page load
    const animateElements = document.querySelectorAll('.hero-content-modern, .service-card-modern, .team-card');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1
    });
    
    animateElements.forEach(element => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(30px)';
        element.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(element);
    });
}

// Enhanced Notification System
function initializeNotificationSystem() {
    window.showNotification = function(message, type = 'success', duration = 3000) {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // Animate in
        setTimeout(() => {
            notification.classList.add('show');
        }, 100);
        
        // Remove after duration
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, duration);
    };
}

// Enhanced Form Interactions
function initializeFormInteractions() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        const inputs = form.querySelectorAll('input, textarea, select');
        
        inputs.forEach(input => {
            // Floating labels effect
            input.addEventListener('focus', function() {
                this.parentElement.classList.add('focused');
            });
            
            input.addEventListener('blur', function() {
                if (!this.value) {
                    this.parentElement.classList.remove('focused');
                }
            });
            
            // Real-time validation
            input.addEventListener('input', function() {
                validateField(this);
            });
        });
        
        // Form submission
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (validateForm(form)) {
                submitForm(form);
            }
        });
    });
}

// Field Validation
function validateField(field) {
    const value = field.value.trim();
    const type = field.type;
    const required = field.required;
    
    // Remove existing error
    const existingError = field.parentElement.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    
    // Validation rules
    let isValid = true;
    let errorMessage = '';
    
    if (required && !value) {
        isValid = false;
        errorMessage = 'This field is required';
    } else if (type === 'email' && value && !isValidEmail(value)) {
        isValid = false;
        errorMessage = 'Please enter a valid email address';
    } else if (type === 'tel' && value && !isValidPhone(value)) {
        isValid = false;
        errorMessage = 'Please enter a valid phone number';
    }
    
    // Show/hide error
    if (!isValid) {
        const errorElement = document.createElement('div');
        errorElement.className = 'field-error';
        errorElement.textContent = errorMessage;
        field.parentElement.appendChild(errorElement);
        field.classList.add('error');
    } else {
        field.classList.remove('error');
        field.classList.add('valid');
    }
    
    return isValid;
}

// Form Validation
function validateForm(form) {
    const inputs = form.querySelectorAll('input[required], textarea[required], select[required]');
    let isValid = true;
    
    inputs.forEach(input => {
        if (!validateField(input)) {
            isValid = false;
        }
    });
    
    return isValid;
}

// Form Submission
function submitForm(form) {
    const submitButton = form.querySelector('button[type="submit"]');
    const originalText = submitButton.innerHTML;
    
    // Show loading state
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
    
    // Simulate API call
    setTimeout(() => {
        // Reset button
        submitButton.disabled = false;
        submitButton.innerHTML = originalText;
        
        // Show success message
        showNotification('Message sent successfully!', 'success');
        
        // Reset form
        form.reset();
        
        // Remove valid classes
        form.querySelectorAll('.valid').forEach(field => {
            field.classList.remove('valid');
        });
    }, 2000);
}

// Parallax Effects
function initializeParallaxEffects() {
    const parallaxElements = document.querySelectorAll('.hero-background, .hero-overlay');
    
    window.addEventListener('scroll', () => {
        const scrolled = window.pageYOffset;
        
        parallaxElements.forEach(element => {
            const speed = element.dataset.speed || 0.5;
            const yPos = -(scrolled * speed);
            element.style.transform = `translateY(${yPos}px)`;
        });
    });
}

// Hero Image Slider
function initializeHeroSlider() {
    const slider = document.querySelector('.hero-slider');
    if (!slider) return;
    
    const slides = slider.querySelectorAll('.hero-slide');
    if (slides.length <= 1) return;
    
    let currentIndex = 0;
    
    setInterval(() => {
        const currentSlide = slides[currentIndex];
        currentSlide.classList.remove('active');
        
        currentIndex = (currentIndex + 1) % slides.length;
        const nextSlide = slides[currentIndex];
        nextSlide.classList.add('active');
    }, 5000);
}

// Mouse Tracking
function initializeMouseTracking() {
    document.addEventListener('mousemove', (e) => {
        mousePosition.x = e.clientX;
        mousePosition.y = e.clientY;
        
        // Update custom cursor if exists
        const cursor = document.querySelector('.custom-cursor');
        if (cursor) {
            cursor.style.left = e.clientX + 'px';
            cursor.style.top = e.clientY + 'px';
        }
        
        // Update gradient background based on mouse position
        updateGradientBackground(e.clientX, e.clientY);
    });
}

// Dynamic Gradient Background
function updateGradientBackground(x, y) {
    const heroBackground = document.querySelector('.hero-background');
    if (!heroBackground) return;
    
    const xPercent = (x / window.innerWidth) * 100;
    const yPercent = (y / window.innerHeight) * 100;
    
    const gradient = `radial-gradient(circle at ${xPercent}% ${yPercent}%, rgba(99, 102, 241, 0.3) 0%, transparent 50%)`;
    
    heroBackground.style.background = `linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%), ${gradient}`;
}

// Theme System
function initializeThemeSystem() {
    const themeToggle = document.querySelector('.theme-toggle');
    if (!themeToggle) return;
    
    // Load saved theme
    const savedTheme = localStorage.getItem('theme') || 'light';
    setTheme(savedTheme);
    
    themeToggle.addEventListener('click', () => {
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        setTheme(newTheme);
        localStorage.setItem('theme', newTheme);
    });
}

function setTheme(theme) {
    currentTheme = theme;
    document.documentElement.setAttribute('data-theme', theme);
    
    const themeToggle = document.querySelector('.theme-toggle');
    if (themeToggle) {
        const icon = themeToggle.querySelector('i');
        icon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
    }
}

// Advanced Animations
function initializeAdvancedAnimations() {
    // Typing effect for hero title
    const heroTitle = document.querySelector('.hero-title-modern');
    if (heroTitle) {
        const text = heroTitle.textContent;
        heroTitle.textContent = '';
        typeWriter(heroTitle, text, 50);
    }
    
    // Counter animation for stats
    const statNumbers = document.querySelectorAll('.stat-number-modern');
    statNumbers.forEach(stat => {
        const target = parseInt(stat.textContent.replace(/[^0-9]/g, ''));
        animateCounter(stat, target, 2000);
    });
}

// Typewriter Effect
function typeWriter(element, text, speed) {
    let i = 0;
    
    function type() {
        if (i < text.length) {
            element.textContent += text.charAt(i);
            i++;
            setTimeout(type, speed);
        }
    }
    
    type();
}

// Counter Animation
function animateCounter(element, target, duration) {
    const start = 0;
    const increment = target / (duration / 16);
    let current = start;
    
    function updateCounter() {
        current += increment;
        if (current < target) {
            element.textContent = Math.floor(current) + (element.textContent.includes('+') ? '+' : (element.textContent.includes('%') ? '%' : ''));
            requestAnimationFrame(updateCounter);
        } else {
            element.textContent = target + (element.textContent.includes('+') ? '+' : (element.textContent.includes('%') ? '%' : ''));
        }
    }
    
    // Start animation when element is in view
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                updateCounter();
                observer.unobserve(entry.target);
            }
        });
    });
    
    observer.observe(element);
}

// Performance Optimizations
function initializePerformanceOptimizations() {
    // Lazy loading for images
    const images = document.querySelectorAll('img[data-src]');
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
    
    // Debounce scroll events
    let scrollTimeout;
    window.addEventListener('scroll', () => {
        if (scrollTimeout) {
            window.cancelAnimationFrame(scrollTimeout);
        }
        
        scrollTimeout = window.requestAnimationFrame(() => {
            // Handle scroll-based animations
            handleScrollAnimations();
        });
    });
}

// Scroll-based Animations
function handleScrollAnimations() {
    const scrolled = window.pageYOffset;
    const windowHeight = window.innerHeight;
    
    // Animate elements based on scroll position
    const animateOnScroll = document.querySelectorAll('[data-animate]');
    
    animateOnScroll.forEach(element => {
        const elementTop = element.offsetTop;
        const elementHeight = element.offsetHeight;
        
        if (scrolled + windowHeight > elementTop + elementHeight * 0.2) {
            element.classList.add('animate');
        }
    });
}

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

function isValidPhone(phone) {
    const phoneRegex = /^[\d\s\-\+\(\)]+$/;
    return phoneRegex.test(phone) && phone.length >= 10;
}

// Smooth Scroll Enhancement
function initializeSmoothScrolling() {
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                const headerHeight = document.querySelector('.modern-header').offsetHeight;
                const targetPosition = targetElement.offsetTop - headerHeight - 20;
                
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
                
                // Update URL without page reload
                history.pushState(null, null, `#${targetId}`);
            }
        });
    });
}

// Enhanced 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
            const region = this.dataset.region;
            localStorage.setItem('selectedRegion', region);
            
            // Show notification
            showNotification(`Region changed to ${region.toUpperCase()}`, 'success');
            
            // Reload content based on region
            loadRegionContent(region);
        });
    });
}

// Load Region Content
function loadRegionContent(region) {
    // Update pricing based on region
    const priceElements = document.querySelectorAll('[data-price]');
    
    priceElements.forEach(element => {
        const basePrice = parseFloat(element.dataset.price);
        const multiplier = getRegionMultiplier(region);
        const currency = getRegionCurrency(region);
        const convertedPrice = basePrice * multiplier;
        
        element.textContent = formatCurrency(convertedPrice, currency);
    });
    
    // Update content based on region
    updateRegionContent(region);
}

function getRegionMultiplier(region) {
    const multipliers = {
        'usa': 1.0,
        'europe': 0.85,
        'africa': 0.0024
    };
    return multipliers[region] || 1.0;
}

function getRegionCurrency(region) {
    const currencies = {
        'usa': 'USD',
        'europe': 'EUR',
        'africa': 'NGN'
    };
    return currencies[region] || 'USD';
}

function formatCurrency(amount, currency) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: currency
    }).format(amount);
}

function updateRegionContent(region) {
    // Update region-specific content
    const regionElements = document.querySelectorAll('[data-region-content]');
    
    regionElements.forEach(element => {
        const content = element.dataset[`${region}Content`];
        if (content) {
            element.textContent = content;
        }
    });
}

// WhatsApp Widget Enhancement
function initializeWhatsAppWidget() {
    const widget = document.querySelector('.whatsapp-widget');
    const button = widget?.querySelector('.whatsapp-button');
    const chat = widget?.querySelector('.whatsapp-chat');
    const chatInput = widget?.querySelector('#chatInput');
    const sendButton = widget?.querySelector('#sendMessage');
    
    if (!widget || !button || !chat) return;
    
    // Toggle chat
    button.addEventListener('click', () => {
        widget.classList.toggle('active');
        
        if (widget.classList.contains('active')) {
            chatInput?.focus();
        }
    });
    
    // Send message
    const sendMessage = () => {
        const message = chatInput?.value.trim();
        
        if (message) {
            // Add user message
            addChatMessage(message, 'user');
            
            // Clear input
            chatInput.value = '';
            
            // Simulate bot response
            setTimeout(() => {
                const botResponse = generateBotResponse(message);
                addChatMessage(botResponse, 'bot');
            }, 1000);
        }
    };
    
    sendButton?.addEventListener('click', sendMessage);
    chatInput?.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
}

function addChatMessage(message, sender) {
    const chatMessages = document.querySelector('#chatMessages');
    if (!chatMessages) return;
    
    const messageElement = document.createElement('div');
    messageElement.className = `message ${sender}`;
    messageElement.textContent = message;
    
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function generateBotResponse(message) {
    const responses = [
        "Thank you for your message! How can I help you today?",
        "I'm here to assist you with any questions about our courses.",
        "Would you like to learn more about our programs?",
        "Our team is ready to help you achieve your learning goals!"
    ];
    
    return responses[Math.floor(Math.random() * responses.length)];
}

// Initialize everything when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    initializeRegionSelector();
    initializeWhatsAppWidget();
});
