document.addEventListener("DOMContentLoaded", function () {
  const themeButtons = document.querySelectorAll("[data-theme-toggle]");
  const savedTheme = localStorage.getItem("site-theme") || "light";

  function applyTheme(theme) {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("site-theme", theme);

    themeButtons.forEach(function (btn) {
      const icon = btn.querySelector("i");
      if (!icon) return;

      if (theme === "dark") {
        icon.className = "fa-regular fa-sun";
      } else {
        icon.className = "fa-regular fa-moon";
      }
    });
  }

  applyTheme(savedTheme);

  themeButtons.forEach(function (btn) {
    btn.addEventListener("click", function () {
      const current =
        document.documentElement.getAttribute("data-theme") || "light";
      applyTheme(current === "dark" ? "light" : "dark");
    });
  });


  /* SCROLL ANIMATIONS */
  const scrollElements = document.querySelectorAll('.animate-on-scroll');
  if (scrollElements.length > 0 && 'IntersectionObserver' in window) {
      const elementObserver = new IntersectionObserver((entries, observer) => {
          entries.forEach(entry => {
              if (entry.isIntersecting) {
                  entry.target.classList.add('is-visible');
                  observer.unobserve(entry.target);
              }
          });
      }, {
          root: null,
          rootMargin: "0px",
          threshold: 0.15
      });

      scrollElements.forEach(el => elementObserver.observe(el));
  } else {
      // Fallback for older browsers
      scrollElements.forEach(el => el.classList.add('is-visible'));
  }

  /* SMOOTH SCROLL for anchor links */
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
          const href = this.getAttribute('href');
          if (href === '#' || href === '#!') return;
          const target = document.querySelector(href);
          if (target) {
              e.preventDefault();
              target.scrollIntoView({ behavior: 'smooth', block: 'start' });
          }
      });
  });

  /* BACK TO TOP */
  const backToTopBtn = document.getElementById('backToTop');
  if (backToTopBtn) {
      window.addEventListener('scroll', function () {
          if (window.scrollY > 600) {
              backToTopBtn.classList.add('is-visible');
          } else {
              backToTopBtn.classList.remove('is-visible');
          }
      }, { passive: true });

      backToTopBtn.addEventListener('click', function () {
          window.scrollTo({ top: 0, behavior: 'smooth' });
      });
  }
});
