/* ============================================
   RSL Showcase Landing - Custom Scripts
   A comprehensive landing page showcasing 25+ RSL components
   ============================================ */

(function() {
    'use strict';

    // ============================================
    // Off-Canvas Panel for Features
    // ============================================
    function initOffCanvasPanel() {
        var openBtn = document.getElementById('open-features-panel');
        var panel = document.getElementById('features-panel');
        var overlay = document.getElementById('features-panel-overlay');
        var closeBtn = panel ? panel.querySelector('.off-canvas-close') : null;

        if (!openBtn || !panel || !overlay) return;

        function openPanel() {
            panel.classList.add('off-canvas-open');
            overlay.classList.add('off-canvas-overlay-visible');
            document.body.classList.add('scroll-lock');
            // Focus the close button for accessibility
            if (closeBtn) {
                setTimeout(function() {
                    closeBtn.focus();
                }, 100);
            }
        }

        function closePanel() {
            panel.classList.remove('off-canvas-open');
            overlay.classList.remove('off-canvas-overlay-visible');
            document.body.classList.remove('scroll-lock');
            // Return focus to trigger button
            openBtn.focus();
        }

        openBtn.addEventListener('click', openPanel);

        if (closeBtn) {
            closeBtn.addEventListener('click', closePanel);
        }

        overlay.addEventListener('click', closePanel);

        // Close on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && panel.classList.contains('off-canvas-open')) {
                closePanel();
            }
        });
    }

    // ============================================
    // Contact Form Submission
    // ============================================
    function initContactForm() {
        var form = document.getElementById('contact-form');
        if (!form) return;

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

            // Get form values
            var name = document.getElementById('contact-name').value;
            var email = document.getElementById('contact-email').value;

            // Validate
            if (!name || !email) {
                if (window.RSL && window.RSL.Toast) {
                    RSL.Toast.show({
                        header: 'Missing Information',
                        body: 'Please fill in all required fields.',
                        position: 'top-right',
                        variant: 'danger',
                        autoDismiss: 5000
                    });
                }
                return;
            }

            // Simulate form submission
            var submitBtn = form.querySelector('button[type="submit"]');
            var originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
            submitBtn.disabled = true;

            setTimeout(function() {
                // Show success toast
                if (window.RSL && window.RSL.Toast) {
                    RSL.Toast.show({
                        header: 'Welcome aboard, ' + name.split(' ')[0] + '!',
                        body: 'Check your email at ' + email + ' for next steps.',
                        position: 'top-right',
                        variant: 'success',
                        autoDismiss: 8000
                    });
                }

                // Reset form
                form.reset();
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }, 1500);
        });
    }

    // ============================================
    // Smooth Scroll for Anchor Links
    // ============================================
    function initSmoothScroll() {
        var links = document.querySelectorAll('a[href^="#"]');

        links.forEach(function(link) {
            link.addEventListener('click', function(e) {
                var href = this.getAttribute('href');

                // Skip if it's just "#" or a modal trigger
                if (href === '#' || this.hasAttribute('data-open-from')) return;

                var target = document.querySelector(href);
                if (target) {
                    e.preventDefault();

                    // Calculate offset for sticky navbar
                    var navbar = document.querySelector('.rsl-navbar');
                    var navbarHeight = navbar ? navbar.offsetHeight : 0;
                    var targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navbarHeight - 20;

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

                    // Update URL without triggering scroll
                    history.pushState(null, null, href);
                }
            });
        });
    }

    // ============================================
    // Active Nav Link on Scroll
    // ============================================
    function initScrollSpy() {
        var sections = document.querySelectorAll('section[id]');
        var navLinks = document.querySelectorAll('.rsl-navbar-link[href^="#"]');

        if (sections.length === 0 || navLinks.length === 0) return;

        function updateActiveLink() {
            var scrollPosition = window.scrollY + 100;

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

                if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
                    navLinks.forEach(function(link) {
                        link.classList.remove('active');
                        if (link.getAttribute('href') === '#' + sectionId) {
                            link.classList.add('active');
                        }
                    });
                }
            });
        }

        window.addEventListener('scroll', updateActiveLink);
        updateActiveLink(); // Run on page load
    }

    // ============================================
    // Typewriter Effect for Hero
    // ============================================
    function initTypewriter() {
        var element = document.querySelector('.rsl-hero-typewriter');
        if (!element) return;

        var words;
        try {
            words = JSON.parse(element.getAttribute('data-hero-typewriter'));
        } catch (e) {
            return;
        }

        if (!words || words.length === 0) return;

        var wordIndex = 0;
        var charIndex = 0;
        var isDeleting = false;
        var typingSpeed = 100;
        var deletingSpeed = 50;
        var pauseDuration = 2000;

        function type() {
            var currentWord = words[wordIndex];

            if (isDeleting) {
                element.textContent = currentWord.substring(0, charIndex - 1);
                charIndex--;
            } else {
                element.textContent = currentWord.substring(0, charIndex + 1);
                charIndex++;
            }

            var speed = isDeleting ? deletingSpeed : typingSpeed;

            if (!isDeleting && charIndex === currentWord.length) {
                // Pause at end of word
                speed = pauseDuration;
                isDeleting = true;
            } else if (isDeleting && charIndex === 0) {
                // Move to next word
                isDeleting = false;
                wordIndex = (wordIndex + 1) % words.length;
                speed = 500;
            }

            setTimeout(type, speed);
        }

        // Start after a delay
        setTimeout(type, 1000);
    }

    // ============================================
    // KPI Count-Up Animation
    // ============================================
    function initCountUp() {
        var kpiValues = document.querySelectorAll('.rsl-kpi-value[data-count-up]');

        if (kpiValues.length === 0) return;

        var observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    var element = entry.target;
                    var text = element.textContent.trim();
                    var suffix = element.getAttribute('data-count-suffix') || '';

                    // Extract number from text
                    var match = text.match(/[\d,]+/);
                    if (!match) return;

                    var targetValue = parseInt(match[0].replace(/,/g, ''), 10);
                    var duration = 2000;
                    var startTime = null;

                    function animate(currentTime) {
                        if (!startTime) startTime = currentTime;
                        var progress = Math.min((currentTime - startTime) / duration, 1);

                        // Easing function (ease out)
                        var easeOut = 1 - Math.pow(1 - progress, 3);
                        var currentValue = Math.floor(easeOut * targetValue);

                        element.textContent = currentValue.toLocaleString() + suffix;

                        if (progress < 1) {
                            requestAnimationFrame(animate);
                        }
                    }

                    requestAnimationFrame(animate);
                    observer.unobserve(element);
                }
            });
        }, { threshold: 0.5 });

        kpiValues.forEach(function(el) {
            observer.observe(el);
        });
    }

    // ============================================
    // Initialize Everything
    // ============================================
    document.addEventListener('DOMContentLoaded', function() {
        initOffCanvasPanel();
        initContactForm();
        initSmoothScroll();
        initScrollSpy();
        initTypewriter();
        initCountUp();

        // Ensure all RSL components are initialized
        if (window.RSL) {
            // Components auto-initialize, but we can force re-init if needed
            if (RSL.Tooltip && RSL.Tooltip.init) RSL.Tooltip.init();
            if (RSL.Popover && RSL.Popover.init) RSL.Popover.init();
            if (RSL.Charts && RSL.Charts.init) RSL.Charts.init();
            if (RSL.ProgressBar && RSL.ProgressBar.init) RSL.ProgressBar.init();
            if (RSL.Timeline && RSL.Timeline.init) RSL.Timeline.init();
            if (RSL.KPICards && RSL.KPICards.init) RSL.KPICards.init();
            if (RSL.Gallery && RSL.Gallery.init) RSL.Gallery.init();
            if (RSL.VideoPlayer && RSL.VideoPlayer.init) RSL.VideoPlayer.init();
            if (RSL.StarRating && RSL.StarRating.init) RSL.StarRating.init();
            if (RSL.Testimonial && RSL.Testimonial.init) RSL.Testimonial.init();
            if (RSL.PricingTable && RSL.PricingTable.init) RSL.PricingTable.init();
            if (RSL.Announcements && RSL.Announcements.init) RSL.Announcements.init();
            if (RSL.AccessibilityWidget && RSL.AccessibilityWidget.init) RSL.AccessibilityWidget.init();
        }
    });

})();
