(function() {
  'use strict';

  // Function to update a single selector item image
  function updateSelectorItemImage(selectorItem, variant) {
    const imageElement = selectorItem.querySelector('.quantity-break__selector-item__image img');
    if (imageElement && variant && variant.featured_image && variant.featured_image.src) {
      imageElement.src = variant.featured_image.src;
    }
  }

  // Function to update all quantity break images for a section
  function updateAllQuantityBreakImages(sectionId, currentVariant) {
    const quantityBreaks = document.getElementById(`quantity-breaks-${sectionId}`);
    if (quantityBreaks && currentVariant && currentVariant.featured_image) {
      quantityBreaks.querySelectorAll('.quantity-break__selector-item__image img').forEach(img => {
        img.src = currentVariant.featured_image.src;
      });
    }
  }

  // Listen for changes on quantity break selector items
  document.addEventListener('change', function(event) {
    const selectorItem = event.target.closest('.quantity-break__selector-item');
    if (selectorItem) {
      const quantityBreaks = selectorItem.closest('quantity-breaks');
      if (quantityBreaks) {
        const variantData = quantityBreaks.getVariantData();
        const selectedValues = Array.from(selectorItem.querySelectorAll('select'), select => select.value);
        
        const variant = variantData.find(v => {
          return !v.options.map((option, index) => {
            return selectedValues[index] === option;
          }).includes(false);
        });
        
        if (variant) {
          updateSelectorItemImage(selectorItem, variant);
        }
      }
    }
  });

  // Listen for variant changes from the main variant selects
  document.addEventListener('change', function(event) {
    const variantSelects = event.target.closest('variant-selects');
    if (variantSelects) {
      const sectionId = variantSelects.dataset.section;
      const quantityBreaks = document.getElementById(`quantity-breaks-${sectionId}`);
      
      if (quantityBreaks) {
        // Wait for the variant change to complete, then update images
        setTimeout(() => {
          const currentVariant = variantSelects.currentVariant;
          if (currentVariant && currentVariant.featured_image) {
            updateAllQuantityBreakImages(sectionId, currentVariant);
          }
        }, 100);
      }
    }
  });

  // Listen for custom events that might trigger image updates
  document.addEventListener('variantChange', function(event) {
    if (event.detail && event.detail.variant && event.detail.sectionId) {
      updateAllQuantityBreakImages(event.detail.sectionId, event.detail.variant);
    }
  });

})();