(async function() {
  const container = document.querySelector('[data-products-loader]');
  if (!container) return;

  const language = (container.dataset.language || 'FR').toLowerCase();
  const isEnglish = language === 'en';

  try {
    const cart = new ShopifyCart({
      domain: 'nv7cqv-bu.myshopify.com',
      storefrontAccessToken: 'dec3d35a2554384d149c72927d1cfd1b'
    });

    const productsData = await cart.getAllProducts();
    const products = productsData.edges;

    const productsHtml = products.map(edge => {
      const product = edge.node;
      const image = product.images.edges[0]?.node;
      const price = parseFloat(product.priceRange.minVariantPrice.amount).toFixed(2);
      const slug = product.handle;
      const productUrl = isEnglish ? `/en/${slug}` : `/${slug}`;
      const productTitle = isEnglish && product.titleEn?.value
        ? product.titleEn.value
        : product.title;

      return `
        <article class="store__product">
          <figure>
            ${image ? `<img src="${image.url}" alt="${image.altText || productTitle}" loading="lazy" />` : ''}
          </figure>
          <p class="line-1">
            <a href="${productUrl}">${productTitle}</a>
          </p>
          <p class="price">${price}€</p>
          <a href="${productUrl}" class="link-block" aria-hidden="true"></a>
        </article>
      `;
    }).join('');

    container.innerHTML = productsHtml;

  } catch (error) {
    console.error('Error loading products:', error);
    container.innerHTML = '<p>Erreur lors du chargement des produits</p>';
  }
})();
