// ===================================
// APPANAIL LANDING PAGE - JAVASCRIPT
// All Interactive Features
// ===================================

// Wait for DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    
    // ===================================
    // MOBILE MENU TOGGLE
    // ===================================
    const hamburger = document.getElementById('hamburger');
    const navMenu = document.getElementById('navMenu');
    const navLinks = document.querySelectorAll('.nav-link');
    
    if (hamburger && navMenu) {
        hamburger.addEventListener('click', function() {
            hamburger.classList.toggle('active');
            navMenu.classList.toggle('mobile-active');
        });
        
        // Close menu when clicking on a link
        navLinks.forEach(link => {
            link.addEventListener('click', function() {
                hamburger.classList.remove('active');
                navMenu.classList.remove('mobile-active');
            });
        });
        
        // Close menu when clicking outside
        document.addEventListener('click', function(event) {
            if (!hamburger.contains(event.target) && !navMenu.contains(event.target)) {
                hamburger.classList.remove('active');
                navMenu.classList.remove('mobile-active');
            }
        });
    }
    
    // ===================================
    // STICKY HEADER ON SCROLL
    // ===================================
    const header = document.getElementById('header');
    let lastScroll = 0;
    
    window.addEventListener('scroll', function() {
        const currentScroll = window.pageYOffset;
        
        if (currentScroll > 100) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
        
        lastScroll = currentScroll;
    });
    
    // ===================================
    // SMOOTH SCROLLING FOR NAVIGATION
    // ===================================
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            
            if (target) {
                const headerHeight = header.offsetHeight;
                const targetPosition = target.offsetTop - headerHeight;
                
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // ===================================
    // COUNTDOWN TIMER (10 minutes)
    // ===================================
    function startCountdown(minutesElement, secondsElement, duration) {
        let timeRemaining = duration;
        
        function updateTimer() {
            const minutes = Math.floor(timeRemaining / 60);
            const seconds = timeRemaining % 60;
            
            minutesElement.textContent = String(minutes).padStart(2, '0');
            secondsElement.textContent = String(seconds).padStart(2, '0');
            
            if (timeRemaining <= 0) {
                timeRemaining = duration; // Reset timer
            } else {
                timeRemaining--;
            }
        }
        
        updateTimer();
        setInterval(updateTimer, 1000);
    }
    
    // Initialize first countdown timer
    const minutes1 = document.getElementById('minutes');
    const seconds1 = document.getElementById('seconds');
    if (minutes1 && seconds1) {
        startCountdown(minutes1, seconds1, 600); // 10 minutes = 600 seconds
    }
    
    // Initialize second countdown timer
    const minutes2 = document.getElementById('minutes2');
    const seconds2 = document.getElementById('seconds2');
    if (minutes2 && seconds2) {
        startCountdown(minutes2, seconds2, 600);
    }
    
    // ===================================
    // ACCORDION FUNCTIONALITY
    // ===================================
    const accordionHeaders = document.querySelectorAll('.accordion-header');
    
    accordionHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const accordionItem = this.parentElement;
            const isActive = accordionItem.classList.contains('active');
            
            // Close all accordion items
            document.querySelectorAll('.accordion-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // Open clicked item if it wasn't active
            if (!isActive) {
                accordionItem.classList.add('active');
            }
        });
    });
    
    // FAQ Accordion
    const faqQuestions = document.querySelectorAll('.faq-question');
    
    faqQuestions.forEach(question => {
        question.addEventListener('click', function() {
            const faqItem = this.parentElement;
            const isActive = faqItem.classList.contains('active');
            
            // Close all FAQ items
            document.querySelectorAll('.faq-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // Open clicked item if it wasn't active
            if (!isActive) {
                faqItem.classList.add('active');
            }
        });
    });
    
    // ===================================
    // SCROLL 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('animated');
            }
        });
    }, observerOptions);
    
    // Observe badge cards
    const badgeCards = document.querySelectorAll('.badge-card[data-animate="slide-up"]');
    badgeCards.forEach((card, index) => {
        card.style.transitionDelay = `${index * 0.1}s`;
        observer.observe(card);
    });
    
    // Observe review cards
    const reviewCards = document.querySelectorAll('.review-card[data-animate="fade-in"]');
    reviewCards.forEach((card, index) => {
        card.style.transitionDelay = `${index * 0.15}s`;
        observer.observe(card);
    });
    
    // ===================================
    // SCROLL TO TOP BUTTON
    // ===================================
    const scrollToTopBtn = document.getElementById('scrollToTop');
    
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            scrollToTopBtn.classList.add('visible');
        } else {
            scrollToTopBtn.classList.remove('visible');
        }
    });
    
    scrollToTopBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    // ===================================
    // PURCHASE NOTIFICATION POPUP
    // ===================================
    const purchasePopup = document.getElementById('purchasePopup');
    const popupClose = document.querySelector('.popup-close');
    
    // Array of customer names and locations
    const customers = [
        { name: 'Sarah M.', location: 'New York, USA' },
        { name: 'John D.', location: 'Los Angeles, USA' },
        { name: 'Emily R.', location: 'Chicago, USA' },
        { name: 'Michael B.', location: 'Houston, USA' },
        { name: 'Jessica L.', location: 'Phoenix, USA' },
        { name: 'David W.', location: 'Philadelphia, USA' },
        { name: 'Ashley T.', location: 'San Antonio, USA' },
        { name: 'Chris H.', location: 'San Diego, USA' },
        { name: 'Amanda K.', location: 'Dallas, USA' },
        { name: 'James P.', location: 'San Jose, USA' },
        { name: 'Lisa G.', location: 'Austin, USA' },
        { name: 'Robert F.', location: 'Jacksonville, USA' },
        { name: 'Maria S.', location: 'Fort Worth, USA' },
        { name: 'William C.', location: 'Columbus, USA' },
        { name: 'Jennifer N.', location: 'Charlotte, USA' }
    ];
    
    function showPurchasePopup() {
        const randomCustomer = customers[Math.floor(Math.random() * customers.length)];
        document.getElementById('popupName').textContent = randomCustomer.name;
        document.getElementById('popupLocation').textContent = randomCustomer.location;
        
        purchasePopup.classList.add('show');
        
        // Auto-hide after 5 seconds
        setTimeout(function() {
            purchasePopup.classList.remove('show');
        }, 5000);
    }
    
    // Show popup every 30 seconds
    setInterval(showPurchasePopup, 30000);
    
    // Show first popup after 5 seconds
    setTimeout(showPurchasePopup, 5000);
    
    // Close popup on click
    if (popupClose) {
        popupClose.addEventListener('click', function() {
            purchasePopup.classList.remove('show');
        });
    }
    
    // ===================================
    // CTA POPUP FUNCTIONALITY
    // ===================================
    const ctaPopup = document.getElementById('ctaPopup');
    const ctaPopupClose = document.querySelector('.cta-popup-close');
    let popupShown = false;
    let scrollPercentage = 0;
    
    // Function to show CTA popup
    function showCtaPopup() {
        if (!popupShown) {
            ctaPopup.classList.add('show');
            popupShown = true;
            
            // Store in sessionStorage so it doesn't show again in same session
            sessionStorage.setItem('ctaPopupShown', 'true');
        }
    }
    
    // Check if popup was already shown in this session
    if (sessionStorage.getItem('ctaPopupShown')) {
        popupShown = true;
    }
    
    // Show popup after 15-20 seconds delay
    const delayTime = Math.floor(Math.random() * (20000 - 15000 + 1)) + 15000;
    setTimeout(function() {
        if (!popupShown) {
            showCtaPopup();
        }
    }, delayTime);
    
    // Show popup on scroll (50-60%)
    window.addEventListener('scroll', function() {
        if (popupShown) return;
        
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight;
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        scrollPercentage = (scrollTop / (documentHeight - windowHeight)) * 100;
        
        if (scrollPercentage >= 50 && scrollPercentage <= 60) {
            showCtaPopup();
        }
    });
    
    // Exit-intent popup (desktop only)
    if (window.innerWidth >= 768) {
        document.addEventListener('mouseout', function(e) {
            if (popupShown) return;
            
            // Check if mouse is leaving from top of viewport
            if (e.clientY <= 0) {
                showCtaPopup();
            }
        });
    }
    
    // Close CTA popup
    if (ctaPopupClose) {
        ctaPopupClose.addEventListener('click', function() {
            ctaPopup.classList.remove('show');
        });
    }
    
    // Close popup when clicking outside
    ctaPopup.addEventListener('click', function(e) {
        if (e.target === ctaPopup) {
            ctaPopup.classList.remove('show');
        }
    });
    
    // Close popup on escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            ctaPopup.classList.remove('show');
        }
    });
    
    // ===================================
    // LAZY LOADING IMAGES
    // ===================================
    const images = document.querySelectorAll('img[loading="lazy"]');
    
    const imageObserver = new IntersectionObserver(function(entries, observer) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                
                // Check if image has src
                if (img.dataset.src) {
                    img.src = img.dataset.src;
                }
                
                img.classList.add('loaded');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
    
    // ===================================
    // TOUCH FEEDBACK FOR MOBILE
    // ===================================
    const buttons = document.querySelectorAll('.btn, button');
    
    buttons.forEach(button => {
        button.addEventListener('touchstart', function() {
            this.style.transform = 'scale(0.98)';
        });
        
        button.addEventListener('touchend', function() {
            this.style.transform = '';
        });
    });
    
    // ===================================
    // PREVENT HORIZONTAL SCROLL
    // ===================================
    function preventHorizontalScroll() {
        const bodyWidth = document.body.scrollWidth;
        const windowWidth = window.innerWidth;
        
        if (bodyWidth > windowWidth) {
            console.warn('Horizontal scroll detected. Check your layout.');
        }
    }
    
    window.addEventListener('resize', preventHorizontalScroll);
    preventHorizontalScroll();
    
    // ===================================
    // PERFORMANCE OPTIMIZATION
    // ===================================
    // Debounce function for scroll events
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // Optimize scroll event listeners
    const optimizedScrollHandler = debounce(function() {
        // Any scroll-related logic that doesn't need immediate response
    }, 100);
    
    window.addEventListener('scroll', optimizedScrollHandler);
    
    // ===================================
    // ANALYTICS & TRACKING (Optional)
    // ===================================
    // Track button clicks
    document.querySelectorAll('a[href*="mwebvora.com"]').forEach(link => {
        link.addEventListener('click', function(e) {
            // Add your analytics tracking code here
            console.log('CTA clicked:', this.textContent);
            
            // Example: Google Analytics
            // gtag('event', 'click', {
            //     'event_category': 'CTA',
            //     'event_label': this.textContent
            // });
        });
    });
    
    // ===================================
    // FORM VALIDATION (If forms are added)
    // ===================================
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Add your form validation logic here
            const formData = new FormData(form);
            
            console.log('Form submitted:', Object.fromEntries(formData));
            
            // You can add AJAX submission here
        });
    });
    
    // ===================================
    // ACCESSIBILITY IMPROVEMENTS
    // ===================================
    // Add keyboard navigation for accordions
    document.querySelectorAll('.accordion-header, .faq-question').forEach(element => {
        element.setAttribute('tabindex', '0');
        
        element.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                this.click();
            }
        });
    });
    
    // Focus management for popups
    ctaPopup.addEventListener('transitionend', function() {
        if (ctaPopup.classList.contains('show')) {
            ctaPopupClose.focus();
        }
    });
    
    // ===================================
    // RESPONSIVE IMAGE LOADING
    // ===================================
    function updateImageSources() {
        const images = document.querySelectorAll('img[data-mobile][data-desktop]');
        const isMobile = window.innerWidth < 768;
        
        images.forEach(img => {
            if (isMobile && img.dataset.mobile) {
                img.src = img.dataset.mobile;
            } else if (!isMobile && img.dataset.desktop) {
                img.src = img.dataset.desktop;
            }
        });
    }
    
    window.addEventListener('resize', debounce(updateImageSources, 250));
    updateImageSources();
    
    // ===================================
    // PREFETCH CTA LINK ON HOVER
    // ===================================
    const ctaLinks = document.querySelectorAll('a[href*="mwebvora.com"]');
    
    ctaLinks.forEach(link => {
        link.addEventListener('mouseenter', function() {
            const linkElement = document.createElement('link');
            linkElement.rel = 'prefetch';
            linkElement.href = this.href;
            document.head.appendChild(linkElement);
        }, { once: true });
    });
    
    // ===================================
    // PRICING CARD HIGHLIGHT
    // ===================================
    const pricingCards = document.querySelectorAll('.pricing-card');
    
    pricingCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            // Remove highlight from all cards
            pricingCards.forEach(c => c.classList.remove('highlighted'));
            // Add highlight to current card
            this.classList.add('highlighted');
        });
    });
    
    // ===================================
    // VIEWPORT HEIGHT FIX FOR MOBILE
    // ===================================
    function setVh() {
        const vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
    }
    
    window.addEventListener('resize', setVh);
    setVh();
    
    // ===================================
    // CONSOLE LOG (Remove in production)
    // ===================================
    console.log('✅ Appanail Landing Page Loaded Successfully!');
    console.log('📱 Mobile Responsive: Active');
    console.log('⏱️ Countdown Timers: Running');
    console.log('🎯 Popups: Configured');
    console.log('🎨 Animations: Active');
    
    // ===================================
    // SERVICE WORKER (Optional - for PWA)
    // ===================================
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
            // Uncomment to register service worker
            // navigator.serviceWorker.register('/sw.js')
            //     .then(registration => console.log('SW registered:', registration))
            //     .catch(error => console.log('SW registration failed:', error));
        });
    }
    
}); // End of DOMContentLoaded

// ===================================
// WINDOW LOAD EVENT
// ===================================
window.addEventListener('load', function() {
    // Hide loading spinner if you add one
    const loader = document.getElementById('loader');
    if (loader) {
        loader.style.display = 'none';
    }
    
    // Page fully loaded
    console.log('🚀 All resources loaded!');
});

// ===================================
// BEFOREUNLOAD EVENT (Optional)
// ===================================
/*
window.addEventListener('beforeunload', function(e) {
    // Uncomment if you want to show a confirmation before leaving
    // e.preventDefault();
    // e.returnValue = '';
    // return '';
});
*/

// ===================================
// ERROR HANDLING
// ===================================
window.addEventListener('error', function(e) {
    console.error('JavaScript Error:', e.message);
    // You can send error logs to your server here
});

// ===================================
// UNHANDLED PROMISE REJECTION
// ===================================
window.addEventListener('unhandledrejection', function(e) {
    console.error('Unhandled Promise Rejection:', e.reason);
    // You can send error logs to your server here
});
