/**
 * Digital Marketplace - Main JavaScript
 * Premium Dark Luxury Theme
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // ============================================
    // NAVBAR SCROLL EFFECT
    // ============================================
    const navbar = document.getElementById('mainNav');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }
    
    // ============================================
    // BACK TO TOP BUTTON
    // ============================================
    const backToTop = document.getElementById('backToTop');
    if (backToTop) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 300) {
                backToTop.classList.add('show');
            } else {
                backToTop.classList.remove('show');
            }
        });
        
        backToTop.addEventListener('click', function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }
    
    // ============================================
    // SEARCH MODAL FOCUS
    // ============================================
    const searchModal = document.getElementById('searchModal');
    if (searchModal) {
        searchModal.addEventListener('shown.bs.modal', function() {
            const searchInput = searchModal.querySelector('input[name="search"]');
            if (searchInput) {
                searchInput.focus();
            }
        });
    }
    
    // ============================================
    // WISHLIST BUTTONS
    // ============================================
    document.querySelectorAll('.wishlist-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = this.dataset.productId;
            const icon = this.querySelector('i');
            
            fetch(BASE_URL + '/api/wishlist.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=toggle&product_id=' + productId + '&csrf_token=' + CSRF_TOKEN
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.classList.toggle('active');
                    if (this.classList.contains('active')) {
                        icon.classList.remove('far');
                        icon.classList.add('fas');
                        showNotification('Added to wishlist!', 'success');
                    } else {
                        icon.classList.remove('fas');
                        icon.classList.add('far');
                        showNotification('Removed from wishlist!', 'info');
                    }
                } else {
                    showNotification(data.message || 'Please login first', 'warning');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Something went wrong', 'error');
            });
        });
    });
    
    // ============================================
    // ADD TO CART
    // ============================================
    document.querySelectorAll('.add-to-cart-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = this.dataset.productId;
            const licenseType = this.dataset.license || 'regular';
            const quantity = document.querySelector('.quantity-input')?.value || 1;
            
            this.disabled = true;
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            
            fetch(BASE_URL + '/api/cart.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=add&product_id=' + productId + '&license_type=' + licenseType + '&quantity=' + quantity + '&csrf_token=' + CSRF_TOKEN
            })
            .then(response => response.json())
            .then(data => {
                this.disabled = false;
                this.innerHTML = originalText;
                
                if (data.success) {
                    updateCartCount(data.cart_count);
                    showNotification('Added to cart!', 'success');
                    
                    // Animate cart icon
                    const cartLink = document.querySelector('.cart-link');
                    if (cartLink) {
                        cartLink.classList.add('animate-bounce');
                        setTimeout(() => cartLink.classList.remove('animate-bounce'), 500);
                    }
                } else {
                    showNotification(data.message || 'Failed to add to cart', 'error');
                }
            })
            .catch(error => {
                this.disabled = false;
                this.innerHTML = originalText;
                console.error('Error:', error);
                showNotification('Something went wrong', 'error');
            });
        });
    });
    
    // ============================================
    // QUANTITY INPUT
    // ============================================
    document.querySelectorAll('.quantity-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const input = this.parentElement.querySelector('.quantity-input');
            const action = this.dataset.action;
            let value = parseInt(input.value) || 1;
            
            if (action === 'increase') {
                value++;
            } else if (action === 'decrease' && value > 1) {
                value--;
            }
            
            input.value = value;
            
            // Trigger change event for price update
            input.dispatchEvent(new Event('change'));
        });
    });
    
    // ============================================
    // LICENSE TYPE SELECTOR
    // ============================================
    document.querySelectorAll('input[name="license_type"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            const priceElement = document.querySelector('.price-current');
            const originalPriceElement = document.querySelector('.price-original');
            
            if (priceElement && this.dataset.price) {
                const newPrice = parseFloat(this.dataset.price);
                const oldPrice = parseFloat(priceElement.dataset.price);
                
                // Animate price change
                animatePriceChange(priceElement, oldPrice, newPrice);
                
                // Update original price if exists
                if (originalPriceElement && this.dataset.originalPrice) {
                    originalPriceElement.textContent = formatPrice(this.dataset.originalPrice);
                }
                
                priceElement.dataset.price = newPrice;
            }
        });
    });
    
    // ============================================
    // PRODUCT IMAGE GALLERY
    // ============================================
    const mainImage = document.querySelector('.product-main-image');
    const thumbnails = document.querySelectorAll('.product-thumbnail');
    
    if (mainImage && thumbnails.length > 0) {
        thumbnails.forEach(function(thumb) {
            thumb.addEventListener('click', function() {
                const newSrc = this.dataset.src;
                mainImage.style.opacity = '0.5';
                
                setTimeout(function() {
                    mainImage.src = newSrc;
                    mainImage.style.opacity = '1';
                }, 200);
                
                thumbnails.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
            });
        });
    }
    
    // ============================================
    // COUPON CODE
    // ============================================
    const applyCouponBtn = document.getElementById('applyCoupon');
    if (applyCouponBtn) {
        applyCouponBtn.addEventListener('click', function() {
            const couponInput = document.getElementById('couponCode');
            const couponCode = couponInput.value.trim();
            
            if (!couponCode) {
                showNotification('Please enter a coupon code', 'warning');
                return;
            }
            
            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            
            fetch(BASE_URL + '/api/coupon.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=apply&code=' + encodeURIComponent(couponCode) + '&csrf_token=' + CSRF_TOKEN
            })
            .then(response => response.json())
            .then(data => {
                this.disabled = false;
                this.innerHTML = 'Apply';
                
                if (data.success) {
                    showNotification('Coupon applied! You saved ' + data.discount_formatted, 'success');
                    location.reload();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                this.disabled = false;
                this.innerHTML = 'Apply';
                showNotification('Something went wrong', 'error');
            });
        });
    }
    
    // ============================================
    // NEWSLETTER FORM
    // ============================================
    const newsletterForm = document.getElementById('newsletterForm');
    if (newsletterForm) {
        newsletterForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const form = this;
            const formData = new FormData(form);
            const submitBtn = form.querySelector('button[type="submit"]');
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            
            fetch(form.action, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
                
                if (data.success) {
                    showNotification(data.message, 'success');
                    form.reset();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
                showNotification('Something went wrong', 'error');
            });
        });
    }
    
    // ============================================
    // COPY TO CLIPBOARD
    // ============================================
    document.querySelectorAll('.copy-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const text = this.dataset.copy;
            
            navigator.clipboard.writeText(text).then(function() {
                showNotification('Copied to clipboard!', 'success');
            }).catch(function() {
                // Fallback for older browsers
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                showNotification('Copied to clipboard!', 'success');
            });
        });
    });
    
    // ============================================
    // TAB NAVIGATION
    // ============================================
    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(function(tab) {
        tab.addEventListener('shown.bs.tab', function(e) {
            // Trigger resize event for any charts or maps
            window.dispatchEvent(new Event('resize'));
        });
    });
    
    // ============================================
    // LAZY LOADING IMAGES
    // ============================================
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    if (img.dataset.src) {
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                    }
                    observer.unobserve(img);
                }
            });
        });
        
        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }
    
    // ============================================
    // PASSWORD TOGGLE
    // ============================================
    document.querySelectorAll('.password-toggle').forEach(function(toggle) {
        toggle.addEventListener('click', function() {
            const input = document.querySelector(this.dataset.target);
            const icon = this.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    });
    
    // ============================================
    // FORM VALIDATION
    // ============================================
    document.querySelectorAll('form[data-validate]').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            
            form.querySelectorAll('[required]').forEach(function(field) {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('is-invalid');
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                showNotification('Please fill in all required fields', 'warning');
            }
        });
    });
    
    // ============================================
    // SMOOTH SCROLL FOR ANCHOR LINKS
    // ============================================
    document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
        anchor.addEventListener('click', function(e) {
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
    
});

// ============================================
// UTILITY FUNCTIONS
// ============================================

/**
 * Show notification toast
 */
