Complete CRUD implementation for Cards, Collections, and Decks with comprehensive data modeling and API services

This commit is contained in:
Randall Stillwell 2025-07-22 19:51:38 -05:00
parent 708c68fb07
commit 4e71e29922
11 changed files with 3356 additions and 314 deletions

View file

@ -3,7 +3,7 @@ import { use3DTilt } from '../hooks/use3DTilt';
interface CardImageDisplayProps { interface CardImageDisplayProps {
card: { card: {
id: number; id: string;
name: string; name: string;
game: string; game: string;
stock_image_url?: string; stock_image_url?: string;

View file

@ -0,0 +1,365 @@
import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../../services/tcgApi';
import type { Card, CreateCardData } from '../../types';
interface CardManagerProps {
isOpen: boolean;
onClose: () => void;
cardId?: string; // For editing existing card
initialCardData?: Card; // For adding card from database
}
const CardManager: React.FC<CardManagerProps> = ({
isOpen,
onClose,
cardId,
initialCardData
}) => {
const queryClient = useQueryClient();
const [formData, setFormData] = useState<CreateCardData>({
cardId: initialCardData?.id || '',
status: 'owned',
quantity: 1,
condition: 'near_mint',
notes: '',
tags: [],
collectionIds: [],
deckIds: [],
});
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [selectedCollections, setSelectedCollections] = useState<string[]>([]);
// Queries
const { data: existingCard } = useQuery({
queryKey: ['user-card', cardId],
queryFn: () => tcgApi.cards.getUserCard(cardId!),
enabled: !!cardId,
});
const { data: cardInfo } = useQuery({
queryKey: ['card-info', formData.cardId],
queryFn: () => tcgApi.cards.getCard(formData.cardId),
enabled: !!formData.cardId,
});
const { data: tags = [] } = useQuery({
queryKey: ['tags'],
queryFn: () => tcgApi.tags.getTags(),
});
const { data: collections = [] } = useQuery({
queryKey: ['collections'],
queryFn: () => tcgApi.collections.getCollections(),
});
// Mutations
const addCardMutation = useMutation({
mutationFn: tcgApi.cards.addCard,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user-cards'] });
queryClient.invalidateQueries({ queryKey: ['collections'] });
onClose();
},
});
const updateCardMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<CreateCardData> }) =>
tcgApi.cards.updateCard(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user-cards'] });
queryClient.invalidateQueries({ queryKey: ['user-card', cardId] });
onClose();
},
});
// Initialize form with existing card data
useEffect(() => {
if (existingCard) {
setFormData({
cardId: existingCard.cardId,
status: existingCard.status,
quantity: existingCard.quantity,
condition: existingCard.condition || 'near_mint',
notes: existingCard.notes || '',
tags: existingCard.tags,
collectionIds: existingCard.collectionIds,
});
setSelectedTags(existingCard.tags);
setSelectedCollections(existingCard.collectionIds);
}
}, [existingCard]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const submitData = {
...formData,
tags: selectedTags,
collectionIds: selectedCollections,
};
if (cardId && existingCard) {
updateCardMutation.mutate({ id: cardId, data: submitData });
} else {
addCardMutation.mutate(submitData);
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 bg-black/50" onClick={onClose}>
<div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-surface-900 rounded-t-3xl max-h-[90vh] overflow-hidden animate-slide-up">
<div className="p-6">
<div className="w-12 h-1.5 bg-surface-300 dark:bg-surface-600 rounded-full mx-auto mb-6"></div>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-bold text-surface-900 dark:text-white">
{cardId ? 'Edit Card' : 'Add Card'}
</h2>
<button
onClick={onClose}
className="p-2 rounded-xl text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="max-h-[calc(90vh-8rem)] overflow-y-auto">
{/* Card Preview */}
{cardInfo && (
<div className="mb-6 p-4 bg-surface-50 dark:bg-surface-800 rounded-2xl">
<div className="flex items-center space-x-4">
<div className="w-16 h-20 bg-surface-200 dark:bg-surface-700 rounded-lg flex items-center justify-center">
{cardInfo.image_url ? (
<img
src={cardInfo.image_url}
alt={cardInfo.name}
className="w-full h-full object-cover rounded-lg"
/>
) : (
<svg className="w-6 h-6 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
)}
</div>
<div className="flex-1">
<h3 className="font-semibold text-surface-900 dark:text-white">{cardInfo.name}</h3>
<p className="text-sm text-surface-600 dark:text-surface-400">{cardInfo.set_name}</p>
<div className="flex items-center space-x-2 mt-2">
<span className="px-2 py-1 bg-primary-100 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300 rounded-full text-xs font-medium">
{cardInfo.game}
</span>
<span className="px-2 py-1 bg-accent-100 dark:bg-accent-900/30 text-accent-700 dark:text-accent-300 rounded-full text-xs font-medium">
{cardInfo.rarity}
</span>
</div>
</div>
</div>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-6" onClick={(e) => e.stopPropagation()}>
{/* Status Toggle */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-3">
Ownership Status
</label>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => setFormData(prev => ({ ...prev, status: 'owned' }))}
className={`p-4 rounded-xl border-2 transition-all ${
formData.status === 'owned'
? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
: 'border-surface-200 dark:border-surface-700'
}`}
>
<div className="text-center">
<div className="text-2xl mb-2"></div>
<div className="font-medium text-surface-900 dark:text-white">Owned</div>
<div className="text-sm text-surface-600 dark:text-surface-400">Cards you own</div>
</div>
</button>
<button
type="button"
onClick={() => setFormData(prev => ({ ...prev, status: 'wanted' }))}
className={`p-4 rounded-xl border-2 transition-all ${
formData.status === 'wanted'
? 'border-accent-500 bg-accent-50 dark:bg-accent-900/20'
: 'border-surface-200 dark:border-surface-700'
}`}
>
<div className="text-center">
<div className="text-2xl mb-2"></div>
<div className="font-medium text-surface-900 dark:text-white">Wanted</div>
<div className="text-sm text-surface-600 dark:text-surface-400">Wishlist cards</div>
</div>
</button>
</div>
</div>
{/* Quantity */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Quantity
</label>
<div className="flex items-center space-x-4">
<button
type="button"
onClick={() => setFormData(prev => ({ ...prev, quantity: Math.max(1, prev.quantity - 1) }))}
className="w-10 h-10 bg-surface-100 dark:bg-surface-700 rounded-lg flex items-center justify-center text-surface-600 dark:text-surface-300 hover:bg-surface-200 dark:hover:bg-surface-600 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
</svg>
</button>
<span className="text-xl font-semibold text-surface-900 dark:text-white min-w-[3rem] text-center">
{formData.quantity}
</span>
<button
type="button"
onClick={() => setFormData(prev => ({ ...prev, quantity: prev.quantity + 1 }))}
className="w-10 h-10 bg-surface-100 dark:bg-surface-700 rounded-lg flex items-center justify-center text-surface-600 dark:text-surface-300 hover:bg-surface-200 dark:hover:bg-surface-600 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</button>
</div>
</div>
{/* Condition */}
{formData.status === 'owned' && (
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Condition
</label>
<select
value={formData.condition}
onChange={(e) => setFormData(prev => ({ ...prev, condition: e.target.value as any }))}
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
>
<option value="mint">Mint (M)</option>
<option value="near_mint">Near Mint (NM)</option>
<option value="excellent">Excellent (EX)</option>
<option value="good">Good (G)</option>
<option value="light_played">Light Played (LP)</option>
<option value="played">Played (P)</option>
<option value="poor">Poor (PO)</option>
</select>
</div>
)}
{/* Tags */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Tags
</label>
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<button
key={tag.id}
type="button"
onClick={() => {
setSelectedTags(prev =>
prev.includes(tag.id)
? prev.filter(id => id !== tag.id)
: [...prev, tag.id]
);
}}
className={`px-3 py-2 rounded-full text-sm font-medium transition-colors ${
selectedTags.includes(tag.id)
? 'text-white'
: 'bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300'
}`}
style={{
backgroundColor: selectedTags.includes(tag.id) ? tag.color : undefined,
}}
>
{tag.name}
</button>
))}
</div>
</div>
{/* Collections */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Collections
</label>
<div className="space-y-2 max-h-32 overflow-y-auto">
{collections.map((collection) => (
<label key={collection.id} className="flex items-center space-x-3">
<input
type="checkbox"
checked={selectedCollections.includes(collection.id)}
onChange={(e) => {
setSelectedCollections(prev =>
e.target.checked
? [...prev, collection.id]
: prev.filter(id => id !== collection.id)
);
}}
className="w-4 h-4 text-primary-600 bg-surface-50 border-surface-300 rounded focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-surface-800 dark:bg-surface-700 dark:border-surface-600"
/>
<span className="text-sm text-surface-700 dark:text-surface-300">
{collection.name}
</span>
</label>
))}
</div>
</div>
{/* Notes */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Notes
</label>
<textarea
value={formData.notes}
onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
rows={3}
placeholder="Add any notes about this card..."
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors resize-none"
/>
</div>
{/* Submit Button */}
<button
type="submit"
disabled={!formData.cardId || addCardMutation.isPending || updateCardMutation.isPending}
className="w-full bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 disabled:from-surface-400 disabled:to-surface-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:shadow-none transform hover:-translate-y-0.5 disabled:transform-none"
>
{(addCardMutation.isPending || updateCardMutation.isPending) ? (
<div className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{cardId ? 'Updating...' : 'Adding...'}
</div>
) : (
cardId ? 'Update Card' : 'Add Card'
)}
</button>
</form>
</div>
</div>
</div>
</div>
);
};
export default CardManager;

View file

@ -0,0 +1,279 @@
import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { tcgApi } from '../../services/tcgApi';
import CardManager from './CardManager';
import type { Card, CardFilters } from '../../types';
interface CardSearchProps {
isOpen: boolean;
onClose: () => void;
onCardSelect?: (card: Card) => void;
}
const CardSearch: React.FC<CardSearchProps> = ({
isOpen,
onClose,
onCardSelect
}) => {
const [searchTerm, setSearchTerm] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [filters, setFilters] = useState<CardFilters>({
game: '',
rarity: '',
status: 'all'
});
const [selectedCard, setSelectedCard] = useState<Card | null>(null);
const [showCardManager, setShowCardManager] = useState(false);
// Debounce search input
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedSearch(searchTerm);
}, 300);
return () => clearTimeout(timer);
}, [searchTerm]);
// Search cards query
const { data: searchResults = [], isLoading } = useQuery({
queryKey: ['card-search', debouncedSearch, filters],
queryFn: () => {
if (debouncedSearch.trim()) {
return tcgApi.cards.searchCards(debouncedSearch, filters);
} else {
return tcgApi.cards.getAllCards(filters);
}
},
enabled: isOpen,
});
const getGameBadgeColor = (game: string) => {
switch (game) {
case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
const getRarityBadgeColor = (rarity: string) => {
switch (rarity.toLowerCase()) {
case 'common': return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
case 'uncommon': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
case 'rare': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
case 'super rare': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'legendary': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'mythic': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
const handleAddCard = (card: Card) => {
setSelectedCard(card);
setShowCardManager(true);
};
if (!isOpen) return null;
return (
<>
<div className="fixed inset-0 z-50 bg-black/50" onClick={onClose}>
<div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-surface-900 rounded-t-3xl h-[90vh] overflow-hidden animate-slide-up">
<div className="p-4 pb-0">
<div className="w-12 h-1.5 bg-surface-300 dark:bg-surface-600 rounded-full mx-auto mb-4"></div>
{/* Header */}
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-bold text-surface-900 dark:text-white">
Browse Cards
</h2>
<button
onClick={onClose}
className="p-2 rounded-xl text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Search Bar */}
<div className="relative mb-4">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg className="h-5 w-5 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search cards..."
className="w-full pl-10 pr-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
/>
</div>
{/* Filters */}
<div className="flex space-x-2 mb-4 overflow-x-auto pb-2">
<select
value={filters.game}
onChange={(e) => setFilters(prev => ({ ...prev, game: e.target.value }))}
className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
>
<option value="">All Games</option>
<option value="MTG">Magic: The Gathering</option>
<option value="POKEMON">Pokémon</option>
<option value="LORCANA">Disney Lorcana</option>
<option value="YUGIOH">Yu-Gi-Oh!</option>
</select>
<select
value={filters.rarity}
onChange={(e) => setFilters(prev => ({ ...prev, rarity: e.target.value }))}
className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
>
<option value="">All Rarities</option>
<option value="Common">Common</option>
<option value="Uncommon">Uncommon</option>
<option value="Rare">Rare</option>
<option value="Super Rare">Super Rare</option>
<option value="Legendary">Legendary</option>
<option value="Mythic">Mythic</option>
</select>
</div>
</div>
{/* Results */}
<div className="flex-1 overflow-y-auto px-4 pb-4" onClick={(e) => e.stopPropagation()}>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<div className="flex flex-col items-center">
<div className="w-8 h-8 bg-gradient-to-r from-primary-500 to-accent-500 rounded-full flex items-center justify-center animate-bounce-subtle mb-3">
<svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
<path d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<p className="text-surface-600 dark:text-surface-400 text-sm">Searching cards...</p>
</div>
</div>
) : searchResults.length === 0 ? (
<div className="text-center py-12">
<div className="w-16 h-16 bg-surface-100 dark:bg-surface-700 rounded-2xl flex items-center justify-center mx-auto mb-4">
<svg className="w-8 h-8 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<h3 className="text-lg font-semibold text-surface-900 dark:text-white mb-2">
No cards found
</h3>
<p className="text-surface-600 dark:text-surface-400">
Try adjusting your search or filters
</p>
</div>
) : (
<div className="space-y-3">
<p className="text-sm text-surface-600 dark:text-surface-400 mb-4">
{searchResults.length} cards found
</p>
{searchResults.map((card) => (
<div
key={card.id}
className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 transition-colors"
>
<div className="flex items-start space-x-4">
{/* Card Image */}
<div className="w-12 h-16 bg-surface-200 dark:bg-surface-700 rounded-lg flex items-center justify-center flex-shrink-0">
{card.image_url ? (
<img
src={card.image_url}
alt={card.name}
className="w-full h-full object-cover rounded-lg"
/>
) : (
<svg className="w-4 h-4 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
)}
</div>
{/* Card Info */}
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-surface-900 dark:text-white truncate">
{card.name}
</h3>
<p className="text-sm text-surface-600 dark:text-surface-400 truncate">
{card.set_name}
</p>
<p className="text-xs text-surface-500 dark:text-surface-500 mt-1">
{card.card_type}
</p>
<div className="flex items-center space-x-2 mt-2">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(card.game)}`}>
{card.game}
</span>
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getRarityBadgeColor(card.rarity)}`}>
{card.rarity}
</span>
</div>
{card.current_price && (
<p className="text-sm font-medium text-green-600 dark:text-green-400 mt-2">
${card.current_price.toFixed(2)}
</p>
)}
</div>
{/* Add Button */}
<button
onClick={() => handleAddCard(card)}
className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white p-2 rounded-xl transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5 flex-shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</button>
</div>
{/* Additional Info Row */}
{(card.mana_cost || (card.power && card.toughness)) && (
<div className="flex items-center justify-between mt-3 pt-3 border-t border-surface-200 dark:border-surface-700">
{card.mana_cost && (
<span className="text-xs text-surface-600 dark:text-surface-400">
Mana Cost: {card.mana_cost}
</span>
)}
{card.power && card.toughness && (
<span className="text-xs text-surface-600 dark:text-surface-400">
{card.power}/{card.toughness}
</span>
)}
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
</div>
{/* Card Manager Modal */}
{showCardManager && selectedCard && (
<CardManager
isOpen={showCardManager}
onClose={() => {
setShowCardManager(false);
setSelectedCard(null);
}}
initialCardData={selectedCard}
/>
)}
</>
);
};
export default CardSearch;

View file

@ -0,0 +1,356 @@
import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../../services/tcgApi';
import type { CreateCollectionData } from '../../types';
interface CollectionManagerProps {
isOpen: boolean;
onClose: () => void;
collectionId?: string; // For editing existing collection
}
const CollectionManager: React.FC<CollectionManagerProps> = ({
isOpen,
onClose,
collectionId
}) => {
const queryClient = useQueryClient();
const [formData, setFormData] = useState<CreateCollectionData>({
name: '',
description: '',
game: '',
tags: [],
color: '#8b5cf6',
icon: '📚',
isPublic: false,
});
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [showIconPicker, setShowIconPicker] = useState(false);
const icons = [
'📚', '🎴', '⚡', '🔥', '💧', '🌿', '⚫', '🟤', '🟡', '🔴',
'🟢', '🔵', '🟣', '⚪', '🌟', '💎', '👑', '🏆', '🎯', '🚀'
];
const colors = [
'#8b5cf6', '#3b82f6', '#10b981', '#f59e0b', '#ef4444',
'#ec4899', '#8b5cf6', '#6366f1', '#06b6d4', '#84cc16'
];
// Queries
const { data: existingCollection } = useQuery({
queryKey: ['collection', collectionId],
queryFn: () => tcgApi.collections.getCollection(collectionId!, false),
enabled: !!collectionId,
});
const { data: tags = [] } = useQuery({
queryKey: ['tags'],
queryFn: () => tcgApi.tags.getTags(),
});
// Mutations
const createMutation = useMutation({
mutationFn: tcgApi.collections.createCollection,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['collections'] });
onClose();
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<CreateCollectionData> }) =>
tcgApi.collections.updateCollection(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['collections'] });
queryClient.invalidateQueries({ queryKey: ['collection', collectionId] });
onClose();
},
});
// Initialize form with existing collection data
useEffect(() => {
if (existingCollection) {
setFormData({
name: existingCollection.name,
description: existingCollection.description || '',
game: existingCollection.game || '',
tags: existingCollection.tags,
color: existingCollection.color || '#8b5cf6',
icon: existingCollection.icon || '📚',
isPublic: existingCollection.isPublic,
});
setSelectedTags(existingCollection.tags);
}
}, [existingCollection]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const submitData = {
...formData,
tags: selectedTags,
};
if (collectionId && existingCollection) {
updateMutation.mutate({ id: collectionId, data: submitData });
} else {
createMutation.mutate(submitData);
}
};
const getGameBadgeColor = (game: string) => {
switch (game) {
case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 bg-black/50" onClick={onClose}>
<div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-surface-900 rounded-t-3xl max-h-[90vh] overflow-hidden animate-slide-up">
<div className="p-6">
<div className="w-12 h-1.5 bg-surface-300 dark:bg-surface-600 rounded-full mx-auto mb-6"></div>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-bold text-surface-900 dark:text-white">
{collectionId ? 'Edit Collection' : 'New Collection'}
</h2>
<button
onClick={onClose}
className="p-2 rounded-xl text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="max-h-[calc(90vh-8rem)] overflow-y-auto">
<form onSubmit={handleSubmit} className="space-y-6" onClick={(e) => e.stopPropagation()}>
{/* Collection Preview */}
<div className="p-4 bg-surface-50 dark:bg-surface-800 rounded-2xl">
<div className="flex items-center space-x-4">
<div
className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl font-semibold shadow-md"
style={{ backgroundColor: formData.color }}
>
{formData.icon}
</div>
<div className="flex-1">
<h3 className="font-semibold text-surface-900 dark:text-white">
{formData.name || 'Collection Name'}
</h3>
{formData.description && (
<p className="text-sm text-surface-600 dark:text-surface-400">
{formData.description}
</p>
)}
{formData.game && (
<span className={`inline-block mt-2 px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(formData.game)}`}>
{formData.game}
</span>
)}
</div>
</div>
</div>
{/* Name */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Collection Name *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
placeholder="Enter collection name..."
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
required
/>
</div>
{/* Description */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Description
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
rows={3}
placeholder="Describe your collection..."
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors resize-none"
/>
</div>
{/* Game */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Game (Optional)
</label>
<select
value={formData.game}
onChange={(e) => setFormData(prev => ({ ...prev, game: e.target.value }))}
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
>
<option value="">All Games</option>
<option value="MTG">Magic: The Gathering</option>
<option value="POKEMON">Pokémon</option>
<option value="LORCANA">Disney Lorcana</option>
<option value="YUGIOH">Yu-Gi-Oh!</option>
<option value="OTHER">Other</option>
</select>
</div>
{/* Icon & Color */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Icon
</label>
<button
type="button"
onClick={() => setShowIconPicker(!showIconPicker)}
className="w-full p-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl flex items-center justify-center text-2xl hover:bg-surface-100 dark:hover:bg-surface-600 transition-colors"
>
{formData.icon}
</button>
{showIconPicker && (
<div className="mt-2 p-3 bg-white dark:bg-surface-800 border border-surface-200 dark:border-surface-700 rounded-xl">
<div className="grid grid-cols-5 gap-2">
{icons.map((icon) => (
<button
key={icon}
type="button"
onClick={() => {
setFormData(prev => ({ ...prev, icon }));
setShowIconPicker(false);
}}
className={`p-2 rounded-lg text-xl hover:bg-surface-100 dark:hover:bg-surface-700 transition-colors ${
formData.icon === icon ? 'bg-primary-100 dark:bg-primary-900/30' : ''
}`}
>
{icon}
</button>
))}
</div>
</div>
)}
</div>
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Color
</label>
<div className="grid grid-cols-5 gap-2">
{colors.map((color) => (
<button
key={color}
type="button"
onClick={() => setFormData(prev => ({ ...prev, color }))}
className={`w-full h-10 rounded-lg transition-all ${
formData.color === color ? 'ring-2 ring-surface-400 ring-offset-2 dark:ring-offset-surface-900' : ''
}`}
style={{ backgroundColor: color }}
/>
))}
</div>
</div>
</div>
{/* Tags */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Tags
</label>
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<button
key={tag.id}
type="button"
onClick={() => {
setSelectedTags(prev =>
prev.includes(tag.id)
? prev.filter(id => id !== tag.id)
: [...prev, tag.id]
);
}}
className={`px-3 py-2 rounded-full text-sm font-medium transition-colors ${
selectedTags.includes(tag.id)
? 'text-white'
: 'bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300'
}`}
style={{
backgroundColor: selectedTags.includes(tag.id) ? tag.color : undefined,
}}
>
{tag.name}
</button>
))}
</div>
</div>
{/* Privacy Toggle */}
<div>
<label className="flex items-center justify-between">
<div>
<span className="text-sm font-medium text-surface-700 dark:text-surface-300">
Public Collection
</span>
<p className="text-xs text-surface-600 dark:text-surface-400 mt-1">
Allow others to view your collection
</p>
</div>
<button
type="button"
onClick={() => setFormData(prev => ({ ...prev, isPublic: !prev.isPublic }))}
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 ${
formData.isPublic ? 'bg-primary-600' : 'bg-surface-200 dark:bg-surface-700'
}`}
>
<span
className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
formData.isPublic ? 'translate-x-5' : 'translate-x-0'
}`}
/>
</button>
</label>
</div>
{/* Submit Button */}
<button
type="submit"
disabled={!formData.name.trim() || createMutation.isPending || updateMutation.isPending}
className="w-full bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 disabled:from-surface-400 disabled:to-surface-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:shadow-none transform hover:-translate-y-0.5 disabled:transform-none"
>
{(createMutation.isPending || updateMutation.isPending) ? (
<div className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{collectionId ? 'Updating...' : 'Creating...'}
</div>
) : (
collectionId ? 'Update Collection' : 'Create Collection'
)}
</button>
</form>
</div>
</div>
</div>
</div>
);
};
export default CollectionManager;

View file

@ -0,0 +1,408 @@
import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../../services/tcgApi';
import type { CreateDeckData } from '../../types';
interface DeckManagerProps {
isOpen: boolean;
onClose: () => void;
deckId?: string; // For editing existing deck
}
const DeckManager: React.FC<DeckManagerProps> = ({
isOpen,
onClose,
deckId
}) => {
const queryClient = useQueryClient();
const [formData, setFormData] = useState<CreateDeckData>({
name: '',
description: '',
game: 'MTG',
format: '',
tags: [],
color: '#8b5cf6',
isPublic: false,
});
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const colors = [
'#8b5cf6', '#3b82f6', '#10b981', '#f59e0b', '#ef4444',
'#ec4899', '#6366f1', '#06b6d4', '#84cc16', '#f97316'
];
// Queries
const { data: existingDeck } = useQuery({
queryKey: ['deck', deckId],
queryFn: () => tcgApi.decks.getDeck(deckId!),
enabled: !!deckId,
});
const { data: tags = [] } = useQuery({
queryKey: ['tags'],
queryFn: () => tcgApi.tags.getTags(),
});
// Mutations
const createMutation = useMutation({
mutationFn: tcgApi.decks.createDeck,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['decks'] });
onClose();
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<CreateDeckData> }) =>
tcgApi.decks.updateDeck(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['decks'] });
queryClient.invalidateQueries({ queryKey: ['deck', deckId] });
onClose();
},
});
// Initialize form with existing deck data
useEffect(() => {
if (existingDeck) {
setFormData({
name: existingDeck.name,
description: existingDeck.description || '',
game: existingDeck.game,
format: existingDeck.format || '',
tags: existingDeck.tags,
color: existingDeck.color || '#8b5cf6',
isPublic: existingDeck.isPublic,
});
setSelectedTags(existingDeck.tags);
}
}, [existingDeck]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const submitData = {
...formData,
tags: selectedTags,
};
if (deckId && existingDeck) {
updateMutation.mutate({ id: deckId, data: submitData });
} else {
createMutation.mutate(submitData);
}
};
const getGameBadgeColor = (game: string) => {
switch (game) {
case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
const getFormatOptions = (game: string) => {
switch (game) {
case 'MTG':
return [
{ value: 'standard', label: 'Standard' },
{ value: 'modern', label: 'Modern' },
{ value: 'commander', label: 'Commander' },
{ value: 'pioneer', label: 'Pioneer' },
{ value: 'legacy', label: 'Legacy' },
{ value: 'vintage', label: 'Vintage' },
{ value: 'draft', label: 'Draft' },
{ value: 'sealed', label: 'Sealed' },
];
case 'POKEMON':
return [
{ value: 'standard', label: 'Standard' },
{ value: 'expanded', label: 'Expanded' },
{ value: 'unlimited', label: 'Unlimited' },
];
case 'LORCANA':
return [
{ value: 'standard', label: 'Standard' },
{ value: 'constructed', label: 'Constructed' },
];
case 'YUGIOH':
return [
{ value: 'advanced', label: 'Advanced' },
{ value: 'traditional', label: 'Traditional' },
];
default:
return [];
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 bg-black/50" onClick={onClose}>
<div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-surface-900 rounded-t-3xl max-h-[90vh] overflow-hidden animate-slide-up">
<div className="p-6">
<div className="w-12 h-1.5 bg-surface-300 dark:bg-surface-600 rounded-full mx-auto mb-6"></div>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-bold text-surface-900 dark:text-white">
{deckId ? 'Edit Deck' : 'New Deck'}
</h2>
<button
onClick={onClose}
className="p-2 rounded-xl text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="max-h-[calc(90vh-8rem)] overflow-y-auto">
<form onSubmit={handleSubmit} className="space-y-6" onClick={(e) => e.stopPropagation()}>
{/* Deck Preview */}
<div className="p-4 bg-surface-50 dark:bg-surface-800 rounded-2xl">
<div className="flex items-center space-x-4">
<div
className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl font-semibold shadow-md"
style={{ backgroundColor: formData.color }}
>
🎴
</div>
<div className="flex-1">
<h3 className="font-semibold text-surface-900 dark:text-white">
{formData.name || 'Deck Name'}
</h3>
{formData.description && (
<p className="text-sm text-surface-600 dark:text-surface-400">
{formData.description}
</p>
)}
<div className="flex items-center space-x-2 mt-2">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(formData.game)}`}>
{formData.game}
</span>
{formData.format && (
<span className="px-2 py-1 bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300 rounded-full text-xs font-medium">
{formData.format}
</span>
)}
</div>
</div>
</div>
</div>
{/* Name */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Deck Name *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
placeholder="Enter deck name..."
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
required
/>
</div>
{/* Description */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Description
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
rows={3}
placeholder="Describe your deck..."
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors resize-none"
/>
</div>
{/* Game and Format */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Game *
</label>
<select
value={formData.game}
onChange={(e) => setFormData(prev => ({ ...prev, game: e.target.value as any, format: '' }))}
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
>
<option value="MTG">Magic: The Gathering</option>
<option value="POKEMON">Pokémon</option>
<option value="LORCANA">Disney Lorcana</option>
<option value="YUGIOH">Yu-Gi-Oh!</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Format
</label>
<select
value={formData.format}
onChange={(e) => setFormData(prev => ({ ...prev, format: e.target.value }))}
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
>
<option value="">Select Format</option>
{getFormatOptions(formData.game).map((format) => (
<option key={format.value} value={format.value}>
{format.label}
</option>
))}
</select>
</div>
</div>
{/* Color */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Color
</label>
<div className="grid grid-cols-5 gap-2">
{colors.map((color) => (
<button
key={color}
type="button"
onClick={() => setFormData(prev => ({ ...prev, color }))}
className={`w-full h-12 rounded-lg transition-all ${
formData.color === color ? 'ring-2 ring-surface-400 ring-offset-2 dark:ring-offset-surface-900' : ''
}`}
style={{ backgroundColor: color }}
/>
))}
</div>
</div>
{/* Tags */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Tags
</label>
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<button
key={tag.id}
type="button"
onClick={() => {
setSelectedTags(prev =>
prev.includes(tag.id)
? prev.filter(id => id !== tag.id)
: [...prev, tag.id]
);
}}
className={`px-3 py-2 rounded-full text-sm font-medium transition-colors ${
selectedTags.includes(tag.id)
? 'text-white'
: 'bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300'
}`}
style={{
backgroundColor: selectedTags.includes(tag.id) ? tag.color : undefined,
}}
>
{tag.name}
</button>
))}
</div>
</div>
{/* Privacy Toggle */}
<div>
<label className="flex items-center justify-between">
<div>
<span className="text-sm font-medium text-surface-700 dark:text-surface-300">
Public Deck
</span>
<p className="text-xs text-surface-600 dark:text-surface-400 mt-1">
Allow others to view your deck
</p>
</div>
<button
type="button"
onClick={() => setFormData(prev => ({ ...prev, isPublic: !prev.isPublic }))}
className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 ${
formData.isPublic ? 'bg-primary-600' : 'bg-surface-200 dark:bg-surface-700'
}`}
>
<span
className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
formData.isPublic ? 'translate-x-5' : 'translate-x-0'
}`}
/>
</button>
</label>
</div>
{/* Deck Cards Section */}
{deckId && existingDeck && (
<div>
<div className="mb-4">
<h3 className="text-lg font-semibold text-surface-900 dark:text-white">
Deck Cards ({existingDeck.mainboard?.length || 0})
</h3>
</div>
{/* Deck Cards List */}
<div className="space-y-2 max-h-48 overflow-y-auto">
{existingDeck.mainboard?.map((deckCard, index) => (
<div key={index} className="flex items-center justify-between p-3 bg-surface-50 dark:bg-surface-700 rounded-lg">
<div className="flex items-center space-x-3">
<span className="text-sm font-medium text-surface-900 dark:text-white">
{deckCard.quantity}x
</span>
<span className="text-sm text-surface-700 dark:text-surface-300">
{deckCard.card?.name || 'Unknown Card'}
</span>
</div>
<button
type="button"
onClick={() => {/* Remove card from deck */}}
className="p-1 text-red-400 hover:text-red-600 rounded transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
))}
</div>
</div>
)}
{/* Submit Button */}
<button
type="submit"
disabled={!formData.name.trim() || createMutation.isPending || updateMutation.isPending}
className="w-full bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 disabled:from-surface-400 disabled:to-surface-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:shadow-none transform hover:-translate-y-0.5 disabled:transform-none"
>
{(createMutation.isPending || updateMutation.isPending) ? (
<div className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{deckId ? 'Updating...' : 'Creating...'}
</div>
) : (
deckId ? 'Update Deck' : 'Create Deck'
)}
</button>
</form>
</div>
</div>
</div>
</div>
);
};
export default DeckManager;

View file

@ -0,0 +1,222 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../../services/tcgApi';
import type { Tag, CreateTagData } from '../../types';
interface TagManagerProps {
isOpen: boolean;
onClose: () => void;
tagId?: string; // For editing existing tag
}
const TagManager: React.FC<TagManagerProps> = ({
isOpen,
onClose,
tagId
}) => {
const queryClient = useQueryClient();
const [formData, setFormData] = useState<CreateTagData>({
name: '',
color: '#8b5cf6',
});
const colors = [
'#8b5cf6', '#3b82f6', '#10b981', '#f59e0b', '#ef4444',
'#ec4899', '#6366f1', '#06b6d4', '#84cc16', '#f97316',
'#06b6d4', '#8b5cf6', '#ec4899', '#10b981', '#f59e0b'
];
// Queries
const { data: existingTag } = useQuery({
queryKey: ['tag', tagId],
queryFn: () => tcgApi.tags.getTags().then(tags => tags.find(t => t.id === tagId)),
enabled: !!tagId,
});
// Mutations
const createMutation = useMutation({
mutationFn: tcgApi.tags.createTag,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tags'] });
onClose();
},
});
const updateMutation = useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<CreateTagData> }) =>
tcgApi.tags.updateTag(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tags'] });
queryClient.invalidateQueries({ queryKey: ['tag', tagId] });
onClose();
},
});
const deleteMutation = useMutation({
mutationFn: tcgApi.tags.deleteTag,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tags'] });
onClose();
},
});
// Initialize form with existing tag data
React.useEffect(() => {
if (existingTag) {
setFormData({
name: existingTag.name,
color: existingTag.color,
});
}
}, [existingTag]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (tagId && existingTag) {
updateMutation.mutate({ id: tagId, data: formData });
} else {
createMutation.mutate(formData);
}
};
const handleDelete = () => {
if (tagId && existingTag) {
if (window.confirm(`Are you sure you want to delete "${existingTag.name}"? This will remove it from all cards, collections, and decks.`)) {
deleteMutation.mutate(tagId);
}
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 bg-black/50" onClick={onClose}>
<div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-surface-900 rounded-t-3xl max-h-[90vh] overflow-hidden animate-slide-up">
<div className="p-6">
<div className="w-12 h-1.5 bg-surface-300 dark:bg-surface-600 rounded-full mx-auto mb-6"></div>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-bold text-surface-900 dark:text-white">
{tagId ? 'Edit Tag' : 'New Tag'}
</h2>
<button
onClick={onClose}
className="p-2 rounded-xl text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="max-h-[calc(90vh-8rem)] overflow-y-auto">
<form onSubmit={handleSubmit} className="space-y-6" onClick={(e) => e.stopPropagation()}>
{/* Tag Preview */}
<div className="p-4 bg-surface-50 dark:bg-surface-800 rounded-2xl">
<div className="flex items-center space-x-4">
<div
className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-lg font-semibold shadow-md"
style={{ backgroundColor: formData.color }}
>
{formData.name ? formData.name.charAt(0).toUpperCase() : 'T'}
</div>
<div className="flex-1">
<h3 className="font-semibold text-surface-900 dark:text-white">
{formData.name || 'Tag Name'}
</h3>
<p className="text-sm text-surface-600 dark:text-surface-400">
This tag will be available for cards, collections, and decks
</p>
</div>
</div>
</div>
{/* Name */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Tag Name *
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
placeholder="Enter tag name..."
className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
required
/>
</div>
{/* Color */}
<div>
<label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
Color
</label>
<div className="grid grid-cols-5 gap-2">
{colors.map((color) => (
<button
key={color}
type="button"
onClick={() => setFormData(prev => ({ ...prev, color }))}
className={`w-full h-12 rounded-lg transition-all ${
formData.color === color ? 'ring-2 ring-surface-400 ring-offset-2 dark:ring-offset-surface-900' : ''
}`}
style={{ backgroundColor: color }}
/>
))}
</div>
</div>
{/* Action Buttons */}
<div className="flex space-x-3">
<button
type="submit"
disabled={!formData.name.trim() || createMutation.isPending || updateMutation.isPending}
className="flex-1 bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 disabled:from-surface-400 disabled:to-surface-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:shadow-none transform hover:-translate-y-0.5 disabled:transform-none"
>
{(createMutation.isPending || updateMutation.isPending) ? (
<div className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{tagId ? 'Updating...' : 'Creating...'}
</div>
) : (
tagId ? 'Update Tag' : 'Create Tag'
)}
</button>
{tagId && (
<button
type="button"
onClick={handleDelete}
disabled={deleteMutation.isPending}
className="px-6 py-4 bg-red-500 hover:bg-red-600 disabled:bg-red-400 text-white font-semibold rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:shadow-none transform hover:-translate-y-0.5 disabled:transform-none"
>
{deleteMutation.isPending ? (
<div className="flex items-center justify-center">
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Deleting...
</div>
) : (
'Delete'
)}
</button>
)}
</div>
</form>
</div>
</div>
</div>
</div>
);
};
export default TagManager;

View file

@ -1,361 +1,448 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { cardService } from '../services/api'; import { tcgApi } from '../services/tcgApi';
import CardSearch from '../components/cards/CardSearch';
import CardManager from '../components/cards/CardManager';
import CardImageDisplay from '../components/CardImageDisplay'; import CardImageDisplay from '../components/CardImageDisplay';
import GlowingCard from '../components/GlowingCard'; import GlowingCard from '../components/GlowingCard';
import type { UserCard, CardFilters } from '../types';
interface Card {
id: number;
name: string;
set_name: string;
set_code: string;
card_number: string;
rarity: string;
game: string;
mana_cost?: string;
cmc?: number;
card_type: string;
colors?: string[];
oracle_text?: string;
power?: string;
toughness?: string;
current_price?: number;
market_price?: number;
verified: boolean;
stock_image_url?: string;
image_url?: string;
artwork_crop_coords?: {
x: number;
y: number;
width: number;
height: number;
};
}
const Cards: React.FC = () => { const Cards: React.FC = () => {
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [selectedGame, setSelectedGame] = useState(''); const [filters, setFilters] = useState<CardFilters>({
const [selectedRarity, setSelectedRarity] = useState(''); game: '',
const [viewMode, setViewMode] = useState<'card' | 'table'>('card'); rarity: '',
status: 'all',
search: '',
});
const [viewMode, setViewMode] = useState<'card' | 'list'>('card');
const [showCardSearch, setShowCardSearch] = useState(false);
const [editingCard, setEditingCard] = useState<string | null>(null);
const { data: cards = [], isLoading, error } = useQuery({ const { data: userCards = [], isLoading, error } = useQuery({
queryKey: ['cards', selectedGame, searchTerm], queryKey: ['user-cards', { ...filters, search: searchTerm }],
queryFn: () => cardService.getAllCards({ queryFn: () => tcgApi.cards.getUserCards({ ...filters, search: searchTerm }),
game: selectedGame || undefined,
search: searchTerm || undefined
}),
}); });
// Filter cards based on rarity (client-side for now) // Filter cards based on current filters
const filteredCards = cards.filter((card: Card) => { const filteredCards = userCards.filter((userCard: UserCard) => {
if (selectedRarity && card.rarity !== selectedRarity) { const card = userCard.card;
return false; if (!card) return false;
}
if (filters.rarity && card.rarity !== filters.rarity) return false;
if (filters.game && card.game !== filters.game) return false;
if (filters.status && filters.status !== 'all' && userCard.status !== filters.status) return false;
return true; return true;
}); });
const getGameBadgeColor = (game: string) => { const getGameBadgeColor = (game: string) => {
switch (game) { switch (game) {
case 'MTG': return 'bg-orange-100 text-orange-800'; case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'POKEMON': return 'bg-yellow-100 text-yellow-800'; case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'LORCANA': return 'bg-purple-100 text-purple-800'; case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
default: return 'bg-gray-100 text-gray-800'; case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
} }
}; };
const getRarityBadgeColor = (rarity: string) => { const getRarityBadgeColor = (rarity: string) => {
switch (rarity.toLowerCase()) { switch (rarity.toLowerCase()) {
case 'common': return 'bg-gray-100 text-gray-800'; case 'common': return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
case 'uncommon': return 'bg-green-100 text-green-800'; case 'uncommon': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
case 'rare': return 'bg-blue-100 text-blue-800'; case 'rare': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
case 'super rare': return 'bg-purple-100 text-purple-800'; case 'super rare': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'legendary': return 'bg-yellow-100 text-yellow-800'; case 'legendary': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'mythic': return 'bg-red-100 text-red-800'; case 'mythic': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
default: return 'bg-gray-100 text-gray-800'; default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
} }
}; };
const getRarityColor = (rarity: string) => { const getStatusBadgeColor = (status: string) => {
switch (rarity.toLowerCase()) { switch (status) {
case 'common': return '#6B7280'; case 'owned': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
case 'uncommon': return '#22C55E'; case 'wanted': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
case 'rare': return '#3B82F6'; default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
case 'super rare': return '#9333EA';
case 'legendary': return '#F59E0B';
case 'mythic': return '#EF4444';
default: return '#6B7280';
} }
}; };
const getConditionBadgeColor = (condition: string) => {
switch (condition) {
case 'mint': return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300';
case 'near_mint': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
case 'excellent': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
case 'good': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'light_played': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'played': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
case 'poor': return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
return ( return (
<div> <div className="space-y-6">
<div className="flex justify-between items-center mb-8"> {/* Header */}
<div className="flex items-center justify-between">
<div> <div>
<h1 className="text-3xl font-bold text-gray-900">Cards Database</h1> <h1 className="text-2xl font-bold text-surface-900 dark:text-white">My Cards</h1>
<p className="text-gray-600 mt-2"> <p className="text-surface-600 dark:text-surface-400 mt-1">
Browse and search all trading cards - {filteredCards.length} cards found {filteredCards.length} cards in your collection
</p> </p>
</div> </div>
<div className="flex items-center gap-4">
{/* View Toggle */} <button
<div className="bg-gray-100 rounded-lg p-1 flex"> onClick={() => setShowCardSearch(true)}
<button className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white px-4 py-2 rounded-xl font-medium transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
onClick={() => setViewMode('card')} >
className={`px-3 py-2 rounded-md text-sm font-medium transition-colors ${ <svg className="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
viewMode === 'card' <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
? 'bg-white text-gray-900 shadow-sm' </svg>
: 'text-gray-600 hover:text-gray-900' Add Cards
}`} </button>
>
🃏 Cards
</button>
<button
onClick={() => setViewMode('table')}
className={`px-3 py-2 rounded-md text-sm font-medium transition-colors ${
viewMode === 'table'
? 'bg-white text-gray-900 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
📊 Table
</button>
</div>
<button className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md font-medium transition-colors">
Add Card
</button>
</div>
</div> </div>
{/* Search and Filter Bar */} {/* Search and Filter Bar */}
<div className="bg-white rounded-lg shadow border border-gray-200 p-6 mb-6"> <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4">
<div className="flex flex-col md:flex-row gap-4"> <div className="space-y-4">
<div className="flex-1"> {/* Search Bar */}
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg className="h-5 w-5 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<input <input
type="text" type="text"
placeholder="Search cards..."
value={searchTerm} value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)} onChange={(e) => setSearchTerm(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="Search your cards..."
className="w-full pl-10 pr-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
/> />
</div> </div>
<div className="flex gap-2">
<select {/* Filters and View Toggle */}
value={selectedGame} <div className="flex items-center justify-between">
onChange={(e) => setSelectedGame(e.target.value)} <div className="flex space-x-2 overflow-x-auto pb-2">
className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" <select
> value={filters.game}
<option value="">All Games</option> onChange={(e) => setFilters(prev => ({ ...prev, game: e.target.value }))}
<option value="MTG">Magic: The Gathering</option> className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
<option value="POKEMON">Pokémon</option> >
<option value="LORCANA">Disney Lorcana</option> <option value="">All Games</option>
</select> <option value="MTG">Magic: The Gathering</option>
<select <option value="POKEMON">Pokémon</option>
value={selectedRarity} <option value="LORCANA">Disney Lorcana</option>
onChange={(e) => setSelectedRarity(e.target.value)} <option value="YUGIOH">Yu-Gi-Oh!</option>
className="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" </select>
>
<option value="">All Rarities</option> <select
<option value="Common">Common</option> value={filters.rarity}
<option value="Uncommon">Uncommon</option> onChange={(e) => setFilters(prev => ({ ...prev, rarity: e.target.value }))}
<option value="Rare">Rare</option> className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
<option value="Super Rare">Super Rare</option> >
<option value="Legendary">Legendary</option> <option value="">All Rarities</option>
<option value="Mythic">Mythic</option> <option value="Common">Common</option>
</select> <option value="Uncommon">Uncommon</option>
<option value="Rare">Rare</option>
<option value="Super Rare">Super Rare</option>
<option value="Legendary">Legendary</option>
<option value="Mythic">Mythic</option>
</select>
<select
value={filters.status}
onChange={(e) => setFilters(prev => ({ ...prev, status: e.target.value as any }))}
className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
>
<option value="all">All Cards</option>
<option value="owned">Owned</option>
<option value="wanted">Wanted</option>
</select>
</div>
{/* View Toggle */}
<div className="flex bg-surface-100 dark:bg-surface-700 rounded-lg p-1">
<button
onClick={() => setViewMode('card')}
className={`p-2 rounded-md transition-colors ${
viewMode === 'card'
? 'bg-white dark:bg-surface-600 text-surface-900 dark:text-white shadow-sm'
: 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-white'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
</svg>
</button>
<button
onClick={() => setViewMode('list')}
className={`p-2 rounded-md transition-colors ${
viewMode === 'list'
? 'bg-white dark:bg-surface-600 text-surface-900 dark:text-white shadow-sm'
: 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-white'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
</svg>
</button>
</div>
</div> </div>
</div> </div>
</div> </div>
{/* Loading State */} {/* Loading State */}
{isLoading && ( {isLoading && (
<div className="bg-white rounded-lg shadow border border-gray-200 p-8 text-center"> <div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto mb-4"></div> <div className="flex flex-col items-center">
<p className="text-gray-600">Loading cards...</p> <div className="w-8 h-8 bg-gradient-to-r from-primary-500 to-accent-500 rounded-full flex items-center justify-center animate-bounce-subtle mb-3">
<svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
<path d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<p className="text-surface-600 dark:text-surface-400 text-sm">Loading your cards...</p>
</div>
</div> </div>
)} )}
{/* Error State */} {/* Error State */}
{error && ( {error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6"> <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-4 mb-6">
<p className="text-red-800">Error loading cards. Please try again.</p> <p className="text-red-800 dark:text-red-400">Error loading cards. Please try again.</p>
</div> </div>
)} )}
{/* Cards Grid */} {/* Cards Display */}
{!isLoading && !error && ( {!isLoading && !error && (
<> <>
{filteredCards.length === 0 ? ( {filteredCards.length === 0 ? (
<div className="bg-white rounded-lg shadow border border-gray-200 p-8"> <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-8">
<div className="text-center"> <div className="text-center">
<span className="text-6xl mb-4 block">🃏</span> <div className="w-16 h-16 bg-surface-100 dark:bg-surface-700 rounded-2xl flex items-center justify-center mx-auto mb-6">
<h3 className="text-xl font-semibold text-gray-900 mb-2"> <svg className="w-8 h-8 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
No cards found <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<h3 className="text-xl font-semibold text-surface-900 dark:text-white mb-2">
{userCards.length === 0 ? 'No cards yet' : 'No matching cards'}
</h3> </h3>
<p className="text-gray-600 mb-6"> <p className="text-surface-600 dark:text-surface-400 mb-6">
Try adjusting your search filters or add some cards to your collection {userCards.length === 0
? 'Start building your collection by adding cards'
: 'Try adjusting your search or filters'
}
</p> </p>
<button className="bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-md font-medium transition-colors mr-4"> {userCards.length === 0 && (
Scan Cards <div className="flex flex-col sm:flex-row gap-3 items-center justify-center">
</button> <button
<button className="bg-gray-100 hover:bg-gray-200 text-gray-800 px-6 py-3 rounded-md font-medium transition-colors"> onClick={() => setShowCardSearch(true)}
Add Manually className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
</button> >
Browse Cards
</button>
<button className="bg-surface-100 dark:bg-surface-700 hover:bg-surface-200 dark:hover:bg-surface-600 text-surface-800 dark:text-surface-300 px-6 py-3 rounded-xl font-medium transition-colors">
Scan Cards
</button>
</div>
)}
</div> </div>
</div> </div>
) : viewMode === 'card' ? ( ) : viewMode === 'card' ? (
/* Card View */ /* Card View */
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-6"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{filteredCards.map((card: Card) => ( {filteredCards.map((userCard: UserCard) => {
<GlowingCard key={card.id} rarity={card.rarity} className="bg-white rounded-lg shadow overflow-hidden hover:shadow-lg"> const card = userCard.card;
{/* Card Image */} if (!card) return null;
<div className="flex justify-center p-4 bg-gray-50">
<CardImageDisplay
card={card}
size="large"
className="mx-auto"
/>
</div>
{/* Card Info */} return (
<div className="p-4"> <GlowingCard key={userCard.id} rarity={card.rarity} className="bg-white dark:bg-surface-800 rounded-xl shadow overflow-hidden hover:shadow-lg transition-all duration-200">
{/* Header */} {/* Card Image */}
<div className="flex justify-between items-start mb-3"> <div className="flex justify-center p-4 bg-surface-50 dark:bg-surface-700/50">
<div className="flex-1 min-w-0"> <div className="relative">
<h3 className="font-semibold text-gray-900 truncate" title={card.name}> <CardImageDisplay
{card.name} card={card}
</h3> size="large"
<p className="text-sm text-gray-600">{card.set_name}</p> className="mx-auto"
</div> />
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(card.game)}`}> {/* Status Badge */}
{card.game} <div className="absolute -top-2 -right-2">
</span> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadgeColor(userCard.status)}`}>
</div> {userCard.status === 'owned' ? '✅' : '❤️'}
{/* Quick Stats */}
<div className="space-y-1 mb-3">
{card.card_type && (
<p className="text-xs text-gray-600 truncate" title={card.card_type}>
{card.card_type}
</p>
)}
<div className="flex justify-between items-center">
{card.mana_cost && (
<span className="text-xs text-gray-600">
Cost: {card.mana_cost}
</span>
)}
{(card.power && card.toughness) && (
<span className="text-xs text-gray-600">
{card.power}/{card.toughness}
</span> </span>
</div>
{/* Quantity Badge */}
{userCard.quantity > 1 && (
<div className="absolute -bottom-2 -right-2">
<span className="bg-surface-800 dark:bg-surface-200 text-white dark:text-surface-900 text-xs font-bold px-2 py-1 rounded-full">
{userCard.quantity}x
</span>
</div>
)} )}
</div> </div>
</div> </div>
{/* Footer */} {/* Card Info */}
<div className="flex justify-between items-center"> <div className="p-4">
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getRarityBadgeColor(card.rarity)}`}> {/* Header */}
{card.rarity} <div className="flex justify-between items-start mb-3">
</span> <div className="flex-1 min-w-0">
<h3 className="font-semibold text-surface-900 dark:text-white truncate" title={card.name}>
{card.current_price && ( {card.name}
<span className="text-sm font-medium text-green-600"> </h3>
${card.current_price.toFixed(2)} <p className="text-sm text-surface-600 dark:text-surface-400 truncate">{card.set_name}</p>
</div>
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(card.game)}`}>
{card.game}
</span> </span>
</div>
{/* Quick Stats */}
<div className="space-y-1 mb-3">
{card.card_type && (
<p className="text-xs text-surface-600 dark:text-surface-400 truncate" title={card.card_type}>
{card.card_type}
</p>
)}
<div className="flex justify-between items-center">
{card.mana_cost && (
<span className="text-xs text-surface-600 dark:text-surface-400">
Cost: {card.mana_cost}
</span>
)}
{(card.power && card.toughness) && (
<span className="text-xs text-surface-600 dark:text-surface-400">
{card.power}/{card.toughness}
</span>
)}
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between mb-3">
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getRarityBadgeColor(card.rarity)}`}>
{card.rarity}
</span>
{card.current_price && (
<span className="text-sm font-medium text-green-600 dark:text-green-400">
${card.current_price.toFixed(2)}
</span>
)}
</div>
{/* Condition Badge */}
{userCard.condition && userCard.status === 'owned' && (
<div className="mb-3">
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getConditionBadgeColor(userCard.condition)}`}>
{userCard.condition.replace('_', ' ').toUpperCase()}
</span>
</div>
)} )}
{/* Edit Button */}
<button
onClick={() => setEditingCard(userCard.id)}
className="w-full bg-surface-100 dark:bg-surface-700 hover:bg-surface-200 dark:hover:bg-surface-600 text-surface-800 dark:text-surface-300 py-2 px-3 rounded-lg text-sm font-medium transition-colors"
>
Edit Card
</button>
</div> </div>
</div> </GlowingCard>
</GlowingCard> );
))} })}
</div> </div>
) : ( ) : (
/* Table View */ /* List View */
<div className="bg-white rounded-lg shadow border border-gray-200 overflow-hidden"> <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 overflow-hidden">
<div className="overflow-x-auto"> <div className="space-y-1">
<table className="min-w-full divide-y divide-gray-200"> {filteredCards.map((userCard: UserCard) => {
<thead className="bg-gray-50"> const card = userCard.card;
<tr> if (!card) return null;
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Card return (
</th> <div key={userCard.id} className="flex items-center p-4 hover:bg-surface-50 dark:hover:bg-surface-700/50 transition-colors">
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> {/* Card Image */}
Type <div className="w-12 h-16 bg-surface-200 dark:bg-surface-700 rounded-lg flex items-center justify-center flex-shrink-0 mr-4">
</th> {card.image_url ? (
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <img
Cost src={card.image_url}
</th> alt={card.name}
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> className="w-full h-full object-cover rounded-lg"
P/T />
</th> ) : (
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <svg className="w-4 h-4 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
Rarity <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</th> </svg>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> )}
Price </div>
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> {/* Card Info */}
Actions <div className="flex-1 min-w-0">
</th> <h3 className="font-semibold text-surface-900 dark:text-white truncate">
</tr> {card.name}
</thead> </h3>
<tbody className="bg-white divide-y divide-gray-200"> <p className="text-sm text-surface-600 dark:text-surface-400 truncate">
{filteredCards.map((card: Card) => ( {card.set_name}
<tr key={card.id} className="hover:bg-gray-50 transition-colors border-l-4" style={{borderLeftColor: getRarityColor(card.rarity)}}> </p>
<td className="px-6 py-4 whitespace-nowrap"> <div className="flex items-center space-x-2 mt-1">
<div className="flex items-center"> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(card.game)}`}>
<CardImageDisplay {card.game}
card={card} </span>
size="small" <span className={`px-2 py-1 rounded-full text-xs font-medium ${getRarityBadgeColor(card.rarity)}`}>
className="mr-3"
/>
<div>
<div className="text-sm font-medium text-gray-900">
{card.name}
</div>
<div className="text-sm text-gray-500">
{card.set_name}
</div>
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(card.game)}`}>
{card.game}
</span>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{card.card_type}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{card.mana_cost || '—'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{(card.power && card.toughness) ? `${card.power}/${card.toughness}` : '—'}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getRarityBadgeColor(card.rarity)}`}>
{card.rarity} {card.rarity}
</span> </span>
</td> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadgeColor(userCard.status)}`}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-green-600"> {userCard.status}
{card.current_price ? `$${card.current_price.toFixed(2)}` : '—'} </span>
</td> </div>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"> </div>
<button className="text-indigo-600 hover:text-indigo-900">
View {/* Quantity and Price */}
</button> <div className="text-right mr-4">
</td> <div className="text-sm font-medium text-surface-900 dark:text-white">
</tr> {userCard.quantity}x
))} </div>
</tbody> {card.current_price && (
</table> <div className="text-sm text-green-600 dark:text-green-400">
${(card.current_price * userCard.quantity).toFixed(2)}
</div>
)}
</div>
{/* Edit Button */}
<button
onClick={() => setEditingCard(userCard.id)}
className="p-2 text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 rounded-lg transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
</div>
);
})}
</div> </div>
</div> </div>
)} )}
</> </>
)} )}
{/* Card Search Modal */}
<CardSearch
isOpen={showCardSearch}
onClose={() => setShowCardSearch(false)}
/>
{/* Card Manager Modal */}
{editingCard && (
<CardManager
isOpen={!!editingCard}
onClose={() => setEditingCard(null)}
cardId={editingCard}
/>
)}
</div> </div>
); );
}; };

