// ==========================================
// Cart Logic (LocalStorage functionality)
// ==========================================

const CART_KEY = 'gp_crackers_cart';

// 1. Get the cart from LocalStorage
function getCart() {
    return JSON.parse(localStorage.getItem(CART_KEY)) || [];
}

// 2. Save the cart to LocalStorage
function saveCart(cart) {
    localStorage.setItem(CART_KEY, JSON.stringify(cart));
    updateCartIcon();
    // Re-render cart page if on it
    if (typeof renderCartPage === 'function') {
        renderCartPage();
    }
}

// 3. Add Item to Cart
function addToCart(productId, name, price, imageSrc) {
    const priceNum = typeof price === 'string' ? parseFloat(price.replace(/[^0-9.-]+/g,"")) : price;

    // Sync with DB FIRST
    $.post('api/cart.php', {
        action: 'add',
        id: productId,
        name: name,
        price: priceNum,
        image: imageSrc,
        quantity: 1
    }).done(function(res) {
        if (res.status === 'unauthorized') {
            window.location.href = 'login.html';
            return;
        }
        
        if (res.status === 'success') {
            // ONLY update LocalStorage if server says OK
            let cart = getCart();
            const existingIndex = cart.findIndex(item => item.id === productId);

            if (existingIndex > -1) {
                cart[existingIndex].quantity += 1;
            } else {
                cart.push({
                    id: productId,
                    name: name,
                    price: priceNum, 
                    image: imageSrc,
                    quantity: 1
                });
            }

            saveCart(cart);
            showToast(`${name} added to cart!`);
        } else {
            console.error('DB Sync Error:', res.message);
        }
    }).fail(function(err) {
        console.error('AJAX Error:', err);
    });
}

// 4. Remove Item from Cart
function removeFromCart(id) {
    const confirmModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    const confirmBtn = document.getElementById('confirmDeleteBtn');
    
    // Show modal
    confirmModal.show();
    
    // Handle confirmation click
    confirmBtn.onclick = () => {
        executeRemove(id);
        confirmModal.hide();
    };
}

// 4.1 Internal helper to actually remove after confirmation
function executeRemove(id) {
    // Sync with DB FIRST
    $.post('api/cart.php', {
        action: 'remove',
        id: id
    }).done(function(res) {
        if (res.status === 'unauthorized') {
            window.location.href = 'login.html';
            return;
        }

        if (res.status === 'success') {
            let cart = getCart();
            cart = cart.filter(item => item.id !== id);
            saveCart(cart);
        } else {
            console.error('DB Sync Error:', res.message);
        }
    }).fail(function(err) {
        console.error('AJAX Error:', err);
    });
}

// 5. Update Item Quantity
function updateQuantity(id, newQuantity) {
    if (newQuantity < 1) {
        removeFromCart(id);
        return;
    }

    // Sync with DB FIRST
    $.post('api/cart.php', {
        action: 'update',
        id: id,
        quantity: newQuantity
    }).done(function(res) {
        if (res.status === 'unauthorized') {
            window.location.href = 'login.html';
            return;
        }

        if (res.status === 'success') {
            let cart = getCart();
            const itemIndex = cart.findIndex(item => item.id === id);
            if (itemIndex > -1) {
                cart[itemIndex].quantity = parseInt(newQuantity);
                saveCart(cart);
            }
        } else {
            console.error('DB Sync Error:', res.message);
        }
    }).fail(function(err) {
        console.error('AJAX Error:', err);
    });
}

// 6. Calculate total price
function getCartTotal() {
    const cart = getCart();
    return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
}

// 7. Calculate total number of items
function getCartItemCount() {
    const cart = getCart();
    return cart.reduce((total, item) => total + item.quantity, 0);
}

// 8. Update Navbar Cart Icon Badge
function updateCartIcon() {
    const count = getCartItemCount();
    const badge = document.getElementById('cart-item-count');
    
    if (badge) {
        if (count > 0) {
            badge.style.display = 'inline-block';
            badge.textContent = count;
        } else {
            badge.style.display = 'none';
            badge.textContent = '0';
        }
    }
}

// 9. Show a temporary toast notification when adding items
function showToast(message) {
    // Check if toast container exists, if not create it
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        `;
        document.body.appendChild(toastContainer);
    }

    const toast = document.createElement('div');
    toast.className = 'toast show align-items-center text-white bg-success border-0 mb-2';
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    toast.style.minWidth = '250px';
    
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body fw-bold">
                <i class="bi bi-check-circle-fill me-2"></i> ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.parentElement.parentElement.remove()"></button>
        </div>
    `;

    toastContainer.appendChild(toast);

    // Auto remove after 3 seconds
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Bind "Add to Cart" buttons dynamically on page load
document.addEventListener('DOMContentLoaded', () => {
    updateCartIcon(); // Initialize indicator

    // Initial sync from DB to LocalStorage
    $.post('api/cart.php', { action: 'fetch' })
    .done(function(res) {
        if (res.status === 'unauthorized') {
            // Clear LocalStorage if not logged in (to avoid ghost items)
            localStorage.removeItem(CART_KEY);
            updateCartIcon();

            // Silence redirect on page load, or only if on cart.html
            if (window.location.pathname.includes('cart.html')) {
                window.location.href = 'login.html';
            }
            return;
        }
        if (res.status === 'success' && res.data) {
            const dbCart = res.data;
            // Always update from DB (it's the source of truth)
            localStorage.setItem(CART_KEY, JSON.stringify(dbCart));
            updateCartIcon();
            // Re-render cart page if on it
            if (typeof renderCartPage === 'function') {
                renderCartPage();
            }
        }
    });

    const addToCartBtns = document.querySelectorAll('.btn-add-cart');
    
    addToCartBtns.forEach((btn) => {
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            
            // Find the closest product card or its container to get info
            const card = e.target.closest('.product-card');
            const container = e.target.closest('[data-product-id]');
            
            if (card && container) {
                const name = card.querySelector('.product-name').textContent;
                const priceText = card.querySelector('.product-price').textContent;
                const imgSource = card.querySelector('.product-img').getAttribute('src');
                const id = container.getAttribute('data-product-id'); 
                
                addToCart(id, name, priceText, imgSource);
            }
        });
    });
});
