$(function(){

  function animateCount(el, duration = 2000) {
    const target = parseInt(el.attr('data-target')); // الرقم المستهدف
    let startTime = null;

    function update(currentTime) {
      if (!startTime) startTime = currentTime;
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const current = Math.floor(progress * target);
      el.text(current);

      if (progress < 1) {
        requestAnimationFrame(update);
      } else {
        el.text(target); // تأكيد الرقم النهائي
      }
    }

    requestAnimationFrame(update);
  }

  function checkVisibleAndAnimate() {
    $('.acheivements_count').each(function () {
      const el = $(this);

      if (el.data('animated')) return;

      const windowHeight = $(window).height();
      const scrollTop = $(window).scrollTop();
      const elTop = el.offset().top;

      if (elTop < scrollTop + windowHeight) {
        animateCount(el);
        el.data('animated', true); // عشان ما يعيد العد
      }
    });
  }

  $(window).on('scroll', checkVisibleAndAnimate);
  $(document).ready(checkVisibleAndAnimate);


});