{% comment %}
  Free Gifts Row - Compact display with individual quantity unlocks per product
  Usage: {% render 'free-gifts-row', block: block, product_form_id: product_form_id %}
{% endcomment %}

{% liquid
  assign max_gifts = block.settings.number_of_gifts | default: '3' | plus: 0
  assign products_count = 0
  if block.settings.gift_product_1 != blank and max_gifts >= 1
    assign products_count = products_count | plus: 1
  endif
  if block.settings.gift_product_2 != blank and max_gifts >= 2
    assign products_count = products_count | plus: 1
  endif
  if block.settings.gift_product_3 != blank and max_gifts >= 3
    assign products_count = products_count | plus: 1
  endif
  if block.settings.gift_product_4 != blank and max_gifts >= 4
    assign products_count = products_count | plus: 1
  endif
  assign is_row = block.settings.row_layout
%}

<style>
  .free-gifts-row-{{ block.id }} {
    margin-top: {{ block.settings.margin_top | divided_by: 10.0 }}rem;
    margin-bottom: {{ block.settings.margin_bottom | divided_by: 10.0 }}rem;
    padding: {{ block.settings.padding | divided_by: 10.0 }}rem;
    background: {{ block.settings.bg_color }};
    border-radius: {{ block.settings.corner_radius }}px;
  }

  .free-gifts-row__title {
    text-align: {{ block.settings.title_alignment }};
    font-size: {{ block.settings.title_size_mobile }}px;
    font-weight: {{ block.settings.title_font_weight }};
    color: {{ block.settings.title_color }};
    margin-bottom: 0.75rem;
  }

  @media screen and (min-width: 750px) {
    .free-gifts-row__title {
      font-size: {{ block.settings.title_size_desktop }}px;
    }
  }

  .free-gifts-row-{{ block.id }} .free-gifts-row__products {
    display: grid;
    grid-template-columns: repeat({{ block.settings.grid_columns | default: '2' }}, 1fr);
    gap: {{ block.settings.products_gap }}px;
  }

  .free-gifts-row-{{ block.id }} .free-gifts-row__product {
    border: {{ block.settings.product_border_width }}px solid {{ block.settings.product_border_color }};
    border-radius: {{ block.settings.product_corner_radius }}px;
    padding: {{ block.settings.product_padding }}px;
    transition: all 0.3s ease;
    position: relative;
    background: {{ block.settings.product_bg_color }};
    {% if is_row %}
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 10px;
    text-align: left;
    {% else %}
    text-align: center;
    {% endif %}
  }

  .free-gifts-row__product.locked {
    opacity: 0.6;
  }

  .free-gifts-row__product.unlocked {
    border-color: {{ block.settings.product_unlocked_border_color }};
    background: {{ block.settings.product_unlocked_bg_color }};
  }

  .free-gifts-row__product-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: {{ block.settings.locked_overlay_color }};
    border-radius: {{ block.settings.product_corner_radius }}px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(2px);
    z-index: 1;
  }

  .free-gifts-row__product.unlocked .free-gifts-row__product-overlay {
    display: none;
  }

  .free-gifts-row__lock-icon {
    font-size: 28px;
    color: {{ block.settings.lock_icon_color }};
    margin-bottom: 4px;
  }

  .free-gifts-row__unlock-text {
    font-size: 11px;
    color: {{ block.settings.lock_icon_color }};
    font-weight: 600;
    text-transform: uppercase;
  }

  .free-gifts-row__product-image {
    {% if is_row %}
    width: {{ block.settings.product_image_width | times: 0.8 }}px;
    min-width: {{ block.settings.product_image_width | times: 0.8 }}px;
    height: {{ block.settings.product_image_width | times: 0.8 }}px;
    {% else %}
    width: {{ block.settings.product_image_width }}%;
    {% endif %}
    aspect-ratio: 1;
    object-fit: cover;
    border-radius: {{ block.settings.image_corner_radius }}px;
    {% unless is_row %}
    margin-bottom: {{ block.settings.image_margin_bottom }}px;
    {% if block.settings.product_image_width < 100 %}
    margin-left: auto;
    margin-right: auto;
    {% endif %}
    {% endunless %}
  }

  /* Row layout: info column beside image */
  .free-gifts-row__product-info {
    {% if is_row %}
    display: flex;
    flex-direction: column;
    flex: 1;
    min-width: 0;
    {% endif %}
  }

  .free-gifts-row__product-title {
    font-size: {{ block.settings.product_title_size }}px;
    font-weight: {{ block.settings.product_title_weight }};
    color: {{ block.settings.product_title_color }};
    margin-top: {{ block.settings.product_title_margin_top }}px;
    margin-bottom: {{ block.settings.product_title_margin_bottom }}px;
    line-height: 1.2;
  }

  .free-gifts-row__product-price {
    font-size: {{ block.settings.product_price_size }}px;
    color: {{ block.settings.product_price_color }};
    text-decoration: line-through;
    margin-top: {{ block.settings.product_price_margin_top }}px;
    margin-bottom: {{ block.settings.product_price_margin_bottom }}px;
  }

  {% if block.settings.hide_price %}
  .free-gifts-row__product-price {
    display: none;
  }
  {% endif %}

  .free-gifts-row__product-free {
    font-size: {{ block.settings.free_text_size }}px;
    font-weight: 700;
    color: {{ block.settings.free_text_color }};
    margin-top: {{ block.settings.free_text_margin_top }}px;
    margin-bottom: {{ block.settings.free_text_margin_bottom }}px;
  }

  .free-gifts-row__product-custom-text {
    font-size: {{ block.settings.custom_text_size | default: 12 }}px;
    color: {{ block.settings.custom_text_color | default: '#666666' }};
    margin-top: {{ block.settings.custom_text_margin_top | default: 4 }}px;
    line-height: 1.3;
  }

  /* Price + FREE label in a row when card row layout is on */
  {% if is_row %}
  .free-gifts-row__product-price-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 6px;
    flex-wrap: wrap;
  }
  .free-gifts-row__product-price-row .free-gifts-row__product-price {
    margin-top: 0;
    margin-bottom: 0;
  }
  .free-gifts-row__product-price-row .free-gifts-row__product-free {
    margin-top: 0;
    margin-bottom: 0;
  }
  {% endif %}

  /* Placeholder card for empty gift slots */
  .free-gifts-row__placeholder {
    border: {{ block.settings.product_border_width }}px dashed {{ block.settings.product_border_color }};
    border-radius: {{ block.settings.product_corner_radius }}px;
    padding: {{ block.settings.product_padding }}px;
    background: {{ block.settings.product_bg_color }};
    opacity: 0.4;
    {% if is_row %}
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 10px;
    {% else %}
    text-align: center;
    {% endif %}
  }

  .free-gifts-row__placeholder-image {
    {% if is_row %}
    width: {{ block.settings.product_image_width | times: 0.8 }}px;
    min-width: {{ block.settings.product_image_width | times: 0.8 }}px;
    height: {{ block.settings.product_image_width | times: 0.8 }}px;
    {% else %}
    width: {{ block.settings.product_image_width }}%;
    margin-bottom: {{ block.settings.image_margin_bottom }}px;
    {% if block.settings.product_image_width < 100 %}
    margin-left: auto;
    margin-right: auto;
    {% endif %}
    {% endif %}
    aspect-ratio: 1;
    background: #e0e0e0;
    border-radius: {{ block.settings.image_corner_radius }}px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .free-gifts-row__placeholder-icon {
    font-size: 28px;
    color: #bbb;
  }

  .free-gifts-row__placeholder-title {
    font-size: {{ block.settings.product_title_size }}px;
    font-weight: {{ block.settings.product_title_weight }};
    color: {{ block.settings.product_title_color }};
    margin-top: {{ block.settings.product_title_margin_top }}px;
    margin-bottom: {{ block.settings.product_title_margin_bottom }}px;
    line-height: 1.2;
  }

  .free-gifts-row__placeholder-free {
    font-size: {{ block.settings.free_text_size }}px;
    font-weight: 700;
    color: {{ block.settings.free_text_color }};
    margin-top: {{ block.settings.free_text_margin_top }}px;
  }

   {% if block.settings.hide_block %}
  .free-gifts-row-{{ block.id }} {
      display: none!important;
  }
  {% endif %}
</style>

<div class="free-gifts-row free-gifts-row-{{ block.id }}" {{ block.shopify_attributes }} data-block-id="{{ block.id }}" data-unlock-type="{{ block.settings.unlock_type }}">
  {% if block.settings.title != blank %}
    <h3 class="free-gifts-row__title">{{ block.settings.title }}</h3>
  {% endif %}

  <div class="free-gifts-row__products">
    {%- comment -%} GIFT 1 {%- endcomment -%}
    {% if max_gifts >= 1 %}
      {% if block.settings.gift_product_1 != blank %}
        {% assign gift_1 = block.settings.gift_product_1 %}
        <div class="free-gifts-row__product locked"
             data-product-index="1"
             data-variant-id="{{ gift_1.selected_or_first_available_variant.id }}"
             data-unlock-qty="{{ block.settings.gift_1_quantity_to_unlock }}"
             data-add-qty="{{ block.settings.gift_1_quantity_to_add }}">
          {% if block.settings.gift_1_custom_image != blank %}
            <img src="{{ block.settings.gift_1_custom_image | image_url: width: 250 }}" alt="{{ block.settings.gift_1_custom_title | default: gift_1.title | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% elsif gift_1.featured_image %}
            <img src="{{ gift_1.featured_image | image_url: width: 250 }}" alt="{{ gift_1.featured_image.alt | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% endif %}
          <div class="free-gifts-row__product-info">
            <h4 class="free-gifts-row__product-title">
              {% if block.settings.gift_1_custom_title != blank %}{{ block.settings.gift_1_custom_title }}{% else %}{{ gift_1.title }}{% endif %}
            </h4>
            {% if is_row %}
            <div class="free-gifts-row__product-price-row">
              <p class="free-gifts-row__product-price">{{ gift_1.price | money }}</p>
              <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            </div>
            {% else %}
            <p class="free-gifts-row__product-price">{{ gift_1.price | money }}</p>
            <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            {% endif %}
            {% if block.settings.gift_1_custom_text != blank %}
              <p class="free-gifts-row__product-custom-text">{{ block.settings.gift_1_custom_text }}</p>
            {% endif %}
          </div>
          <div class="free-gifts-row__product-overlay">
            <span class="free-gifts-row__lock-icon material-symbols-outlined">lock</span>
            {% if block.settings.unlock_type == 'quantity' %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.gift_1_quantity_to_unlock }}{{ block.settings.quantity_unlock_suffix | default: "+ to unlock" }}</span>
            {% else %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.subscribe_unlock_text | default: "Subscribe to unlock" }}</span>
            {% endif %}
          </div>
        </div>
      {% else %}
        <div class="free-gifts-row__placeholder">
          <div class="free-gifts-row__placeholder-image">
            <span class="free-gifts-row__placeholder-icon material-symbols-outlined">cardgiftcard</span>
          </div>
          <div class="free-gifts-row__product-info">
            <p class="free-gifts-row__placeholder-title">Gift1</p>
            <p class="free-gifts-row__placeholder-free">{{ block.settings.free_text }}</p>
          </div>
        </div>
      {% endif %}
    {% endif %}

    {%- comment -%} GIFT 2 {%- endcomment -%}
    {% if max_gifts >= 2 %}
      {% if block.settings.gift_product_2 != blank %}
        {% assign gift_2 = block.settings.gift_product_2 %}
        <div class="free-gifts-row__product locked"
             data-product-index="2"
             data-variant-id="{{ gift_2.selected_or_first_available_variant.id }}"
             data-unlock-qty="{{ block.settings.gift_2_quantity_to_unlock }}"
             data-add-qty="{{ block.settings.gift_2_quantity_to_add }}">
          {% if block.settings.gift_2_custom_image != blank %}
            <img src="{{ block.settings.gift_2_custom_image | image_url: width: 250 }}" alt="{{ block.settings.gift_2_custom_title | default: gift_2.title | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% elsif gift_2.featured_image %}
            <img src="{{ gift_2.featured_image | image_url: width: 250 }}" alt="{{ gift_2.featured_image.alt | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% endif %}
          <div class="free-gifts-row__product-info">
            <h4 class="free-gifts-row__product-title">
              {% if block.settings.gift_2_custom_title != blank %}{{ block.settings.gift_2_custom_title }}{% else %}{{ gift_2.title }}{% endif %}
            </h4>
            {% if is_row %}
            <div class="free-gifts-row__product-price-row">
              <p class="free-gifts-row__product-price">{{ gift_2.price | money }}</p>
              <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            </div>
            {% else %}
            <p class="free-gifts-row__product-price">{{ gift_2.price | money }}</p>
            <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            {% endif %}
            {% if block.settings.gift_2_custom_text != blank %}
              <p class="free-gifts-row__product-custom-text">{{ block.settings.gift_2_custom_text }}</p>
            {% endif %}
          </div>
          <div class="free-gifts-row__product-overlay">
            <span class="free-gifts-row__lock-icon material-symbols-outlined">lock</span>
            {% if block.settings.unlock_type == 'quantity' %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.gift_2_quantity_to_unlock }}{{ block.settings.quantity_unlock_suffix | default: "+ to unlock" }}</span>
            {% else %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.subscribe_unlock_text | default: "Subscribe to unlock" }}</span>
            {% endif %}
          </div>
        </div>
      {% else %}
        <div class="free-gifts-row__placeholder">
          <div class="free-gifts-row__placeholder-image">
            <span class="free-gifts-row__placeholder-icon material-symbols-outlined">cardgiftcard</span>
          </div>
          <div class="free-gifts-row__product-info">
            <p class="free-gifts-row__placeholder-title">Gift2</p>
            <p class="free-gifts-row__placeholder-free">{{ block.settings.free_text }}</p>
          </div>
        </div>
      {% endif %}
    {% endif %}

    {%- comment -%} GIFT 3 {%- endcomment -%}
    {% if max_gifts >= 3 %}
      {% if block.settings.gift_product_3 != blank %}
        {% assign gift_3 = block.settings.gift_product_3 %}
        <div class="free-gifts-row__product locked"
             data-product-index="3"
             data-variant-id="{{ gift_3.selected_or_first_available_variant.id }}"
             data-unlock-qty="{{ block.settings.gift_3_quantity_to_unlock }}"
             data-add-qty="{{ block.settings.gift_3_quantity_to_add }}">
          {% if block.settings.gift_3_custom_image != blank %}
            <img src="{{ block.settings.gift_3_custom_image | image_url: width: 250 }}" alt="{{ block.settings.gift_3_custom_title | default: gift_3.title | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% elsif gift_3.featured_image %}
            <img src="{{ gift_3.featured_image | image_url: width: 250 }}" alt="{{ gift_3.featured_image.alt | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% endif %}
          <div class="free-gifts-row__product-info">
            <h4 class="free-gifts-row__product-title">
              {% if block.settings.gift_3_custom_title != blank %}{{ block.settings.gift_3_custom_title }}{% else %}{{ gift_3.title }}{% endif %}
            </h4>
            {% if is_row %}
            <div class="free-gifts-row__product-price-row">
              <p class="free-gifts-row__product-price">{{ gift_3.price | money }}</p>
              <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            </div>
            {% else %}
            <p class="free-gifts-row__product-price">{{ gift_3.price | money }}</p>
            <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            {% endif %}
            {% if block.settings.gift_3_custom_text != blank %}
              <p class="free-gifts-row__product-custom-text">{{ block.settings.gift_3_custom_text }}</p>
            {% endif %}
          </div>
          <div class="free-gifts-row__product-overlay">
            <span class="free-gifts-row__lock-icon material-symbols-outlined">lock</span>
            {% if block.settings.unlock_type == 'quantity' %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.gift_3_quantity_to_unlock }}{{ block.settings.quantity_unlock_suffix | default: "+ to unlock" }}</span>
            {% else %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.subscribe_unlock_text | default: "Subscribe to unlock" }}</span>
            {% endif %}
          </div>
        </div>
      {% else %}
        <div class="free-gifts-row__placeholder">
          <div class="free-gifts-row__placeholder-image">
            <span class="free-gifts-row__placeholder-icon material-symbols-outlined">cardgiftcard</span>
          </div>
          <div class="free-gifts-row__product-info">
            <p class="free-gifts-row__placeholder-title">Gift3</p>
            <p class="free-gifts-row__placeholder-free">{{ block.settings.free_text }}</p>
          </div>
        </div>
      {% endif %}
    {% endif %}

    {%- comment -%} GIFT 4 {%- endcomment -%}
    {% if max_gifts >= 4 %}
      {% if block.settings.gift_product_4 != blank %}
        {% assign gift_4 = block.settings.gift_product_4 %}
        <div class="free-gifts-row__product locked"
             data-product-index="4"
             data-variant-id="{{ gift_4.selected_or_first_available_variant.id }}"
             data-unlock-qty="{{ block.settings.gift_4_quantity_to_unlock }}"
             data-add-qty="{{ block.settings.gift_4_quantity_to_add }}">
          {% if block.settings.gift_4_custom_image != blank %}
            <img src="{{ block.settings.gift_4_custom_image | image_url: width: 250 }}" alt="{{ block.settings.gift_4_custom_title | default: gift_4.title | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% elsif gift_4.featured_image %}
            <img src="{{ gift_4.featured_image | image_url: width: 250 }}" alt="{{ gift_4.featured_image.alt | escape }}" class="free-gifts-row__product-image" loading="lazy">
          {% endif %}
          <div class="free-gifts-row__product-info">
            <h4 class="free-gifts-row__product-title">
              {% if block.settings.gift_4_custom_title != blank %}{{ block.settings.gift_4_custom_title }}{% else %}{{ gift_4.title }}{% endif %}
            </h4>
            {% if is_row %}
            <div class="free-gifts-row__product-price-row">
              <p class="free-gifts-row__product-price">{{ gift_4.price | money }}</p>
              <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            </div>
            {% else %}
            <p class="free-gifts-row__product-price">{{ gift_4.price | money }}</p>
            <p class="free-gifts-row__product-free">{{ block.settings.free_text }}</p>
            {% endif %}
            {% if block.settings.gift_4_custom_text != blank %}
              <p class="free-gifts-row__product-custom-text">{{ block.settings.gift_4_custom_text }}</p>
            {% endif %}
          </div>
          <div class="free-gifts-row__product-overlay">
            <span class="free-gifts-row__lock-icon material-symbols-outlined">lock</span>
            {% if block.settings.unlock_type == 'quantity' %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.gift_4_quantity_to_unlock }}{{ block.settings.quantity_unlock_suffix | default: "+ to unlock" }}</span>
            {% else %}
              <span class="free-gifts-row__unlock-text">{{ block.settings.subscribe_unlock_text | default: "Subscribe to unlock" }}</span>
            {% endif %}
          </div>
        </div>
      {% else %}
        <div class="free-gifts-row__placeholder">
          <div class="free-gifts-row__placeholder-image">
            <span class="free-gifts-row__placeholder-icon material-symbols-outlined">cardgiftcard</span>
          </div>
          <div class="free-gifts-row__product-info">
            <p class="free-gifts-row__placeholder-title">Gift4</p>
            <p class="free-gifts-row__placeholder-free">{{ block.settings.free_text }}</p>
          </div>
        </div>
      {% endif %}
    {% endif %}
  </div>