View file

@ -1,34 +1,318 @@
import React from 'react'; import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../services/tcgApi';
import CollectionManager from '../components/collections/CollectionManager';
import type { Collection, CollectionFilters } from '../types';
const Collections: React.FC = () => { const Collections: React.FC = () => {
const queryClient = useQueryClient();
const [showCreateModal, setShowCreateModal] = useState(false);
const [editingCollection, setEditingCollection] = useState<string | null>(null);
const [filters, setFilters] = useState<CollectionFilters>({
search: '',
game: '',
isFavorite: false,
});
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
// Queries
const { data: collections = [], isLoading } = useQuery({
queryKey: ['collections', filters],
queryFn: () => tcgApi.collections.getCollections(filters),
});
// Mutations
const deleteMutation = useMutation({
mutationFn: tcgApi.collections.deleteCollection,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['collections'] });
},
});
const toggleFavoriteMutation = useMutation({
mutationFn: ({ id, isFavorite }: { id: string; isFavorite: boolean }) =>
tcgApi.collections.updateCollection(id, { isFavorite }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['collections'] });
},
});
const handleDeleteCollection = (id: string, name: string) => {
if (window.confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) {
deleteMutation.mutate(id);
}
};
const handleToggleFavorite = (collection: Collection) => {
toggleFavoriteMutation.mutate({
id: collection.id,
isFavorite: !collection.isFavorite
});
};
const getGameBadgeColor = (game: string) => {
switch (game) {
case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
const filteredCollections = collections.filter(collection => {
const matchesSearch = !filters.search ||
collection.name.toLowerCase().includes(filters.search.toLowerCase()) ||
collection.description?.toLowerCase().includes(filters.search.toLowerCase());
const matchesGame = !filters.game || collection.game === filters.game;
const matchesFavorite = !filters.isFavorite || collection.isFavorite;
return matchesSearch && matchesGame && matchesFavorite;
});
return ( return (
<div> <div className="space-y-6">
<div className="flex justify-between items-center mb-8"> {/* Header */}
<div className="flex items-center justify-between">
<div> <div>
<h1 className="text-3xl font-bold text-gray-900">Collections</h1> <h1 className="text-2xl font-bold text-surface-900 dark:text-white">Collections</h1>
<p className="text-gray-600 mt-2"> <p className="text-surface-600 dark:text-surface-400 mt-1">
Organize and manage your trading card collections Organize and manage your card collections
</p> </p>
</div> </div>
<button className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md font-medium transition-colors">
<button
onClick={() => setShowCreateModal(true)}
className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white px-4 py-2 rounded-xl font-medium transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
>
<svg className="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
New Collection New Collection
</button> </button>
</div> </div>
<div className="bg-white rounded-lg shadow border border-gray-200 p-8"> {/* Search and Filters */}
<div className="text-center"> <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4">
<span className="text-6xl mb-4 block">📚</span> <div className="space-y-4">
<h3 className="text-xl font-semibold text-gray-900 mb-2"> {/* Search Bar */}
No collections yet <div className="relative">
</h3> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<p className="text-gray-600 mb-6"> <svg className="h-5 w-5 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
Create your first collection to start organizing your cards <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</p> </svg>
<button className="bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-md font-medium transition-colors"> </div>
Create Collection <input
</button> type="text"
value={filters.search}
onChange={(e) => setFilters(prev => ({ ...prev, search: e.target.value }))}
placeholder="Search collections..."
className="w-full pl-10 pr-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
/>
</div>
{/* Filters and View Toggle */}
<div className="flex items-center justify-between">
<div className="flex space-x-2 overflow-x-auto pb-2">
<select
value={filters.game}
onChange={(e) => setFilters(prev => ({ ...prev, game: e.target.value }))}
className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
>
<option value="">All Games</option>
<option value="MTG">Magic: The Gathering</option>
<option value="POKEMON">Pokémon</option>
<option value="LORCANA">Disney Lorcana</option>
<option value="YUGIOH">Yu-Gi-Oh!</option>
<option value="OTHER">Other</option>
</select>
<button
onClick={() => setFilters(prev => ({ ...prev, isFavorite: !prev.isFavorite }))}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
filters.isFavorite
? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300'
: 'bg-surface-50 dark:bg-surface-700 text-surface-700 dark:text-surface-300 border border-surface-300 dark:border-surface-600'
}`}
>
Favorites
</button>
</div>
{/* View Mode Toggle */}
<div className="flex bg-surface-100 dark:bg-surface-700 rounded-lg p-1">
<button
onClick={() => setViewMode('grid')}
className={`p-2 rounded-md transition-colors ${
viewMode === 'grid'
? 'bg-white dark:bg-surface-600 text-surface-900 dark:text-white shadow-sm'
: 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-white'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
</svg>
</button>
<button
onClick={() => setViewMode('list')}
className={`p-2 rounded-md transition-colors ${
viewMode === 'list'
? 'bg-white dark:bg-surface-600 text-surface-900 dark:text-white shadow-sm'
: 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-white'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
</svg>
</button>
</div>
</div>
</div> </div>
</div> </div>
{/* Collections List */}
{isLoading ? (
<div className="flex items-center justify-center py-12">
<div className="flex flex-col items-center">
<div className="w-8 h-8 bg-gradient-to-r from-primary-500 to-accent-500 rounded-full flex items-center justify-center animate-bounce-subtle mb-3">
<svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
<path d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<p className="text-surface-600 dark:text-surface-400 text-sm">Loading collections...</p>
</div>
</div>
) : filteredCollections.length === 0 ? (
<div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-8">
<div className="text-center">
<div className="w-16 h-16 bg-surface-100 dark:bg-surface-700 rounded-2xl flex items-center justify-center mx-auto mb-6">
<svg className="w-8 h-8 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<h3 className="text-xl font-semibold text-surface-900 dark:text-white mb-2">
{collections.length === 0 ? 'No collections yet' : 'No matching collections'}
</h3>
<p className="text-surface-600 dark:text-surface-400 mb-6">
{collections.length === 0
? 'Create your first collection to start organizing your cards'
: 'Try adjusting your search or filters'
}
</p>
{collections.length === 0 && (
<button
onClick={() => setShowCreateModal(true)}
className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
>
Create Collection
</button>
)}
</div>
</div>
) : (
<div className={viewMode === 'grid' ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4' : 'space-y-4'}>
{filteredCollections.map((collection) => (
<div
key={collection.id}
className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 transition-all duration-200 hover:shadow-md"
>
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-3">
<div
className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl font-semibold shadow-md"
style={{ backgroundColor: collection.color || '#8b5cf6' }}
>
{collection.icon || '📚'}
</div>
<div className="flex-1">
<h3 className="font-semibold text-surface-900 dark:text-white">
{collection.name}
</h3>
{collection.description && (
<p className="text-sm text-surface-600 dark:text-surface-400 line-clamp-2">
{collection.description}
</p>
)}
</div>
</div>
{/* Favorite Button */}
<button
onClick={() => handleToggleFavorite(collection)}
className={`p-2 rounded-lg transition-colors ${
collection.isFavorite
? 'text-yellow-500 hover:text-yellow-600'
: 'text-surface-400 hover:text-yellow-500'
}`}
>
<svg className="w-5 h-5" fill={collection.isFavorite ? 'currentColor' : 'none'} stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
</svg>
</button>
</div>
{/* Stats */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-4 text-sm text-surface-600 dark:text-surface-400">
<span>{collection.cardCount || 0} cards</span>
{collection.totalValue && (
<span className="text-green-600 dark:text-green-400 font-medium">
${collection.totalValue.toFixed(2)}
</span>
)}
</div>
{collection.game && (
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(collection.game)}`}>
{collection.game}
</span>
)}
</div>
{/* Actions */}
<div className="flex items-center space-x-2">
<button
onClick={() => {/* Navigate to collection detail */}}
className="flex-1 bg-primary-50 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300 py-2 px-3 rounded-lg text-sm font-medium hover:bg-primary-100 dark:hover:bg-primary-900/30 transition-colors"
>
View Cards
</button>
<button
onClick={() => setEditingCollection(collection.id)}
className="p-2 text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 rounded-lg transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<button
onClick={() => handleDeleteCollection(collection.id, collection.name)}
className="p-2 text-red-400 hover:text-red-600 rounded-lg transition-colors"
disabled={deleteMutation.isPending}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
))}
</div>
)}
{/* Collection Manager Modal */}
<CollectionManager
isOpen={showCreateModal || !!editingCollection}
onClose={() => {
setShowCreateModal(false);
setEditingCollection(null);
}}
collectionId={editingCollection || undefined}
/>
</div> </div>
); );
}; };

