const navLinks = document.querySelectorAll(".nav-link");
const currentPath = window.location.pathname.split("/").pop() || "index.html";

const pageMap = {
  "index.html": "home",
  "": "home",
  "about.html": "about",
  "menu.html": "menu",
  "catering.html": "catering",
  "contact.html": "contact",
};

const activePage = pageMap[currentPath] || "home";

if ("serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("./sw.js").catch(() => {});
  });
}

navLinks.forEach((link) => {
  link.classList.toggle("is-active", link.dataset.page === activePage);
});

const gallery = document.querySelector("[data-gallery]");

if (gallery) {
  const image = gallery.querySelector("[data-gallery-image]");
  const status = gallery.querySelector("[data-gallery-status]");
  const price = gallery.querySelector("[data-gallery-price]");
  const prevButton = gallery.querySelector("[data-gallery-prev]");
  const nextButton = gallery.querySelector("[data-gallery-next]");
  const thumbs = Array.from(gallery.querySelectorAll("[data-gallery-thumb]"));
  const slides = thumbs.map((thumb, index) => ({
    src: thumb.querySelector("img")?.getAttribute("src") || "",
    alt: "Tasty Eats food slideshow image " + (index + 1),
    price: thumb.dataset.price || "",
  }));
  let currentIndex = 0;

  const renderSlide = (index) => {
    currentIndex = (index + slides.length) % slides.length;
    const currentSlide = slides[currentIndex];

    if (image && currentSlide) {
      image.src = currentSlide.src;
      image.alt = currentSlide.alt;
    }

    if (status) {
      status.textContent = (currentIndex + 1) + " / " + slides.length;
    }

    if (price) {
      price.textContent = currentSlide.price;
      price.classList.toggle("is-hidden", !currentSlide.price);
    }

    thumbs.forEach((thumb, thumbIndex) => {
      const isActive = thumbIndex === currentIndex;
      thumb.classList.toggle("is-active", isActive);
      if (isActive) {
        thumb.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
      }
    });
  };

  prevButton?.addEventListener("click", () => {
    renderSlide(currentIndex - 1);
  });

  nextButton?.addEventListener("click", () => {
    renderSlide(currentIndex + 1);
  });

  thumbs.forEach((thumb, index) => {
    thumb.addEventListener("click", () => {
      renderSlide(index);
    });
  });

  renderSlide(0);
}
