/* eslint-disable @next/next/no-img-element -- External card image URLs; next/image migration is out of scope. */ import { useState, useEffect } from 'react'; import { VOCAB } from '../lib/collection-vocabulary.js'; import { Modal, SearchBar, Button } from './ui'; export default function CollectionSelectionModal({ isOpen, onClose, cards, onAddToCollections, }) { const [collections, setCollections] = useState([]); const [selectedCollections, setSelectedCollections] = useState([]); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [searchQuery, setSearchQuery] = useState(''); const [prevIsOpen, setPrevIsOpen] = useState(isOpen); if (isOpen && !prevIsOpen) { setPrevIsOpen(true); setSelectedCollections([]); setSearchQuery(''); } else if (!isOpen && prevIsOpen) { setPrevIsOpen(false); } useEffect(() => { if (!isOpen) return; const fetchCollections = async () => { setLoading(true); try { const response = await fetch('/api/collections?excludeSystem=true'); if (response.ok) { const data = await response.json(); setCollections(Array.isArray(data) ? data : data.collections || []); } else { console.error('Failed to fetch collections:', response.status, response.statusText); setCollections([]); } } catch (error) { console.error('Error fetching collections:', error); setCollections([]); } finally { setLoading(false); } }; fetchCollections(); }, [isOpen]); const handleCollectionToggle = (collectionId) => { setSelectedCollections((prev) => prev.includes(collectionId) ? prev.filter((id) => id !== collectionId) : [...prev, collectionId] ); }; const getFilteredCollections = () => { if (!searchQuery.trim()) return collections; return collections.filter( (collection) => collection.name.toLowerCase().includes(searchQuery.toLowerCase()) || collection.description?.toLowerCase().includes(searchQuery.toLowerCase()) ); }; const handleSelectAll = () => { const filteredCollections = getFilteredCollections(); const allSelected = filteredCollections.every((collection) => selectedCollections.includes(collection.id) ); if (allSelected) { setSelectedCollections((prev) => prev.filter((id) => !filteredCollections.some((c) => c.id === id)) ); } else { const newSelections = filteredCollections .filter((collection) => !selectedCollections.includes(collection.id)) .map((collection) => collection.id); setSelectedCollections((prev) => [...prev, ...newSelections]); } }; const handleSubmit = async () => { if (selectedCollections.length === 0) return; setSubmitting(true); try { const results = []; for (const collectionId of selectedCollections) { for (const card of cards) { const response = await fetch(`/api/collections/${collectionId}/cards`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cardId: card.id, quantity: 1 }), }); results.push({ collectionId, cardId: card.id, success: response.ok, }); } } onAddToCollections(results, selectedCollections, cards); onClose(); } catch (error) { console.error('Error adding cards to collections:', error); } finally { setSubmitting(false); } }; const filteredCollections = getFilteredCollections(); const allFilteredSelected = filteredCollections.length > 0 && filteredCollections.every((collection) => selectedCollections.includes(collection.id) ); return (
{cards.slice(0, 3).map((card) => (
{card.image_url ? ( {card.name} ) : (
No Image
)}
))} {cards.length > 3 && (
+{cards.length - 3}
)}

{cards.length} card{cards.length !== 1 ? 's' : ''} selected

Choose lists to add {cards.length === 1 ? 'this card' : 'these cards'} to

setSearchQuery(e.target.value)} onClear={() => setSearchQuery('')} placeholder="Search lists…" />
{loading ? (

Loading lists...

) : filteredCollections.length === 0 ? (

{searchQuery ? 'No lists match your search' : 'No lists found'}

{searchQuery ? 'Try a different search term' : 'Create your first list to get started'}

) : ( <> {filteredCollections.length > 1 && (
)}
{filteredCollections.map((collection) => { const isSelected = selectedCollections.includes(collection.id); return (
handleCollectionToggle(collection.id)} >
handleCollectionToggle(collection.id)} className="w-4 h-4 rounded" style={{ accentColor: 'var(--accent-ember)' }} />
{collection.image ? ( {collection.name} ) : (
)}

{collection.name}

{collection.description && (

{collection.description}

)}
{collection.card_count || 0} cards {collection.is_public && ( Public )}
); })}
)}
{selectedCollections.length > 0 && ( {selectedCollections.length} list {selectedCollections.length !== 1 ? 's' : ''} selected )}
); }