// Navbar js
(function initParkHavenNavbar() {
  const servicesData = {
    "healthy-start": {
      title: "Healthy Start",
      img: "images/service-dropdown/makeover.webp",
      desc: "Advanced pediatric care in a boutique setting for the next generation.",
      subs: [],
    },
    "urgent-care": {
      title: "Urgent Dental Care",
      subs: [
        {
          name: "Emergency Dentist",
          img: "images/service-dropdown/emergency.png",
        },
        {
          name: "Root Canal Therapy",
          img: "images/service-dropdown/root.png",
        },
        {
          name: "Extractions",
          img: "images/service-dropdown/extractions.png",
        },
      ],
    },
    "general-care": {
      title: "General & Family Care",
      subs: [
        {
          name: "Family Dentistry",
          img: "images/service-dropdown/family.png",
        },
        {
          name: "Hygiene Services",
          img: "images/service-dropdown/hygiene.png",
        },
      ],
    },
    "gum-disease": {
      title: "Gum Disease",
      subs: [
        {
          name: "Non-Surgical Therapy",
          img: "images/service-dropdown/non-surgical.png",
        },
      ],
    },
    "cosmetic-care": {
      title: "Cosmetic Care",
      subs: [
        {
          name: "Bonded Fillings",
          img: "images/service-dropdown/cosmetic.png",
        },
        {
          name: "Porcelain Veneers",
          img: "images/service-dropdown/teeth-white.png",
        },
        {
          name: "Teeth Whitening",
          img: "images/service-dropdown/teeth-white-female.png",
        },
      ],
    },
    implants: {
      title: "Dental Implants",
      subs: [
        {
          name: "Implant Placement",
          img: "images/service-dropdown/implants.png",
        },
        {
          name: "Restoration",
          img: "images/service-dropdown/restoration.png",
        },
      ],
    },
    orthodontics: {
      title: "Orthodontics",
      subs: [
        {
          name: "Invisalign®",
          img: "images/service-dropdown/invisalign.png",
        },
      ],
    },
    "restorative-care": {
      title: "Restorative Care",
      subs: [
        {
          name: "Bridges",
          img: "images/service-dropdown/crowns.png",
        },
        {
          name: "Crowns",
          img: "images/service-dropdown/crown.png",
        },
      ],
    },
    "additional-care": {
      title: "Additional Care",
      subs: [
        {
          name: "TMJ Therapy",
          img: "images/service-dropdown/tmj.jpeg",
        },
        {
          name: "Mouthguards",
          img: "images/service-dropdown/mouth-guard.png",
        },
      ],
    },
    "childrens-care": {
      title: "Children’s Care",
      subs: [
        {
          name: "Kids Dentistry",
          img: "images/service-dropdown/kids-dentistry.png",
        },
      ],
    },
  };

  const extraData = {
    about: {
      title: "About Us",
      links: [
        { name: "Meet Our Team", icon: "groups" },
        { name: "Our Office", icon: "apartment" },
        { name: "COVID-19 Protocol", icon: "health_and_safety" },
        { name: "Patient FAQ's", icon: "quiz" },
      ],
    },
    forms: {
      title: "Forms",
      links: [
        { name: "Medical History", icon: "description" },
        { name: "Wisdom Teeth", icon: "dentistry" },
        { name: "Dental Implants", icon: "medical_services" },
      ],
    },
  };

  // Desktop Functions
  function updateDesktopMegaMenu(key, event) {
    const data = servicesData[key];
    const title = document.getElementById("park-haven-navbar-mega-title");
    const grid = document.getElementById("park-haven-navbar-mega-grid");
    const container = document.getElementById(
      "park-haven-navbar-mega-content-container",
    );

    document
      .querySelectorAll(".side-nav-item")
      .forEach((item) =>
        item.classList.remove("park-haven-navbar-active-sidebar-item"),
      );
    if (event)
      event.currentTarget.classList.add(
        "park-haven-navbar-active-sidebar-item",
      );

    container.style.opacity = "0";
    setTimeout(() => {
      title.textContent = data.title;
      grid.innerHTML = "";

      if (key === "healthy-start") {
        grid.className = "w-full";
        grid.innerHTML = `
                        <div class="relative w-full h-[400px] rounded-2xl overflow-hidden shadow-2xl">
                            <img src="${data.img}" class="w-full h-full object-cover">
                            <div class="absolute inset-0 bg-gradient-to-t from-primary/60 via-transparent to-transparent"></div>
                            <div class="absolute bottom-8 left-8 right-8">
                                <h4 class="text-2xl font-bold text-white mb-2">${data.title}</h4>
                                <p class="text-white/80 max-w-xl">${data.desc}</p>
                            </div>
                        </div>
                    `;
      } else {
        grid.className = "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8";
        data.subs.forEach((sub) => {
          const card = document.createElement("div");
          card.className =
            "park-haven-navbar-service-card group/card bg-white/10 backdrop-blur-md rounded-xl overflow-hidden border border-white/10 cursor-pointer";
          card.innerHTML = `
                            <div class="aspect-[16/10] overflow-hidden"><img src="${sub.img}" class="w-full h-full object-cover group-hover/card:scale-110 transition-transform duration-700"></div>
                            <div class="p-6"><h4 class="font-bold text-lg mb-4 group-hover/card:text-secondary-accent transition-colors">${sub.name}</h4><div class="flex items-center gap-2 text-white/50 text-[10px] font-black uppercase tracking-widest"><span>LEARN MORE</span><span class="material-symbols-outlined text-[14px] group-hover/card:translate-x-1 transition-transform">arrow_forward</span></div></div>
                        `;
          grid.appendChild(card);
        });
      }
      container.style.opacity = "1";
      container.style.transition = "opacity 0.3s ease";
    }, 100);
  }

  function initDesktopNav() {
    const container = document.getElementById(
      "park-haven-navbar-desktop-services-nav",
    );
    if (!container) return;
    container.innerHTML = "";
    Object.keys(servicesData).forEach((key) => {
      const s = servicesData[key];
      const btn = document.createElement("button");
      btn.className =
        "side-nav-item flex justify-between items-center px-8 py-3.5 text-left font-bold text-white/70 hover:bg-white/10 transition-all";
      btn.innerHTML = `<span>${s.title}</span><span class="material-symbols-outlined text-[18px]">chevron_right</span>`;
      btn.onmouseenter = (e) => updateDesktopMegaMenu(key, e);
      container.appendChild(btn);
    });
    updateDesktopMegaMenu("healthy-start");
  }

  // Mobile Functions
  const slider = document.getElementById("park-haven-navbar-mobile-nav-slider");

  function drillDown(tier) {
    if (slider) slider.style.transform = `translateX(-${(tier * 100) / 3}%)`;
  }

  function populateTier3(serviceKey) {
    const list = document.getElementById("park-haven-navbar-tier-3-list");
    const title = document.getElementById("park-haven-navbar-tier-3-title");
    const data = servicesData[serviceKey];
    if (!list || !title || !data) return;

    title.textContent = data.title;
    list.innerHTML = "";
    data.subs.forEach((sub) => {
      const a = document.createElement("a");
      a.href = "#";
      a.className =
        "block py-5 border-b border-white/10 text-white/70 font-semibold text-lg";
      a.textContent = sub.name;
      list.appendChild(a);
    });
    drillDown(2);
  }

  function populateTier2(type) {
    const list = document.getElementById("park-haven-navbar-tier-2-list");
    const title = document.getElementById("park-haven-navbar-tier-2-title");
    if (!list || !title) return;
    list.innerHTML = "";

    if (type === "services") {
      title.textContent = "Services";
      Object.keys(servicesData).forEach((key) => {
        const s = servicesData[key];
        const btn = document.createElement("button");
        btn.className =
          "w-full flex items-center justify-between py-5 border-b border-white/10 text-white font-bold text-lg text-left";
        btn.innerHTML = `<span>${s.title}</span><span class="material-symbols-outlined text-secondary-accent">chevron_right</span>`;
        btn.onclick = () => {
          if (key === "healthy-start") {
            window.location.href = "#";
          } else {
            populateTier3(key);
          }
        };
        list.appendChild(btn);
      });
    } else if (extraData[type]) {
      const data = extraData[type];
      title.textContent = data.title;
      data.links.forEach((link) => {
        const a = document.createElement("a");
        a.href = "#";
        a.className =
          "flex items-center gap-4 py-5 border-b border-white/10 text-white font-bold text-lg";
        a.innerHTML = `<span class="material-symbols-outlined text-secondary-accent">${link.icon}</span><span>${link.name}</span>`;
        list.appendChild(a);
      });
    }
    drillDown(1);
  }

  // Event Listeners
  const mobileToggle = document.getElementById(
    "park-haven-navbar-mobile-toggle",
  );
  const mobileClose = document.getElementById("park-haven-navbar-mobile-close");
  const mobileOverlay = document.getElementById(
    "park-haven-navbar-mobile-overlay",
  );

  if (mobileToggle) {
    mobileToggle.addEventListener("click", () => {
      mobileOverlay.classList.add("active");
      document.body.classList.add("park-haven-navbar-mobile-menu-open");
      drillDown(0);
    });
  }

  if (mobileClose) {
    mobileClose.addEventListener("click", () => {
      mobileOverlay.classList.remove("active");
      document.body.classList.remove("park-haven-navbar-mobile-menu-open");
    });
  }

  document
    .getElementById("park-haven-navbar-mobile-services-btn")
    ?.addEventListener("click", () => populateTier2("services"));
  document
    .getElementById("park-haven-navbar-mobile-about-btn")
    ?.addEventListener("click", () => populateTier2("about"));
  document
    .getElementById("park-haven-navbar-mobile-forms-btn")
    ?.addEventListener("click", () => populateTier2("forms"));
  document
    .getElementById("park-haven-navbar-mobile-back-to-main")
    ?.addEventListener("click", () => drillDown(0));
  document
    .getElementById("park-haven-navbar-mobile-back-to-tier-2")
    ?.addEventListener("click", () => drillDown(1));

  // Initialization
  window.addEventListener("DOMContentLoaded", () => {
    initDesktopNav();
  });
})();
// Hero slider js
const parkHavenSlider = (function () {
  const state = {
    current: 0,
    slides: [],
    dots: [],
  };

  function init() {
    state.slides = document.querySelectorAll(".park-haven-hero-slider-slide");
    state.dots = document.querySelectorAll(".park-haven-hero-slider-dot");

    if (state.slides.length === 0) return;

    // Initial UI state setup
    showSlide(0);
  }

  function showSlide(index) {
    // Bounds checking
    if (index >= state.slides.length) index = 0;
    if (index < 0) index = state.slides.length - 1;

    // UI Reset
    state.slides.forEach((s) => s.classList.remove("active"));
    state.dots.forEach((d) => d.classList.remove("active"));

    // UI Activation
    state.slides[index].classList.add("active");
    state.dots[index].classList.add("active");

    state.current = index;
  }

  return {
    init,
    next: () => {
      showSlide(state.current + 1);
    },
    prev: () => {
      showSlide(state.current - 1);
    },
    goTo: (index) => {
      showSlide(index);
    },
  };
})();

