// G.AZ Fashions - Main JavaScript File

document.addEventListener('DOMContentLoaded', function() {
    // Initialize all components
    initializeScrollToTop();
    initializeImageLazyLoading();
    initializeFormValidation();
    initializeCartAnimations();
    initializeProductImageZoom();
    initializeResponsiveScrolling();
    initializeAddToCartHandlers();
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            if (alert.classList.contains('alert-dismissible')) {
                const closeBtn = alert.querySelector('.btn-close');
                if (closeBtn) {
                    closeBtn.click();
                }
            }
        });
    }, 5000);
});

// Scroll to top functionality
function initializeScrollToTop() {
    // Create scroll to top button
    const scrollBtn = document.createElement('button');
    scrollBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
    scrollBtn.className = 'scroll-to-top';
    scrollBtn.title = 'Scroll to top';
    scrollBtn.setAttribute('aria-label', 'Scroll to top');
    document.body.appendChild(scrollBtn);
    
    // Show/hide button based on scroll position
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            scrollBtn.classList.add('show');
        } else {
            scrollBtn.classList.remove('show');
        }
    });
    
    // Smooth scroll to top
    scrollBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// Lazy loading for images
function initializeImageLazyLoading() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// Form validation enhancement
function initializeFormValidation() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const requiredFields = form.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                    field.classList.add('is-valid');
                }
            });
            
            // Email validation
            const emailFields = form.querySelectorAll('input[type="email"]');
            emailFields.forEach(field => {
                if (field.value && !isValidEmail(field.value)) {
                    field.classList.add('is-invalid');
                    isValid = false;
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                showNotification('Please fill in all required fields correctly.', 'error');
            }
        });
        
        // Real-time validation
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            input.addEventListener('blur', function() {
                validateField(this);
            });
        });
    });
}

// Field validation helper
function validateField(field) {
    if (field.hasAttribute('required') && !field.value.trim()) {
        field.classList.add('is-invalid');
        field.classList.remove('is-valid');
    } else if (field.type === 'email' && field.value && !isValidEmail(field.value)) {
        field.classList.add('is-invalid');
        field.classList.remove('is-valid');
    } else if (field.value) {
        field.classList.remove('is-invalid');
        field.classList.add('is-valid');
    }
}

// Email validation helper
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// Cart animations
function initializeCartAnimations() {
    const addToCartButtons = document.querySelectorAll('form[action*="add_to_cart"] button[type="submit"]');
    
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            // Add loading state
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
            this.disabled = true;
            
            // Animate button
            this.style.transform = 'scale(0.95)';
            
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
            
            // Reset button after form submission
            setTimeout(() => {
                this.innerHTML = originalText;
                this.disabled = false;
            }, 2000);
        });
    });
    
    // Cart badge animation
    const cartBadge = document.querySelector('.navbar-nav .badge');
    if (cartBadge) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList') {
                    cartBadge.style.transform = 'scale(1.3)';
                    setTimeout(() => {
                        cartBadge.style.transform = 'scale(1)';
                    }, 200);
                }
            });
        });
        
        observer.observe(cartBadge, { childList: true });
    }
}

// Product image zoom
function initializeProductImageZoom() {
    const productImages = document.querySelectorAll('.product-image img');
    
    productImages.forEach(img => {
        img.addEventListener('mouseover', function() {
            this.style.transform = 'scale(1.1)';
            this.style.transition = 'transform 0.3s ease';
        });
        
        img.addEventListener('mouseout', function() {
            this.style.transform = 'scale(1)';
        });
        
        // Click to zoom
        img.addEventListener('click', function() {
            openImageModal(this.src, this.alt);
        });
    });
}

// Image modal for zoom
function openImageModal(src, alt) {
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">${alt}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="${src}" alt="${alt}" class="img-fluid">
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
    
    modal.addEventListener('hidden.bs.modal', function() {
        document.body.removeChild(modal);
    });
}

// Notification system - Modern Toast
function showNotification(message, type = 'info') {
    // Create toast container if it doesn't exist
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }

    // Create toast notification
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    
    // Icon based on type
    let icon = 'info-circle';
    if (type === 'success') icon = 'check-circle';
    if (type === 'error') icon = 'exclamation-circle';
    if (type === 'warning') icon = 'exclamation-triangle';
    
    toast.innerHTML = `
        <div class="toast-icon">
            <i class="fas fa-${icon}"></i>
        </div>
        <div class="toast-content">
            <p class="toast-message">${message}</p>
        </div>
        <button class="toast-close" aria-label="Close">
            <i class="fas fa-times"></i>
        </button>
        <div class="toast-progress">
            <div class="toast-progress-bar"></div>
        </div>
    `;
    
    // Add to container
    container.appendChild(toast);
    
    // Trigger animation
    requestAnimationFrame(() => {
        toast.classList.add('show');
    });
    
    // Close button functionality
    const closeBtn = toast.querySelector('.toast-close');
    closeBtn.addEventListener('click', () => {
        dismissToast(toast);
    });
    
    // Auto dismiss after 3 seconds
    const dismissTimeout = setTimeout(() => {
        dismissToast(toast);
    }, 3000);
    
    // Store timeout on toast element for manual dismissal
    toast.dataset.timeoutId = dismissTimeout;
}

