document.addEventListener('DOMContentLoaded', function() {
    setTimeout(updateCartCountOnLoad, 100);
});

function updateCartCountOnLoad() {
    var cartCount = document.querySelector('.cart-count');
    if (!cartCount) {
        return; 
    }
    
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/php/cart_handler.php?action=get_details', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data.success) {
                    if (data.cartDetails && data.cartDetails.length > 0) {
                        var total = 0;
                        for (var i = 0; i < data.cartDetails.length; i++) {
                            total += data.cartDetails[i].quantity;
                        }
                        cartCount.textContent = total;
                        cartCount.style.display = 'inline';
                    } else {
                        cartCount.style.display = 'none';
                    }
                }
            } catch (e) {
                console.log('Error parsing response');
            }
        }
    };
    xhr.send();
}