function showNotification(message, type = 'info') {
    const container = document.querySelector('.flash-messages-container') || document.body;
    
    const alert = document.createElement('div');
    alert.className = 'alert alert-' + type + ' alert-dismissible fade show';
    alert.innerHTML = `
        <i class="fas fa-${getIconForType(type)} me-2"></i>${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    container.appendChild(alert);
    
    // Auto dismiss
    setTimeout(function() {
        const bsAlert = new bootstrap.Alert(alert);
        bsAlert.close();
    }, 5000);
}

/**
 * Get icon class for notification type
 */
function getIconForType(type) {
    const icons = {
        success: 'check-circle',
        error: 'exclamation-circle',
        warning: 'exclamation-triangle',
        info: 'info-circle'
    };
    return icons[type] || 'info-circle';
}

/**
 * Update cart count badge
 */
function updateCartCount(count) {
    const badge = document.querySelector('.cart-badge');
    if (badge) {
        badge.textContent = count;
        badge.style.display = count > 0 ? 'flex' : 'none';
    } else if (count > 0) {
        const cartLink = document.querySelector('.cart-link');
        if (cartLink) {
            const newBadge = document.createElement('span');
            newBadge.className = 'cart-badge';
            newBadge.textContent = count;
            cartLink.appendChild(newBadge);
        }
    }
}

/**
 * Format price with currency
 */
function formatPrice(price) {
    const symbol = typeof CURRENCY_SYMBOL !== 'undefined' ? CURRENCY_SYMBOL : '$';
    const position = typeof CURRENCY_POSITION !== 'undefined' ? CURRENCY_POSITION : 'before';
    
    const formatted = parseFloat(price).toFixed(2);
    
    if (position === 'after') {
        return formatted + ' ' + symbol;
    }
    return symbol + formatted;
}

/**
 * Animate price change
 */
function animatePriceChange(element, from, to) {
    const duration = 300;
    const start = performance.now();
    
    function update(currentTime) {
        const elapsed = currentTime - start;
        const progress = Math.min(elapsed / duration, 1);
        
        // Easing function
        const easeOutQuart = 1 - Math.pow(1 - progress, 4);
        
        const current = from + (to - from) * easeOutQuart;
        element.textContent = formatPrice(current);
        
        if (progress < 1) {
            requestAnimationFrame(update);
        }
    }
    
    requestAnimationFrame(update);
}

/**
 * Debounce function
 */
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * Throttle function
 */
function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

/**
 * AJAX helper
 */
function ajax(url, options = {}) {
    const defaults = {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    };
    
    const settings = Object.assign({}, defaults, options);
    
    return fetch(url, settings)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        });
}
