var Wick = Wick || {};
Wick.Footer = (function(){
  let $accordion = $('.footer-menu__inner .accordion'),
    $accordionContent = $('.footer-menu__inner .accordion__content'),
    $paymentList = $('footer .payments__list'),
    $waysToPayList = $('footer .payways__list'),
    $paymentListCheckoutFooter = $('footer .payments-checkout__list'),
    $paymentListOrderSummery = $('.right-aside .footer-checkout .payments-checkout__list'),
    paymentSmallListClass = 'payments__list--small',
    waysToPaySmallListClass = 'payways__list--small',
    paymentCheckoutSmallListClass = 'payments-checkout__list--small',
    collapsedState = "accordion_collapsed",
    windowWidth = $(window).width();

  const elementClassAdjustments = [
    { $element: $paymentList, count: 6, className: paymentSmallListClass },
    { $element: $paymentListOrderSummery, count: 6, className: paymentCheckoutSmallListClass, isGreaterThan: true },
    { $element: $paymentListCheckoutFooter, count: 6, className: paymentCheckoutSmallListClass, isGreaterThan: false },
    { $element: $waysToPayList, count: 6, className: waysToPaySmallListClass, isGreaterThan: false, checkForWindowWidth: true }
  ];

  function accordionClickHandler() {
    if ($(this).find($accordionContent).is(':visible')) {
      $accordionContent.hide()
      $accordion.not($(this)).removeClass(collapsedState)
      $(this).find($accordionContent).show()
    }
  }

  function applyClassBasedOnChildrenCount($element, count, className, isGreaterThan = false, checkForWindowWidth = false) {
    let hasEnoughChildren = isGreaterThan ? $element.children().length > count : $element.children().length < count;

    if(checkForWindowWidth && windowWidth < 576) {
      if(hasEnoughChildren) {
        $element.addClass(className);
      }
    } else if (!checkForWindowWidth) {
      if(hasEnoughChildren) {
        $element.addClass(className);
      }
    }
  }

  function onWindowResize() {
    windowWidth = $(window).width();

    let isChildrenCountLessThanSix = $waysToPayList.children().length < 6;

    if(isChildrenCountLessThanSix && windowWidth > 576 ) {
      $waysToPayList.removeClass(waysToPaySmallListClass);
    } else if (isChildrenCountLessThanSix) {
      $waysToPayList.addClass(waysToPaySmallListClass);
    }
  }

  function init () {
    $accordion.click(accordionClickHandler);

    elementClassAdjustments.forEach(function(item) {
      applyClassBasedOnChildrenCount(item.$element, item.count, item.className, item.isGreaterThan, item.checkForWindowWidth);
    });

    $(window).resize(_.debounce(onWindowResize, 200));
  }

  init();
})();