// Global variables
let loadingOverlay, toastContainer;
let currentQuantities = {};

// Initialize when DOM loads
document.addEventListener('DOMContentLoaded', function() {
    loadingOverlay = document.getElementById('loadingOverlay');
    toastContainer = document.getElementById('toastContainer');
    
    // Initialize quantities from localStorage
    loadQuantities();
    
    // Navbar scroll effect
    window.addEventListener('scroll', function() {
        const navbar = document.querySelector('.navbar');
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    });
    
    // Category filtering
    document.querySelectorAll('.category-card, [data-category]').forEach(el => {
        el.addEventListener('click', function(e) {
            e.stopPropagation();
            const categoryId = this.getAttribute('data-category');
            if (categoryId) {
                filterByCategory(categoryId);
            }
        });
    });
    
    // Initialize floating cart count
    initializeFloatingCart();
    
    // Update cart count
    updateCartCount();
});

// Initialize floating cart
function initializeFloatingCart() {
    const floatingCount = document.getElementById('floatingCartCount');
    const mainCount = document.getElementById('cartCount');
    
    if (floatingCount && mainCount) {
        floatingCount.textContent = mainCount.textContent;
        if (mainCount.textContent === '0' || mainCount.textContent === '') {
            floatingCount.style.display = 'none';
        } else {
            floatingCount.style.display = 'flex';
        }
    }
}

// Load quantities from localStorage
function loadQuantities() {
    const saved = localStorage.getItem('cartQuantities');
    if (saved) {
        currentQuantities = JSON.parse(saved);
        // Update UI for each product
        Object.keys(currentQuantities).forEach(id => {
            const qtyControl = document.getElementById(`qty-control-${id}`);
            const qtyValue = document.getElementById(`qty-value-${id}`);
            const addBtn = document.getElementById(`add-btn-${id}`);
            
            if (qtyControl && currentQuantities[id] > 0) {
                qtyControl.style.display = 'flex';
                if (addBtn) addBtn.style.display = 'none';
                if (qtyValue) qtyValue.textContent = currentQuantities[id];
            }
        });
    }
}

// Save quantities to localStorage
function saveQuantities() {
    localStorage.setItem('cartQuantities', JSON.stringify(currentQuantities));
}

// Update cart quantity UI
function updateCartQuantityUI(productId, quantity) {
    const qtyControl = document.getElementById(`qty-control-${productId}`);
    const qtyValue = document.getElementById(`qty-value-${productId}`);
    const addBtn = document.getElementById(`add-btn-${productId}`);
    
    if (quantity > 0) {
        if (qtyControl) qtyControl.style.display = 'flex';
        if (addBtn) addBtn.style.display = 'none';
        if (qtyValue) qtyValue.textContent = quantity;
    } else {
        if (qtyControl) qtyControl.style.display = 'none';
        if (addBtn) addBtn.style.display = 'flex';
        delete currentQuantities[productId];
    }
    
    currentQuantities[productId] = quantity;
    saveQuantities();
}

// Add to cart with quantity control
function addToCartWithQuantity(productId) {
    const currentQty = currentQuantities[productId] || 0;
    const newQty = currentQty + 1;
    updateCartQuantityUI(productId, newQty);
    addToCart(productId, 1);
}

// Update cart quantity (for +/- buttons)
function updateCartQuantity(productId, change) {
    const currentQty = currentQuantities[productId] || 0;
    const newQty = currentQty + change;
    
    if (newQty < 0) return;
    
    if (newQty === 0) {
        // Remove from cart
        updateCartQuantityUI(productId, 0);
        // Make API call to remove
        showLoading();
        fetch(`api/remove_from_cart_by_equipment.php?equipment_id=${productId}`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            hideLoading();
            if (data.success) {
                updateCartCount();
                syncFloatingCartCount();
                showToast('Item removed from cart', 'success');
            }
        })
        .catch(error => {
            hideLoading();
            console.error('Error:', error);
        });
    } else {
        updateCartQuantityUI(productId, newQty);
        addToCart(productId, change);
    }
}

