const gallery = document.querySelectorAll(".gallery img");
const lightbox = document.getElementById("lightbox");
const lightboxImg = document.getElementById("lightbox-img");
const closeBtn = document.getElementById("close");
const navLeft = document.getElementById("nav-left");
const navRight = document.getElementById("nav-right");
let currentIndex = 0;

function showImage(index) {
  lightboxImg.src = gallery[index].src;
  currentIndex = index;
  lightbox.classList.remove("hidden");
}

function showPrevImage() {
  currentIndex = (currentIndex - 1 + gallery.length) % gallery.length;
  showImage(currentIndex);
}

function showNextImage() {
  currentIndex = (currentIndex + 1) % gallery.length;
  showImage(currentIndex);
}

gallery.forEach((img, index) => {
  img.addEventListener("click", () => showImage(index));
});

closeBtn.addEventListener("click", () => lightbox.classList.add("hidden"));
navLeft.addEventListener("click", showPrevImage);
navRight.addEventListener("click", showNextImage);

document.addEventListener("keydown", (e) => {
  if (e.key === "Escape") lightbox.classList.add("hidden");
  if (e.key === "ArrowLeft") showPrevImage();
  if (e.key === "ArrowRight") showNextImage();
});

// ---- SWIPE ----
let touchStartX = 0;
let touchEndX = 0;

lightbox.addEventListener("touchstart", (e) => {
  touchStartX = e.changedTouches[0].screenX;
}, false);

lightbox.addEventListener("touchend", (e) => {
  touchEndX = e.changedTouches[0].screenX;
  handleSwipe();
}, false);

function handleSwipe() {
  let diff = touchEndX - touchStartX;
  if (Math.abs(diff) > 50) {
    if (diff > 0) {
      showPrevImage(); // swipe höger
    } else {
      showNextImage(); // swipe vänster
    }
  }
}

