import { useState, useEffect } from 'react'; import { useRouter } from 'next/router'; import Layout from '../components/Layout'; import PermissionIndicator from '../components/PermissionIndicator'; export default function Collections() { const router = useRouter(); // Mock user data for now const user = { email: 'me@randallstillwell.com', role: 'user' }; const [collections, setCollections] = useState([]); const [loading, setLoading] = useState(true); const [showCreateModal, setShowCreateModal] = useState(false); const [editingCollection, setEditingCollection] = useState(null); const [searchQuery, setSearchQuery] = useState(''); const [sortBy, setSortBy] = useState('name'); // name, value, cardCount, createdAt const [newCollection, setNewCollection] = useState({ name: '', description: '', isPublic: false, image: '', tags: [] }); const [showSuccessModal, setShowSuccessModal] = useState(false); const [createdCollection, setCreatedCollection] = useState(null); const fetchCollections = async () => { try { const response = await fetch('/api/collections'); if (response.ok) { const data = await response.json(); // Fetch thumbnail cards for each collection const collectionsWithThumbnails = await Promise.all( data.map(async (collection) => { try { const thumbnailResponse = await fetch(`/api/collections/${collection.id}/thumbnails`); const thumbnails = thumbnailResponse.ok ? await thumbnailResponse.json() : []; return { ...collection, thumbnails }; } catch (error) { console.error(`Error fetching thumbnails for collection ${collection.id}:`, error); return { ...collection, thumbnails: [] }; } }) ); setCollections(collectionsWithThumbnails); } else { console.error('Failed to fetch collections'); setCollections([]); // Empty array on error } } catch (error) { console.error('Error fetching collections:', error); setCollections([]); // Empty array on error } finally { setLoading(false); } }; useEffect(() => { fetchCollections(); }, []); const sortOptions = [ { value: 'name', label: 'Name (A-Z)' }, { value: 'value', label: 'Value (High to Low)' }, { value: 'cardCount', label: 'Card Count (High to Low)' }, { value: 'createdAt', label: 'Date Created (Newest)' } ]; const sortCollections = (collections, sortBy) => { return [...collections].sort((a, b) => { switch (sortBy) { case 'name': return a.name.localeCompare(b.name); case 'value': return b.value - a.value; case 'cardCount': return b.cardCount - a.cardCount; case 'createdAt': return new Date(b.createdAt) - new Date(a.createdAt); default: return 0; } }); }; const filteredCollections = collections.filter(collection => { const matchesSearch = collection.name.toLowerCase().includes(searchQuery.toLowerCase()) || collection.description.toLowerCase().includes(searchQuery.toLowerCase()); return matchesSearch; }); const sortedCollections = sortCollections(filteredCollections, sortBy); const handleCreateCollection = async () => { try { const response = await fetch('/api/collections', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: newCollection.name, description: newCollection.description, isPublic: newCollection.isPublic, image: newCollection.image, tags: newCollection.tags }) }); if (response.ok) { const createdCollection = await response.json(); setCreatedCollection(createdCollection); setShowCreateModal(false); setShowSuccessModal(true); // Reset form setNewCollection({ name: '', description: '', isPublic: false, image: '', tags: [] }); // Refresh collections list fetchCollections(); } else { const error = await response.json(); alert(error.error || 'Failed to create collection'); } } catch (error) { console.error('Error creating collection:', error); alert('Network error. Please try again.'); } }; const handleUpdateCollection = () => { setCollections(collections.map(c => c.id === editingCollection.id ? editingCollection : c )); setEditingCollection(null); }; const handleDeleteCollection = (id) => { if (confirm('Are you sure you want to delete this collection?')) { setCollections(collections.filter(c => c.id !== id)); } }; const formatCurrency = (amount) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount); }; const formatDate = (dateString) => { return new Date(dateString).toLocaleDateString(); }; const CollectionThumbnail = ({ collection }) => { const { thumbnails = [], image } = collection; // If collection has a custom hero image, use it if (image) { return (
{collection.name}
); } // If no thumbnails available, show placeholder if (!thumbnails || thumbnails.length === 0) { return (
📦

No cards yet

); } // Show main card (rarest) and grid of 4 others const mainCard = thumbnails[0]; // Rarest card const gridCards = thumbnails.slice(1, 5); // Next 4 cards return (
{/* Main card (rarest) - takes up 2/3 of the space */}
{mainCard ? (
{mainCard.name} {/* Rarity glow effect */}
{/* Card name overlay */}

{mainCard.name}

{mainCard.rarity}

) : (
No image
)}
{/* Grid of 4 other cards - takes up 1/3 of the space */}
{Array.from({ length: 4 }).map((_, index) => { const card = gridCards[index]; return (
{card ? (
{card.name} {/* Subtle rarity glow for grid cards */}
) : (
+
)}
); })}
); }; if (loading) { return (
); } return ( {/* Header */}

My Collections

Organize and manage your card collections

{/* Filters and Search */}
setSearchQuery(e.target.value)} />
{/* Collections Grid */}
{sortedCollections.length === 0 ? (
📦

{searchQuery ? 'No collections found' : 'No collections yet'}

{searchQuery ? 'Try adjusting your search terms' : 'Create your first collection to get started' }

{!searchQuery && ( )}
) : (
{sortedCollections.map(collection => (
router.push(`/collection/${collection.id}`)} > {/* Thumbnail Section */} {/* Collection Info */}
{/* Header with name and actions */}

{collection.name}

{collection.description && (

{collection.description}

)}
{/* Compact Stats */}
{collection.cardCount} cards {formatCurrency(collection.value)}
{formatDate(collection.createdAt)}
{/* Tags */} {collection.tags && collection.tags.length > 0 && (
{collection.tags.slice(0, 2).map(tag => ( {tag} ))} {collection.tags.length > 2 && ( +{collection.tags.length - 2} )}
)}
))}
)}
{/* Create Collection Modal */} {showCreateModal && (

Create New Collection

setNewCollection({...newCollection, name: e.target.value})} placeholder="Enter collection name" />