import { useEffect, useState } from 'react'

// Lightbox state tracked by photo id, not index — the list can reorder
// (polling refetch) or shrink (filter change, delete) underneath an open
// lightbox. When the open photo leaves the list, close for good — otherwise
// the lightbox would pop back open when the photo returns to the list.
export default function useLightbox(photos) {
  const [openId, setOpenId] = useState(null)
  const index = openId ? photos.findIndex((p) => p.id === openId) : -1

  useEffect(() => {
    if (openId && index < 0) setOpenId(null)
  }, [openId, index])

  return {
    index,
    // Bounds-safe: callers may hold a stale index (the list can shrink
    // between render and dispatch).
    openAt: (i) => photos[i] && setOpenId(photos[i].id),
    show: (id) => setOpenId(id),
    close: () => setOpenId(null),
  }
}