function dismissToast(toast) {
    // Clear any pending timeout
    if (toast.dataset.timeoutId) {
        clearTimeout(parseInt(toast.dataset.timeoutId));
    }
    
    // Add hide class for animation
    toast.classList.remove('show');
    toast.classList.add('hide');
    
    // Remove from DOM after animation
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
        
        // Remove container if empty
        const container = document.querySelector('.toast-container');
        if (container && container.children.length === 0) {
            container.remove();
        }
    }, 300);
}

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

// Loading state for forms
document.querySelectorAll('form').forEach(form => {
    form.addEventListener('submit', function() {
        const submitBtn = form.querySelector('button[type="submit"]');
        if (submitBtn && !submitBtn.disabled) {
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
            submitBtn.disabled = true;
            
            // Prevent double submission
            setTimeout(() => {
                if (!form.checkValidity()) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            }, 100);
        }
    });
});

// Product quantity controls
document.querySelectorAll('input[name="quantity"]').forEach(input => {
    const container = input.parentElement;
    
    // Add plus/minus buttons if they don't exist
    if (!container.querySelector('.quantity-btn')) {
        const minusBtn = document.createElement('button');
        minusBtn.type = 'button';
        minusBtn.className = 'btn btn-outline-secondary btn-sm quantity-btn';
        minusBtn.innerHTML = '<i class="fas fa-minus"></i>';
        
        const plusBtn = document.createElement('button');
        plusBtn.type = 'button';
        plusBtn.className = 'btn btn-outline-secondary btn-sm quantity-btn';
        plusBtn.innerHTML = '<i class="fas fa-plus"></i>';
        
        container.insertBefore(minusBtn, input);
        container.appendChild(plusBtn);
        
        minusBtn.addEventListener('click', () => {
            if (input.value > 1) {
                input.value = parseInt(input.value) - 1;
                input.dispatchEvent(new Event('change'));
            }
        });
        
        plusBtn.addEventListener('click', () => {
            input.value = parseInt(input.value) + 1;
            input.dispatchEvent(new Event('change'));
        });
    }
});

// Search functionality (if search box exists)
const searchBox = document.querySelector('input[type="search"]');
if (searchBox) {
    let searchTimeout;
    
    searchBox.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.toLowerCase();
        
        searchTimeout = setTimeout(() => {
            const products = document.querySelectorAll('.product-card');
            
            products.forEach(product => {
                const title = product.querySelector('.card-title').textContent.toLowerCase();
                const description = product.querySelector('.card-text')?.textContent.toLowerCase() || '';
                
                if (title.includes(query) || description.includes(query)) {
                    product.style.display = 'block';
                } else {
                    product.style.display = query ? 'none' : 'block';
                }
            });
        }, 300);
    });
}

// Performance monitoring
if ('performance' in window) {
    window.addEventListener('load', function() {
        const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
        console.log(`Page load time: ${loadTime}ms`);
        
        // Log slow loading images
        const images = document.querySelectorAll('img');
        images.forEach(img => {
            img.addEventListener('load', function() {
                if (this.naturalWidth === 0 || this.naturalHeight === 0) {
                    console.warn('Failed to load image:', this.src);
                }
            });
        });
    });
}

// Responsive scrolling functionality - only for mobile screens
function initializeResponsiveScrolling() {
    function setupMobileScrolling() {
        const isMobile = window.innerWidth <= 767.98;
        const scrollableElements = document.querySelectorAll('.scrollable-horizontal');
        
        scrollableElements.forEach(element => {
            // Remove any existing event listeners
            element.replaceWith(element.cloneNode(true));
        });
        
        if (isMobile) {
            // Re-select elements after cloning
            const newScrollableElements = document.querySelectorAll('.scrollable-horizontal');
            
            newScrollableElements.forEach(element => {
                element.style.scrollBehavior = 'smooth';
                
                let isDown = false;
                let startX;
                let scrollLeft;
                
                element.addEventListener('mousedown', (e) => {
                    isDown = true;
                    element.classList.add('active');
                    startX = e.pageX - element.offsetLeft;
                    scrollLeft = element.scrollLeft;
                    e.preventDefault();
                });
                
                element.addEventListener('mouseleave', () => {
                    isDown = false;
                    element.classList.remove('active');
                });
                
                element.addEventListener('mouseup', () => {
                    isDown = false;
                    element.classList.remove('active');
                });
                
                element.addEventListener('mousemove', (e) => {
                    if (!isDown) return;
                    e.preventDefault();
                    const x = e.pageX - element.offsetLeft;
                    const walk = (x - startX) * 2;
                    element.scrollLeft = scrollLeft - walk;
                });
                
                // Touch events for mobile
                element.addEventListener('touchstart', (e) => {
                    startX = e.touches[0].pageX - element.offsetLeft;
                    scrollLeft = element.scrollLeft;
                });
                
                element.addEventListener('touchmove', (e) => {
                    if (!startX) return;
                    const x = e.touches[0].pageX - element.offsetLeft;
                    const walk = (x - startX) * 2;
                    element.scrollLeft = scrollLeft - walk;
                });
                
                element.addEventListener('selectstart', (e) => {
                    e.preventDefault();
                });
            });
        }
    }
    
    // Initial setup
    setupMobileScrolling();
    
    // Re-setup on window resize
    window.addEventListener('resize', setupMobileScrolling);
}

