import React, { useState, useEffect, useRef, useCallback } from 'react'; import { AlertCircle, Loader2 } from 'lucide-react'; import { getApiUrl } from '../config'; import GalleryCard from './GalleryCard'; const CLIPS_PER_PAGE = 20; export default function Gallery() { const [clips, setClips] = useState([]); const [loading, setLoading] = useState(true); const [loadingMore, setLoadingMore] = useState(false); const [error, setError] = useState(null); const [hasMore, setHasMore] = useState(true); const [offset, setOffset] = useState(0); const loaderRef = useRef(null); const fetchClips = useCallback(async (currentOffset = 0, append = false) => { try { if (currentOffset === 0) setLoading(true); else setLoadingMore(true); const res = await fetch( getApiUrl(`/api/gallery/clips?limit=${CLIPS_PER_PAGE}&offset=${currentOffset}`) ); if (!res.ok) throw new Error('Failed to fetch clips'); const data = await res.json(); const newClips = data.clips || []; if (append) { setClips(prev => [...prev, ...newClips]); } else { setClips(newClips); } setHasMore(data.has_more ?? newClips.length === CLIPS_PER_PAGE); setOffset(currentOffset + newClips.length); } catch (err) { setError(err.message); } finally { setLoading(false); setLoadingMore(false); } }, []); // Initial load useEffect(() => { fetchClips(0, false); }, [fetchClips]); // Infinite scroll observer useEffect(() => { if (!hasMore || loadingMore || loading) return; const observer = new IntersectionObserver( (entries) => { if (entries[0].isIntersecting && hasMore && !loadingMore) { fetchClips(offset, true); } }, { rootMargin: '200px', threshold: 0.1 } ); const node = loaderRef.current; if (node) { observer.observe(node); } return () => { if (node) { observer.unobserve(node); } }; }, [hasMore, loadingMore, loading, offset, fetchClips]); if (loading) { return (
Loading your viral history...
Error loading gallery: {error}
Library
No clips found yet.
Process some videos to populate your gallery!