// ===================================
// Vertex Consulting - Custom JavaScript
// ===================================

document.addEventListener('DOMContentLoaded', function() {

    // ===================================
    // Navbar Theme Toggle Integration
    // ===================================
    const navbarToggle = document.getElementById('theme-toggle');

    function updateNavbarIcon() {
        if (navbarToggle) {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const icon = navbarToggle.querySelector('i');
            if (icon) {
                if (currentTheme === 'dark') {
                    icon.className = 'fas fa-moon';
                } else {
                    icon.className = 'fas fa-sun';
                }
            }
        }
    }

    if (navbarToggle) {
        // Set initial icon based on current theme
        updateNavbarIcon();

        navbarToggle.addEventListener('click', function() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('rsl-theme', newTheme);
            updateNavbarIcon();
        });
    }

    // ===================================
    // Scroll Progress Indicator
    // ===================================
    const scrollProgress = document.querySelector('.scroll-progress') || document.getElementById('scroll-progress');

    function updateScrollProgress() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrollPercent = (scrollTop / docHeight) * 100;
        scrollProgress.style.width = scrollPercent + '%';
    }

    window.addEventListener('scroll', updateScrollProgress);

    // ===================================
    // Navbar Scroll Effect
    // ===================================
    const navbar = document.querySelector('.rsl-navbar');

    function handleNavbarScroll() {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    }

    window.addEventListener('scroll', handleNavbarScroll);

    // ===================================
    // Welcome Toast Sequence
    // ===================================
    setTimeout(function() {
        showToast({
            type: 'info',
            title: 'Welcome! 👋',
            message: 'Discover strategic solutions for your business',
            duration: 4000,
            position: 'top-right'
        });
    }, 1000);

    setTimeout(function() {
        showToast({
            type: 'success',
            title: '500+ Enterprise Clients',
            message: 'Join industry leaders achieving measurable results',
            duration: 5000,
            position: 'top-right'
        });
    }, 5500);

    setTimeout(function() {
        showToast({
            type: 'info',
            title: 'Free Consultation Available',
            message: 'Schedule your strategic assessment today',
            duration: 4000,
            position: 'top-right'
        });
    }, 11000);

    // ===================================
    // Counter Animation for Stats
    // ===================================
    function animateCounter(element) {
        const target = parseFloat(element.getAttribute('data-count'));
        const duration = 2000; // 2 seconds
        const start = 0;
        const increment = target / (duration / 16); // 60 FPS
        let current = start;

        const updateCounter = function() {
            current += increment;
            if (current >= target) {
                element.textContent = target.toLocaleString();
            } else {
                element.textContent = Math.floor(current).toLocaleString();
                requestAnimationFrame(updateCounter);
            }
        };

        updateCounter();
    }

    // Trigger counter animation when stats come into view
    const observerOptions = {
        threshold: 0.5,
        rootMargin: '0px'
    };

    const statsObserver = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                const statValue = entry.target.querySelector('.stat-value[data-count]');
                if (statValue && !statValue.classList.contains('animated')) {
                    statValue.classList.add('animated');
                    animateCounter(statValue);
                }
            }
        });
    }, observerOptions);

    document.querySelectorAll('.stat-card').forEach(function(card) {
        statsObserver.observe(card);
    });

    // ===================================
    // Animate Elements on Scroll
    // ===================================
    const animateObserver = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                entry.target.classList.add('animated');
            }
        });
    }, {
        threshold: 0.2,
        rootMargin: '0px'
    });

    document.querySelectorAll('[data-animate-in]').forEach(function(element) {
        animateObserver.observe(element);
    });

    // ===================================
    // Newsletter Form Submission
    // ===================================
    const newsletterForm = document.getElementById('newsletter-form');

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

            const emailInput = document.getElementById('newsletter-email');
            const email = emailInput.value.trim();

            // Validate email
            if (!email || !email.includes('@') || !email.includes('.')) {
                generateAlert({
                    type: 'danger',
                    message: 'Invalid Email',
                    details: 'Please enter a valid email address.',
                    location: '#newsletter-alert',
                    timeout: 5000,
                    animation: 'fade-slide-up'
                });
                return;
            }

            // Show success alert
            generateAlert({
                type: 'success',
                message: 'Success!',
                details: 'Welcome aboard! Check your email for next steps.',
                location: '#newsletter-alert',
                timeout: 5000,
                animation: 'fade-slide-up'
            });

            // Show toast
            showToast({
                type: 'success',
                title: 'Subscribed!',
                message: 'Check your inbox for a confirmation email',
                duration: 5000,
                position: 'top-right'
            });

            // Clear form
            newsletterForm.reset();
        });
    }

    // ===================================
    // Smooth Scroll for Navigation Links
    // ===================================
    document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');

            // Skip empty hash or modal/offcanvas triggers
            if (href === '#' || href.length <= 1) {
                return;
            }

            const target = document.querySelector(href);
            if (target) {
                e.preventDefault();
                const navbarHeight = navbar.offsetHeight;
                const targetPosition = target.offsetTop - navbarHeight - 20;

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

                // Close mobile menu if open
                const mobileMenu = document.querySelector('.rsl-navbar-menu');
                if (mobileMenu && mobileMenu.classList.contains('active')) {
                    const toggleBtn = document.querySelector('.rsl-navbar-toggle');
                    if (toggleBtn) {
                        toggleBtn.click();
                    }
                }
            }
        });
    });

});

