// Mobile App JavaScript
document.addEventListener('DOMContentLoaded', function() {
    initializeMobileCarousel();
    initializeWishlistButtons();
    initializeCartAnimations();
    updateCartCounter();
});

// Mobile Hero Carousel
function initializeMobileCarousel() {
    const slides = document.querySelectorAll('.hero-slide');
    const indicators = document.querySelectorAll('.indicator');
    let currentSlide = 0;
    let slideInterval;

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

    function showSlide(index) {
        // Remove active class from all slides and indicators
        slides.forEach(slide => slide.classList.remove('active'));
        indicators.forEach(indicator => indicator.classList.remove('active'));

        // Add active class to current slide and indicator
        slides[index].classList.add('active');
        if (indicators[index]) {
            indicators[index].classList.add('active');
        }
    }

    function nextSlide() {
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide(currentSlide);
    }

    function startCarousel() {
        slideInterval = setInterval(nextSlide, 4000);
    }

    function stopCarousel() {
        clearInterval(slideInterval);
    }

    // Add click event listeners to indicators
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            currentSlide = index;
            showSlide(currentSlide);
            stopCarousel();
            startCarousel(); // Restart carousel
        });
    });

    // Touch/swipe support for mobile
    let startX = 0;
    let startY = 0;

    const heroCarousel = document.querySelector('.hero-carousel');
    if (heroCarousel) {
        heroCarousel.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
            stopCarousel();
        });

        heroCarousel.addEventListener('touchmove', (e) => {
            e.preventDefault(); // Prevent scrolling
        });

        heroCarousel.addEventListener('touchend', (e) => {
            const endX = e.changedTouches[0].clientX;
            const endY = e.changedTouches[0].clientY;
            
            const deltaX = startX - endX;
            const deltaY = startY - endY;
            
            // Check if horizontal swipe is dominant
            if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
                if (deltaX > 0) {
                    // Swipe left - next slide
                    currentSlide = (currentSlide + 1) % slides.length;
                } else {
                    // Swipe right - previous slide
                    currentSlide = (currentSlide - 1 + slides.length) % slides.length;
                }
                showSlide(currentSlide);
            }
            
            startCarousel(); // Restart carousel
        });

        // Pause on touch/hover
        heroCarousel.addEventListener('mouseenter', stopCarousel);
        heroCarousel.addEventListener('mouseleave', startCarousel);
    }

    // Start the carousel
    startCarousel();
}

// Wishlist functionality
function initializeWishlistButtons() {
    const wishlistBtns = document.querySelectorAll('.wishlist-btn');
    
    wishlistBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            
            const icon = this.querySelector('i');
            if (icon.classList.contains('far')) {
                icon.classList.remove('far');
                icon.classList.add('fas');
                this.style.color = '#e74c3c';
                showNotification('Added to wishlist!', 'success');
            } else {
                icon.classList.remove('fas');
                icon.classList.add('far');
                this.style.color = '#666666';
                showNotification('Removed from wishlist!', 'info');
            }
            
            // Add heart animation
            this.style.transform = 'scale(1.2)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 200);
        });
    });
}

// Cart animations and feedback
function initializeCartAnimations() {
    const addToCartForms = document.querySelectorAll('form[action*="add_to_cart"]');
    
    addToCartForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const button = this.querySelector('button[type="submit"]');
            if (button) {
                // Add loading state
                const originalText = button.innerHTML;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                button.disabled = true;
                
                // Simulate processing time
                setTimeout(() => {
                    button.innerHTML = '<i class="fas fa-check"></i>';
                    button.style.background = '#27ae60';
                    
                    // Show success notification
                    showNotification('Added to cart!', 'success');
                    
                    // Update cart counter
                    updateCartCounter();
                    
                    // Reset button after 2 seconds
                    setTimeout(() => {
                        button.innerHTML = originalText;
                        button.style.background = '';
                        button.disabled = false;
                    }, 2000);
                }, 500);
            }
        });
    });
}