View file

@ -1,34 +1,370 @@
import React from 'react'; import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../services/tcgApi';
import DeckManager from '../components/decks/DeckManager';
import type { Deck, DeckFilters } from '../types';
const Decks: React.FC = () => { const Decks: React.FC = () => {
const queryClient = useQueryClient();
const [showCreateModal, setShowCreateModal] = useState(false);
const [editingDeck, setEditingDeck] = useState<string | null>(null);
const [filters, setFilters] = useState<DeckFilters>({
search: '',
game: '',
format: '',
isFavorite: false,
});
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
// Queries
const { data: decks = [], isLoading } = useQuery({
queryKey: ['decks', filters],
queryFn: () => tcgApi.decks.getDecks(filters),
});
// Mutations
const deleteMutation = useMutation({
mutationFn: tcgApi.decks.deleteDeck,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['decks'] });
},
});
const toggleFavoriteMutation = useMutation({
mutationFn: ({ id, isFavorite }: { id: string; isFavorite: boolean }) =>
tcgApi.decks.updateDeck(id, { isFavorite }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['decks'] });
},
});
const handleDeleteDeck = (id: string, name: string) => {
if (window.confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) {
deleteMutation.mutate(id);
}
};
const handleToggleFavorite = (deck: Deck) => {
toggleFavoriteMutation.mutate({
id: deck.id,
isFavorite: !deck.isFavorite
});
};
const getGameBadgeColor = (game: string) => {
switch (game) {
case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
const getFormatBadgeColor = (format: string) => {
switch (format.toLowerCase()) {
case 'standard': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
case 'modern': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
case 'commander': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
case 'pioneer': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
case 'legacy': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
case 'vintage': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
}
};
const filteredDecks = decks.filter(deck => {
const matchesSearch = !filters.search ||
deck.name.toLowerCase().includes(filters.search.toLowerCase()) ||
deck.description?.toLowerCase().includes(filters.search.toLowerCase());
const matchesGame = !filters.game || deck.game === filters.game;
const matchesFormat = !filters.format || deck.format === filters.format;
const matchesFavorite = !filters.isFavorite || deck.isFavorite;
return matchesSearch && matchesGame && matchesFormat && matchesFavorite;
});
return ( return (
<div> <div className="space-y-6">
<div className="flex justify-between items-center mb-8"> {/* Header */}
<div className="flex items-center justify-between">
<div> <div>
<h1 className="text-3xl font-bold text-gray-900">Decks</h1> <h1 className="text-2xl font-bold text-surface-900 dark:text-white">My Decks</h1>
<p className="text-gray-600 mt-2"> <p className="text-surface-600 dark:text-surface-400 mt-1">
Build and optimize your decks with AI assistance Build and manage your card decks
</p> </p>
</div> </div>
<button className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md font-medium transition-colors">
<button
onClick={() => setShowCreateModal(true)}
className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white px-4 py-2 rounded-xl font-medium transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
>
<svg className="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
New Deck New Deck
</button> </button>
</div> </div>
<div className="bg-white rounded-lg shadow border border-gray-200 p-8"> {/* Search and Filter Bar */}
<div className="text-center"> <div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4">
<span className="text-6xl mb-4 block">🎴</span> <div className="space-y-4">
<h3 className="text-xl font-semibold text-gray-900 mb-2"> {/* Search Bar */}
No decks yet <div className="relative">
</h3> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<p className="text-gray-600 mb-6"> <svg className="h-5 w-5 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
Start building your first deck from your collection <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</p> </svg>
<button className="bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-md font-medium transition-colors"> </div>
Build Deck <input
</button> type="text"
value={filters.search}
onChange={(e) => setFilters(prev => ({ ...prev, search: e.target.value }))}
placeholder="Search decks..."
className="w-full pl-10 pr-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
/>
</div>
{/* Filters and View Toggle */}
<div className="flex items-center justify-between">
<div className="flex space-x-2 overflow-x-auto pb-2">
<select
value={filters.game}
onChange={(e) => setFilters(prev => ({ ...prev, game: e.target.value }))}
className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
>
<option value="">All Games</option>
<option value="MTG">Magic: The Gathering</option>
<option value="POKEMON">Pokémon</option>
<option value="LORCANA">Disney Lorcana</option>
<option value="YUGIOH">Yu-Gi-Oh!</option>
</select>
<select
value={filters.format}
onChange={(e) => setFilters(prev => ({ ...prev, format: e.target.value }))}
className="px-3 py-2 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors whitespace-nowrap"
>
<option value="">All Formats</option>
<option value="standard">Standard</option>
<option value="modern">Modern</option>
<option value="commander">Commander</option>
<option value="pioneer">Pioneer</option>
<option value="legacy">Legacy</option>
<option value="vintage">Vintage</option>
</select>
<button
onClick={() => setFilters(prev => ({ ...prev, isFavorite: !prev.isFavorite }))}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
filters.isFavorite
? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300'
: 'bg-surface-50 dark:bg-surface-700 text-surface-700 dark:text-surface-300 border border-surface-300 dark:border-surface-600'
}`}
>
Favorites
</button>
</div>
{/* View Mode Toggle */}
<div className="flex bg-surface-100 dark:bg-surface-700 rounded-lg p-1">
<button
onClick={() => setViewMode('grid')}
className={`p-2 rounded-md transition-colors ${
viewMode === 'grid'
? 'bg-white dark:bg-surface-600 text-surface-900 dark:text-white shadow-sm'
: 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-white'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
</svg>
</button>
<button
onClick={() => setViewMode('list')}
className={`p-2 rounded-md transition-colors ${
viewMode === 'list'
? 'bg-white dark:bg-surface-600 text-surface-900 dark:text-white shadow-sm'
: 'text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-white'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
</svg>
</button>
</div>
</div>
</div> </div>
</div> </div>
{/* Decks List */}
{isLoading ? (
<div className="flex items-center justify-center py-12">
<div className="flex flex-col items-center">
<div className="w-8 h-8 bg-gradient-to-r from-primary-500 to-accent-500 rounded-full flex items-center justify-center animate-bounce-subtle mb-3">
<svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
<path d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<p className="text-surface-600 dark:text-surface-400 text-sm">Loading decks...</p>
</div>
</div>
) : filteredDecks.length === 0 ? (
<div className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-8">
<div className="text-center">
<div className="w-16 h-16 bg-surface-100 dark:bg-surface-700 rounded-2xl flex items-center justify-center mx-auto mb-6">
<svg className="w-8 h-8 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<h3 className="text-xl font-semibold text-surface-900 dark:text-white mb-2">
{decks.length === 0 ? 'No decks yet' : 'No matching decks'}
</h3>
<p className="text-surface-600 dark:text-surface-400 mb-6">
{decks.length === 0
? 'Start building your first deck from your collection'
: 'Try adjusting your search or filters'
}
</p>
{decks.length === 0 && (
<button
onClick={() => setShowCreateModal(true)}
className="bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
>
Create Deck
</button>
)}
</div>
</div>
) : (
<div className={viewMode === 'grid' ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4' : 'space-y-4'}>
{filteredDecks.map((deck) => (
<div
key={deck.id}
className="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 transition-all duration-200 hover:shadow-md"
>
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-3">
<div
className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl font-semibold shadow-md"
style={{ backgroundColor: deck.color || '#8b5cf6' }}
>
🎴
</div>
<div className="flex-1">
<h3 className="font-semibold text-surface-900 dark:text-white">
{deck.name}
</h3>
{deck.description && (
<p className="text-sm text-surface-600 dark:text-surface-400 line-clamp-2">
{deck.description}
</p>
)}
</div>
</div>
{/* Favorite Button */}
<button
onClick={() => handleToggleFavorite(deck)}
className={`p-2 rounded-lg transition-colors ${
deck.isFavorite
? 'text-yellow-500 hover:text-yellow-600'
: 'text-surface-400 hover:text-yellow-500'
}`}
>
<svg className="w-5 h-5" fill={deck.isFavorite ? 'currentColor' : 'none'} stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
</svg>
</button>
</div>
{/* Stats */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-4 text-sm text-surface-600 dark:text-surface-400">
<span>{deck.totalCards || 0} cards</span>
{deck.totalValue && (
<span className="text-green-600 dark:text-green-400 font-medium">
${deck.totalValue.toFixed(2)}
</span>
)}
</div>
<div className="flex items-center space-x-2">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(deck.game)}`}>
{deck.game}
</span>
{deck.format && (
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getFormatBadgeColor(deck.format)}`}>
{deck.format}
</span>
)}
</div>
</div>
{/* Deck Status */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center space-x-2">
{deck.isLegal !== undefined && (
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
deck.isLegal
? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300'
: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
}`}>
{deck.isLegal ? '✅ Legal' : '❌ Illegal'}
</span>
)}
{deck.averageManaValue && (
<span className="px-2 py-1 bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300 rounded-full text-xs font-medium">
{deck.averageManaValue.toFixed(1)} CMC
</span>
)}
</div>
</div>
{/* Actions */}
<div className="flex items-center space-x-2">
<button
onClick={() => {/* Navigate to deck detail */}}
className="flex-1 bg-primary-50 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300 py-2 px-3 rounded-lg text-sm font-medium hover:bg-primary-100 dark:hover:bg-primary-900/30 transition-colors"
>
View Deck
</button>
<button
onClick={() => setEditingDeck(deck.id)}
className="p-2 text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 rounded-lg transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<button
onClick={() => handleDeleteDeck(deck.id, deck.name)}
className="p-2 text-red-400 hover:text-red-600 rounded-lg transition-colors"
disabled={deleteMutation.isPending}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
))}
</div>
)}
{/* Deck Manager Modal */}
<DeckManager
isOpen={showCreateModal || !!editingDeck}
onClose={() => {
setShowCreateModal(false);
setEditingDeck(null);
}}
deckId={editingDeck || undefined}
/>
</div> </div>
); );
}; };