// ===================================
// Toast Helper Function
// ===================================
function showToast(options) {
    const toast = document.createElement('div');
    toast.className = 'rsl-toast rsl-fixed rsl-' + (options.position || 'top-right');

    const typeColors = {
        success: '#28a745',
        info: '#17a2b8',
        warning: '#ffc107',
        danger: '#dc3545'
    };

    const typeIcons = {
        success: 'fa-check-circle',
        info: 'fa-info-circle',
        warning: 'fa-exclamation-triangle',
        danger: 'fa-times-circle'
    };

    toast.innerHTML = `
        <div class="rsl-toast-header" style="background-color: ${typeColors[options.type] || '#007bff'}">
            <strong><i class="fas ${typeIcons[options.type] || 'fa-bell'}"></i> ${options.title || 'Notification'}</strong>
            <button class="rsl-toast-close" aria-label="Close">&times;</button>
        </div>
        <div class="rsl-toast-body">
            ${options.message || ''}
        </div>
    `;

    document.body.appendChild(toast);

    // Show toast
    setTimeout(function() {
        toast.style.opacity = '1';
        toast.style.transform = 'translateY(0)';
    }, 10);

    // Close button
    const closeBtn = toast.querySelector('.rsl-toast-close');
    closeBtn.addEventListener('click', function() {
        hideToast(toast);
    });

    // Auto close
    if (options.duration) {
        setTimeout(function() {
            hideToast(toast);
        }, options.duration);
    }
}

