document.addEventListener("DOMContentLoaded", function () {
  const links = document.querySelectorAll(".service-list-two a");

  for (const link of links) {
    link.addEventListener("click", smoothScroll);
  }

  function smoothScroll(e) {
    e.preventDefault();
    const targetId = this.getAttribute("href");
    const targetElement = document.querySelector(targetId);

    // Getting the top position of the target element with an offset of 350 pixels from the top
    const targetOffsetTop = targetElement.offsetTop + 350;

    // Remove 'active' class from all links
    links.forEach((link) => {
      link.classList.remove("active");
    });

    // Add 'active' class to the clicked link
    this.classList.add("active");

    // Scroll to the target with an offset of 350 pixels from the top
    window.scrollTo({
      top: targetOffsetTop,
      behavior: "smooth",
    });
  }

  window.addEventListener("scroll", highlightActiveLink);

  function highlightActiveLink() {
    const scrollPosition = window.scrollY;

    // Remove 'active' class from all links
    links.forEach((link) => {
      link.classList.remove("active");
    });

    // Find the section in view and add 'active' class to its corresponding link
    for (const link of links) {
      const targetId = link.getAttribute("href");
      const targetSection = document.querySelector(targetId);
      const targetSectionTop = targetSection.offsetTop;
      const targetSectionBottom = targetSectionTop + targetSection.offsetHeight;

      if (
        scrollPosition >= targetSectionTop &&
        scrollPosition < targetSectionBottom
      ) {
        link.classList.add("active");
      }
    }
  }
});
