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

  const addToCartBtn = document.querySelector('[data-shopify-add-to-cart]');

  if (!addToCartBtn) {
    return;
  }

  const buttonTextDiv = addToCartBtn.querySelector('.txt[data-button-text]');

  if (!buttonTextDiv) {
    console.error('Button text div not found');
    return;
  }

  const texts = {
    add: addToCartBtn.dataset.textAdd || 'Add to cart',
    adding: addToCartBtn.dataset.textAdding || 'Adding...',
    added: addToCartBtn.dataset.textAdded || 'Added! ✓',
    error: addToCartBtn.dataset.textError || 'Error - Try again'
  };

  addToCartBtn.addEventListener('click', async function(e) {
    e.preventDefault();

    const variantId = this.dataset.variantId;

    if (!variantId) {
      console.error('No variant ID found');
      return;
    }

    addToCartBtn.disabled = true;
    const originalText = buttonTextDiv.textContent;
    buttonTextDiv.textContent = texts.adding;

    try {
      const cartResult = await cart.addToCart(variantId, 1);

      buttonTextDiv.textContent = texts.added;
      addToCartBtn.classList.add('success');

      document.dispatchEvent(new CustomEvent('cart:updated', {
        detail: { cart: cartResult }
      }));

      setTimeout(() => {
        addToCartBtn.disabled = false;
        buttonTextDiv.textContent = originalText;
        addToCartBtn.classList.remove('success');
      }, 1500);

    } catch (error) {
      console.error('Error adding to cart:', error);

      buttonTextDiv.textContent = texts.error;
      addToCartBtn.classList.add('error');

      setTimeout(() => {
        addToCartBtn.disabled = false;
        buttonTextDiv.textContent = originalText;
        addToCartBtn.classList.remove('error');
      }, 2000);
    }
  });
})();
