Add trading and friends features with UI components and services

This commit is contained in:
Matthieu
2025-11-24 14:43:49 +01:00
parent e94952ad20
commit 459cc0eced
12 changed files with 1923 additions and 8 deletions

View File

@@ -0,0 +1,305 @@
import React, { useState, useEffect } from 'react';
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
import { getFriends, Friend } from '../services/friendsService';
import { getUserCollection, getCardsByIds } from '../services/api';
import { Card } from '../types';
import TradeCreator from './TradeCreator';
interface UserProfile {
id: string;
username: string | null;
collection_visibility: 'public' | 'friends' | 'private' | null;
}
interface CollectionItem {
card: Card;
quantity: number;
}
type Tab = 'public' | 'friends';
export default function Community() {
const { user } = useAuth();
const [activeTab, setActiveTab] = useState<Tab>('public');
const [searchQuery, setSearchQuery] = useState('');
const [publicUsers, setPublicUsers] = useState<UserProfile[]>([]);
const [friends, setFriends] = useState<Friend[]>([]);
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
const [loading, setLoading] = useState(true);
const [loadingCollection, setLoadingCollection] = useState(false);
const [showTradeCreator, setShowTradeCreator] = useState(false);
useEffect(() => {
if (user) {
loadData();
}
}, [user]);
const loadData = async () => {
if (!user) return;
setLoading(true);
try {
const [publicData, friendsData] = await Promise.all([
loadPublicUsers(),
getFriends(user.id),
]);
setPublicUsers(publicData);
setFriends(friendsData);
} catch (error) {
console.error('Error loading community data:', error);
} finally {
setLoading(false);
}
};
const loadPublicUsers = async (): Promise<UserProfile[]> => {
const { data, error } = await supabase
.from('profiles')
.select('id, username, collection_visibility')
.eq('collection_visibility', 'public')
.neq('id', user?.id)
.order('username');
if (error) throw error;
return data || [];
};
const loadUserCollection = async (userId: string) => {
setLoadingCollection(true);
try {
const collectionMap = await getUserCollection(userId);
if (collectionMap.size === 0) {
setSelectedUserCollection([]);
return;
}
const cardIds = Array.from(collectionMap.keys());
const cards = await getCardsByIds(cardIds);
const collectionWithCards = cards.map((card) => ({
card,
quantity: collectionMap.get(card.id) || 0,
}));
setSelectedUserCollection(collectionWithCards);
} catch (error) {
console.error('Error loading collection:', error);
setSelectedUserCollection([]);
} finally {
setLoadingCollection(false);
}
};
const handleViewCollection = async (userProfile: UserProfile) => {
setSelectedUser(userProfile);
await loadUserCollection(userProfile.id);
};
const filteredPublicUsers = publicUsers.filter(
(u) => !searchQuery || u.username?.toLowerCase().includes(searchQuery.toLowerCase())
);
const friendProfiles: UserProfile[] = friends.map((f) => ({
id: f.id,
username: f.username,
collection_visibility: 'friends' as const,
}));
const filteredFriends = friendProfiles.filter(
(f) => !searchQuery || f.username?.toLowerCase().includes(searchQuery.toLowerCase())
);
if (loading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
// If viewing a user's collection
if (selectedUser) {
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-6">
<div>
<button
onClick={() => {
setSelectedUser(null);
setSelectedUserCollection([]);
}}
className="text-blue-400 hover:text-blue-300 mb-2"
>
Back to Community
</button>
<h1 className="text-3xl font-bold">{selectedUser.username}'s Collection</h1>
</div>
<button
onClick={() => setShowTradeCreator(true)}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition"
>
<ArrowLeftRight size={20} />
Propose Trade
</button>
</div>
{/* Collection Grid */}
{loadingCollection ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="animate-spin text-blue-500" size={48} />
</div>
) : selectedUserCollection.length === 0 ? (
<p className="text-gray-400 text-center py-12">This collection is empty</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-7 xl:grid-cols-9 gap-2 sm:gap-3">
{selectedUserCollection.map(({ card, quantity }) => (
<div key={card.id} className="relative group">
<div className="rounded-lg overflow-hidden shadow-lg">
<img
src={card.image_uris?.normal || card.image_uris?.small}
alt={card.name}
className="w-full h-auto"
/>
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs font-bold px-2 py-1 rounded-full">
x{quantity}
</div>
</div>
<div className="mt-1 text-xs text-center truncate px-1">{card.name}</div>
</div>
))}
</div>
)}
{/* Trade Creator Modal */}
{showTradeCreator && (
<TradeCreator
receiverId={selectedUser.id}
receiverUsername={selectedUser.username || 'Unknown'}
receiverCollection={selectedUserCollection}
onClose={() => setShowTradeCreator(false)}
onTradeCreated={() => {
setShowTradeCreator(false);
alert('Trade proposal sent!');
}}
/>
)}
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-4xl mx-auto">
<h1 className="text-3xl font-bold mb-6">Community</h1>
{/* Search */}
<div className="relative mb-6">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search users..."
className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
{/* Tabs */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setActiveTab('public')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'public'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Globe size={18} />
Public Collections ({filteredPublicUsers.length})
</button>
<button
onClick={() => setActiveTab('friends')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'friends'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Users size={18} />
Friends ({filteredFriends.length})
</button>
</div>
{/* User List */}
<div className="space-y-3">
{activeTab === 'public' && (
<>
{filteredPublicUsers.length === 0 ? (
<p className="text-gray-400 text-center py-8">
No public collections found
</p>
) : (
filteredPublicUsers.map((userProfile) => (
<div
key={userProfile.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<div className="flex items-center gap-3">
<Globe size={20} className="text-green-400" />
<span className="font-medium">{userProfile.username || 'Unknown'}</span>
</div>
<button
onClick={() => handleViewCollection(userProfile)}
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
>
<Eye size={16} />
View Collection
</button>
</div>
))
)}
</>
)}
{activeTab === 'friends' && (
<>
{filteredFriends.length === 0 ? (
<p className="text-gray-400 text-center py-8">
{friends.length === 0
? 'Add friends to see their collections'
: 'No friends match your search'}
</p>
) : (
filteredFriends.map((friend) => (
<div
key={friend.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<div className="flex items-center gap-3">
<Users size={20} className="text-blue-400" />
<span className="font-medium">{friend.username || 'Unknown'}</span>
</div>
<button
onClick={() => handleViewCollection(friend)}
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
>
<Eye size={16} />
View Collection
</button>
</div>
))
)}
</>
)}
</div>
</div>
</div>
);
}

312
src/components/Friends.tsx Normal file
View File

@@ -0,0 +1,312 @@
import React, { useState, useEffect } from 'react';
import { Search, UserPlus, UserMinus, Check, X, Users, Clock, Send } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import {
getFriends,
getPendingRequests,
getSentRequests,
searchUsers,
sendFriendRequest,
acceptFriendRequest,
declineFriendRequest,
removeFriend,
Friend,
} from '../services/friendsService';
type Tab = 'friends' | 'requests' | 'search';
export default function Friends() {
const { user } = useAuth();
const [activeTab, setActiveTab] = useState<Tab>('friends');
const [friends, setFriends] = useState<Friend[]>([]);
const [pendingRequests, setPendingRequests] = useState<Friend[]>([]);
const [sentRequests, setSentRequests] = useState<Friend[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<{ id: string; username: string | null }[]>([]);
const [loading, setLoading] = useState(true);
const [searching, setSearching] = useState(false);
useEffect(() => {
if (user) {
loadFriendsData();
}
}, [user]);
const loadFriendsData = async () => {
if (!user) return;
setLoading(true);
try {
const [friendsData, pendingData, sentData] = await Promise.all([
getFriends(user.id),
getPendingRequests(user.id),
getSentRequests(user.id),
]);
setFriends(friendsData);
setPendingRequests(pendingData);
setSentRequests(sentData);
} catch (error) {
console.error('Error loading friends:', error);
} finally {
setLoading(false);
}
};
const handleSearch = async () => {
if (!user || searchQuery.trim().length < 2) return;
setSearching(true);
try {
const results = await searchUsers(searchQuery, user.id);
setSearchResults(results || []);
} catch (error) {
console.error('Error searching users:', error);
} finally {
setSearching(false);
}
};
const handleSendRequest = async (addresseeId: string) => {
if (!user) return;
try {
await sendFriendRequest(user.id, addresseeId);
setSearchResults((prev) => prev.filter((u) => u.id !== addresseeId));
await loadFriendsData();
} catch (error) {
console.error('Error sending friend request:', error);
alert('Failed to send friend request');
}
};
const handleAcceptRequest = async (friendshipId: string) => {
try {
await acceptFriendRequest(friendshipId);
await loadFriendsData();
} catch (error) {
console.error('Error accepting request:', error);
}
};
const handleDeclineRequest = async (friendshipId: string) => {
try {
await declineFriendRequest(friendshipId);
await loadFriendsData();
} catch (error) {
console.error('Error declining request:', error);
}
};
const handleRemoveFriend = async (friendshipId: string) => {
if (!confirm('Remove this friend?')) return;
try {
await removeFriend(friendshipId);
await loadFriendsData();
} catch (error) {
console.error('Error removing friend:', error);
}
};
const isAlreadyFriendOrPending = (userId: string) => {
return (
friends.some((f) => f.id === userId) ||
pendingRequests.some((f) => f.id === userId) ||
sentRequests.some((f) => f.id === userId)
);
};
if (loading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-2xl mx-auto">
<h1 className="text-3xl font-bold mb-6">Friends</h1>
{/* Tabs */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setActiveTab('friends')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'friends'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Users size={18} />
Friends ({friends.length})
</button>
<button
onClick={() => setActiveTab('requests')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'requests'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Clock size={18} />
Requests ({pendingRequests.length})
</button>
<button
onClick={() => setActiveTab('search')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'search'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Search size={18} />
Search
</button>
</div>
{/* Friends List */}
{activeTab === 'friends' && (
<div className="space-y-3">
{friends.length === 0 ? (
<p className="text-gray-400 text-center py-8">
No friends yet. Search for users to add them!
</p>
) : (
friends.map((friend) => (
<div
key={friend.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<span className="font-medium">{friend.username || 'Unknown'}</span>
<button
onClick={() => handleRemoveFriend(friend.friendshipId)}
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
title="Remove friend"
>
<UserMinus size={20} />
</button>
</div>
))
)}
</div>
)}
{/* Requests Tab */}
{activeTab === 'requests' && (
<div className="space-y-6">
{/* Received Requests */}
<div>
<h2 className="text-lg font-semibold mb-3 text-gray-300">Received Requests</h2>
{pendingRequests.length === 0 ? (
<p className="text-gray-500 text-sm">No pending requests</p>
) : (
<div className="space-y-3">
{pendingRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<span className="font-medium">{request.username || 'Unknown'}</span>
<div className="flex gap-2">
<button
onClick={() => handleAcceptRequest(request.friendshipId)}
className="p-2 text-green-400 hover:bg-green-400/20 rounded-lg transition"
title="Accept"
>
<Check size={20} />
</button>
<button
onClick={() => handleDeclineRequest(request.friendshipId)}
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
title="Decline"
>
<X size={20} />
</button>
</div>
</div>
))}
</div>
)}
</div>
{/* Sent Requests */}
<div>
<h2 className="text-lg font-semibold mb-3 text-gray-300">Sent Requests</h2>
{sentRequests.length === 0 ? (
<p className="text-gray-500 text-sm">No sent requests</p>
) : (
<div className="space-y-3">
{sentRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<div className="flex items-center gap-2">
<Send size={16} className="text-gray-500" />
<span className="font-medium">{request.username || 'Unknown'}</span>
</div>
<span className="text-sm text-yellow-500">Pending</span>
</div>
))}
</div>
)}
</div>
</div>
)}
{/* Search Tab */}
{activeTab === 'search' && (
<div className="space-y-4">
<div className="flex gap-2">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
placeholder="Search by username..."
className="flex-1 px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<button
onClick={handleSearch}
disabled={searching || searchQuery.trim().length < 2}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg transition"
>
{searching ? (
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
) : (
<Search size={20} />
)}
</button>
</div>
{searchResults.length > 0 && (
<div className="space-y-3">
{searchResults.map((result) => (
<div
key={result.id}
className="flex items-center justify-between bg-gray-800 p-4 rounded-lg"
>
<span className="font-medium">{result.username || 'Unknown'}</span>
{isAlreadyFriendOrPending(result.id) ? (
<span className="text-sm text-gray-500">Already connected</span>
) : (
<button
onClick={() => handleSendRequest(result.id)}
className="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition text-sm"
>
<UserPlus size={16} />
Add Friend
</button>
)}
</div>
))}
</div>
)}
{searchQuery.length >= 2 && searchResults.length === 0 && !searching && (
<p className="text-gray-400 text-center py-4">No users found</p>
)}
</div>
)}
</div>
</div>
);
}

View File

@@ -1,9 +1,9 @@
import React, { useState, useRef, useEffect } from 'react';
import { Home, PlusSquare, Library, LogOut, Settings, ChevronDown, Search, Heart, Menu } from 'lucide-react';
import { Home, PlusSquare, Library, LogOut, Settings, ChevronDown, Search, Heart, Menu, Users, ArrowLeftRight, Globe } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter';
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
interface NavigationProps {
currentPage: Page;
@@ -53,8 +53,11 @@ import React, { useState, useRef, useEffect } from 'react';
const navItems = [
{ id: 'home' as const, label: 'Decks', icon: Library },
{ id: 'collection' as const, label: 'Collection', icon: Library },
{ id: 'community' as const, label: 'Community', icon: Globe },
{ id: 'friends' as const, label: 'Friends', icon: Users },
{ id: 'trades' as const, label: 'Trades', icon: ArrowLeftRight },
{ id: 'search' as const, label: 'Search', icon: Search },
{ id: 'life-counter' as const, label: 'Life Counter', icon: Heart },
{ id: 'life-counter' as const, label: 'Life', icon: Heart },
];
const handleSignOut = async () => {

View File

@@ -1,14 +1,23 @@
import React, { useState, useEffect } from 'react';
import { Save } from 'lucide-react';
import { Save, Globe, Users, Lock } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../lib/supabase';
const THEME_COLORS = ['red', 'green', 'blue', 'yellow', 'grey', 'purple'];
const VISIBILITY_OPTIONS = [
{ value: 'public', label: 'Public', icon: Globe, description: 'Anyone can view your collection' },
{ value: 'friends', label: 'Friends Only', icon: Users, description: 'Only friends can view your collection' },
{ value: 'private', label: 'Private', icon: Lock, description: 'Only you can view your collection' },
] as const;
type CollectionVisibility = 'public' | 'friends' | 'private';
export default function Profile() {
const { user } = useAuth();
const [username, setUsername] = useState('');
const [themeColor, setThemeColor] = useState('blue');
const [collectionVisibility, setCollectionVisibility] = useState<CollectionVisibility>('private');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -17,13 +26,14 @@ export default function Profile() {
if (user) {
const { data, error } = await supabase
.from('profiles')
.select('username, theme_color')
.select('username, theme_color, collection_visibility')
.eq('id', user.id)
.single();
if (data) {
setUsername(data.username || '');
setThemeColor(data.theme_color || 'blue');
setCollectionVisibility((data.collection_visibility as CollectionVisibility) || 'private');
}
setLoading(false);
}
@@ -44,6 +54,7 @@ export default function Profile() {
id: user.id,
username,
theme_color: themeColor,
collection_visibility: collectionVisibility,
updated_at: new Date()
});
@@ -107,6 +118,35 @@ export default function Profile() {
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Collection Visibility
</label>
<div className="space-y-2">
{VISIBILITY_OPTIONS.map((option) => {
const Icon = option.icon;
return (
<button
key={option.value}
type="button"
onClick={() => setCollectionVisibility(option.value)}
className={`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left
${collectionVisibility === option.value
? 'border-blue-500 bg-blue-500/10'
: 'border-gray-700 hover:border-gray-600 bg-gray-800'
}`}
>
<Icon size={20} className={collectionVisibility === option.value ? 'text-blue-400' : 'text-gray-400'} />
<div>
<div className="font-medium">{option.label}</div>
<div className="text-sm text-gray-400">{option.description}</div>
</div>
</button>
);
})}
</div>
</div>
<button
type="submit"
disabled={saving}

View File

@@ -0,0 +1,380 @@
import React, { useState, useEffect } from 'react';
import { X, ArrowLeftRight, Plus, Minus, Send, Gift } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { getUserCollection, getCardsByIds } from '../services/api';
import { createTrade } from '../services/tradesService';
import { Card } from '../types';
interface CollectionItem {
card: Card;
quantity: number;
}
interface TradeCreatorProps {
receiverId: string;
receiverUsername: string;
receiverCollection: CollectionItem[];
onClose: () => void;
onTradeCreated: () => void;
}
interface SelectedCard {
card: Card;
quantity: number;
maxQuantity: number;
}
export default function TradeCreator({
receiverId,
receiverUsername,
receiverCollection,
onClose,
onTradeCreated,
}: TradeCreatorProps) {
const { user } = useAuth();
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState('');
// Cards I'm offering (from my collection)
const [myOfferedCards, setMyOfferedCards] = useState<Map<string, SelectedCard>>(new Map());
// Cards I want (from their collection)
const [wantedCards, setWantedCards] = useState<Map<string, SelectedCard>>(new Map());
useEffect(() => {
loadMyCollection();
}, [user]);
const loadMyCollection = async () => {
if (!user) return;
setLoading(true);
try {
const collectionMap = await getUserCollection(user.id);
if (collectionMap.size === 0) {
setMyCollection([]);
return;
}
const cardIds = Array.from(collectionMap.keys());
const cards = await getCardsByIds(cardIds);
const collectionWithCards = cards.map((card) => ({
card,
quantity: collectionMap.get(card.id) || 0,
}));
setMyCollection(collectionWithCards);
} catch (error) {
console.error('Error loading my collection:', error);
} finally {
setLoading(false);
}
};
const addToOffer = (card: Card, maxQuantity: number) => {
setMyOfferedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(card.id);
if (existing) {
if (existing.quantity < existing.maxQuantity) {
newMap.set(card.id, { ...existing, quantity: existing.quantity + 1 });
}
} else {
newMap.set(card.id, { card, quantity: 1, maxQuantity });
}
return newMap;
});
};
const removeFromOffer = (cardId: string) => {
setMyOfferedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(cardId);
if (existing && existing.quantity > 1) {
newMap.set(cardId, { ...existing, quantity: existing.quantity - 1 });
} else {
newMap.delete(cardId);
}
return newMap;
});
};
const addToWanted = (card: Card, maxQuantity: number) => {
setWantedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(card.id);
if (existing) {
if (existing.quantity < existing.maxQuantity) {
newMap.set(card.id, { ...existing, quantity: existing.quantity + 1 });
}
} else {
newMap.set(card.id, { card, quantity: 1, maxQuantity });
}
return newMap;
});
};
const removeFromWanted = (cardId: string) => {
setWantedCards((prev) => {
const newMap = new Map(prev);
const existing = newMap.get(cardId);
if (existing && existing.quantity > 1) {
newMap.set(cardId, { ...existing, quantity: existing.quantity - 1 });
} else {
newMap.delete(cardId);
}
return newMap;
});
};
const handleSubmit = async () => {
if (!user) return;
// At least one side should have cards (allowing gifts)
if (myOfferedCards.size === 0 && wantedCards.size === 0) {
alert('Please select at least one card to trade or gift');
return;
}
setSubmitting(true);
try {
const senderCards = Array.from(myOfferedCards.values()).map((item) => ({
cardId: item.card.id,
quantity: item.quantity,
}));
const receiverCards = Array.from(wantedCards.values()).map((item) => ({
cardId: item.card.id,
quantity: item.quantity,
}));
await createTrade({
senderId: user.id,
receiverId,
message: message || undefined,
senderCards,
receiverCards,
});
onTradeCreated();
} catch (error) {
console.error('Error creating trade:', error);
alert('Failed to create trade');
} finally {
setSubmitting(false);
}
};
const isGift = myOfferedCards.size > 0 && wantedCards.size === 0;
const isRequest = myOfferedCards.size === 0 && wantedCards.size > 0;
return (
<div className="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center p-4">
<div className="bg-gray-800 rounded-lg w-full max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-gray-700">
<div className="flex items-center gap-2">
<ArrowLeftRight size={24} className="text-blue-400" />
<h2 className="text-xl font-bold">Trade with {receiverUsername}</h2>
</div>
<button
onClick={onClose}
className="p-2 hover:bg-gray-700 rounded-lg transition"
>
<X size={24} />
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-hidden flex flex-col md:flex-row">
{/* My Collection (Left) */}
<div className="flex-1 p-4 border-b md:border-b-0 md:border-r border-gray-700 overflow-y-auto">
<h3 className="text-lg font-semibold mb-3 text-green-400">
My Collection (I give)
</h3>
{loading ? (
<div className="flex justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
) : myCollection.length === 0 ? (
<p className="text-gray-400 text-center py-4">Your collection is empty</p>
) : (
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
{myCollection.map(({ card, quantity }) => {
const offered = myOfferedCards.get(card.id);
const remainingQty = quantity - (offered?.quantity || 0);
return (
<div
key={card.id}
className={`relative cursor-pointer rounded-lg overflow-hidden transition ${
offered ? 'ring-2 ring-green-500' : 'hover:ring-2 hover:ring-gray-500'
}`}
onClick={() => remainingQty > 0 && addToOffer(card, quantity)}
>
<img
src={card.image_uris?.small}
alt={card.name}
className={`w-full h-auto ${remainingQty === 0 ? 'opacity-50' : ''}`}
/>
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
{remainingQty}/{quantity}
</div>
{offered && (
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-xs px-1.5 py-0.5 rounded">
+{offered.quantity}
</div>
)}
</div>
);
})}
</div>
)}
</div>
{/* Their Collection (Right) */}
<div className="flex-1 p-4 overflow-y-auto">
<h3 className="text-lg font-semibold mb-3 text-blue-400">
{receiverUsername}'s Collection (I want)
</h3>
{receiverCollection.length === 0 ? (
<p className="text-gray-400 text-center py-4">Their collection is empty</p>
) : (
<div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
{receiverCollection.map(({ card, quantity }) => {
const wanted = wantedCards.get(card.id);
const remainingQty = quantity - (wanted?.quantity || 0);
return (
<div
key={card.id}
className={`relative cursor-pointer rounded-lg overflow-hidden transition ${
wanted ? 'ring-2 ring-blue-500' : 'hover:ring-2 hover:ring-gray-500'
}`}
onClick={() => remainingQty > 0 && addToWanted(card, quantity)}
>
<img
src={card.image_uris?.small}
alt={card.name}
className={`w-full h-auto ${remainingQty === 0 ? 'opacity-50' : ''}`}
/>
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs px-1.5 py-0.5 rounded">
{remainingQty}/{quantity}
</div>
{wanted && (
<div className="absolute bottom-1 left-1 bg-blue-500 text-white text-xs px-1.5 py-0.5 rounded">
+{wanted.quantity}
</div>
)}
</div>
);
})}
</div>
)}
</div>
</div>
{/* Trade Summary */}
<div className="border-t border-gray-700 p-4">
<div className="flex flex-col md:flex-row gap-4 mb-4">
{/* I Give */}
<div className="flex-1">
<h4 className="text-sm font-semibold text-green-400 mb-2">I Give:</h4>
{myOfferedCards.size === 0 ? (
<p className="text-gray-500 text-sm">Nothing selected (gift request)</p>
) : (
<div className="flex flex-wrap gap-2">
{Array.from(myOfferedCards.values()).map((item) => (
<div
key={item.card.id}
className="flex items-center gap-1 bg-green-900/50 px-2 py-1 rounded text-sm"
>
<span>{item.card.name}</span>
<span className="text-green-400">x{item.quantity}</span>
<button
onClick={() => removeFromOffer(item.card.id)}
className="ml-1 text-red-400 hover:text-red-300"
>
<Minus size={14} />
</button>
</div>
))}
</div>
)}
</div>
{/* I Want */}
<div className="flex-1">
<h4 className="text-sm font-semibold text-blue-400 mb-2">I Want:</h4>
{wantedCards.size === 0 ? (
<p className="text-gray-500 text-sm">Nothing selected (gift)</p>
) : (
<div className="flex flex-wrap gap-2">
{Array.from(wantedCards.values()).map((item) => (
<div
key={item.card.id}
className="flex items-center gap-1 bg-blue-900/50 px-2 py-1 rounded text-sm"
>
<span>{item.card.name}</span>
<span className="text-blue-400">x{item.quantity}</span>
<button
onClick={() => removeFromWanted(item.card.id)}
className="ml-1 text-red-400 hover:text-red-300"
>
<Minus size={14} />
</button>
</div>
))}
</div>
)}
</div>
</div>
{/* Message */}
<div className="mb-4">
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Add a message (optional)"
className="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>
{/* Submit */}
<div className="flex justify-end gap-3">
<button
onClick={onClose}
className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={submitting || (myOfferedCards.size === 0 && wantedCards.size === 0)}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg transition"
>
{submitting ? (
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
) : isGift ? (
<>
<Gift size={20} />
Send Gift
</>
) : isRequest ? (
<>
<Send size={20} />
Request Cards
</>
) : (
<>
<Send size={20} />
Propose Trade
</>
)}
</button>
</div>
</div>
</div>
</div>
);
}

326
src/components/Trades.tsx Normal file
View File

@@ -0,0 +1,326 @@
import React, { useState, useEffect } from 'react';
import { ArrowLeftRight, Check, X, Clock, History, Plus, Package } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import {
getTrades,
getTradeHistory,
acceptTrade,
declineTrade,
cancelTrade,
Trade,
TradeItem,
} from '../services/tradesService';
import { getCardsByIds } from '../services/api';
import { Card } from '../types';
type Tab = 'pending' | 'history';
interface TradeWithCards extends Trade {
cardDetails?: Map<string, Card>;
}
export default function Trades() {
const { user } = useAuth();
const [activeTab, setActiveTab] = useState<Tab>('pending');
const [pendingTrades, setPendingTrades] = useState<TradeWithCards[]>([]);
const [tradeHistory, setTradeHistory] = useState<TradeWithCards[]>([]);
const [loading, setLoading] = useState(true);
const [processingTradeId, setProcessingTradeId] = useState<string | null>(null);
useEffect(() => {
if (user) {
loadTrades();
}
}, [user]);
const loadTrades = async () => {
if (!user) return;
setLoading(true);
try {
const [pending, history] = await Promise.all([
getTrades(user.id).then((trades) => trades.filter((t) => t.status === 'pending')),
getTradeHistory(user.id),
]);
// Load card details for all trades
const allCardIds = new Set<string>();
[...pending, ...history].forEach((trade) => {
trade.items?.forEach((item) => allCardIds.add(item.card_id));
});
let cardDetails = new Map<string, Card>();
if (allCardIds.size > 0) {
const cards = await getCardsByIds(Array.from(allCardIds));
cards.forEach((card) => cardDetails.set(card.id, card));
}
setPendingTrades(pending.map((t) => ({ ...t, cardDetails })));
setTradeHistory(history.map((t) => ({ ...t, cardDetails })));
} catch (error) {
console.error('Error loading trades:', error);
} finally {
setLoading(false);
}
};
const handleAccept = async (tradeId: string) => {
setProcessingTradeId(tradeId);
try {
const success = await acceptTrade(tradeId);
if (success) {
await loadTrades();
} else {
alert('Failed to execute trade. Please check your collection.');
}
} catch (error) {
console.error('Error accepting trade:', error);
alert('Error accepting trade');
} finally {
setProcessingTradeId(null);
}
};
const handleDecline = async (tradeId: string) => {
setProcessingTradeId(tradeId);
try {
await declineTrade(tradeId);
await loadTrades();
} catch (error) {
console.error('Error declining trade:', error);
} finally {
setProcessingTradeId(null);
}
};
const handleCancel = async (tradeId: string) => {
if (!confirm('Cancel this trade offer?')) return;
setProcessingTradeId(tradeId);
try {
await cancelTrade(tradeId);
await loadTrades();
} catch (error) {
console.error('Error cancelling trade:', error);
} finally {
setProcessingTradeId(null);
}
};
const getStatusColor = (status: Trade['status']) => {
switch (status) {
case 'accepted':
return 'text-green-400';
case 'declined':
return 'text-red-400';
case 'cancelled':
return 'text-gray-400';
default:
return 'text-yellow-400';
}
};
const renderTradeItems = (
items: TradeItem[] | undefined,
ownerId: string,
cardDetails: Map<string, Card> | undefined,
label: string
) => {
const ownerItems = items?.filter((i) => i.owner_id === ownerId) || [];
if (ownerItems.length === 0) {
return (
<div className="text-gray-500 text-sm italic">
{label}: Nothing (gift)
</div>
);
}
return (
<div>
<div className="text-gray-400 text-sm mb-1">{label}:</div>
<div className="flex flex-wrap gap-2">
{ownerItems.map((item) => {
const card = cardDetails?.get(item.card_id);
return (
<div
key={item.id}
className="flex items-center gap-2 bg-gray-700 px-2 py-1 rounded text-sm"
>
{card?.image_uris?.small && (
<img
src={card.image_uris.small}
alt={card.name}
className="w-8 h-11 rounded"
/>
)}
<span>{card?.name || item.card_id}</span>
{item.quantity > 1 && (
<span className="text-gray-400">x{item.quantity}</span>
)}
</div>
);
})}
</div>
</div>
);
};
const renderTrade = (trade: TradeWithCards, showActions: boolean) => {
const isSender = trade.sender_id === user?.id;
const otherUser = isSender ? trade.receiver : trade.sender;
return (
<div key={trade.id} className="bg-gray-800 rounded-lg p-4 space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ArrowLeftRight size={18} className="text-blue-400" />
<span className="font-medium">
{isSender ? `To: ${otherUser?.username}` : `From: ${otherUser?.username}`}
</span>
</div>
<span className={`text-sm capitalize ${getStatusColor(trade.status)}`}>
{trade.status}
</span>
</div>
{/* Trade Items */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{renderTradeItems(
trade.items,
trade.sender_id,
trade.cardDetails,
isSender ? 'You give' : 'They give'
)}
{renderTradeItems(
trade.items,
trade.receiver_id,
trade.cardDetails,
isSender ? 'You receive' : 'They receive'
)}
</div>
{/* Message */}
{trade.message && (
<div className="text-gray-400 text-sm">
<span className="text-gray-500">Message:</span> {trade.message}
</div>
)}
{/* Actions */}
{showActions && trade.status === 'pending' && (
<div className="flex gap-2 pt-2 border-t border-gray-700">
{isSender ? (
<button
onClick={() => handleCancel(trade.id)}
disabled={processingTradeId === trade.id}
className="flex items-center gap-2 px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm"
>
<X size={16} />
Cancel
</button>
) : (
<>
<button
onClick={() => handleAccept(trade.id)}
disabled={processingTradeId === trade.id}
className="flex items-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 rounded-lg transition text-sm"
>
{processingTradeId === trade.id ? (
<div className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white"></div>
) : (
<Check size={16} />
)}
Accept
</button>
<button
onClick={() => handleDecline(trade.id)}
disabled={processingTradeId === trade.id}
className="flex items-center gap-2 px-3 py-2 bg-red-600 hover:bg-red-700 rounded-lg transition text-sm"
>
<X size={16} />
Decline
</button>
</>
)}
</div>
)}
{/* Timestamp */}
<div className="text-gray-500 text-xs">
{new Date(trade.created_at || '').toLocaleDateString()}
</div>
</div>
);
};
if (loading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 text-white p-6">
<div className="max-w-3xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h1 className="text-3xl font-bold">Trades</h1>
</div>
{/* Tabs */}
<div className="flex gap-2 mb-6">
<button
onClick={() => setActiveTab('pending')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'pending'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<Clock size={18} />
Pending ({pendingTrades.length})
</button>
<button
onClick={() => setActiveTab('history')}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
activeTab === 'history'
? 'bg-blue-600 text-white'
: 'bg-gray-800 text-gray-300 hover:bg-gray-700'
}`}
>
<History size={18} />
History
</button>
</div>
{/* Pending Trades */}
{activeTab === 'pending' && (
<div className="space-y-4">
{pendingTrades.length === 0 ? (
<div className="text-center py-12">
<Package size={48} className="mx-auto text-gray-600 mb-4" />
<p className="text-gray-400">No pending trades</p>
<p className="text-gray-500 text-sm mt-2">
Visit a friend's collection to propose a trade
</p>
</div>
) : (
pendingTrades.map((trade) => renderTrade(trade, true))
)}
</div>
)}
{/* Trade History */}
{activeTab === 'history' && (
<div className="space-y-4">
{tradeHistory.length === 0 ? (
<p className="text-gray-400 text-center py-8">No trade history yet</p>
) : (
tradeHistory.map((trade) => renderTrade(trade, false))
)}
</div>
)}
</div>
</div>
);
}