/* ============================================
   Academic LMS Template Custom Scripts
   Description: Smooth scrolling, scroll spy, back to top button,
   and application modal functionality
   ============================================ */

(function() {
    'use strict';

    // Wait for DOM to be ready
    document.addEventListener('DOMContentLoaded', function() {

        // ============================================
        // Smooth Scroll Navigation with Offset
        // ============================================
        const navLinks = document.querySelectorAll('.rsl-navbar-link[href^="#"]');
        const navbarHeight = document.querySelector('.rsl-navbar')?.offsetHeight || 80;

        navLinks.forEach(function(link) {
            link.addEventListener('click', function(e) {
                const href = link.getAttribute('href');

                // Only handle anchor links
                if (href && href.startsWith('#') && href !== '#') {
                    e.preventDefault();

                    const targetId = href.substring(1);
                    const targetElement = document.getElementById(targetId);

                    if (targetElement) {
                        const offsetPosition = targetElement.offsetTop - navbarHeight - 20;

                        window.scrollTo({
                            top: offsetPosition,
                            behavior: 'smooth'
                        });

                        // Update URL without jumping
                        if (history.pushState) {
                            history.pushState(null, null, href);
                        }

                        // Close mobile menu if open
                        const navMenu = document.querySelector('.rsl-navbar-menu');
                        if (navMenu && navMenu.classList.contains('active')) {
                            navMenu.classList.remove('active');
                            const toggle = document.querySelector('.rsl-navbar-toggle');
                            if (toggle) {
                                toggle.setAttribute('aria-expanded', 'false');
                            }
                        }

                        // Set focus to target for accessibility
                        targetElement.setAttribute('tabindex', '-1');
                        targetElement.focus();
                    }
                }
            });
        });

        // ============================================
        // Scroll Spy - Active Nav Link Indicator
        // ============================================
        const sections = document.querySelectorAll('section[id]');

        function updateActiveNav() {
            const scrollPos = window.pageYOffset + navbarHeight + 100;

            sections.forEach(function(section) {
                const sectionTop = section.offsetTop;
                const sectionHeight = section.offsetHeight;
                const sectionId = section.getAttribute('id');

                if (scrollPos >= sectionTop && scrollPos < sectionTop + sectionHeight) {
                    // Remove active from all links
                    navLinks.forEach(function(link) {
                        link.classList.remove('active');
                    });

                    // Add active to current section link
                    const activeLink = document.querySelector('.rsl-navbar-link[href="#' + sectionId + '"]');
                    if (activeLink) {
                        activeLink.classList.add('active');
                    }
                }
            });
        }

        // Throttle scroll event for performance
        let scrollTimeout;
        window.addEventListener('scroll', function() {
            if (scrollTimeout) {
                window.cancelAnimationFrame(scrollTimeout);
            }
            scrollTimeout = window.requestAnimationFrame(function() {
                updateActiveNav();
                updateBackToTopButton();
            });
        });

        // Initial check
        updateActiveNav();

        // ============================================
        // Back to Top Button
        // ============================================
        const backToTopButton = document.getElementById('back-to-top');

        function updateBackToTopButton() {
            if (backToTopButton) {
                if (window.pageYOffset > 300) {
                    backToTopButton.classList.add('visible');
                } else {
                    backToTopButton.classList.remove('visible');
                }
            }
        }

        if (backToTopButton) {
            backToTopButton.addEventListener('click', function() {
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });

            // Keyboard support
            backToTopButton.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                }
            });
        }

        // ============================================
        // Application Modal - Auto-focus first field
        // ============================================
        const applyModal = document.getElementById('apply-modal');

        // RSL modal.js handles opening/closing automatically via data-open-from attribute
        // We just need to focus the first field when modal opens
        if (applyModal) {
            // Use MutationObserver to detect when modal becomes visible
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.attributeName === 'class') {
                        if (applyModal.classList.contains('visible')) {
                            // Modal is now open, focus first field
                            const firstInput = applyModal.querySelector('input:not([type="hidden"])');
                            if (firstInput) {
                                setTimeout(function() {
                                    firstInput.focus();
                                }, 150);
                            }
                        }
                    }
                });
            });

            observer.observe(applyModal, { attributes: true });
        }

        // ============================================
        // Form Validation for Apply Modal
        // ============================================
        const applyForm = document.getElementById('apply-form');

        if (applyForm) {
            applyForm.addEventListener('submit', function(e) {
                e.preventDefault();

                // Basic validation
                const firstName = document.getElementById('firstName');
                const lastName = document.getElementById('lastName');
                const email = document.getElementById('email');
                const program = document.getElementById('program');

                let isValid = true;

                // Reset previous errors
                const errorMessages = applyForm.querySelectorAll('.error-message');
                errorMessages.forEach(function(msg) {
                    msg.remove();
                });

                // Validate required fields
                [firstName, lastName, email, program].forEach(function(field) {
                    if (field && !field.value.trim()) {
                        isValid = false;
                        showError(field, 'This field is required');
                    }
                });

                // Validate email format
                if (email && email.value.trim()) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(email.value.trim())) {
                        isValid = false;
                        showError(email, 'Please enter a valid email address');
                    }
                }

                if (isValid) {
                    // Success - show confirmation
                    showSuccessMessage();
                    applyForm.reset();
                }
            });
        }

        function showError(field, message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.style.color = '#dc2626';
            errorDiv.style.fontSize = '0.875rem';
            errorDiv.style.marginTop = '0.25rem';
            errorDiv.textContent = message;
            errorDiv.setAttribute('role', 'alert');

            field.parentNode.appendChild(errorDiv);
            field.setAttribute('aria-invalid', 'true');
            field.setAttribute('aria-describedby', 'error-' + field.id);
            errorDiv.id = 'error-' + field.id;
        }

        function showSuccessMessage() {
            const successDiv = document.createElement('div');
            successDiv.className = 'success-message';
            successDiv.style.cssText = 'background: #10b981; color: white; padding: 1rem; border-radius: 8px; margin-top: 1rem; text-align: center;';
            successDiv.textContent = 'Application submitted successfully! We will contact you soon.';
            successDiv.setAttribute('role', 'status');
            successDiv.setAttribute('aria-live', 'polite');

            applyForm.appendChild(successDiv);

            // Remove success message after 5 seconds
            setTimeout(function() {
                successDiv.remove();
            }, 5000);

            // Close modal after 3 seconds
            setTimeout(function() {
                if (applyModal) {
                    applyModal.classList.remove('active');
                    document.body.style.overflow = '';
                }
            }, 3000);
        }

        // ============================================
        // Respect User Motion Preferences
        // ============================================
        const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');

        if (prefersReducedMotion.matches) {
            // Override smooth scroll behavior
            document.documentElement.style.scrollBehavior = 'auto';
        }

        // ============================================
        // Keyboard Navigation Enhancements
        // ============================================
        // Note: ESC key handling for modal is done by RSL modal.js automatically

        // ============================================
        // Stat Counter Animation (Optional Enhancement)
        // ============================================
        const statNumbers = document.querySelectorAll('.stat-number');
        let hasAnimated = false;

        function animateCounters() {
            if (hasAnimated) return;

            const statsSection = document.querySelector('.stats-section');
            if (!statsSection) return;

            const rect = statsSection.getBoundingClientRect();
            const isVisible = rect.top < window.innerHeight && rect.bottom > 0;

            if (isVisible && !prefersReducedMotion.matches) {
                hasAnimated = true;

                statNumbers.forEach(function(stat) {
                    const text = stat.textContent;
                    const hasPlus = text.includes('+');
                    const hasPercent = text.includes('%');
                    const numberMatch = text.match(/[\d,]+/);

                    if (numberMatch) {
                        const targetNumber = parseInt(numberMatch[0].replace(/,/g, ''));
                        animateNumber(stat, targetNumber, hasPlus, hasPercent);
                    }
                });
            }
        }

        function animateNumber(element, target, hasPlus, hasPercent) {
            const duration = 2000; // 2 seconds
            const steps = 60;
            const increment = target / steps;
            let current = 0;

            const timer = setInterval(function() {
                current += increment;
                if (current >= target) {
                    current = target;
                    clearInterval(timer);
                }

                let displayValue = Math.floor(current).toLocaleString();
                if (hasPlus) displayValue += '+';
                if (hasPercent) displayValue += '%';

                element.textContent = displayValue;
            }, duration / steps);
        }

        // Check on scroll
        window.addEventListener('scroll', animateCounters);
        // Check on load
        animateCounters();

        // ============================================
        // Announce Page Load for Screen Readers
        // ============================================
        const announcement = document.createElement('div');
        announcement.setAttribute('role', 'status');
        announcement.setAttribute('aria-live', 'polite');
        announcement.className = 'sr-only';
        announcement.textContent = 'Academic LMS template loaded. Use tab to navigate or click on menu items to jump to sections.';
        document.body.appendChild(announcement);

        // Remove after announcement
        setTimeout(function() {
            announcement.remove();
        }, 3000);

        // ============================================
        // Console Info
        // ============================================
        console.log('%c Academic LMS Template ', 'background: #1e3a5f; color: white; padding: 10px; font-size: 14px; font-weight: bold;');
        console.log('%c Built with Responsive Slot Layout (RSL) ', 'background: #3b82f6; color: white; padding: 5px; font-size: 12px;');
        console.log('Accessibility: WCAG 2.1 AAA compliant');
        console.log('Features: Smooth scroll, scroll spy, keyboard navigation, screen reader support');

    }); // End DOMContentLoaded

})();
