/**
 * GET BACK PHYSIOTHERAPY — Main JavaScript
 * Handles: navbar scroll, mobile menu, FAQ accordion,
 * scroll reveal, counter animation, smooth scroll
 */

document.addEventListener("DOMContentLoaded", () => {
  /* ==========================================
     NAVBAR — scroll state
  ========================================== */
  const navbar = document.getElementById("navbar");

  const handleNavbarScroll = () => {
    if (window.scrollY > 60) {
      navbar.classList.add("scrolled");
    } else {
      navbar.classList.remove("scrolled");
    }
  };

  window.addEventListener("scroll", handleNavbarScroll, { passive: true });
  handleNavbarScroll();

  /* ==========================================
     MOBILE MENU
  ========================================== */
  const hamburger = document.getElementById("hamburger");
  const mobileNav = document.getElementById("mobileNav");
  const mobileLinks = mobileNav ? mobileNav.querySelectorAll("a") : [];

  if (hamburger && mobileNav) {
    hamburger.addEventListener("click", () => {
      hamburger.classList.toggle("open");
      mobileNav.classList.toggle("open");
      document.body.style.overflow = mobileNav.classList.contains("open")
        ? "hidden"
        : "";
    });

    mobileLinks.forEach((link) => {
      link.addEventListener("click", () => {
        hamburger.classList.remove("open");
        mobileNav.classList.remove("open");
        document.body.style.overflow = "";
      });
    });
  }

  /* ==========================================
     SMOOTH SCROLL for anchor links
  ========================================== */
  document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
    anchor.addEventListener("click", (e) => {
      const target = document.querySelector(anchor.getAttribute("href"));
      if (target) {
        e.preventDefault();
        const offset = 80;
        const top =
          target.getBoundingClientRect().top + window.pageYOffset - offset;
        window.scrollTo({ top, behavior: "smooth" });
      }
    });
  });

  /* ==========================================
     FAQ ACCORDION
  ========================================== */
  document.querySelectorAll(".faq-question").forEach((btn) => {
    btn.addEventListener("click", () => {
      const item = btn.closest(".faq-item");
      const isOpen = item.classList.contains("open");

      // Close all
      document
        .querySelectorAll(".faq-item")
        .forEach((i) => i.classList.remove("open"));

      // Toggle current
      if (!isOpen) item.classList.add("open");
    });
  });

  /* ==========================================
     SCROLL REVEAL
  ========================================== */
  const revealEls = document.querySelectorAll(".reveal");

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("visible");
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.12 },
  );

  revealEls.forEach((el) => observer.observe(el));

  /* ==========================================
     COUNTER ANIMATION
  ========================================== */
  const counters = document.querySelectorAll("[data-count]");

  const countObserver = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const el = entry.target;
          const target = parseInt(el.dataset.count, 10);
          const suffix = el.dataset.suffix || "";
          const dur = 1800;
          const step = 16;
          const inc = target / (dur / step);
          let current = 0;

          const timer = setInterval(() => {
            current += inc;
            if (current >= target) {
              current = target;
              clearInterval(timer);
            }
            el.textContent = Math.floor(current).toLocaleString() + suffix;
          }, step);

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

  counters.forEach((el) => countObserver.observe(el));

  /* ==========================================
     SCROLL TO TOP
  ========================================== */
  const scrollTopBtn = document.getElementById("scrollTop");

  if (scrollTopBtn) {
    window.addEventListener(
      "scroll",
      () => {
        if (window.scrollY > 400) {
          scrollTopBtn.classList.add("visible");
        } else {
          scrollTopBtn.classList.remove("visible");
        }
      },
      { passive: true },
    );

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

  /* ==========================================
     TESTIMONIAL AUTO-SCROLL (mobile)
  ========================================== */
  // Simple auto-highlight cycling (visual only)
  const testimonialCards = document.querySelectorAll(".testimonial-card");
  let currentCard = 0;

  if (testimonialCards.length > 0 && window.innerWidth < 640) {
    setInterval(() => {
      testimonialCards[currentCard].style.borderColor = "";
      currentCard = (currentCard + 1) % testimonialCards.length;
      testimonialCards[currentCard].style.borderColor = "var(--cyan)";
    }, 3000);
  }

  /* ==========================================
     HERO VIDEO FALLBACK
  ========================================== */
  const heroVideo = document.getElementById("heroVideo");
  if (heroVideo) {
    heroVideo.addEventListener("error", () => {
      heroVideo.parentElement.style.background =
        "linear-gradient(135deg, #0f2440 0%, #1a3a5c 60%, #00b4d8 100%)";
    });
  }

  /* ==========================================
     CONTACT FORM — basic validation feedback
  ========================================== */
  const contactForm = document.getElementById("contactForm");
  if (contactForm) {
    contactForm.addEventListener("submit", (e) => {
      e.preventDefault();
      const btn = contactForm.querySelector('[type="submit"]');
      const original = btn.textContent;
      btn.textContent = "Message Sent ✓";
      btn.style.background = "#2ecc71";
      btn.disabled = true;
      setTimeout(() => {
        btn.textContent = original;
        btn.style.background = "";
        btn.disabled = false;
        contactForm.reset();
      }, 3000);
    });
  }

  /* ==========================================
     BOOKING FORM — inline submit feedback
  ========================================== */
  const bookingForm = document.getElementById("bookingFormInline");
  if (bookingForm) {
    bookingForm.addEventListener("submit", (e) => {
      e.preventDefault();
      const btn = bookingForm.querySelector('[type="submit"]');
      btn.textContent = "Request Sent! ✓";
      btn.style.background = "#fff";
      btn.style.color = "var(--navy)";
      setTimeout(() => {
        btn.textContent = "Book Appointment";
        btn.style.background = "";
        btn.style.color = "";
        bookingForm.reset();
      }, 3000);
    });
  }

  /* ==========================================
     GALLERY LIGHTBOX (simple)
  ========================================== */
  const galleryItems = document.querySelectorAll(".gallery-item");
  galleryItems.forEach((item) => {
    item.addEventListener("click", () => {
      const img = item.querySelector("img");
      if (!img) return;

      const overlay = document.createElement("div");
      overlay.style.cssText = `
        position:fixed;inset:0;z-index:9999;
        background:rgba(0,0,0,.92);
        display:flex;align-items:center;justify-content:center;
        cursor:zoom-out;
        animation:fadeIn .25s ease;
      `;

      const clone = document.createElement("img");
      clone.src = img.src;
      clone.alt = img.alt;
      clone.style.cssText =
        "max-width:90vw;max-height:90vh;border-radius:8px;box-shadow:0 20px 60px rgba(0,0,0,.5);";

      const closeBtn = document.createElement("button");
      closeBtn.innerHTML = "×";
      closeBtn.style.cssText = `
        position:absolute;top:20px;right:28px;
        background:none;border:none;color:#fff;
        font-size:2.5rem;cursor:pointer;line-height:1;
        opacity:.8;transition:opacity .2s;
      `;

      overlay.appendChild(clone);
      overlay.appendChild(closeBtn);
      document.body.appendChild(overlay);
      document.body.style.overflow = "hidden";

      const close = () => {
        document.body.removeChild(overlay);
        document.body.style.overflow = "";
      };

      overlay.addEventListener("click", close);
      closeBtn.addEventListener("click", close);
    });
  });
});
// team slider
$(".team-slider").owlCarousel({
  loop: true,
  margin: 10,
  nav: true,
  dots: false,
  autoplay: true,
  smartSpeed: 700,
  responsive: {
    0: {
      items: 1,
    },
    768: {
      items: 2,
    },
    992: {
      items: 3,
    },
  },
});
// testimonial
$(".testimonials-slider").owlCarousel({
  loop: true,
  margin: 24,
  nav: true,
  dots: false,
  autoplay: true,
  autoplayTimeout: 5000,
  autoplayHoverPause: true,
  smartSpeed: 800,

  responsive: {
    0: {
      items: 1,
    },
    768: {
      items: 2,
    },
    1200: {
      items: 3,
    },
  },
});
$(".insurance-slider").owlCarousel({
  loop: true,
  margin: 20,
  nav: false,
  dots: false,

  autoplay: true,
  autoplayTimeout: 2500,
  autoplayHoverPause: true,

  smartSpeed: 800,

  responsive: {
    0: {
      items: 2,
    },
    576: {
      items: 3,
    },
    992: {
      items: 5,
    },
    1200: {
      items: 6,
    },
  },
});