// Map global handlers for button clicks
window.parkHavenGoToSlide = (index) => parkHavenSlider.goTo(index);
window.parkHavenNextSlide = () => parkHavenSlider.next();
window.parkHavenPrevSlide = () => parkHavenSlider.prev();

document.addEventListener("DOMContentLoaded", parkHavenSlider.init);

// Main service section js
document.addEventListener("DOMContentLoaded", function () {
  (function initParkHavenServiceSlider() {
    const servicesData = [
      {
        title:
          "Dental <span class=' bg-clip-text text-secondary'>Implants</span>",
        description:
          "We believe that everyone deserves to have a smile that looks and feels great. We offer a variety of cosmetic dentistry services, and our team will help you choose the right treatment to get started.",
        image: "./images/implant-new.png",
      },
      {
        title:
          "Cosmetic <span class=' bg-clip-text text-secondary'> Dentistry</span>",
        description:
          "Crafting brilliant smiles that enhance your natural beauty. Our digital smile design protocol allows you to preview your results before we begin.",
        image: "./images/cosmetic-new.png",
      },
      {
        title:
          "Invisalign",
        description:
          "Clear aligner therapy powered by 3D predictive modeling. Straighter teeth faster, with zero metal and maximum comfort throughout the journey.",
        image: "./images/invisalign-new.png",
      },
      {
        title:
          "Dental <span class=' bg-clip-text text-secondary'> Crowns</span>",
        description:
          "Creating a positive foundation for lifelong oral health. Our specialized pediatric team uses a child-friendly approach to ensure comfort and confidence.",
        image: "./images/dental-crown.png",
      },
      {
        title:
          "Kids <span class=' bg-clip-text text-secondary'> Dentistry</span>",
        description:
          "Precision cleaning using airflow technology. Maintain a healthy biome and prevent gum disease with our high-frequency maintenance protocols.",
        image: "./images/kids-dentistry.png",
      },
      {
        title:
          "Hygiene <span class=' bg-clip-text text-secondary'> Services</span>",
        description:
          "Complex procedures made simple through advanced imaging and minimally invasive techniques. Faster recovery times for wisdom teeth and beyond.",
        image: "./images/hygiene.png",
      },
    ];

    let currentIdx = 0;
    let isTransitioning = false;

    const textLayer = document.getElementById("service-text-content");
    const iconLayer = document.getElementById("main-service-icon");
    const dotsContainer = document.getElementById("pagination-dots-container");
    const prevBtn = document.getElementById("prev-slide-btn");
    const nextBtn = document.getElementById("next-slide-btn");

    function createDots() {
      dotsContainer.innerHTML = "";
      servicesData.forEach((_, idx) => {
        const btn = document.createElement("button");
        btn.className = `w-3.5 h-3.5 rounded-full transition-all hover:bg-primary/50 ${idx === currentIdx ? "bg-secondary scale-125 shadow-[0_0_10px_rgba(76,107,231,0.5)]" : "bg-white/20"}`;
        btn.setAttribute("aria-label", `Go to slide ${idx + 1}`);
        btn.onclick = () => goToSlide(idx);
        dotsContainer.appendChild(btn);
      });
    }

    function updateDisplay() {
      if (isTransitioning) return;
      isTransitioning = true;

      const data = servicesData[currentIdx];

      // Animate Out
      textLayer.classList.add("opacity-0", "translate-y-4");
      iconLayer.classList.add("opacity-0", "scale-90", "rotate-[-5deg]");

      setTimeout(() => {
        // Update Content
        document.getElementById("service-title").innerHTML = data.title;
        document.getElementById("service-description").innerText =
          data.description;
        iconLayer.src = data.image;

        // Update Dots
        Array.from(dotsContainer.children).forEach((dot, idx) => {
          dot.className = `w-3.5 h-3.5 rounded-full transition-all hover:bg-primary/50 ${idx === currentIdx ? "bg-secondary scale-125 shadow-[0_0_10px_rgba(76,107,231,0.5)]" : "bg-white/20"}`;
        });

        // Animate In
        setTimeout(() => {
          textLayer.classList.remove("opacity-0", "translate-y-4");
          iconLayer.classList.remove("opacity-0", "scale-90", "rotate-[-5deg]");
          isTransitioning = false;
        }, 50);
      }, 400);
    }

    function nextSlide() {
      if (isTransitioning) return;
      currentIdx = (currentIdx + 1) % servicesData.length;
      updateDisplay();
    }

    function prevSlide() {
      if (isTransitioning) return;
      currentIdx = (currentIdx - 1 + servicesData.length) % servicesData.length;
      updateDisplay();
    }

    function goToSlide(idx) {
      if (isTransitioning || idx === currentIdx) return;
      currentIdx = idx;
      updateDisplay();
    }

    // Attach event listeners
    nextBtn.addEventListener("click", nextSlide);
    prevBtn.addEventListener("click", prevSlide);

    createDots();
  })();
});

