import { useEffect, useMemo, useRef, useState } from 'react'

// Lightbox state tracked by photo id, not index — the list can reorder or
// shrink underneath an open lightbox. While open, the visible list is FROZEN
// to the ids present at open time (mapped to live photo objects, so votes
// still update the open photo): voting a photo out of the active filter must
// not yank it from under the viewer. Filters re-apply on close. If the open
// photo disappears entirely (deleted), the lightbox closes for good.
export default function useLightbox(photos) {
  const [openId, setOpenId] = useState(null)
  const frozen = useRef(null)

  const byId = useMemo(() => new Map(photos.map((p) => [p.id, p])), [photos])
  const view =
    openId && frozen.current ? frozen.current.map((id) => byId.get(id)).filter(Boolean) : photos
  const index = openId ? view.findIndex((p) => p.id === openId) : -1

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

  const open = (id) => {
    if (!frozen.current) frozen.current = photos.map((p) => p.id)
    setOpenId(id)
  }

  return {
    index,
    view,
    openAt: (i) => view[i] && open(view[i].id),
    show: (id) => open(id),
    close: () => {
      frozen.current = null
      setOpenId(null)
    },
  }
}
