(function() {
  const SELECTORS = {
    card: '.kitchen-card',
    priceBlock: '.kitchen-card__price',
    wasPriceBlock: '.price__was-block',
    stickersBlock: '.strip-stickers',
    colourSwatchesContainer: '.colour-swatches__container',
  }
  const CLASSES = {
    pricePaddedTop: 'kitchen-card__price--padded-top',
    pricePaddedBottom: 'kitchen-card__price--padded-bottom',
  };

  const ITEMS_PER_ROW_DESKTOP = 3;
  const ITEMS_PER_ROW_MOBILE = 2;
  const DEBOUNCE_DELAY = 200;

  function getItemsPerRow() {
    return Wick.Responsive.getCurrentBreakpoint() === 'up-lg'
      ? ITEMS_PER_ROW_DESKTOP
      : ITEMS_PER_ROW_MOBILE;
  }

  function alignRowItems($row, targetSelector, classToAdd) {
    const $itemsWithElement = $row.filter(`:has(${targetSelector})`);
    const $itemsWithoutElement = $row.not($itemsWithElement);

    if ($itemsWithElement.length > 0 && $itemsWithoutElement.length > 0) {
      $itemsWithoutElement
        .find(SELECTORS.priceBlock)
        .addClass(classToAdd);
    }
  }

  function updateHeightColourSwatches($row) {
    const $container = $row.find(SELECTORS.colourSwatchesContainer)
    let maxHeight = 0;

    $container.each(function() {
      const currentHeight = $(this).height();
      if (currentHeight > maxHeight) {
        maxHeight = currentHeight;
      }
    });

    $container.height(maxHeight);
  }

  function clearCards($cards) {
    $cards.find(SELECTORS.priceBlock).removeClass(CLASSES.pricePaddedTop);
    $cards.find(SELECTORS.priceBlock).removeClass(CLASSES.pricePaddedBottom);
    $cards.find(SELECTORS.colourSwatchesContainer).height('auto');
  }

  function alignCardsGrid() {
    const $cards = $(SELECTORS.card);
    const itemsPerRow = getItemsPerRow();

    clearCards($cards)

    if(Wick.Responsive.getCurrentBreakpoint() === 'down-sm') {
      return
    }

    const rowCount = Math.ceil($cards.length / itemsPerRow);

    for (let i = 0; i < rowCount; i++) {
      const $currentRow = $cards.slice(i * itemsPerRow, (i + 1) * itemsPerRow);

      alignRowItems($currentRow, SELECTORS.wasPriceBlock, CLASSES.pricePaddedTop);
      alignRowItems($currentRow, SELECTORS.stickersBlock, CLASSES.pricePaddedBottom);
      updateHeightColourSwatches($currentRow);
    }
  }

  $(document).ready(function() {
    alignCardsGrid();
    $(window).on('resize', _.debounce(alignCardsGrid, DEBOUNCE_DELAY));
    $(window).on('kitchenCardChanged', alignCardsGrid);
  });
})();