"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import { Mountain, Maximize2, X, ChevronLeft, ChevronRight } from "lucide-react";
interface TripImage {
id: string;
url: string;
caption: string | null;
}
export function ImageGallery({ images }: { images: TripImage[] }) {
const [activeIndex, setActiveIndex] = useState(0);
const [lightboxOpen, setLightboxOpen] = useState(false);
const hasMultiple = images.length > 1;
function showPrev() {
setActiveIndex((i) => (i - 1 + images.length) % images.length);
}
function showNext() {
setActiveIndex((i) => (i + 1) % images.length);
}
// Saat lightbox terbuka: kunci scroll body + dukung keyboard (Esc tutup,
// panah kiri/kanan untuk ganti foto).
useEffect(() => {
if (!lightboxOpen) return;
function onKey(e: KeyboardEvent) {
// Logika prev/next di-inline (bukan panggil showPrev/showNext) supaya
// effect tidak bergantung pada fungsi yang dibuat ulang tiap render.
if (e.key === "Escape") setLightboxOpen(false);
else if (e.key === "ArrowLeft") {
setActiveIndex((i) => (i - 1 + images.length) % images.length);
} else if (e.key === "ArrowRight") {
setActiveIndex((i) => (i + 1) % images.length);
}
}
document.addEventListener("keydown", onKey);
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = prevOverflow;
};
}, [lightboxOpen, images.length]);
if (images.length === 0) {
return (
);
}
const activeImage = images[activeIndex];
return (
{/* Main Image — klik untuk lihat ukuran penuh */}
{/* Thumbnails */}
{hasMultiple && (
{images.map((img, i) => (
))}
)}
{/* Lightbox — penampil foto ukuran penuh */}
{lightboxOpen && (
{/* Top bar */}
{activeIndex + 1} / {images.length}
{/* Area gambar — klik latar untuk menutup */}
setLightboxOpen(false)}
>
e.stopPropagation()}
>
{hasMultiple && (
<>
>
)}
{activeImage.caption && (
{activeImage.caption}
)}
{/* Thumbnail strip di dalam lightbox */}
{hasMultiple && (
{images.map((img, i) => (
))}
)}
)}
);
}