import { useEffect, useState } from 'react' import { createPortal } from 'react-dom' import { ChevronLeft, ChevronRight, X } from 'lucide-react' import styles from './ImageLightbox.module.css' interface ImageLightboxProps { open: boolean images: string[] initialIndex?: number alt?: string onClose: () => void } export function ImageLightbox({ open, images, initialIndex = 0, alt = 'Product image', onClose, }: ImageLightboxProps) { const [index, setIndex] = useState(initialIndex) const [mounted, setMounted] = useState(open) useEffect(() => { if (open) { setMounted(true) setIndex(initialIndex) } }, [open, initialIndex]) useEffect(() => { if (!open) return const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose() if (event.key === 'ArrowLeft') setIndex((current) => Math.max(0, current - 1)) if (event.key === 'ArrowRight') { setIndex((current) => Math.min(images.length - 1, current + 1)) } } document.addEventListener('keydown', onKey) document.body.style.overflow = 'hidden' return () => { document.removeEventListener('keydown', onKey) document.body.style.overflow = '' } }, [open, images.length, onClose]) useEffect(() => { if (!mounted || open) return const timer = setTimeout(() => setMounted(false), 200) return () => clearTimeout(timer) }, [mounted, open]) if (!mounted || images.length === 0) return null const current = images[index] ?? images[0] const hasPrev = index > 0 const hasNext = index < images.length - 1 return createPortal(
event.stopPropagation()}> {hasPrev && ( )}
{`${alt}
{index + 1} / {images.length}
{hasNext && ( )}
{images.length > 1 && (
event.stopPropagation()}> {images.map((src, imageIndex) => ( ))}
)}
, document.body, ) }