// JS principal de AloeMarket

document.addEventListener("DOMContentLoaded", () => {
  const forms = document.querySelectorAll(".js-add-to-cart-form");
  const badge = document.getElementById("cart-count-badge");

  forms.forEach((form) => {
    form.addEventListener("submit", async (e) => {
      e.preventDefault(); // evita recargar la página

      const url = form.getAttribute("action");
      const formData = new FormData(form);

      try {
        const response = await fetch(url, {
          method: "POST",
          headers: {
            "X-Requested-With": "XMLHttpRequest",
          },
          body: formData,
        });

        if (!response.ok) {
          console.error("Error al agregar al carrito");
          return;
        }

        const data = await response.json();

        if (data.success) {
          // actualizar badge del navbar
          if (badge) {
            badge.textContent = data.cart_item_count;
            badge.classList.remove("d-none");
          }

          // pequeño feedback (puedes cambiar por toast de Bootstrap)
          console.log(data.message);
        } else {
          console.warn(data.error || "Error inesperado");
        }
      } catch (err) {
        console.error("Error en la petición AJAX:", err);
      }
    });
  });
});