// Update cart counter in bottom navigation
function updateCartCounter() {
    fetch('/cart/count', {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        const count = data.count || 0;
        
        // Update header cart count
        const headerCartCount = document.querySelector('.cart-count');
        if (headerCartCount) {
            headerCartCount.textContent = count;
            headerCartCount.style.display = count > 0 ? 'flex' : 'none';
        }
        
        // Update bottom navigation cart count
        const cartNavItem = document.querySelector('.bottom-navigation .nav-item[href*="cart"]');
        if (cartNavItem) {
            if (count > 0) {
                cartNavItem.setAttribute('data-cart-count', count);
            } else {
                cartNavItem.removeAttribute('data-cart-count');
            }
        }
        
        // Remove any old dynamically created counters to avoid conflicts
        const oldCounter = cartNavItem && cartNavItem.querySelector('.cart-counter');
        if (oldCounter) {
            oldCounter.remove();
        }
    })
    .catch(error => {
        console.error('Failed to update cart counter:', error);
    });
}

// Show notification
function showNotification(message, type = 'info') {
    // Remove existing notification
    const existing = document.querySelector('.mobile-notification');
    if (existing) {
        existing.remove();
    }

    // Create notification
    const notification = document.createElement('div');
    notification.className = 'mobile-notification';
    
    let bgColor = '#3498db';
    let icon = 'fa-info-circle';
    
    if (type === 'success') {
        bgColor = '#27ae60';
        icon = 'fa-check-circle';
    } else if (type === 'error') {
        bgColor = '#e74c3c';
        icon = 'fa-exclamation-circle';
    }
    
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas ${icon}"></i>
            <span>${message}</span>
        </div>
    `;

    // Add styles
    notification.style.cssText = `
        position: fixed;
        top: 80px;
        left: 20px;
        right: 20px;
        background: ${bgColor};
        color: white;
        padding: 12px 16px;
        border-radius: 8px;
        z-index: 10000;
        transform: translateY(-100px);
        transition: transform 0.3s ease;
        font-size: 14px;
        font-weight: 600;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;

    notification.querySelector('.notification-content').style.cssText = `
        display: flex;
        align-items: center;
        gap: 8px;
    `;

    document.body.appendChild(notification);

    // Animate in
    setTimeout(() => {
        notification.style.transform = 'translateY(0)';
    }, 100);

    // Auto remove
    setTimeout(() => {
        notification.style.transform = 'translateY(-100px)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 300);
    }, 3000);
}

// Smooth scrolling for better UX
function initializeSmoothScrolling() {
    const links = document.querySelectorAll('a[href^="#"]');
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
}

// Initialize smooth scrolling
document.addEventListener('DOMContentLoaded', initializeSmoothScrolling);

// Handle bottom navigation active state
function initializeBottomNavigation() {
    const navItems = document.querySelectorAll('.bottom-navigation .nav-item');
    const currentPath = window.location.pathname;
    
    navItems.forEach(item => {
        item.classList.remove('active');
        const href = item.getAttribute('href');
        
        if (href === currentPath || 
            (currentPath === '/' && href.includes('index')) ||
            (currentPath.includes('products') && href.includes('products')) ||
            (currentPath.includes('cart') && href.includes('cart'))) {
            item.classList.add('active');
        }
    });
}

// Initialize bottom navigation
document.addEventListener('DOMContentLoaded', initializeBottomNavigation);

// Add pull-to-refresh functionality (basic)
let startY = 0;
let pullDistance = 0;
const maxPull = 100;

document.addEventListener('touchstart', function(e) {
    if (window.scrollY === 0) {
        startY = e.touches[0].clientY;
    }
});

document.addEventListener('touchmove', function(e) {
    if (window.scrollY === 0 && startY) {
        pullDistance = e.touches[0].clientY - startY;
        if (pullDistance > 0 && pullDistance < maxPull) {
            e.preventDefault();
            // Visual feedback could be added here
        }
    }
});

// Optimize images for mobile
function initializeImageOptimization() {
    const images = document.querySelectorAll('img');
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                if (img.dataset.src) {
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                }
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// Initialize image optimization
document.addEventListener('DOMContentLoaded', initializeImageOptimization);