// Sync floating cart count with main count
function syncFloatingCartCount() {
    const floatingCount = document.getElementById('floatingCartCount');
    const mainCount = document.getElementById('cartCount');
    
    if (floatingCount && mainCount) {
        const newCount = mainCount.textContent;
        const oldCount = floatingCount.textContent;
        
        floatingCount.textContent = newCount;
        
        // Add bounce animation if count changed
        if (newCount !== oldCount && newCount !== '0') {
            floatingCount.style.animation = 'none';
            setTimeout(() => {
                floatingCount.style.animation = 'bounceIn 0.5s ease';
            }, 10);
        }
        
        // Show/hide based on count
        if (newCount === '0' || newCount === '') {
            floatingCount.style.display = 'none';
        } else {
            floatingCount.style.display = 'flex';
        }
    }
}

// Update floating cart count immediately
function updateFloatingCartCount() {
    const floatingCount = document.getElementById('floatingCartCount');
    const mainCount = document.getElementById('cartCount');
    
    if (floatingCount && mainCount) {
        const newCount = mainCount.textContent;
        const oldCount = floatingCount.textContent;
        
        floatingCount.textContent = newCount;
        
        // Add bounce animation if count changed and not zero
        if (newCount !== oldCount && newCount !== '0') {
            floatingCount.style.animation = 'none';
            setTimeout(() => {
                floatingCount.style.animation = 'bounceIn 0.5s ease';
            }, 10);
        }
        
        // Show/hide based on count
        if (newCount === '0' || newCount === '') {
            floatingCount.style.display = 'none';
        } else {
            floatingCount.style.display = 'flex';
        }
    }
}

// Animate floating cart
function animateFloatingCart() {
    const floatingCart = document.getElementById('floatingCartMobile');
    if (floatingCart) {
        floatingCart.classList.add('pulse');
        setTimeout(() => {
            floatingCart.classList.remove('pulse');
        }, 500);
    }
}

// Animate cart icon on mobile
function animateCartIcon() {
    const cartWrapper = document.querySelector('.cart-icon-wrapper');
    if (cartWrapper) {
        cartWrapper.classList.add('pulse');
        setTimeout(() => {
            cartWrapper.classList.remove('pulse');
        }, 500);
    }
}

// Add to cart
function addToCart(equipmentId, quantity = 1) {
    showLoading();
    
    fetch('api/add_to_cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `equipment_id=${equipmentId}&quantity=${quantity}`
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            showToast(data.message || 'Item added to cart successfully!', 'success');
            
            // Update both cart counts immediately
            const cartCountElement = document.getElementById('cartCount');
            
            if (cartCountElement) {
                const currentCount = parseInt(cartCountElement.textContent) || 0;
                const newCount = currentCount + quantity;
                cartCountElement.textContent = newCount;
                
                if (newCount === 0) {
                    cartCountElement.style.display = 'none';
                } else {
                    cartCountElement.style.display = 'inline-flex';
                }
                
                // Animate main cart count
                cartCountElement.style.animation = 'none';
                setTimeout(() => {
                    cartCountElement.style.animation = 'bounceIn 0.5s ease';
                }, 10);
            }
            
            // Update floating cart count immediately
            const floatingCount = document.getElementById('floatingCartCount');
            if (floatingCount) {
                const currentFloatingCount = parseInt(floatingCount.textContent) || 0;
                const newFloatingCount = currentFloatingCount + quantity;
                floatingCount.textContent = newFloatingCount;
                
                if (newFloatingCount === 0) {
                    floatingCount.style.display = 'none';
                } else {
                    floatingCount.style.display = 'flex';
                }
                
                // Animate floating cart count
                floatingCount.style.animation = 'none';
                setTimeout(() => {
                    floatingCount.style.animation = 'bounceIn 0.5s ease';
                }, 10);
            }
            
            // Animate floating cart button
            animateFloatingCart();
            
            // Animate desktop cart icon
            const cartIcon = document.querySelector('.cart-icon');
            if (cartIcon) {
                cartIcon.style.transform = 'scale(1.2)';
                setTimeout(() => {
                    cartIcon.style.transform = 'scale(1)';
                }, 300);
            }
        } else {
            showToast(data.message || 'Error adding item to cart', 'error');
            // Revert UI if error
            if (quantity === 1) {
                const currentQty = currentQuantities[equipmentId] || 0;
                updateCartQuantityUI(equipmentId, currentQty - 1);
            }
        }
    })
    .catch(error => {
        hideLoading();
        console.error('Error:', error);
        showToast('Network error. Please try again.', 'error');
    });
}

