{% liquid
  assign item_count = 0
  if block.settings.gift_1 != blank
    assign item_count = item_count | plus: 1
  endif
  if block.settings.gift_2 != blank
    assign item_count = item_count | plus: 1
  endif
  if block.settings.gift_3 != blank
    assign item_count = item_count | plus: 1
  endif
  if block.settings.gift_4 != blank
    assign item_count = item_count | plus: 1
  endif
%}
<style>
  .free-price--label {
      background: {{ block.settings.gift_badge_color }};
      border-radius: {{ block.settings.gift_badge_radius }}px;
      padding-right: 12px;
      padding-left: 12px;
      color: {{ block.settings.gift_badge_textcolor }};
      font-size: 12px;
      vertical-align: middle;
      margin: 0;
      text-transform: uppercase;
      font-weight: 700;
      position: absolute;
      top: -20px;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      white-space: nowrap;
  }
  .free-price--label strong {
    text-decoration: line-through;
  }

  /* ── Scratch-off overlay (injected by JS only on unlock) ── */
  .quantity-gift__scratch {
    position: absolute;
    inset: 0;
    z-index: 10;
    border-radius: inherit;
    pointer-events: auto;
    transition: opacity 0.5s ease;
  }
  .quantity-gift__scratch canvas {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    border-radius: inherit;
    cursor: crosshair;
    display: block;
  }
  .quantity-gift__scratch-hint {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 4px;
    pointer-events: none;
    z-index: 1;
    transition: opacity 0.3s ease;
  }
  .quantity-gift__scratch-hint__icon {
    font-size: 24px;
    line-height: 1;
  }
  .quantity-gifts-4 .quantity-gift__scratch-hint__icon {
    font-size: 18px;
  }
  .quantity-gifts-4 .quantity-gift__scratch-hint__cta {
    font-size: 8px;
    letter-spacing: 0.8px;
  }
  .quantity-gift__scratch-hint__cta {
    font-size: 9px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1.2px;
    color: #ffffff;
    text-shadow: 0 1px 3px rgba(0,0,0,0.4);
    white-space: nowrap;
    text-align: center;
  }
</style>
{%- style -%}
  {% if block.settings.enable_hiddengifts %}
  quantity-gifts {
      display: none!important;
  }
  {% endif %}
{%- endstyle -%}
<div
  class="quantity-gifts-container {{ block.settings.visibility }}"
  style="
    --margin-top: {{ block.settings.margin_top | divided_by: 10.0 }}rem;
    --margin-bottom: {{ block.settings.margin_bottom | divided_by: 10.0 }}rem;
  "
  {{ block.shopify_attributes }}