function hideToast(toast) {
    toast.style.opacity = '0';
    toast.style.transform = 'translateY(-20px)';
    setTimeout(function() {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 300);
}

// ===================================
// Get Started Function
// ===================================
function showGetStarted() {
    rslPrompt({
        title: 'Start Your Free Trial',
        message: 'Enter your email address to get started:',
        placeholder: 'your@email.com',
        inputType: 'email',
        type: 'info',
        confirmText: 'Start Free Trial',
        required: false
    }).then(function(email) {
        if (email) {
            // Validate email
            if (email.includes('@') && email.includes('.')) {
                // Show success alert
                rslAlert({
                    type: 'success',
                    title: 'Welcome Aboard!',
                    message: 'Check your inbox for your account activation link.',
                    animation: 'zoom-in'
                });

                // Show success toast
                showToast({
                    type: 'success',
                    title: 'Account Created!',
                    message: 'Welcome to TechLaunch Pro',
                    duration: 5000,
                    position: 'top-right'
                });
            } else {
                rslAlert({
                    type: 'error',
                    title: 'Invalid Email',
                    message: 'Please enter a valid email address.',
                    animation: 'shake'
                });
            }
        }
    });
}

// ===================================
// Pricing Confirm Function
// ===================================
function showPricingConfirm(plan) {
    rslConfirm({
        title: 'Start ' + plan + ' Plan?',
        message: 'You\'ll get instant access to all ' + plan + ' features with a 14-day free trial.',
        type: 'info',
        confirmText: 'Start Trial',
        cancelText: 'Maybe Later'
    }).then(function(confirmed) {
        if (confirmed) {
            // Show prompt for email
            showGetStarted();
        } else {
            showToast({
                type: 'info',
                title: 'No Problem',
                message: 'Take your time! We\'ll be here when you\'re ready.',
                duration: 4000,
                position: 'top-right'
            });
        }
    });
}

// ===================================
// Contact Sales Function
// ===================================
function showContactSales() {
    rslPrompt({
        title: 'Contact Sales',
        message: 'Enter your work email and we\'ll get in touch:',
        placeholder: 'name@company.com',
        inputType: 'email',
        type: 'info',
        confirmText: 'Request Demo',
        required: false
    }).then(function(email) {
        if (email) {
            if (email.includes('@') && email.includes('.')) {
                rslAlert({
                    type: 'success',
                    title: 'Request Received!',
                    message: 'Our sales team will contact you within 24 hours.',
                    animation: 'zoom-in'
                });

                showToast({
                    type: 'success',
                    title: 'Demo Requested',
                    message: 'Check your email for confirmation',
                    duration: 5000,
                    position: 'top-right'
                });
            } else {
                rslAlert({
                    type: 'error',
                    title: 'Invalid Email',
                    message: 'Please enter a valid email address.',
                    animation: 'shake'
                });
            }
        }
    });
}

// ===================================
// Open Off-Canvas Panels
// ===================================
function openOffCanvas(featureId) {
    const offcanvas = document.getElementById(featureId + '-offcanvas');
    if (offcanvas) {
        // Trigger off-canvas open
        offcanvas.classList.add('show');
        document.body.classList.add('rsl-offcanvas-open');

        // Create backdrop
        const backdrop = document.createElement('div');
        backdrop.className = 'rsl-offcanvas-backdrop show';
        document.body.appendChild(backdrop);

        // Close handlers
        const closeBtn = offcanvas.querySelector('.rsl-offcanvas-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                closeOffCanvas(offcanvas, backdrop);
            });
        }

        backdrop.addEventListener('click', function() {
            closeOffCanvas(offcanvas, backdrop);
        });
    }
}

function closeOffCanvas(offcanvas, backdrop) {
    offcanvas.classList.remove('show');
    backdrop.classList.remove('show');
    setTimeout(function() {
        document.body.classList.remove('rsl-offcanvas-open');
        if (backdrop.parentNode) {
            backdrop.parentNode.removeChild(backdrop);
        }
    }, 300);
}

// ===================================
// Open Modal
// ===================================
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.style.display = 'block';
        setTimeout(function() {
            modal.classList.add('show');
        }, 10);

        // Close handlers
        const closeBtn = modal.querySelector('.rsl-modal-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                closeModal(modal);
            });
        }

        const dismissBtn = modal.querySelector('[data-dismiss-modal]');
        if (dismissBtn) {
            dismissBtn.addEventListener('click', function() {
                closeModal(modal);
            });
        }

        // Close on backdrop click
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModal(modal);
            }
        });
    }
}

function closeModal(modal) {
    modal.classList.remove('show');
    setTimeout(function() {
        modal.style.display = 'none';
    }, 300);
}

// ===================================
// Demo Video Modal
// ===================================
// Note: openDemoVideo() is now defined inline in index.html
// to handle the off-canvas video player

// ===================================
// Copy Code Function
// ===================================
function copyCode() {
    showToast({
        type: 'success',
        title: 'Copied!',
        message: 'Code copied to clipboard',
        duration: 3000,
        position: 'top-right'
    });
}

// ===================================
// Keyboard Navigation Enhancements
// ===================================
document.addEventListener('keydown', function(e) {
    // ESC key closes modals and off-canvas
    if (e.key === 'Escape') {
        // Close any open modals
        document.querySelectorAll('.rsl-modal.show').forEach(function(modal) {
            closeModal(modal);
        });

        // Close any open off-canvas
        document.querySelectorAll('.rsl-offcanvas.show').forEach(function(offcanvas) {
            const backdrop = document.querySelector('.rsl-offcanvas-backdrop');
            if (backdrop) {
                closeOffCanvas(offcanvas, backdrop);
            }
        });
    }
});

// ===================================
// Performance: Lazy Load Images
// ===================================
if ('IntersectionObserver' in window) {
    const imageObserver = new IntersectionObserver(function(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                const img = entry.target;
                if (img.dataset.src) {
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                    imageObserver.unobserve(img);
                }
            }
        });
    });

    document.querySelectorAll('img[data-src]').forEach(function(img) {
        imageObserver.observe(img);
    });
}