// Show product modal
function showProductModal(productId) {
    const modal = new bootstrap.Modal(document.getElementById('productModal'));
    const modalBody = document.getElementById('modalBody');
    
    modalBody.innerHTML = '<div class="text-center"><div class="spinner-border text-primary"></div><p class="mt-2">Loading product details...</p></div>';
    modal.show();
    
    fetch(`api/get_equipment_details.php?id=${productId}`)
        .then(response => response.json())
        .then(product => {
            if (product.error) {
                modalBody.innerHTML = `<div class="alert alert-danger">${product.error}</div>`;
                return;
            }
            
            const currentQty = currentQuantities[product.id] || 0;
            const imageUrl = product.image_url;
            const hasImage = imageUrl && imageUrl !== '' && imageUrl !== null;
            
            let imageHtml = '';
            if (hasImage) {
                imageHtml = `
                    <img src="${imageUrl}" 
                         alt="${escapeHtml(product.name)}" 
                         style="max-width: 100%; max-height: 250px; border-radius: 10px; object-fit: contain;"
                         onerror="this.onerror=null; this.style.display='none'; this.parentElement.querySelector('.fallback-icon').style.display='flex';">
                    <div class="fallback-icon" style="display: none; flex-direction: column; align-items: center; justify-content: center;">
                        <i class="fas fa-cogs" style="font-size: 3rem; color: white;"></i>
                        <p style="color: white; font-size: 0.8rem; margin-top: 5px;">Image not available</p>
                    </div>
                `;
            } else {
                imageHtml = `
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
                        <i class="fas fa-cogs" style="font-size: 3rem; color: white;"></i>
                        <p style="color: white; font-size: 0.8rem; margin-top: 5px;">No image available</p>
                    </div>
                `;
            }
            
            modalBody.innerHTML = `
                <div class="modal-product-image" style="text-align: center; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; margin-bottom: 1.5rem; min-height: 200px; display: flex; align-items: center; justify-content: center;">
                    ${imageHtml}
                </div>
                
                <div class="text-center">
                    <h3 class="mb-2" style="font-weight: 700;">${escapeHtml(product.name)}</h3>
                    <div class="mb-3">
                        <span class="badge" style="background: var(--secondary, #ff6b35); font-size: 0.85rem; padding: 5px 12px;">
                            ${escapeHtml(product.category_name)}
                        </span>
                    </div>
                    
                    <div class="mb-3">
                        <p class="text-muted" style="line-height: 1.6;">${escapeHtml(product.description)}</p>
                    </div>
                    
                    <div class="mb-3">
                        <h2 style="color: var(--secondary, #ff6b35); font-weight: 800; font-size: 2rem;">
                            $${parseFloat(product.price).toLocaleString()}
                            <small style="font-size: 0.8rem; color: #64748b;">/ unit</small>
                        </h2>
                    </div>
                    
                    <div class="mb-3">
                        ${product.stock_quantity > 0 ? 
                            `<span class="text-success" style="background: #d1fae5; padding: 4px 12px; border-radius: 20px; font-size: 0.85rem;">
                                <i class="fas fa-check-circle"></i> In Stock (${product.stock_quantity} available)
                            </span>` : 
                            `<span class="text-danger" style="background: #fee2e2; padding: 4px 12px; border-radius: 20px; font-size: 0.85rem;">
                                <i class="fas fa-times-circle"></i> Out of Stock
                            </span>`
                        }
                    </div>
                    
                    <div class="modal-quantity-control" style="${currentQty > 0 ? 'display: flex; align-items: center; justify-content: center; gap: 1rem; margin: 1rem 0;' : 'display: none;'}" id="modal-qty-control">
                        <button class="qty-btn" style="width: 40px; height: 40px; border-radius: 10px; font-size: 1.2rem;" onclick="updateCartQuantityFromModal(${product.id}, -1)">-</button>
                        <span class="qty-value" id="modal-qty-value" style="font-size: 1.2rem; font-weight: 600; min-width: 50px;">${currentQty}</span>
                        <button class="qty-btn" style="width: 40px; height: 40px; border-radius: 10px; font-size: 1.2rem;" onclick="updateCartQuantityFromModal(${product.id}, 1)">+</button>
                    </div>
                    
                    <button class="btn-add-cart" id="modal-add-btn" onclick="addToCartFromModal(${product.id})" style="${currentQty > 0 ? 'display: none;' : 'display: block; width: 100%; max-width: 200px; margin: 0 auto; background: linear-gradient(135deg, #ff6b35, #ff8c42);'}">
                        <i class="fas fa-shopping-cart"></i> Add to Cart
                    </button>
                </div>
            `;
        })
        .catch(error => {
            console.error('Error:', error);
            modalBody.innerHTML = `<div class="alert alert-danger">Error loading product details. Please try again.</div>`;
        });
}