// Gallery js
const galleryApp = (function () {
  let current = 0;
  const total = 5;
  const data = [
    {
      title: "Main Reception",
      img: "images/gallery/16.png",
    },
    {
      title: "Premium Lounge",
      img: "images/gallery/13.png",
    },
    {
      title: "Advanced Technology",
      img: "images/gallery/7.png",
    },
    {
      title: "Stress-Free Environment",
      img: "images/gallery/14.png",
    },
    {
      title: "Hygiene Guaranteed",
      img: "images/gallery/2.png",
    },
  ];

  function update() {
    for (let i = 0; i < total; i++) {
      const slide = document.getElementById(`gallery-slide-${i}`);
      const dot = document.getElementById(`dot-${i}`);

      // Reset classes
      slide.classList.remove(
        "active",
        "prev",
        "next",
        "hidden-left",
        "hidden-right",
      );
      dot.classList.remove("active");

      if (i === current) {
        slide.classList.add("active");
        dot.classList.add("active");
      } else if (i === (current - 1 + total) % total) {
        slide.classList.add("prev");
      } else if (i === (current + 1) % total) {
        slide.classList.add("next");
      } else {
        // Determine if it should hide left or right based on shortest path
        let diff = i - current;
        if (diff > total / 2) diff -= total;
        if (diff < -total / 2) diff += total;

        if (diff > 0) {
          slide.classList.add("hidden-right");
        } else {
          slide.classList.add("hidden-left");
        }
      }
    }
  }

  return {
    next: () => {
      current = (current + 1) % total;
      update();
    },
    prev: () => {
      current = (current - 1 + total) % total;
      update();
    },
    goTo: (index) => {
      current = index;
      update();
    },
    openModal: (index) => {
      const modal = document.getElementById("gallery-modal");
      const modalImg = document.getElementById("modal-image");
      const modalTitle = document.getElementById("modal-title");

      modalImg.src = data[index].img;
      modalTitle.innerText = data[index].title;

      modal.classList.add("active");
      document.body.style.overflow = "hidden";
    },
    closeModal: () => {
      const modal = document.getElementById("gallery-modal");
      modal.classList.remove("active");
      document.body.style.overflow = "";
    },
    init: () => {
      update();
      // Keyboard navigation
      window.addEventListener("keydown", (e) => {
        if (e.key === "ArrowRight") galleryApp.next();
        if (e.key === "ArrowLeft") galleryApp.prev();
        if (e.key === "Escape") galleryApp.closeModal();
      });
    },
  };
})();

