jQuery(document).ready(function() {
  var owl = jQuery('.contact-box-banner .owl-carousel');
  owl.owlCarousel({
    margin: 20,
    nav:true,
    autoplay : true,
    lazyLoad: true,
    autoplayTimeout: 5000,
    loop: true,
    dots: true,
    navText : ['<i class="fas fa-chevron-left"></i>','<i class="fas fa-chevron-right"></i>'],
    responsive: {
      0: {
        items: 1
      },
      576: {
        items: 2
      },
      768: {
        items: 5
      },
      1000: {
        stagePadding: 60,
        items: 7
      },
      1200: {
        stagePadding: 120,
        items: 7
      }
    }
  });
});

document.addEventListener("DOMContentLoaded", function () {
  const counters = document.querySelectorAll(".counter-main h5");
  const speed = 200; // lower = faster

  // Convert text like "15K+" → 15000
  const parseValue = (text) => {
    let clean = text.replace(/[^\d]/g, ""); // extract digits
    let num = parseInt(clean, 10) || 0;

    if (/k/i.test(text)) {
      num *= 1000;
    } else if (/m/i.test(text)) {
      num *= 1000000;
    }
    return num;
  };

  const getSuffix = (text) => {
    return text.replace(/[0-9]/g, "").toUpperCase(); // keep non-numeric chars
  };

  const animateCounter = (counter, finalText) => {
    const target = parseValue(finalText);
    const suffix = getSuffix(finalText);

    const updateCount = () => {
      const current = parseInt(counter.innerText.replace(/[^\d]/g, "")) || 0;
      const increment = Math.ceil(target / speed);

      if (current < target) {
        counter.innerText = current + increment + suffix;
        setTimeout(updateCount, 30);
      } else {
        counter.innerText = finalText; // show exact final value
      }
    };

    updateCount();
  };

  const options = { threshold: 0.5 };
  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const finalText = entry.target.innerText.trim();
        entry.target.innerText = "0"; // start from 0
        animateCounter(entry.target, finalText);
        observer.unobserve(entry.target);
      }
    });
  }, options);

  counters.forEach(counter => {
    observer.observe(counter);
  });
});


jQuery(".slider-content-box h2").html(function () {
    var html = jQuery(this).html().trim();

    // Replace <br> with a placeholder
    html = html.replace(/<br\s*\/?>/gi, " ___BR___ ");

    var words = html.split(/\s+/);

    if (words.length >= 2) {
        words[1] = `<span class="second-word">${words[1]}</span>`;
    }

    if (words.length >= 5) {
        words[5] = `<span class="second-word">${words[5]}</span>`;
    }

    var result = words.join(" ");

    // Restore <br>
    return result.replace(/___BR___/g, "<br>");
});