</div>

<script>
(function() {
  const blockId = '{{ block.id }}';
  const unlockType = '{{ block.settings.unlock_type }}';
  const multiplyByQuantity = {{ block.settings.multiply_gifts_by_quantity | default: false }};

  // ─── Gift variant IDs for this block (used by cart watcher) ───────────────
  const giftVariantIds = [
    {% if block.settings.gift_product_1 != blank and max_gifts >= 1 %}'{{ block.settings.gift_product_1.selected_or_first_available_variant.id }}',{% endif %}
    {% if block.settings.gift_product_2 != blank and max_gifts >= 2 %}'{{ block.settings.gift_product_2.selected_or_first_available_variant.id }}',{% endif %}
    {% if block.settings.gift_product_3 != blank and max_gifts >= 3 %}'{{ block.settings.gift_product_3.selected_or_first_available_variant.id }}',{% endif %}
    {% if block.settings.gift_product_4 != blank and max_gifts >= 4 %}'{{ block.settings.gift_product_4.selected_or_first_available_variant.id }}',{% endif %}
  ].filter(Boolean);

  // ─── Per-gift unlock quantities (for quantity mode) ───────────────────────
  const giftUnlockQtys = {
    {% if block.settings.gift_product_1 != blank and max_gifts >= 1 %}'{{ block.settings.gift_product_1.selected_or_first_available_variant.id }}': {{ block.settings.gift_1_quantity_to_unlock | default: 1 }},{% endif %}
    {% if block.settings.gift_product_2 != blank and max_gifts >= 2 %}'{{ block.settings.gift_product_2.selected_or_first_available_variant.id }}': {{ block.settings.gift_2_quantity_to_unlock | default: 2 }},{% endif %}
    {% if block.settings.gift_product_3 != blank and max_gifts >= 3 %}'{{ block.settings.gift_product_3.selected_or_first_available_variant.id }}': {{ block.settings.gift_3_quantity_to_unlock | default: 3 }},{% endif %}
    {% if block.settings.gift_product_4 != blank and max_gifts >= 4 %}'{{ block.settings.gift_product_4.selected_or_first_available_variant.id }}': {{ block.settings.gift_4_quantity_to_unlock | default: 4 }},{% endif %}
  };

  // ─── Per-gift add-to-cart quantities (Liquid-rendered, always reliable) ────
  const giftAddQtys = {
    {% if block.settings.gift_product_1 != blank and max_gifts >= 1 %}'{{ block.settings.gift_product_1.selected_or_first_available_variant.id }}': {{ block.settings.gift_1_quantity_to_add | default: 1 }},{% endif %}
    {% if block.settings.gift_product_2 != blank and max_gifts >= 2 %}'{{ block.settings.gift_product_2.selected_or_first_available_variant.id }}': {{ block.settings.gift_2_quantity_to_add | default: 1 }},{% endif %}
    {% if block.settings.gift_product_3 != blank and max_gifts >= 3 %}'{{ block.settings.gift_product_3.selected_or_first_available_variant.id }}': {{ block.settings.gift_3_quantity_to_add | default: 1 }},{% endif %}
    {% if block.settings.gift_product_4 != blank and max_gifts >= 4 %}'{{ block.settings.gift_product_4.selected_or_first_available_variant.id }}': {{ block.settings.gift_4_quantity_to_add | default: 1 }},{% endif %}
  };

  // ─── Use event delegation pattern like upsell-block ───────────────────────
  const initFreeGifts = function() {
    const container = document.querySelector(`[data-block-id="${blockId}"]`);
    if (!container) return;

    const productCards = container.querySelectorAll('.free-gifts-row__product');
    if (!productCards.length) return;

    function unlockGifts(quantity) {
      const newlyUnlocked = [];

      productCards.forEach((card) => {
        const unlockQty = parseInt(card.getAttribute('data-unlock-qty') || 1);
        const shouldBeUnlocked = quantity >= unlockQty;
        const wasUnlocked = card.dataset.unlocked === 'true';

        if (shouldBeUnlocked) {
          card.classList.add('unlocked');
          card.classList.remove('locked');
          card.dataset.unlocked = 'true';
          if (!wasUnlocked && unlockType === 'quantity') {
            newlyUnlocked.push(card);
          }
        } else {
          card.classList.remove('unlocked');
          card.classList.add('locked');
          card.dataset.unlocked = 'false';
        }
      });
    }

    // Get unlocked gifts to add with main product
    function getUnlockedGifts(mainProductQuantity = 1, hasSubscription = false) {
      const unlockedGifts = [];
      productCards.forEach(card => {
        if (card.dataset.unlocked === 'true') {
          const variantId = card.getAttribute('data-variant-id');
          const baseQty = parseInt(card.getAttribute('data-add-qty') || 1);

          const shouldMultiply = multiplyByQuantity && (
            (hasSubscription && unlockType === 'subscription') ||
            (unlockType === 'quantity')
          );
          const finalQty = shouldMultiply ? (baseQty * mainProductQuantity) : baseQty;

          unlockedGifts.push({
            id: parseInt(variantId),
            quantity: finalQty,
            properties: { '_free_gift': 'true' }
          });
        }
      });
      return unlockedGifts;
    }

    // Store reference to gifts globally so main ATC can access them
    window.freeGiftsData = window.freeGiftsData || {};
    window.freeGiftsData[blockId] = {
      getUnlockedGifts: getUnlockedGifts,
      unlockGifts: unlockGifts,
      unlockType: unlockType
    };

    // ── Global: add subscription-unlock gifts from the cart drawer toggle ──────
    if (!window.freeGiftsAddForSubscription) {
      window.freeGiftsAddForSubscription = function(mainProductQuantity = 1) {
        const giftsToAdd = [];
        if (window.freeGiftsData) {
          Object.values(window.freeGiftsData).forEach(blockData => {
            if (blockData.unlockType !== 'subscription') return;
            blockData.unlockGifts(999);
            const gifts = blockData.getUnlockedGifts(mainProductQuantity, true);
            gifts.forEach(g => giftsToAdd.push(g));
          });
        }

        if (!giftsToAdd.length) return Promise.resolve();

        return fetch('/cart/add.js', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ items: giftsToAdd })
        })
        .then(r => r.json())
        .then(() => {
          document.dispatchEvent(new CustomEvent('cartQuantityUpdated', { bubbles: true }));
        })
        .catch(err => console.error('[freeGiftsAddForSubscription]', err));
      };
    }

    // Event listeners based on unlock type
    if (unlockType === 'subscription') {
      function getWidget() {
        return document.querySelector('theme-subscription-widget') ||
               document.querySelector('[id^="SubscriptionWidget-"]');
      }

      function isSubscriptionSelected() {
        const widget = getWidget();
        if (!widget) return false;

        const sectionId = widget.id ? widget.id.replace('SubscriptionWidget-', '') : '';
        const productForm = sectionId
          ? document.getElementById('product-form-' + sectionId)
          : document.querySelector('form[action="/cart/add"]');
        if (productForm) {
          const spInput = productForm.querySelector('input[name="selling_plan"]');
          if (spInput && spInput.value && spInput.value.trim() !== '') return true;
        }

        if (typeof widget.isSubSelected === 'boolean') return widget.isSubSelected;

        if (widget.querySelector('.subscription__box--subscription.subscription__box--selected')) return true;

        const subToggle = widget.querySelector('.subscription__toggle-option[data-type="subscription"]');
        if (subToggle && subToggle.dataset.selected === 'true') return true;

        return false;
      }

      function checkSubscription() {
        unlockGifts(isSubscriptionSelected() ? 999 : 0);
      }

      const widget = getWidget();
      if (widget) {
        new MutationObserver(() => setTimeout(checkSubscription, 50))
          .observe(widget, { attributes: true, subtree: true, attributeFilter: ['class', 'data-selected', 'value'] });
      }

      const sectionId = widget ? (widget.id || '').replace('SubscriptionWidget-', '') : '';
      const productForm = sectionId
        ? document.getElementById('product-form-' + sectionId)
        : document.querySelector('form[action="/cart/add"]');
      if (productForm) {
        new MutationObserver(() => setTimeout(checkSubscription, 50))
          .observe(productForm, { attributes: true, subtree: true, attributeFilter: ['value'] });
      }

      document.body.addEventListener('click', (e) => {
        if (e.target.closest('theme-subscription-widget') ||
            e.target.closest('[id^="SubscriptionWidget-"]') ||
            e.target.closest('.subscription__box') ||
            e.target.closest('.subscription__toggle-option')) {
          setTimeout(checkSubscription, 150);
        }
      });

      setTimeout(checkSubscription, 800);

    } else if (unlockType === 'quantity') {
      function registerWithQuantityBreaks() {
        const qbEl = document.querySelector('quantity-breaks[id^="quantity-breaks-"]');
        if (!qbEl) return false;
        const sectionId = qbEl.id.replace('quantity-breaks-', '');
        const qgId = 'quantity-gifts-' + sectionId;

        let qgEl = document.getElementById(qgId);
        if (!qgEl) {
          qgEl = document.createElement('div');
          qgEl.id = qgId;
          qgEl.style.display = 'none';
          document.body.appendChild(qgEl);
        }

        const existing = qgEl.unlockGifts;
        qgEl.unlockGifts = function(qty) {
          if (existing) existing.call(this, qty);
          unlockGifts(qty);
        };

        const initialQty = parseInt(qbEl.querySelector('input[name="quantity"]:checked')?.value || 1);
        unlockGifts(initialQty);

        return true;
      }

      function listenToQuantityRadios() {
        document.querySelectorAll('input[name="quantity"]').forEach(input => {
          input.addEventListener('change', () => {
            unlockGifts(parseInt(input.value || 1));
          });
        });
      }

      document.addEventListener('quantity-update', (e) => {
        if (e.detail && e.detail.quantity) {
          unlockGifts(e.detail.quantity);
        }
      });

      if (!registerWithQuantityBreaks()) {
        setTimeout(() => {
          if (!registerWithQuantityBreaks()) {
            listenToQuantityRadios();
            const checked = document.querySelector('input[name="quantity"]:checked');
            unlockGifts(parseInt(checked?.value || 1));
          }
        }, 500);
      } else {
        listenToQuantityRadios();
      }

    } else if (unlockType === 'none') {
      unlockGifts(999);
    }
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initFreeGifts);
  } else {
    initFreeGifts();
  }

  // ─────────────────────────────────────────────────────────────────────────
  // CART WATCHER
  // ─────────────────────────────────────────────────────────────────────────
  if (!window.freeGiftCartWatcherBound) {
    window.freeGiftCartWatcherBound = true;
    window._fgWatcherRemoving = false;

    let watcherDebounceTimer = null;

    function getCartDrawerItems() {
      return document.querySelector('cart-drawer-items') || document.querySelector('cart-items');
    }

    async function runCartWatcher() {
      if (window._fgWatcherRemoving) return;

      const allGiftVariantIds = [];
      const allGiftUnlockQtys = {};
      const allBlockUnlockTypes = {};
      const allGiftBaseAddQtys = {};
      const allGiftMultiply = {};

      if (window.freeGiftsBlockRegistry) {
        window.freeGiftsBlockRegistry.forEach(reg => {
          reg.variantIds.forEach(vid => {
            allGiftVariantIds.push(vid);
            allGiftUnlockQtys[vid] = reg.unlockQtys[vid];
            allBlockUnlockTypes[vid] = reg.unlockType;
            allGiftBaseAddQtys[vid] = (reg.addQtys && reg.addQtys[vid]) || (() => {
              const baseQtysMap = reg.getBaseAddQtys ? reg.getBaseAddQtys() : {};
              return baseQtysMap[vid] || 1;
            })();
            allGiftMultiply[vid] = reg.multiplyByQuantity || false;
          });
        });
      }

      if (!allGiftVariantIds.length) return;

      let cart;
      try {
        const res = await fetch('/cart.js');
        cart = await res.json();
      } catch (e) {
        return;
      }

      const cartItems = cart.items || [];

      const toRemove = [];

      allGiftVariantIds.forEach(giftVid => {
        const giftInCart = cartItems.find(item =>
          String(item.variant_id) === String(giftVid) &&
          item.properties && item.properties['_free_gift'] === 'true'
        );
        if (!giftInCart) return;

        const unlockType = allBlockUnlockTypes[giftVid];

        if (unlockType === 'none') {
          const hasNonGiftItems = cartItems.some(item =>
            !(item.properties && item.properties['_free_gift'] === 'true')
          );
          if (!hasNonGiftItems) toRemove.push({ handle: giftInCart.handle, variantId: String(giftVid) });

        } else if (unlockType === 'quantity') {
          const requiredQty = allGiftUnlockQtys[giftVid] || 1;
          const nonGiftQty = cartItems.reduce((sum, item) => {
            if (item.properties && item.properties['_free_gift'] === 'true') return sum;
            return sum + item.quantity;
          }, 0);
          if (nonGiftQty < requiredQty) toRemove.push({ handle: giftInCart.handle, variantId: String(giftVid) });

        } else if (unlockType === 'subscription') {
          const hasSubscription = cartItems.some(item =>
            !(item.properties && item.properties['_free_gift'] === 'true') &&
            item.selling_plan_allocation != null
          );
          if (!hasSubscription) toRemove.push({ handle: giftInCart.handle, variantId: String(giftVid) });
        }
      });

      // ── Build toUpdate list: gifts whose qty should scale with main product ──
      const toUpdate = [];
      const nonGiftQty = cartItems.reduce((sum, item) => {
        if (item.properties && item.properties['_free_gift'] === 'true') return sum;
        return sum + item.quantity;
      }, 0);

      allGiftVariantIds.forEach(giftVid => {
        const giftInCart = cartItems.find(item =>
          String(item.variant_id) === String(giftVid) &&
          item.properties && item.properties['_free_gift'] === 'true'
        );
        if (!giftInCart) return;
        if (toRemove.some(r => r.variantId === String(giftVid))) return;

        const unlockType = allBlockUnlockTypes[giftVid];
        let expectedQty = null;

        if (unlockType === 'subscription' && allGiftMultiply[giftVid]) {
          const subscribedItem = cartItems.find(item =>
            !(item.properties && item.properties['_free_gift'] === 'true') &&
            item.selling_plan_allocation != null
          );
          const mainQty = subscribedItem ? subscribedItem.quantity : nonGiftQty;
          expectedQty = (allGiftBaseAddQtys[giftVid] || 1) * mainQty;

        } else if (unlockType === 'quantity') {
          if (allGiftMultiply[giftVid]) {
            expectedQty = (allGiftBaseAddQtys[giftVid] || 1) * nonGiftQty;
          } else {
            expectedQty = allGiftBaseAddQtys[giftVid] || 1;
          }
        }

        if (expectedQty !== null && giftInCart.quantity !== expectedQty) {
          toUpdate.push({
            key: giftInCart.key,
            quantity: expectedQty,
            handle: giftInCart.handle,
            variantId: String(giftVid)
          });
        }
      });

      // ── Build toAdd list: quantity-unlock gifts that SHOULD be in cart but aren't ──
      const toAdd = [];
      const hasAnyNonGift = nonGiftQty > 0;

      if (hasAnyNonGift) {
        allGiftVariantIds.forEach(giftVid => {
          if (allBlockUnlockTypes[giftVid] !== 'quantity') return;
          const requiredQty = allGiftUnlockQtys[giftVid] || 1;
          if (nonGiftQty < requiredQty) return;
          const alreadyInCart = cartItems.some(item =>
            String(item.variant_id) === String(giftVid) &&
            item.properties && item.properties['_free_gift'] === 'true'
          );
          if (alreadyInCart) return;
          if (toRemove.some(r => r.variantId === String(giftVid))) return;
          const addQty = allGiftMultiply[giftVid]
            ? (allGiftBaseAddQtys[giftVid] || 1) * nonGiftQty
            : (allGiftBaseAddQtys[giftVid] || 1);
          toAdd.push({ id: parseInt(giftVid), quantity: addQty, properties: { '_free_gift': 'true' } });
          if (window.freeGiftsData) {
            Object.values(window.freeGiftsData).forEach(blockData => {
              if (blockData.unlockType === 'quantity') blockData.unlockGifts(nonGiftQty);
            });
          }
        });
      }

      if (!toRemove.length && !toAdd.length && !toUpdate.length) return;

      const cartDrawerItems = getCartDrawerItems();

      // ── Apply quantity updates ────────────────────────────────────────────
      const doUpdates = () => {
        if (!toUpdate.length) { doRemovals(); return; }

        const updateNext = (items) => {
          if (!items.length) {
            fetch('/cart/update.js', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                updates: {},
                sections: ['cart-drawer', 'cart-icon-bubble'],
                sections_url: window.location.pathname
              })
            })
            .then(r => r.json())
            .then(data => {
              const sectionHtml = data.sections && data.sections['cart-drawer'];
              if (sectionHtml) {
                const doc = new DOMParser().parseFromString(sectionHtml, 'text/html');
                const newCD = doc.querySelector('#CartDrawer');
                const existingCD = document.querySelector('#CartDrawer');
                if (newCD && existingCD) existingCD.innerHTML = newCD.innerHTML;
                const overlay = document.querySelector('#CartDrawer-Overlay');
                const cdEl = document.querySelector('cart-drawer');
                if (overlay && cdEl) overlay.addEventListener('click', cdEl.close.bind(cdEl));
              }
              const bubbleHtml = data.sections && data.sections['cart-icon-bubble'];
              if (bubbleHtml) {
                const bDoc = new DOMParser().parseFromString(bubbleHtml, 'text/html');
                const nb = bDoc.querySelector('.shopify-section');
                const eb = document.getElementById('cart-icon-bubble');
                if (nb && eb) eb.innerHTML = nb.innerHTML;
              }
              doRemovals();
            })
            .catch(() => doRemovals());
            return;
          }

          const { key, quantity } = items[0];
          fetch('/cart/change.js', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: key, quantity })
          })
          .then(r => r.json())
          .then(() => updateNext(items.slice(1)))
          .catch(() => updateNext(items.slice(1)));
        };

        updateNext(toUpdate);
      };

      const doRemovals = () => {
        if (!toRemove.length || !cartDrawerItems) return;
        window._fgWatcherRemoving = true;

        const removeNext = (items) => {
          if (!items.length) { window._fgWatcherRemoving = false; return; }
          const { handle } = items[0];
          const cartEl = document.querySelector(`.cart-item--product-${handle}[data-is-free-gift="true"]`);
          if (!cartEl) { removeNext(items.slice(1)); return; }
          const lineIndex = cartEl.dataset.index;
          cartDrawerItems.updateQuantity(lineIndex, 0);
          const onUpdated = () => {
            document.removeEventListener('cartQuantityUpdated', onUpdated);
            removeNext(items.slice(1));
          };
          document.addEventListener('cartQuantityUpdated', onUpdated, { once: true });
        };
        removeNext(toRemove);
      };

      if (toAdd.length) {
        fetch('/cart/add.js', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ items: toAdd })
        })
        .then(r => r.json())
        .then(() => {
          if (toRemove.length || toUpdate.length) {
            doUpdates();
          } else {
            const anyCartEl = document.querySelector('.cart-item[data-index]');
            if (anyCartEl && cartDrawerItems) {
              const idx = anyCartEl.dataset.index;
              const currentQty = parseInt(anyCartEl.querySelector('.quantity__input, [data-quantity-variant-id]')?.value || anyCartEl.dataset.quantity || 1);
              cartDrawerItems.updateQuantity(idx, currentQty);
            } else {
              document.dispatchEvent(new CustomEvent('cartQuantityUpdated', { bubbles: true }));
            }
          }
        })
        .catch(err => console.error('Free Gifts Watcher add error:', err));
      } else {
        doUpdates();
      }
    }

    function debouncedWatcher() {
      if (window._fgWatcherRemoving) return;
      clearTimeout(watcherDebounceTimer);
      watcherDebounceTimer = setTimeout(runCartWatcher, 300);
    }

    document.addEventListener('cartQuantityUpdated', debouncedWatcher);

    if (typeof subscribe === 'function' && typeof PUB_SUB_EVENTS !== 'undefined') {
      subscribe(PUB_SUB_EVENTS.cartUpdate, debouncedWatcher);
    }
  }

  // ─── Register this block in the global registry ───────────────────────────
  window.freeGiftsBlockRegistry = window.freeGiftsBlockRegistry || [];
  window.freeGiftsBlockRegistry = window.freeGiftsBlockRegistry.filter(r => r.blockId !== blockId);

  function getGiftBaseAddQtys() {
    const map = {};
    document.querySelectorAll(`[data-block-id="${blockId}"] .free-gifts-row__product`).forEach(card => {
      const vid = card.getAttribute('data-variant-id');
      if (vid) map[vid] = parseInt(card.getAttribute('data-add-qty') || 1);
    });
    {% if block.settings.gift_product_1 != blank and max_gifts >= 1 %}
    if (!map['{{ block.settings.gift_product_1.selected_or_first_available_variant.id }}'])
      map['{{ block.settings.gift_product_1.selected_or_first_available_variant.id }}'] = {{ block.settings.gift_1_quantity_to_add | default: 1 }};
    {% endif %}
    {% if block.settings.gift_product_2 != blank and max_gifts >= 2 %}
    if (!map['{{ block.settings.gift_product_2.selected_or_first_available_variant.id }}'])
      map['{{ block.settings.gift_product_2.selected_or_first_available_variant.id }}'] = {{ block.settings.gift_2_quantity_to_add | default: 1 }};
    {% endif %}
    {% if block.settings.gift_product_3 != blank and max_gifts >= 3 %}
    if (!map['{{ block.settings.gift_product_3.selected_or_first_available_variant.id }}'])
      map['{{ block.settings.gift_product_3.selected_or_first_available_variant.id }}'] = {{ block.settings.gift_3_quantity_to_add | default: 1 }};
    {% endif %}
    {% if block.settings.gift_product_4 != blank and max_gifts >= 4 %}
    if (!map['{{ block.settings.gift_product_4.selected_or_first_available_variant.id }}'])
      map['{{ block.settings.gift_product_4.selected_or_first_available_variant.id }}'] = {{ block.settings.gift_4_quantity_to_add | default: 1 }};
    {% endif %}
    return map;
  }

  window.freeGiftsBlockRegistry.push({
    blockId,
    unlockType,
    variantIds: giftVariantIds,
    unlockQtys: giftUnlockQtys,
    addQtys: giftAddQtys,
    getBaseAddQtys: getGiftBaseAddQtys,
    multiplyByQuantity: multiplyByQuantity
  });

  // ─────────────────────────────────────────────────────────────────────────
  // ATC INTERCEPT
  // ─────────────────────────────────────────────────────────────────────────
  if (!document.body.dataset.freeGiftsAtcHandlerBound) {
    document.body.dataset.freeGiftsAtcHandlerBound = 'true';

    document.body.addEventListener('click', async function(e) {
      let button = e.target.closest('button[type="submit"][name="add"]');
      if (!button) {
        button = e.target.closest('button[type="button"][form]');
        if (!button) return;
      }

      let form = button.closest('form');
      if (!form) {
        const formId = button.getAttribute('form');
        if (formId) form = document.getElementById(formId);
      }
      if (!form) {
        form = button.closest('product-form')?.querySelector('form');
      }
      if (!form) return;

      const formData = new FormData(form);
      let mainProductQuantity = 1;

      if (window.qbBundleData && window.qbBundleData.items && window.qbBundleData.items.length > 0) {
        mainProductQuantity = window.qbBundleData.items.reduce((sum, item) => sum + (item.quantity || 0), 0);
      } else {
        mainProductQuantity = parseInt(formData.get('quantity') || 1);
      }

      const sellingPlan = formData.get('selling_plan');
      const hasSubscription = sellingPlan && sellingPlan !== '';

      let allFreeGifts = [];
      if (window.freeGiftsData) {
        Object.values(window.freeGiftsData).forEach(giftBlock => {
          const gifts = giftBlock.getUnlockedGifts(mainProductQuantity, hasSubscription);
          allFreeGifts = allFreeGifts.concat(gifts);
        });
      }

      if (allFreeGifts.length === 0) return;

      e.preventDefault();
      e.stopPropagation();
      e.stopImmediatePropagation();

      try {
        const _cartRes = await fetch('/cart.js').then(r => r.json());
        const _cartItems = _cartRes.items || [];
        allFreeGifts = allFreeGifts.filter(gift => {
          return !_cartItems.some(item =>
            String(item.variant_id) === String(gift.id) &&
            item.properties && item.properties['_free_gift'] === 'true'
          );
        });
      } catch (err) {
        console.warn('[FreeGifts] Cart pre-check failed, proceeding without dedup:', err);
      }

      let items = [];

      if (window.qbBundleData && window.qbBundleData.items && window.qbBundleData.items.length > 0) {
        items = window.qbBundleData.items.map(item => {
          const cartItem = { id: parseInt(item.id), quantity: parseInt(item.quantity) };
          if (sellingPlan) cartItem.selling_plan = sellingPlan;
          return cartItem;
        });
      } else {
        const qbEl = document.querySelector('quantity-breaks[id^="quantity-breaks-"]');
        if (qbEl && qbEl.formVariants && qbEl.formVariants.length > 0) {
          const variantCounts = {};
          qbEl.formVariants.forEach(vid => {
            variantCounts[vid] = (variantCounts[vid] || 0) + 1;
          });
          items = Object.entries(variantCounts).map(([vid, qty]) => ({
            id: parseInt(vid),
            quantity: qty,
            selling_plan: sellingPlan || undefined
          }));
        } else {
          const mainVariantId = parseInt(formData.get('id'));
          if (!mainVariantId) return;
          const mainItem = { id: mainVariantId, quantity: mainProductQuantity };
          if (sellingPlan) mainItem.selling_plan = sellingPlan;
          items = [mainItem];
        }
      }

      items = items.concat(allFreeGifts);

      button.classList.add('loading');
      button.disabled = true;
      const spinner = button.querySelector('.loading-overlay__spinner');
      if (spinner) spinner.classList.remove('hidden');

      fetch('/cart/add.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'X-Free-Gift-Bundle': 'true'
        },
        body: JSON.stringify({ items: items })
      })
      .then(response => {
        if (!response.ok) {
          return response.json().then(err => { throw new Error(err.description || `HTTP ${response.status}`); });
        }
        return response.json();
      })
      .then(() => {
        return fetch(`?sections=cart-drawer,cart-icon-bubble&timestamp=${Date.now()}`);
      })
      .then(res => res.json())
      .then(sections => {
        button.classList.remove('loading');
        button.disabled = false;
        if (spinner) spinner.classList.add('hidden');

        const cartDrawer = document.querySelector('cart-drawer');

        if (cartDrawer && sections['cart-drawer']) {
          const parser = new DOMParser();
          const doc = parser.parseFromString(sections['cart-drawer'], 'text/html');
          const newDrawerInner = doc.querySelector('.drawer__inner');
          const existingDrawerInner = cartDrawer.querySelector('.drawer__inner');
          if (newDrawerInner && existingDrawerInner) {
            existingDrawerInner.outerHTML = newDrawerInner.outerHTML;
          }
          cartDrawer.classList.remove('is-empty');
          cartDrawer.open();
        }

        if (sections['cart-icon-bubble']) {
          const iconBubbleEl = document.getElementById('cart-icon-bubble');
          if (iconBubbleEl) {
            const parser = new DOMParser();
            const doc = parser.parseFromString(sections['cart-icon-bubble'], 'text/html');
            const newBubble = doc.querySelector('.cart-count-bubble');
            const existingBubble = iconBubbleEl.querySelector('.cart-count-bubble');
            if (newBubble && existingBubble) existingBubble.innerHTML = newBubble.innerHTML;
            else if (newBubble && !existingBubble) iconBubbleEl.appendChild(newBubble.cloneNode(true));
            else if (!newBubble && existingBubble) existingBubble.remove();
          }
        }

        document.dispatchEvent(new CustomEvent('cartQuantityUpdated', { bubbles: true }));
        document.dispatchEvent(new CustomEvent('cart:updated', { bubbles: true }));
      })
      .catch(error => {
        console.error('Free Gifts: Error:', error);
        alert('Failed to add items: ' + error.message);
        button.classList.remove('loading');
        button.disabled = false;
        if (spinner) spinner.classList.add('hidden');
      });

      return false;
    }, true);
  }
})();
</script>