document.addEventListener("DOMContentLoaded", galleryApp.init);

// TRANSFORMATION SECTION JS
function initParkHavenTransformations() {
  const sliders = document.querySelectorAll(
    ".park-haven-transformation-section-slider",
  );

  sliders.forEach((slider) => {
    const handle = slider.querySelector(
      ".park-haven-transformation-section-slider-handle",
    );
    const beforeClip = slider.querySelector(
      ".park-haven-transformation-section-before-clip",
    );
    const beforeImage = beforeClip.querySelector("img");

    if (!handle || !beforeClip) return;

    const updateSliderPosition = (clientX) => {
      const rect = slider.getBoundingClientRect();
      let x = clientX - rect.left;

      // Clamp bounds
      if (x < 0) x = 0;
      if (x > rect.width) x = rect.width;

      const percentage = (x / rect.width) * 100;
      handle.style.left = `${percentage}%`;
      beforeClip.style.width = `${percentage}%`;

      // Keep before image fixed relative to the container while its clip changes
      // This ensures the two images align perfectly
      beforeImage.style.width = `${rect.width}px`;
    };

    const onPointerMove = (e) => {
      if (e.buttons === 1 || e.type === "touchmove") {
        const clientX = e.clientX || (e.touches && e.touches[0].clientX);
        updateSliderPosition(clientX);
      }
    };

    const onPointerDown = (e) => {
      const clientX = e.clientX || (e.touches && e.touches[0].clientX);
      updateSliderPosition(clientX);
    };

    // Set initial image width correctly on mount
    const resizeObserver = new ResizeObserver((entries) => {
      for (let entry of entries) {
        beforeImage.style.width = `${entry.contentRect.width}px`;
      }
    });
    resizeObserver.observe(slider);

    // Event Listeners
    slider.addEventListener("mousemove", onPointerMove);
    slider.addEventListener("mousedown", onPointerDown);
    slider.addEventListener("touchstart", onPointerDown, { passive: true });
    slider.addEventListener("touchmove", onPointerMove, { passive: true });
  });

  // Micro-feedback for buttons
  document.querySelectorAll("button, a").forEach((el) => {
    el.addEventListener("click", function () {
      this.classList.add("scale-95");
      setTimeout(() => this.classList.remove("scale-95"), 150);
    });
  });
}