>
  <quantity-gifts
    class="quantity-gifts quantity-gifts-{{ item_count }}"
    id="quantity-gifts-{{ section.id }}"
    data-section="{{ section.id }}"
    data-main-product="{{ product.handle }}"
    style="--item-count: {{ item_count }};--unlocked-bg-color:{{ block.settings.unlocked_bg_color }};--unlocked-border-color:{{ block.settings.unlocked_border_color }};--gift-box-tie-color:{{ block.settings.gift_box_tie_color }};"
  >
    {% for i in (1..4) %}
      {% liquid
        case i
          when 1
            assign gift_product = block.settings.gift_1
            assign required_quantity = block.settings.gift_1_quantity
            assign badge_text = block.settings.gift_1_badge
            assign top_text = block.settings.gift_1_top_text
            assign bottom_text = block.settings.gift_1_bottom_text
            assign custom_image = block.settings.gift_1_image
            assign no_animation = block.settings.gift_1_no_animation
            assign scratch_title = block.settings.scratch_title_1
          when 2
            assign gift_product = block.settings.gift_2
            assign required_quantity = block.settings.gift_2_quantity
            assign badge_text = block.settings.gift_2_badge
            assign top_text = block.settings.gift_2_top_text
            assign bottom_text = block.settings.gift_2_bottom_text
            assign custom_image = block.settings.gift_2_image
            assign no_animation = block.settings.gift_2_no_animation
            assign scratch_title = block.settings.scratch_title_2
          when 3
            assign gift_product = block.settings.gift_3
            assign required_quantity = block.settings.gift_3_quantity
            assign badge_text = block.settings.gift_3_badge
            assign top_text = block.settings.gift_3_top_text
            assign bottom_text = block.settings.gift_3_bottom_text
            assign custom_image = block.settings.gift_3_image
            assign no_animation = block.settings.gift_3_no_animation
            assign scratch_title = block.settings.scratch_title_3
          when 4
            assign gift_product = block.settings.gift_4
            assign required_quantity = block.settings.gift_4_quantity
            assign badge_text = block.settings.gift_4_badge
            assign top_text = block.settings.gift_4_top_text
            assign bottom_text = block.settings.gift_4_bottom_text
            assign custom_image = block.settings.gift_4_image
            assign no_animation = block.settings.gift_4_no_animation
            assign scratch_title = block.settings.scratch_title_4
        endcase
      %}
      {% unless gift_product == blank %}
        <style>
          .cart-item--product-{{ gift_product.handle }} .quantity {
            display: none;
          }
        </style>
        <div
          class="quantity-gift{% if no_animation %} quantity-gift--no-animation{% endif %} quantity-gift--product-{{ gift_product.handle }}"
          data-quantity="{{ required_quantity }}"
          data-unlocked="false"
          data-product="{{ gift_product.first_available_variant.id }}"
          data-handle="{{ gift_product.handle }}"
          {%- if block.settings.enable_scratch -%}
          data-scratch-color="{{ block.settings.scratch_cover_color }}"
          data-scratch-radius="{{ block.settings.scratch_brush_size }}"
          data-scratch-threshold="{{ block.settings.scratch_reveal_threshold }}"
          data-scratch-hint="{{ block.settings.scratch_hint_text | escape }}"
          data-scratch-emoji="{{ block.settings.scratch_show_emoji }}"
          data-scratch-title="{{ scratch_title | escape }}"
          data-real-title="{{ gift_product.title | escape }}"
          {%- endif -%}
        >
          <div class="quantity-gift__container color-{{ block.settings.unlocked_color }}" style="border-radius:{{ block.settings.gift_radius }}rem;">
            <div class="free-price--label">
              <span class="free-text">{{ badge_text }} </span>
            </div>

            <div class="quantity-gift__lock color-background-1">
              <span class="quantity-gift__lock__top">{{ top_text }}</span>
              <span class="lock"></span>
              <span class="quantity-gift__lock__bottom">{{ bottom_text }}</span>
            </div>
            <div class="quantity-gift__image">
              {% liquid
                assign image = gift_product.featured_image
                if custom_image != blank
                  assign image = custom_image
                endif
              %}
              {% if image != blank %}
                <img
                  src="{{ image | image_url: width: 500 }}"
                  {% if image.alt != blank %}
                    alt="{{ image.alt }}"
                  {% endif %}
                  width="auto"
                  height="auto"
                  loading="lazy"
                >
              {% endif %}
            </div>
            <div class="gift-box">
              <div class="gift-box-body color-{{ block.settings.gift_box_color }}">
                <div class="gift-box-lid">
                  <div class="gift-box-bowtie">&nbsp</div>
                </div>
              </div>
            </div>
            {%- comment -%} Scratch overlay is NOT in markup — injected by JS only when data-unlocked flips to true {%- endcomment -%}
          </div>
          <h3 class="quantity-gift__title">
            {%- if block.settings.enable_scratch and scratch_title != blank -%}
              {{ scratch_title }}
            {%- else -%}
              {{ gift_product.title }}
            {%- endif -%}
          </h3>
          {% assign product_form_id = 'gift-form-' | append: section.id | append: block.id | append: forloop.index %}
          <product-form
            class="hidden"
            data-is-cart-upsell="true"
            data-section="{{ section.id }}-{{ block.id }}-{{ forloop.index0 }}"
          >
            {%- form 'product',
              gift_product,
              id: product_form_id,
              class: 'form',
              novalidate: 'novalidate',
              data-type: 'add-to-cart-form'
            -%}
              <input type="hidden" name="id" value="{{ gift_product.first_available_variant.id }}">
              <button type="submit">+</button>
            {%- endform -%}
          </product-form>
        </div>
      {% endunless %}
    {% endfor %}
  </quantity-gifts>
  {% if item_count == 0 %}
    <p class="title h2 center">Select your gift product(s)</p>
  {% endif %}
</div>