410
src/services/tcgApi.ts Normal file
View file

@ -0,0 +1,410 @@
import axios from 'axios';
import type {
Card,
UserCard,
Collection,
Deck,
Tag,
CreateCardData,
CreateCollectionData,
CreateDeckData,
CreateTagData,
CardFilters,
CollectionFilters,
DeckFilters,
UserStats,
} from '../types';
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000';
// Create axios instance with default config
const api = axios.create({
baseURL: API_BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor for auth token
api.interceptors.request.use((config) => {
const token = localStorage.getItem('tcg-vault-token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Response interceptor for error handling
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('tcg-vault-token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
// ============================================================================
// CARD SERVICES
// ============================================================================
export const cardService = {
// Get all cards from database (for browsing/searching)
getAllCards: async (filters?: CardFilters): Promise<Card[]> => {
const response = await api.get('/api/cards', { params: filters });
return response.data.data;
},
// Get single card from database
getCard: async (id: string): Promise<Card> => {
const response = await api.get(`/api/cards/${id}`);
return response.data.data;
},
// Search cards in database
searchCards: async (query: string, filters?: Omit<CardFilters, 'search'>): Promise<Card[]> => {
const response = await api.get('/api/cards/search', {
params: { q: query, ...filters }
});
return response.data.data;
},
// Get user's cards (owned/wanted)
getUserCards: async (filters?: CardFilters): Promise<UserCard[]> => {
const response = await api.get('/api/user-cards', { params: filters });
return response.data.data;
},
// Get single user card
getUserCard: async (id: string): Promise<UserCard> => {
const response = await api.get(`/api/user-cards/${id}`);
return response.data.data;
},
// Add card to user collection
addCard: async (data: CreateCardData): Promise<UserCard> => {
const response = await api.post('/api/user-cards', data);
return response.data.data;
},
// Update user card
updateCard: async (id: string, data: Partial<CreateCardData>): Promise<UserCard> => {
const response = await api.put(`/api/user-cards/${id}`, data);
return response.data.data;
},
// Delete user card
deleteCard: async (id: string): Promise<void> => {
await api.delete(`/api/user-cards/${id}`);
},
// Bulk operations
bulkAddCards: async (cards: CreateCardData[]): Promise<UserCard[]> => {
const response = await api.post('/api/user-cards/bulk', { cards });
return response.data.data;
},
bulkUpdateCards: async (updates: { id: string; data: Partial<CreateCardData> }[]): Promise<UserCard[]> => {
const response = await api.put('/api/user-cards/bulk', { updates });
return response.data.data;
},
bulkDeleteCards: async (ids: string[]): Promise<void> => {
await api.delete('/api/user-cards/bulk', { data: { ids } });
},
// Move cards between collections/decks
moveCardsToCollection: async (cardIds: string[], collectionId: string): Promise<void> => {
await api.post('/api/user-cards/move-to-collection', { cardIds, collectionId });
},
moveCardsToDeck: async (cardIds: string[], deckId: string): Promise<void> => {
await api.post('/api/user-cards/move-to-deck', { cardIds, deckId });
},
};
// ============================================================================
// COLLECTION SERVICES
// ============================================================================
export const collectionService = {
// Get all user collections
getCollections: async (filters?: CollectionFilters): Promise<Collection[]> => {
const response = await api.get('/api/collections', { params: filters });
return response.data.data;
},
// Get single collection with cards
getCollection: async (id: string, includeCards = true): Promise<Collection> => {
const response = await api.get(`/api/collections/${id}`, {
params: { include_cards: includeCards }
});
return response.data.data;
},
// Create new collection
createCollection: async (data: CreateCollectionData): Promise<Collection> => {
const response = await api.post('/api/collections', data);
return response.data.data;
},
// Update collection
updateCollection: async (id: string, data: Partial<CreateCollectionData>): Promise<Collection> => {
const response = await api.put(`/api/collections/${id}`, data);
return response.data.data;
},
// Delete collection
deleteCollection: async (id: string): Promise<void> => {
await api.delete(`/api/collections/${id}`);
},
// Collection card management
addCardsToCollection: async (collectionId: string, cardIds: string[]): Promise<void> => {
await api.post(`/api/collections/${collectionId}/cards`, { cardIds });
},
removeCardsFromCollection: async (collectionId: string, cardIds: string[]): Promise<void> => {
await api.delete(`/api/collections/${collectionId}/cards`, { data: { cardIds } });
},
// Collection stats
getCollectionStats: async (id: string): Promise<{
cardCount: number;
totalValue: number;
gameBreakdown: Record<string, number>;
rarityBreakdown: Record<string, number>;
}> => {
const response = await api.get(`/api/collections/${id}/stats`);
return response.data.data;
},
// Duplicate collection
duplicateCollection: async (id: string, newName: string): Promise<Collection> => {
const response = await api.post(`/api/collections/${id}/duplicate`, { name: newName });
return response.data.data;
},
// Export collection
exportCollection: async (id: string, format: 'csv' | 'json' | 'txt'): Promise<Blob> => {
const response = await api.get(`/api/collections/${id}/export`, {
params: { format },
responseType: 'blob'
});
return response.data;
},
};
// ============================================================================
// DECK SERVICES
// ============================================================================
export const deckService = {
// Get all user decks
getDecks: async (filters?: DeckFilters): Promise<Deck[]> => {
const response = await api.get('/api/decks', { params: filters });
return response.data.data;
},
// Get single deck with cards
getDeck: async (id: string): Promise<Deck> => {
const response = await api.get(`/api/decks/${id}`);
return response.data.data;
},
// Create new deck
createDeck: async (data: CreateDeckData): Promise<Deck> => {
const response = await api.post('/api/decks', data);
return response.data.data;
},
// Update deck
updateDeck: async (id: string, data: Partial<CreateDeckData>): Promise<Deck> => {
const response = await api.put(`/api/decks/${id}`, data);
return response.data.data;
},
// Delete deck
deleteDeck: async (id: string): Promise<void> => {
await api.delete(`/api/decks/${id}`);
},
// Deck card management
addCardToDeck: async (deckId: string, cardId: string, quantity: number, board: 'mainboard' | 'sideboard' = 'mainboard'): Promise<void> => {
await api.post(`/api/decks/${deckId}/cards`, { cardId, quantity, board });
},
updateDeckCard: async (deckId: string, cardId: string, quantity: number, board: 'mainboard' | 'sideboard' = 'mainboard'): Promise<void> => {
await api.put(`/api/decks/${deckId}/cards/${cardId}`, { quantity, board });
},
removeDeckCard: async (deckId: string, cardId: string): Promise<void> => {
await api.delete(`/api/decks/${deckId}/cards/${cardId}`);
},
// Deck validation
validateDeck: async (id: string): Promise<{
isLegal: boolean;
errors: string[];
warnings: string[];
}> => {
const response = await api.get(`/api/decks/${id}/validate`);
return response.data.data;
},
// Deck stats
getDeckStats: async (id: string): Promise<{
totalCards: number;
totalValue: number;
averageManaValue: number;
colorBreakdown: Record<string, number>;
typeBreakdown: Record<string, number>;
manaCurve: Record<number, number>;
ownedCards: number;
neededCards: number;
}> => {
const response = await api.get(`/api/decks/${id}/stats`);
return response.data.data;
},
// Import/Export decks
importDeck: async (data: { name: string; format: string; decklist: string }): Promise<Deck> => {
const response = await api.post('/api/decks/import', data);
return response.data.data;
},
exportDeck: async (id: string, format: 'mtgo' | 'arena' | 'txt' | 'json'): Promise<string> => {
const response = await api.get(`/api/decks/${id}/export`, { params: { format } });
return response.data.data;
},
// Duplicate deck
duplicateDeck: async (id: string, newName: string): Promise<Deck> => {
const response = await api.post(`/api/decks/${id}/duplicate`, { name: newName });
return response.data.data;
},
};
// ============================================================================
// TAG SERVICES
// ============================================================================
export const tagService = {
// Get all user tags
getTags: async (): Promise<Tag[]> => {
const response = await api.get('/api/tags');
return response.data.data;
},
// Create new tag
createTag: async (data: CreateTagData): Promise<Tag> => {
const response = await api.post('/api/tags', data);
return response.data.data;
},
// Update tag
updateTag: async (id: string, data: Partial<CreateTagData>): Promise<Tag> => {
const response = await api.put(`/api/tags/${id}`, data);
return response.data.data;
},
// Delete tag
deleteTag: async (id: string): Promise<void> => {
await api.delete(`/api/tags/${id}`);
},
// Get entities by tag
getEntitiesByTag: async (tagId: string): Promise<{
cards: UserCard[];
collections: Collection[];
decks: Deck[];
}> => {
const response = await api.get(`/api/tags/${tagId}/entities`);
return response.data.data;
},
};
// ============================================================================
// STATS AND ANALYTICS
// ============================================================================
export const statsService = {
// Get user statistics
getUserStats: async (): Promise<UserStats> => {
const response = await api.get('/api/stats');
return response.data.data;
},
// Get price alerts
getPriceAlerts: async (): Promise<{
increases: Array<{ card: Card; oldPrice: number; newPrice: number; change: number }>;
decreases: Array<{ card: Card; oldPrice: number; newPrice: number; change: number }>;
}> => {
const response = await api.get('/api/stats/price-alerts');
return response.data.data;
},
};
// ============================================================================
// SCANNER INTEGRATION
// ============================================================================
export const scannerService = {
// Process OCR scan result
processOCR: async (imageData: string): Promise<{
cards: Array<{
card: Card;
confidence: number;
}>;
}> => {
const response = await api.post('/api/scanner/ocr', { imageData });
return response.data.data;
},
// Add scanned cards to collection
addScannedCards: async (cards: CreateCardData[]): Promise<UserCard[]> => {
const response = await api.post('/api/scanner/add-cards', { cards });
return response.data.data;
},
};
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
export const utilityService = {
// Health check
healthCheck: async (): Promise<{ status: string; timestamp: string }> => {
const response = await api.get('/api/health');
return response.data;
},
// Upload image
uploadImage: async (file: File): Promise<{ url: string }> => {
const formData = new FormData();
formData.append('image', file);
const response = await api.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return response.data.data;
},
};
// Export all services
export const tcgApi = {
cards: cardService,
collections: collectionService,
decks: deckService,
tags: tagService,
stats: statsService,
scanner: scannerService,
utils: utilityService,
};
export default tcgApi;

295
src/types/index.ts Normal file
View file

@ -0,0 +1,295 @@
// Core entity interfaces for TCG Vault
export interface User {
id: string;
username: string;
email: string;
firstName?: string;
lastName?: string;
roles: string[];
createdAt: string;
updatedAt: string;
}
export interface Tag {
id: string;
name: string;
color: string;
userId: string;
createdAt: string;
}
export interface Card {
id: string;
// Card database info
name: string;
set_name: string;
set_code: string;
card_number: string;
rarity: string;
game: 'MTG' | 'POKEMON' | 'LORCANA' | 'YUGIOH' | 'OTHER';
card_type: string;
// Game-specific attributes
mana_cost?: string;
cmc?: number;
colors?: string[];
oracle_text?: string;
power?: string;
toughness?: string;
// Pricing
current_price?: number;
market_price?: number;
price_history?: PricePoint[];
// Images
image_url?: string;
stock_image_url?: string;
artwork_crop_coords?: {
x: number;
y: number;
width: number;
height: number;
};
// System fields
verified: boolean;
createdAt: string;
updatedAt: string;
}
export interface PricePoint {
date: string;
price: number;
source: string;
}
export interface UserCard {
id: string;
userId: string;
cardId: string;
card?: Card; // Populated card data
// Ownership status
status: 'owned' | 'wanted';
quantity: number;
condition?: 'mint' | 'near_mint' | 'excellent' | 'good' | 'light_played' | 'played' | 'poor';
// Organization
tags: string[]; // Tag IDs
notes?: string;
// Acquisition info
acquired_date?: string;
acquired_price?: number;
acquired_from?: string;
// Collection associations
collectionIds: string[];
deckIds: string[];
createdAt: string;
updatedAt: string;
}
export interface Collection {
id: string;
userId: string;
// Basic info
name: string;
description?: string;
game?: 'MTG' | 'POKEMON' | 'LORCANA' | 'YUGIOH' | 'OTHER';
// Organization
tags: string[]; // Tag IDs
color?: string;
icon?: string;
// Status
isPublic: boolean;
isFavorite: boolean;
// Stats (calculated)
cardCount?: number;
totalValue?: number;
completionPercentage?: number;
// Metadata
createdAt: string;
updatedAt: string;
// Populated data
cards?: UserCard[];
userTags?: Tag[];
}
export interface Deck {
id: string;
userId: string;
// Basic info
name: string;
description?: string;
game: 'MTG' | 'POKEMON' | 'LORCANA' | 'YUGIOH' | 'OTHER';
format?: string; // Standard, Commander, etc.
// Organization
tags: string[]; // Tag IDs
color?: string;
// Status
isPublic: boolean;
isFavorite: boolean;
isLegal?: boolean;
// Deck composition
mainboard: DeckCard[];
sideboard?: DeckCard[];
// Stats (calculated)
totalCards?: number;
totalValue?: number;
averageManaValue?: number;
colorIdentity?: string[];
// Metadata
createdAt: string;
updatedAt: string;
// Populated data
userTags?: Tag[];
}
export interface DeckCard {
cardId: string;
card?: Card; // Populated card data
quantity: number;
category?: string; // For organization within deck
notes?: string;
// Override card status for deck building
status: 'owned' | 'needed' | 'considering';
}
// API Response types
export interface ApiResponse<T> {
data: T;
message?: string;
success: boolean;
}
export interface PaginatedResponse<T> {
data: T[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
success: boolean;
}
// Filter and Search types
export interface CardFilters {
game?: string;
rarity?: string;
cardType?: string;
colors?: string[];
manaCost?: {
min?: number;
max?: number;
};
price?: {
min?: number;
max?: number;
};
search?: string;
tags?: string[];
status?: 'owned' | 'wanted' | 'all';
}
export interface CollectionFilters {
game?: string;
tags?: string[];
search?: string;
isPublic?: boolean;
isFavorite?: boolean;
}
export interface DeckFilters {
game?: string;
format?: string;
tags?: string[];
search?: string;
isPublic?: boolean;
isFavorite?: boolean;
isLegal?: boolean;
}
// Form types for creation/editing
export interface CreateCardData {
cardId: string; // Reference to card in database
status: 'owned' | 'wanted';
quantity: number;
condition?: string;
notes?: string;
tags?: string[];
collectionIds?: string[];
deckIds?: string[];
acquired_date?: string;
acquired_price?: number;
acquired_from?: string;
}
export interface CreateCollectionData {
name: string;
description?: string;
game?: string;
tags?: string[];
color?: string;
icon?: string;
isPublic?: boolean;
isFavorite?: boolean;
}
export interface CreateDeckData {
name: string;
description?: string;
game: string;
format?: string;
tags?: string[];
color?: string;
isPublic?: boolean;
isFavorite?: boolean;
}
export interface CreateTagData {
name: string;
color: string;
}
// Statistics and Analytics
export interface UserStats {
totalCards: number;
totalCollections: number;
totalDecks: number;
totalValue: number;
cardsByGame: Record<string, number>;
cardsByRarity: Record<string, number>;
cardsByStatus: {
owned: number;
wanted: number;
};
recentActivity: ActivityItem[];
}
export interface ActivityItem {
id: string;
type: 'card_added' | 'collection_created' | 'deck_created' | 'card_moved';
description: string;
entityId: string;
entityType: 'card' | 'collection' | 'deck';
createdAt: string;
}