document.addEventListener("DOMContentLoaded", initParkHavenTransformations);

// Team slider js
(function () {
  document.addEventListener("DOMContentLoaded", () => {
    const container = document.getElementById("park-haven-team-section");
    if (!container) return;

    const track = container.querySelector("#slider-track");
    const prevBtn = container.querySelector("#prev-btn");
    const nextBtn = container.querySelector("#next-btn");
    const fraction = container.querySelector("#fraction-pagination");
    const progress = container.querySelector("#progress-bar");
    const cards = container.querySelectorAll(
      ".park-haven-team-section-team-card",
    );

    // Mouse Tracking Prismatic Effect
    cards.forEach((card) => {
      const img = card.querySelector(".park-haven-team-section-prismatic-mask");
      if (!img) return;

      card.addEventListener("mousemove", (e) => {
        const { left, top, width, height } = card.getBoundingClientRect();
        const x = (e.clientX - left) / width;
        const y = (e.clientY - top) / height;

        img.style.transformOrigin = `${x * 100}% ${y * 100}%`;
      });

      card.addEventListener("mouseleave", () => {
        img.style.transformOrigin = "center center";
      });
    });

    // Slider Logic
    const updateUI = () => {
      const scrollLeft = track.scrollLeft;
      const maxScroll = track.scrollWidth - track.clientWidth;

      const itemsVisible = window.innerWidth >= 768 ? 3 : 1;
      const totalItems = cards.length;
      const totalPages = Math.max(1, totalItems - itemsVisible + 1);

      const itemWidth = cards[0].offsetWidth + 24; // width + gutter
      const currentPage = Math.min(
        totalPages,
        Math.floor(scrollLeft / itemWidth) + 1,
      );

      fraction.innerText = `${currentPage.toString().padStart(2, "0")}/${totalPages.toString().padStart(2, "0")}`;
      progress.style.width = `${(currentPage / totalPages) * 100}%`;
    };

    nextBtn.addEventListener("click", () => {
      const itemWidth = cards[0].offsetWidth + 24;
      track.scrollBy({ left: itemWidth, behavior: "smooth" });
    });

    prevBtn.addEventListener("click", () => {
      const itemWidth = cards[0].offsetWidth + 24;
      track.scrollBy({ left: -itemWidth, behavior: "smooth" });
    });

    track.addEventListener("scroll", updateUI);
    window.addEventListener("resize", updateUI);

    // Initial call
    setTimeout(updateUI, 100);
  });
})();