// Add to cart handlers with loading states
function initializeAddToCartHandlers() {
    // Handle all add to cart forms
    document.addEventListener('submit', function(e) {
        if (e.target.classList.contains('quick-add-form') || 
            e.target.classList.contains('add-to-cart-form')) {
            handleAddToCart(e, e.target);
        }
    });
}

// Global function for handling add to cart
function handleAddToCart(event, form) {
    event.preventDefault();
    
    const button = form.querySelector('button[type="submit"]');
    const btnText = button.querySelector('.btn-text');
    const btnLoading = button.querySelector('.btn-loading');
    
    // Store original text before changing
    if (btnText && !btnText.dataset.original) {
        btnText.dataset.original = btnText.textContent;
    }
    
    // Show loading state
    button.classList.add('loading');
    button.disabled = true;
    if (btnText) btnText.style.display = 'none';
    if (btnLoading) btnLoading.style.display = 'inline-block';
    
    // Submit form via AJAX to prevent page reload
    fetch(form.action, {
        method: 'POST',
        body: new FormData(form),
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        if (response.ok) {
            // Show success state
            button.classList.remove('loading');
            button.classList.add('success');
            if (btnText) {
                btnText.textContent = 'Added!';
                btnText.style.display = 'inline';
            }
            if (btnLoading) btnLoading.style.display = 'none';
            
            // Update cart counter if it exists
            updateCartCounter();
            
            // Reset button after 2 seconds
            setTimeout(() => {
                button.classList.remove('success');
                button.disabled = false;
                if (btnText) {
                    const originalText = btnText.dataset.original || 'Add';
                    btnText.textContent = originalText;
                }
            }, 2000);
        } else {
            throw new Error('Failed to add to cart');
        }
    })
    .catch(error => {
        // Show error state
        button.classList.remove('loading');
        button.disabled = false;
        if (btnText) {
            btnText.style.display = 'inline';
            btnText.textContent = 'Try Again';
        }
        if (btnLoading) btnLoading.style.display = 'none';
        
        // Reset button after 3 seconds
        setTimeout(() => {
            if (btnText) {
                const originalText = btnText.dataset.original || 'Add';
                btnText.textContent = originalText;
            }
        }, 3000);
    });
}

// Update cart counter
function updateCartCounter() {
    fetch('/api/cart/count', {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // Update desktop cart counters
        const cartButtons = document.querySelectorAll('.cart-count, .cart-counter');
        cartButtons.forEach(button => {
            button.textContent = data.count;
            if (data.count > 0) {
                button.style.display = 'inline-block';
            } else {
                button.style.display = 'none';
            }
        });
        
        // Update mobile bottom navigation cart badge
        const mobileCartItem = document.querySelector('.bottom-navigation .nav-item[href*="cart"]');
        if (mobileCartItem) {
            // Remove existing badge
            const existingBadge = mobileCartItem.querySelector('.cart-badge');
            if (existingBadge) {
                existingBadge.remove();
            }
            
            // Add new badge if count > 0
            if (data.count > 0) {
                const badge = document.createElement('span');
                badge.className = 'position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger cart-badge';
                badge.textContent = data.count;
                badge.style.fontSize = '10px';
                badge.style.minWidth = '18px';
                badge.style.height = '18px';
                badge.style.lineHeight = '18px';
                badge.style.textAlign = 'center';
                badge.style.marginTop = '-8px';
                badge.style.marginLeft = '-8px';
                mobileCartItem.appendChild(badge);
            }
            
            // Also update data attribute for CSS-based badge
            mobileCartItem.setAttribute('data-cart-count', data.count > 0 ? data.count : '');
        }
    })
    .catch(error => console.log('Cart update error:', error));
}

// Service worker registration (for future PWA support)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        // navigator.serviceWorker.register('/sw.js')
        //     .then(registration => console.log('SW registered'))
        //     .catch(error => console.log('SW registration failed'));
    });
}
