"use client" import { useState } from "react" import Link from "next/link" import Image from "next/image" import { Button } from "@/components/ui/button" import { GalleryModal } from "@/components/gallery-modal" import { Search } from "lucide-react" interface GalleryMasonryProps { generations: any[] className?: string enableInfiniteScroll?: boolean } export function GalleryMasonry({ generations, className, enableInfiniteScroll = true }: GalleryMasonryProps) { const [selectedGen, setSelectedGen] = useState(null) const [displayGenerations, setDisplayGenerations] = useState(generations) const [cursor, setCursor] = useState(generations.length > 0 ? generations[generations.length - 1].id : null) const [isLoading, setIsLoading] = useState(false) const [hasMore, setHasMore] = useState(enableInfiniteScroll) const loadMore = async () => { if (!enableInfiniteScroll || !cursor || isLoading || !hasMore) return setIsLoading(true) try { const res = await fetch(`/api/gallery?cursor=${cursor}&limit=20`) if (!res.ok) throw new Error("Failed to fetch") const data = await res.json() if (data.data.length === 0) { setHasMore(false) } else { setDisplayGenerations(prev => [...prev, ...data.data]) setCursor(data.nextCursor) if (!data.nextCursor) setHasMore(false) } } catch (error) { console.error("Error loading more:", error) } finally { setIsLoading(false) } } return ( <> {/* Masonry Layout using Columns */}
{displayGenerations.map((gen) => (
setSelectedGen(gen)} > {/* Username Overlay */}
@{gen.user?.username || "user"}
{gen.prompt} {/* Hover Overlay */}

"{gen.prompt}"

))}
{/* Loading / End of List Indicators */}
{isLoading && (
Loading More...
)} {!isLoading && hasMore && ( )} {!hasMore && displayGenerations.length > 0 && (

You've reached the end

)}
{/* Intersection Element for auto-loading */} {hasMore && !isLoading && (
{ if (node) { const observer = new IntersectionObserver( (entries) => { if (entries[0].isIntersecting) { loadMore(); } }, { threshold: 0.1, rootMargin: "200px" } ); observer.observe(node); // Cleanup happens automatically when node unmounts usually, but for strictness we rely on React lifecycle if we used useEffect. // Since this is a ref callback, it's slightly different. A useEffect is safer. } }} className="h-4 w-full" /> )} {generations.length === 0 && (

No Masterpieces Yet

)} setSelectedGen(null)} generation={selectedGen} /> ) }