function updateCartQuantityFromModal(productId, change) {
    updateCartQuantity(productId, change);
    updateModalQuantityDisplay(productId);
}

function updateModalQuantityDisplay(productId) {
    const modalQtyValue = document.getElementById('modal-qty-value');
    const modalQtyControl = document.getElementById('modal-qty-control');
    const modalAddBtn = document.getElementById('modal-add-btn');
    
    const currentQty = currentQuantities[productId] || 0;
    
    if (modalQtyValue) {
        modalQtyValue.textContent = currentQty;
    }
    
    if (modalQtyControl && modalAddBtn) {
        if (currentQty > 0) {
            modalQtyControl.style.display = 'flex';
            modalAddBtn.style.display = 'none';
        } else {
            modalQtyControl.style.display = 'none';
            modalAddBtn.style.display = 'block';
        }
    }
}

function addToCartFromModal(productId) {
    addToCartWithQuantity(productId);
    setTimeout(() => {
        updateModalQuantityDisplay(productId);
    }, 100);
}

function updateModalQuantity(productId, newQty) {
    const modalQtyControl = document.getElementById('modal-qty-control');
    const modalAddBtn = document.getElementById('modal-add-btn');
    const modalQtyValue = document.getElementById('modal-qty-value');
    
    if (newQty > 0) {
        if (modalQtyControl) modalQtyControl.style.display = 'flex';
        if (modalAddBtn) modalAddBtn.style.display = 'none';
        if (modalQtyValue) modalQtyValue.textContent = newQty;
    } else {
        if (modalQtyControl) modalQtyControl.style.display = 'none';
        if (modalAddBtn) modalAddBtn.style.display = 'block';
    }
}

function addToCartWithQuantityModal(productId) {
    addToCartWithQuantity(productId);
    updateModalQuantity(productId, 1);
    const modal = bootstrap.Modal.getInstance(document.getElementById('productModal'));
    if (modal) {
        setTimeout(() => modal.hide(), 500);
    }
}

// Update cart count
function updateCartCount() {
    fetch('api/get_cart_count.php')
        .then(response => response.json())
        .then(data => {
            const cartCountElement = document.getElementById('cartCount');
            const floatingCountElement = document.getElementById('floatingCartCount');
            
            if (cartCountElement && data.count !== undefined) {
                const oldCount = parseInt(cartCountElement.textContent) || 0;
                cartCountElement.textContent = data.count;
                
                if (data.count === 0) {
                    cartCountElement.style.display = 'none';
                } else {
                    cartCountElement.style.display = 'inline-flex';
                    if (data.count > oldCount) {
                        cartCountElement.style.animation = 'none';
                        setTimeout(() => {
                            cartCountElement.style.animation = 'bounceIn 0.5s ease';
                        }, 10);
                    }
                }
            }
            
            // Update floating cart count
            if (floatingCountElement && data.count !== undefined) {
                floatingCountElement.textContent = data.count;
                if (data.count === 0) {
                    floatingCountElement.style.display = 'none';
                } else {
                    floatingCountElement.style.display = 'flex';
                }
            }
        })
        .catch(error => console.error('Error:', error));
}

// Filter by category
function filterByCategory(categoryId) {
    showLoading();
    
    fetch(`api/get_equipment.php?category_id=${categoryId}`)
        .then(response => response.json())
        .then(data => {
            hideLoading();
            displayProducts(data);
            
            const featuredSection = document.getElementById('featured');
            if (featuredSection) {
                featuredSection.scrollIntoView({ 
                    behavior: 'smooth' 
                });
            }
        })
        .catch(error => {
            hideLoading();
            console.error('Error:', error);
            showToast('Error loading products', 'error');
        });
}

// Load all products
function loadAllProducts() {
    showLoading();
    
    fetch('api/get_equipment.php')
        .then(response => response.json())
        .then(data => {
            hideLoading();
            displayProducts(data);
        })
        .catch(error => {
            hideLoading();
            console.error('Error:', error);
            showToast('Error loading products', 'error');
        });
}