// Testimonials JS
function initParkHavenReviewsSlider() {
  const container = document.getElementById("park-haven-slider");
  const prevBtn = document.getElementById("park-haven-prev");
  const nextBtn = document.getElementById("park-haven-next");
  const dotsContainer = document.getElementById("park-haven-dots");
  const dots = dotsContainer.querySelectorAll(
    ".park-haven-reviews-section__dot",
  );
  const totalSlides = dots.length;
  let currentSlide = 0;

  function updateSlider() {
    container.style.transform = `translateX(-${currentSlide * 100}%)`;

    dots.forEach((dot, idx) => {
      if (idx === currentSlide) {
        dot.classList.add("park-haven-reviews-section__dot--active");
      } else {
        dot.classList.remove("park-haven-reviews-section__dot--active");
      }
    });
  }

  function nextSlide() {
    currentSlide = (currentSlide + 1) % totalSlides;
    updateSlider();
  }

  function prevSlide() {
    currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
    updateSlider();
  }

  // Click Events
  nextBtn.addEventListener("click", nextSlide);
  prevBtn.addEventListener("click", prevSlide);

  // Dot Navigation
  dots.forEach((dot, idx) => {
    dot.addEventListener("click", () => {
      currentSlide = idx;
      updateSlider();
    });
  });

  // Swipe Support
  let startX;
  container.addEventListener(
    "touchstart",
    (e) => {
      startX = e.touches[0].clientX;
    },
    { passive: true },
  );

  container.addEventListener(
    "touchend",
    (e) => {
      const endX = e.changedTouches[0].clientX;
      const deltaX = startX - endX;
      if (Math.abs(deltaX) > 50) {
        if (deltaX > 0) nextSlide();
        else prevSlide();
      }
    },
    { passive: true },
  );
}

// Initialize on DOM load
document.addEventListener("DOMContentLoaded", initParkHavenReviewsSlider);
