import { tns } from '@shop/engine/node_modules/tiny-slider/src/tiny-slider';

wpj.domUtils.initOpeners();

const WpjTabs = require('@assets/js/wpj.tabs.js');
new WpjTabs('[data-tabs="shoes-size"]');

if (MODULES.WATCHDOG) {
   import('@assets/js/wpj.watchdog.js').then(wpjWatchdog => {
      wpjWatchdog.initWatchdog();
   });
}

if (typeof initProductGallerySlider === 'undefined' && $('#product-gallery').length) {
   import('@assets/js/wpj.product.helpers.js').then(productHelpers => {
      if (typeof initProductGallerySlider === 'undefined') {
         productHelpers.initProductGallerySlider({
            slideBy: 1,
            gutter: 10,
            items: 2,
            responsive: {
               768: {
                  items: 3
               },
               1260: {
                  gutter: 40
               }
            }
         });
      }
   });
}

if ($('#accessories').length) {
   const related_products = tns({
      container: '#accessories .catalog-row-related',
      items: 2,
      slideBy: 1,
      nav: false,
      loop: false,
      gutter: 5,
      controls: true,
      controlsText: ['', ''],
      responsive: {
         768: {
            items: 3
         },
         992: {
            items: 4
         },
         1260: {
            items: 5
         },
         1400: {
            items: 6
         }
      }
   });
}

if ($('.product-articles').length) {
   const related_articles = tns({
      container: '.product-articles .articles-row',
      items: 1,
      slideBy: 1,
      nav: false,
      loop: false,
      gutter: 10,
      controls: true,
      controlsText: ['', ''],
      responsive: {
         370: {
            items: 2
         },
         768: {
            items: 3,
            gutter: 40,
            disabled: true
         }
      }
   });
}

// sticky info

const $window = $(window),
   $header = $('.header'),
   productStickyInfo = $('.product-sticky-info-wrapper'),
   productStickyStart = $('.product-bottom').offset().top;
$window.scroll(function() {
   const scrollTop = $window.scrollTop();

   if (productStickyStart) {
      if (scrollTop > productStickyStart && !productStickyInfo.hasClass('is-stuck')) {
         productStickyInfo.addClass('is-stuck');
         $header.addClass('active-sticky-info');
      } else if (scrollTop <= productStickyStart) {
         productStickyInfo.removeClass('is-stuck');
         $header.removeClass('active-sticky-info');
      }
   }
});

const $sizeConvertionWrapper = $('[data-variation-size-convertion-wrapper]');
$(document).on('click', '[data-variation-size-convertion-trigger]', function(e) {
   $sizeConvertionWrapper.toggleClass('active');
}).on('click', '.product-variation-size-convertion', function(e) {
   $sizeConvertionWrapper.toggleClass('active');
}).on('click', function(e) {
   if (!$(e.target).closest('[data-variation-size-convertion-wrapper]').length && $sizeConvertionWrapper.hasClass('active')) {
      $sizeConvertionWrapper.removeClass('active');
   }
}).ready(function(e) {
   let variations = $('.product-variations');
   if (!variations.find('[name="IDvariation"]:checked').length) {
      const variation = variations.find('[name="IDvariation"]:not(.soldout)').first();
      $(variation).click()
      checkSelectedVariant($(variation).val());
   }else {
      const variation = variations.find('[name="IDvariation"]:checked').first();
      checkSelectedVariant($(variation).val());
   }
});

// rwd toggles
$('.resp-toggle').on('click', function(e) {
   if ($(window).width() < 992) {
      $(this).toggleClass('opened');
      $(this).next().slideToggle('opened');
   }
});

function checkSelectedVariant(variationId) {
   if (!variationId) {
      return;
   }

   const checkedVars = $('.product-colors [name^="IDLabel_"]:checked');
   const allowedVars = $(checkedVars[0]).data('allowed-vars')?.split(',').filter(variable => variable);

   if(!checkedVars.length || !allowedVars.length) {
      return;
   }

   const value = $(checkedVars[0]).val();

   // add for all other variations class soldout
   $('[data-other-variations] input').each(function(index, elem ) {
      $(elem).addClass('soldout');
      $('[data-id="' + elem.value + '"]').addClass('soldout');
   });

   // based on soldout variation add or remove class soldout for all checked variations
   $('[name^="IDLabel_"]:checked').each((index, elem) => {
      if (!wpj.variations[variationId].soldout) {
         $(elem).removeClass('soldout');
         $('label[for="' + elem.id + '"]').removeClass('soldout');
      } else {
         $(elem).addClass('soldout');
         $('label[for="' + elem.id + '"]').addClass('soldout');
      }
   });

   const variationMap = new Map();
// Find other variations that include Color in a variation.combinations
   for (let key in wpj.variations) {
      const combinationsValues = Object.values(wpj.variations[key].combinations);
      allowedVars.forEach(variable => {
         if (combinationsValues?.includes(+value) && combinationsValues.includes(+variable)) {
            variationMap.set(key, {
               soldout: wpj.variations[key].soldout,
               otherVariation: combinationsValues.filter(variat => variat !== +value),
            });
         }
      })
   }

   // set or remove class soldout for variations that include selected color in variation.combinations
   variationMap.forEach((variation) => {
      variation.otherVariation.forEach((otherVariation) => {
         const otherVariant = $('[data-id="' + otherVariation + '"]');

         if(!otherVariant.length) return;

         if (!variation.soldout) {
            otherVariant.removeClass('soldout');
         } else {
            otherVariant.addClass('soldout');
         }
      })
   });
}

$(document).on('variationSelected', function(e) {
   const variationId = e.target.value;
   checkSelectedVariant(variationId);
});