// Display products
function displayProducts(products) {
    const productsGrid = document.getElementById('featuredGrid');
    if (!productsGrid) return;
    
    if (!products || products.length === 0) {
        productsGrid.innerHTML = `
            <div class="text-center" style="grid-column: 1/-1; padding: 3rem;">
                <i class="fas fa-box-open" style="font-size: 4rem; color: var(--text-gray); margin-bottom: 1rem;"></i>
                <h3>No products found</h3>
                <p>Try selecting a different category</p>
            </div>
        `;
        return;
    }
    
    productsGrid.innerHTML = products.map(product => {
        const currentQty = currentQuantities[product.id] || 0;
        const hasImage = product.image_url && product.image_url !== '' && product.image_url !== null;
        const displayStyle = currentQty > 0 ? 'flex' : 'none';
        const buttonStyle = currentQty > 0 ? 'none' : 'block';
        
        let imgSrc = '';
        if (hasImage) {
            imgSrc = product.image_url;
            if (!imgSrc.startsWith('/') && !imgSrc.startsWith('http')) {
                imgSrc = '/' + imgSrc;
            }
            imgSrc = imgSrc.replace(/\/\//g, '/');
        }
        
        return `
            <div class="product-card">
                <div class="product-badge">${escapeHtml(product.category_name)}</div>
                <div class="product-image">
                    ${hasImage ? 
                        `<img src="${imgSrc}" alt="${escapeHtml(product.name)}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.onerror=null; this.style.display='none'; this.parentElement.querySelector('.fallback-icon').style.display='flex';">` : 
                        `<i class="fas fa-cogs"></i>`
                    }
                    ${hasImage ? `<div class="fallback-icon" style="display: none; width: 100%; height: 100%; align-items: center; justify-content: center;"><i class="fas fa-cogs" style="font-size: 3rem;"></i></div>` : ''}
                    <div class="product-actions">
                        <button class="action-btn quick-view" onclick="showProductModal(${product.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                <div class="product-info">
                    <h3>${escapeHtml(product.name)}</h3>
                    <p>${escapeHtml(product.description ? product.description.substring(0, 60) : '')}...</p>
                    <div class="product-price">
                        $${parseFloat(product.price).toLocaleString()}
                        <small>/ unit</small>
                    </div>
                    <div class="product-quantity-control" id="qty-control-${product.id}" style="display: ${displayStyle};">
                        <button class="qty-btn qty-minus" onclick="updateCartQuantity(${product.id}, -1)">-</button>
                        <span class="qty-value" id="qty-value-${product.id}">${currentQty}</span>
                        <button class="qty-btn qty-plus" onclick="updateCartQuantity(${product.id}, 1)">+</button>
                    </div>
                    <button class="btn-add-cart" id="add-btn-${product.id}" onclick="addToCartWithQuantity(${product.id})" style="display: ${buttonStyle};" ${product.stock_quantity < 1 ? 'disabled' : ''}>
                        <i class="fas fa-shopping-cart"></i> ${product.stock_quantity > 0 ? 'Add to Cart' : 'Out of Stock'}
                    </button>
                </div>
            </div>
        `;
    }).join('');
}

// Cart page functions
function updateQuantity(cartItemId, change) {
    showLoading();
    
    fetch('api/update_cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `cart_item_id=${cartItemId}&change=${change}`
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            location.reload();
        } else {
            showToast('Error updating quantity', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('Error:', error);
        showToast('Network error', 'error');
    });
}

function removeFromCart(cartItemId) {
    if (!confirm('Are you sure you want to remove this item?')) return;
    
    showLoading();
    
    fetch('api/remove_from_cart.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `cart_item_id=${cartItemId}`
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.success) {
            location.reload();
        } else {
            showToast('Error removing item', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        console.error('Error:', error);
        showToast('Network error', 'error');
    });
}

// Show/hide loading
function showLoading() {
    if (loadingOverlay) loadingOverlay.classList.add('active');
}

function hideLoading() {
    if (loadingOverlay) loadingOverlay.classList.remove('active');
}

// Show toast notification
function showToast(message, type = 'success') {
    if (!toastContainer) return;
    
    const toast = document.createElement('div');
    toast.className = `toast-custom ${type}`;
    toast.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
        <span>${escapeHtml(message)}</span>
    `;
    
    toastContainer.appendChild(toast);
    
    setTimeout(() => toast.classList.add('show'), 100);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Escape HTML
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}