console.log('js-fc-stats_panel.js');
// Listener for count up

function addCommas(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

function removeCommas(in_string) {
  return in_string.replace(/\,/g, '');
}

const animateValue = (obj, start, duration) => {
  let startTimestamp = null;

  //set initial width
  let initial_width = obj.getBoundingClientRect().width;
  obj.style.minWidth = `${initial_width}px`;

  // get end number
  let endNum = parseFloat(removeCommas(obj.innerHTML));
  let decimals = false;
  let hundreds = false;
  if (endNum % 1 > 0) {
    decimals = true;
  }

  if (endNum > 10000) {
    hundreds = true;
  }

  //1 second before, slow it down


  let previousTimestamp = undefined;
  let idealFps = 45;
  let idealFpsInterval = 1000 / idealFps;

  const step = (timestamp) => {

    if (!startTimestamp) startTimestamp = timestamp;
    if (!previousTimestamp) previousTimestamp = timestamp;

    let progress = (timestamp - startTimestamp) / duration;

    if (timestamp - previousTimestamp > idealFpsInterval) {
      let _a = -0.0031;
      let _b = 1.9346;
      let _c = -0.9286;

      let multiplier = _a + (_b * progress) + (_c * Math.pow(progress, 2));
      if (multiplier > 0.997) {
        multiplier = 1;
        progress = 1;
      }

      let newVal = multiplier * (endNum - start) + start;
      if (decimals) {
        newVal = Math.floor(newVal * 100) / 100;
        newVal = newVal.toFixed(Math.max(1, (newVal.toString().split('.')[1] || []).length));
      }
      else if (hundreds) { newVal = Math.floor(newVal / 100) * 100; }
      else { newVal = Math.floor(newVal); }
      obj.innerHTML = addCommas(newVal);
      previousTimestamp = timestamp;
    }
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }

  };
  window.requestAnimationFrame(step);
}
const callback = entries => {
  entries.forEach(entry => {
    const el = entry.target
    if (document.documentElement.clientWidth > 767) {
      if (entry.isIntersecting && !el.classList.contains('is-visible')) {
        animateValue(el, 0, 5000);
        el.classList.add('is-visible')
      }
    }
  })
}

const IO = new IntersectionObserver(callback, { threshold: 1 })

const stat_countup = document.querySelectorAll('.page-template.platform .stats_panel .stat [number], .page-template.home .stats_panel .stat [number]');
// const stat_industries = document.querySelectorAll( '.stat_item p' );

stat_countup.forEach(el => {
  IO.observe(el)
});