{%- if block.settings.enable_scratch -%}
<script>
(function() {

  function buildOverlay(giftEl) {
    var color     = giftEl.dataset.scratchColor    || '#aaaaaa';
    var hintText  = giftEl.dataset.scratchHint     || 'SCRATCH HERE';
    var radius    = parseInt(giftEl.dataset.scratchRadius)    || 20;
    var threshold = parseInt(giftEl.dataset.scratchThreshold) || 40;
    var container = giftEl.querySelector('.quantity-gift__container');

    // Build overlay DOM
    var overlay = document.createElement('div');
    overlay.className = 'quantity-gift__scratch';

    var canvas = document.createElement('canvas');
    overlay.appendChild(canvas);

    var hint = document.createElement('div');
    hint.className = 'quantity-gift__scratch-hint';
    var hintInner = giftEl.dataset.scratchEmoji === 'true'
      ? '<span class="quantity-gift__scratch-hint__icon">\uD83C\uDF81</span>'
      : '';
    hintInner += '<span class="quantity-gift__scratch-hint__cta">' + hintText + '</span>';
    hint.innerHTML = hintInner;
    overlay.appendChild(hint);

    container.appendChild(overlay);

    // Size and paint canvas after layout
    function setupCanvas() {
      var rect = container.getBoundingClientRect();
      var w = Math.round(rect.width);
      var h = Math.round(rect.height);
      if (w === 0 || h === 0) { setTimeout(setupCanvas, 150); return; }

      canvas.width  = w;
      canvas.height = h;
      var ctx = canvas.getContext('2d');
      ctx.globalCompositeOperation = 'source-over';
      ctx.fillStyle = color;
      ctx.fillRect(0, 0, w, h);

      var isDrawing = false;

      function getPos(e) {
        var r  = canvas.getBoundingClientRect();
        var cx = e.touches ? e.touches[0].clientX : e.clientX;
        var cy = e.touches ? e.touches[0].clientY : e.clientY;
        return {
          x: (cx - r.left) * (canvas.width  / r.width),
          y: (cy - r.top)  * (canvas.height / r.height)
        };
      }

      function scratchAt(pos) {
        ctx.globalCompositeOperation = 'destination-out';
        ctx.beginPath();
        ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
        ctx.fill();
      }

      function checkReveal() {
        try {
          var pixels  = ctx.getImageData(0, 0, w, h).data;
          var total   = pixels.length / 4;
          var cleared = 0;
          for (var i = 3; i < pixels.length; i += 4) {
            if (pixels[i] === 0) cleared++;
          }
          if ((cleared / total) * 100 >= threshold) {
            overlay.style.opacity = '0';
            // Reveal real product title
            var titleEl = giftEl.querySelector('.quantity-gift__title');
            if (titleEl && giftEl.dataset.realTitle) {
              titleEl.textContent = giftEl.dataset.realTitle;
            }
            setTimeout(function() { overlay.style.display = 'none'; }, 500);
          }
        } catch(e) {}
      }

      function onStart(e) {
        e.preventDefault();
        isDrawing = true;
        hint.style.opacity = '0';
        scratchAt(getPos(e));
      }
      function onMove(e) {
        if (!isDrawing) return;
        e.preventDefault();
        scratchAt(getPos(e));
      }
      function onEnd() {
        if (!isDrawing) return;
        isDrawing = false;
        checkReveal();
      }

      canvas.addEventListener('mousedown',  onStart);
      canvas.addEventListener('mousemove',  onMove);
      canvas.addEventListener('mouseup',    onEnd);
      canvas.addEventListener('mouseleave', onEnd);
      canvas.addEventListener('touchstart', onStart, { passive: false });
      canvas.addEventListener('touchmove',  onMove,  { passive: false });
      canvas.addEventListener('touchend',   onEnd);
    }

    requestAnimationFrame(function() { requestAnimationFrame(setupCanvas); });
  }

  function onUnlock(giftEl) {
    if (giftEl._scratchBuilt) return;
    giftEl._scratchBuilt = true;
    buildOverlay(giftEl);
  }

  function onLock(giftEl) {
    // Remove overlay if the gift gets re-locked (e.g. customer reduces qty)
    var existing = giftEl.querySelector('.quantity-gift__scratch');
    if (existing) {
      existing.remove();
      giftEl._scratchBuilt = false;
    }
    // Restore mystery title
    var titleEl = giftEl.querySelector('.quantity-gift__title');
    var mysteryTitle = giftEl.dataset.scratchTitle;
    if (titleEl && mysteryTitle) {
      titleEl.textContent = mysteryTitle;
    }
  }

  function watchGifts(root) {
    root.querySelectorAll('.quantity-gift[data-scratch-color]').forEach(function(gift) {
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(m) {
          if (m.attributeName !== 'data-unlocked') return;
          if (gift.dataset.unlocked === 'true') {
            onUnlock(gift);
          } else {
            onLock(gift);
          }
        });
      });
      observer.observe(gift, { attributes: true });
    });
  }

  function checkSettledState() {
    // After all CEs have run connectedCallback and settled, sync any gifts already unlocked
    document.querySelectorAll('.quantity-gift[data-scratch-color]').forEach(function(gift) {
      if (gift.dataset.unlocked === 'true') {
        onUnlock(gift);
      }
    });
  }

  function init() {
    document.querySelectorAll('.quantity-gifts-container').forEach(watchGifts);
    // rAF x2 ensures connectedCallbacks have fired and data-unlocked is in final state
    requestAnimationFrame(function() {
      requestAnimationFrame(checkSettledState);
    });
  }

  // Attach synchronously so our observer is in place before custom element connectedCallbacks fire
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  document.addEventListener('shopify:section:load', init);
})();
</script>
{%- endif -%}