/**
 * Fletcher Physiotherapy - Main JavaScript
 * =========================================
 */

document.addEventListener("DOMContentLoaded", function () {
  // ---- Navbar scroll effect ----
  const navbar = document.getElementById("mainNavbar");
  window.addEventListener("scroll", function () {
    if (window.scrollY > 60) {
      navbar.classList.add("scrolled");
    } else {
      navbar.classList.remove("scrolled");
    }
    toggleScrollTop();
  });

  // ---- Scroll-to-top button ----
  const scrollTopBtn = document.getElementById("scrollTop");

  function toggleScrollTop() {
    if (window.scrollY > 400) {
      scrollTopBtn.classList.add("visible");
    } else {
      scrollTopBtn.classList.remove("visible");
    }
  }

  if (scrollTopBtn) {
    scrollTopBtn.addEventListener("click", function () {
      window.scrollTo({ top: 0, behavior: "smooth" });
    });
  }

  // ---- Intersection Observer for fade-up animations ----
  const fadeEls = document.querySelectorAll(".fade-up");

  const observer = new IntersectionObserver(
    function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          // Staggered delay support via data-delay attribute
          const delay = entry.target.getAttribute("data-delay") || 0;
          setTimeout(function () {
            entry.target.classList.add("visible");
          }, delay);
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.12, rootMargin: "0px 0px -40px 0px" },
  );

  fadeEls.forEach(function (el) {
    observer.observe(el);
  });

  // ---- Hero video fallback ----
  const heroVideo = document.getElementById("heroVideo");
  if (heroVideo) {
    heroVideo.addEventListener("error", function () {
      // If video fails, show a fallback background image
      const heroSection = document.querySelector(".hero-video-wrap");
      if (heroSection) {
        heroSection.style.background =
          'url("images/hero-fallback.jpg") center/cover no-repeat';
      }
    });
  }

  // ---- Smooth scroll for anchor links ----
  document.querySelectorAll('a[href^="#"]').forEach(function (anchor) {
    anchor.addEventListener("click", function (e) {
      const target = document.querySelector(this.getAttribute("href"));
      if (target) {
        e.preventDefault();
        const offset = navbar ? navbar.offsetHeight + 10 : 80;
        const top =
          target.getBoundingClientRect().top + window.scrollY - offset;
        window.scrollTo({ top: top, behavior: "smooth" });
      }
    });
  });

  // ---- Mobile menu: close on nav link click ----
  const navLinks = document.querySelectorAll(
    ".navbar-nav .nav-link:not(.dropdown-toggle)",
  );
  const navbarCollapse = document.getElementById("navbarNav");

  navLinks.forEach(function (link) {
    link.addEventListener("click", function () {
      if (navbarCollapse && navbarCollapse.classList.contains("show")) {
        const toggler = document.querySelector(".navbar-toggler");
        if (toggler) toggler.click();
      }
    });
  });

  // ---- Active nav link on scroll ----
  const sections = document.querySelectorAll("section[id]");

  function highlightNav() {
    const scrollPos = window.scrollY + 120;
    sections.forEach(function (section) {
      const top = section.offsetTop;
      const height = section.offsetHeight;
      const id = section.getAttribute("id");
      const link = document.querySelector('.navbar-nav a[href="#' + id + '"]');
      if (link) {
        if (scrollPos >= top && scrollPos < top + height) {
          document
            .querySelectorAll(".navbar-nav .nav-link")
            .forEach((l) => l.classList.remove("active"));
          link.classList.add("active");
        }
      }
    });
  }

  window.addEventListener("scroll", highlightNav);

  // ---- Appointment form submission ----
  const apptForm = document.getElementById("appointmentForm");
  if (apptForm) {
    apptForm.addEventListener("submit", function (e) {
      e.preventDefault();
      const btn = apptForm.querySelector('button[type="submit"]');
      const original = btn.textContent;
      btn.disabled = true;
      btn.textContent = "Sending…";

      // Simulate form submission (replace with real backend logic)
      setTimeout(function () {
        btn.textContent = "✓ Request Sent!";
        btn.style.background = "#27ae60";
        setTimeout(function () {
          btn.disabled = false;
          btn.textContent = original;
          btn.style.background = "";
          apptForm.reset();
        }, 3000);
      }, 1500);
    });
  }

  // ---- Counter animation for stats ----
  const counters = document.querySelectorAll(".counter-num");

  const counterObserver = new IntersectionObserver(
    function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          const el = entry.target;
          const target = parseInt(el.getAttribute("data-target"), 10);
          const suffix = el.getAttribute("data-suffix") || "";
          let current = 0;
          const step = Math.ceil(target / 60);

          const timer = setInterval(function () {
            current += step;
            if (current >= target) {
              current = target;
              clearInterval(timer);
            }
            el.textContent = current + suffix;
          }, 25);

          counterObserver.unobserve(el);
        }
      });
    },
    { threshold: 0.5 },
  );

  counters.forEach(function (el) {
    counterObserver.observe(el);
  });

  $(".services-slider").owlCarousel({
    loop: true,
    margin: 30,
    nav: true,
    dots: false,
    autoplay: true,
    autoplayTimeout: 4000,
    smartSpeed: 800,
    responsive: {
      0: { items: 1 },
      768: { items: 2 },
      1200: { items: 3 },
    },
  });

  $(".blog-slider").owlCarousel({
    loop: true,
    margin: 30,
    nav: true,
    dots: false,
    autoplay: true,
    autoplayTimeout: 5000,
    smartSpeed: 800,
    responsive: {
      0: { items: 1 },
      768: { items: 1 },
      1200: { items: 2 },
    },
  });
  $(".conditions-slider").owlCarousel({
    loop: true,
    margin: 30,
    nav: false,
    dots: false,
    autoplay: true,
    autoplayTimeout: 4000,
    smartSpeed: 800,

    responsive: {
      0: {
        items: 1,
      },
      576: {
        items: 2,
      },
      992: {
        items: 3,
      },
      1200: {
        items: 4,
      },
    },
  });

  $(".more_blog-slider").owlCarousel({
    loop: true,
    margin: 30,
    nav: true,
    dots: false,
    autoplay: true,
    autoplayTimeout: 4000,
    smartSpeed: 800,
    responsive: {
      0: { items: 1 },
      768: { items: 2 },
      1200: { items: 3 },
    },
  });
});
