/**
 * @file
 * Javascript functionality for component counter.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentCounter = Drupal.componentCounter || {};
  Drupal.behaviors.counter = {
    attach: function (context) {
      Drupal.componentCounter.counter(context);
    }
  }
  Drupal.componentCounter.counter = function (context) {
    const $counter = $(once('counterItems', '.component-builder.component-item--type-counter', context));
    if ($counter.length > 0) {
      var checkScroll = 0;
      $(window).scroll(function () {
        var hT = $('.field--name-field-counter-number').offset().top,
          hH = $('.field--name-field-counter-number').outerHeight(),
          wH = $(window).height(),
          wS = $(this).scrollTop();
        if (wS > (hT + hH - wH) && checkScroll == 0) {
          checkScroll = 1;
          const ele = document.getElementsByClassName("field--name-field-counter-number");
          for (let i = 0; i < ele.length; i++) {
            let counts = setInterval(updated, 0.001);
            let upto = 0;
            let value = parseInt(ele[i].textContent.replaceAll('+', '').trim());

            function updated() {
              // var count= document.getElementById("counter");
              upto += 30;
              ele[i].innerHTML = upto;
              if (upto >= value || upto === 50000) {
                clearInterval(counts);
                ele[i].innerHTML = value + '+';
              }
            }
          }
        }
      });
    }
  }

})(jQuery, Drupal, once);

