How to implement proper cart logic?

The cart behaves incorrectly: When adding a product for the first time, only its quantity is displayed, the image and ID are not transmitted, I tried to find out the value of the ID that is transmitted when adding the first product via console.log and it returned null, but if I add another product to the cart it is displayed correctly. PRODUCT.HTML:

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', () => {
      // Получение данных о продукте
      const urlParams = new URLSearchParams(window.location.search);
      const productId = urlParams.get('id');

      if (productId) {
        fetch(`/product/${productId}`)
          .then(response => response.json())
          .then(product => {
            const buttonsContainer = document.getElementById('buttonsContainer');

            document.getElementById('product-name').textContent = product.name;
            document.getElementById('price').textContent = `Цена: ${product.price}`;
            document.getElementById('short-sub').textContent = product.short_description;
            document.getElementById('productDescription').textContent = product.description;
            document.getElementById('article').textContent = `Артикул: ${product.article}`;
            document.getElementById('volume').textContent = `Объем: ${product.volume}`;
            document.getElementById('points').textContent = `Баллы: ${product.points}`;
            document.getElementById('productImage1').src = `images/${product.image_2_url}`;
            // Дополнительно можете добавить код для изображения и других данных

            buttonsContainer.innerHTML = `
                <a href="order.html"><button class="buy-button"><b>КУПИТЬ</b></button></a>
                <button class="cart-button" data-product-id="${product.id}" data-image-url="${product.image_url}"><b>В КОРЗИНУ</b></button>
              `;
            
            // Добавление товаров в корзину
            const addToCartButtons = document.querySelectorAll('.cart-button');

            addToCartButtons.forEach(button => {
              button.addEventListener('click', (event) => {
                const imageUrl = event.target.getAttribute('data-image-url');
                addToCart(productId, imageUrl);
              });
            });
          })
          .catch(error => {
            console.error('Error fetching product data:', error);
          });
      }
    

    function addToCart(productId, imageUrl) {
  let cart = JSON.parse(localStorage.getItem('cart')) || [];
  let productExists = false;

  cart.forEach(item => {
    if (item.id === productId) {
      item.quantity += 1;
      productExists = true;
    }
  });

  if (!productExists) {
    cart.push({ id: productId, quantity: 1, image: imageUrl });
  }

  localStorage.setItem('cart', JSON.stringify(cart));

  alert('Товар добавлен в корзину');
}

    });
</script>

CART.HTML:

<script type="text/javascript">
            document.addEventListener('DOMContentLoaded', () => {
  displayCart();
});

function displayCart() {
  const cart = JSON.parse(localStorage.getItem('cart')) || [];
  console.log('Loaded cart:', cart); // Добавлено логирование

  const cartContainer = document.getElementById('cart-container');

  cart.forEach(item => {
    const productElement = document.createElement('div');
    productElement.className = 'product';
    productElement.innerHTML = `<div class="q"><b><p>${item.quantity}</p></b></div><img src="${item.image || 'images/default.png'}">`; // Указано изображение по умолчанию
    cartContainer.appendChild(productElement);
  });
}

        </script>

Here is the logic that should be instead: I add product 1 to the cart, which was empty, then in the cart I see this product with quantity 1, when I add this product again, the quantity increases, then I add product 2 to the cart where there is already product 1 , I go to the cart and see product 1 and product 2 with different quantity values ​​and so on.