Add Toast context for notifications and refactor community features
This commit is contained in:
46
src/App.tsx
46
src/App.tsx
@@ -1,22 +1,20 @@
|
||||
import React, { useState } from 'react';
|
||||
import DeckManager from './components/DeckManager';
|
||||
import DeckList from './components/DeckList';
|
||||
import LoginForm from './components/LoginForm';
|
||||
import Navigation from './components/Navigation';
|
||||
import Collection from './components/Collection';
|
||||
import DeckEditor from './components/DeckEditor';
|
||||
import Profile from './components/Profile';
|
||||
import CardSearch from './components/CardSearch';
|
||||
import LifeCounter from './components/LifeCounter';
|
||||
import Friends from './components/Friends';
|
||||
import Trades from './components/Trades';
|
||||
import Community from './components/Community';
|
||||
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||
import DeckManager from './components/DeckManager';
|
||||
import DeckList from './components/DeckList';
|
||||
import LoginForm from './components/LoginForm';
|
||||
import Navigation from './components/Navigation';
|
||||
import Collection from './components/Collection';
|
||||
import DeckEditor from './components/DeckEditor';
|
||||
import CardSearch from './components/CardSearch';
|
||||
import LifeCounter from './components/LifeCounter';
|
||||
import Community from './components/Community';
|
||||
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||
import { ToastProvider } from './contexts/ToastContext';
|
||||
|
||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
|
||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'search' | 'life-counter' | 'community';
|
||||
|
||||
function AppContent() {
|
||||
function AppContent() {
|
||||
const [currentPage, setCurrentPage] = useState<Page>('home');
|
||||
const [selectedDeckId, setSelectedDeckId] = useState<string | null>(null);
|
||||
const { user, loading } = useAuth();
|
||||
@@ -66,16 +64,10 @@ import React, { useState } from 'react';
|
||||
) : null;
|
||||
case 'collection':
|
||||
return <Collection />;
|
||||
case 'profile':
|
||||
return <Profile />;
|
||||
case 'search':
|
||||
return <CardSearch />;
|
||||
case 'life-counter':
|
||||
return <LifeCounter />;
|
||||
case 'friends':
|
||||
return <Friends />;
|
||||
case 'trades':
|
||||
return <Trades />;
|
||||
case 'community':
|
||||
return <Community />;
|
||||
case 'login':
|
||||
@@ -92,14 +84,16 @@ import React, { useState } from 'react';
|
||||
<PWAInstallPrompt />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function App() {
|
||||
function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<AppContent />
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default App;
|
||||
export default App;
|
||||
|
||||
@@ -1,11 +1,32 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2 } from 'lucide-react';
|
||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { getFriends, Friend } from '../services/friendsService';
|
||||
import {
|
||||
getFriends,
|
||||
getPendingRequests,
|
||||
getSentRequests,
|
||||
searchUsers,
|
||||
sendFriendRequest,
|
||||
acceptFriendRequest,
|
||||
declineFriendRequest,
|
||||
removeFriend,
|
||||
Friend,
|
||||
} from '../services/friendsService';
|
||||
import {
|
||||
getTrades,
|
||||
getTradeHistory,
|
||||
acceptTrade,
|
||||
declineTrade,
|
||||
cancelTrade,
|
||||
Trade,
|
||||
TradeItem,
|
||||
} from '../services/tradesService';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { Card } from '../types';
|
||||
import TradeCreator from './TradeCreator';
|
||||
import ConfirmModal from './ConfirmModal';
|
||||
|
||||
interface UserProfile {
|
||||
id: string;
|
||||
@@ -18,44 +39,85 @@ interface CollectionItem {
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
type Tab = 'public' | 'friends';
|
||||
type Tab = 'browse' | 'friends' | 'trades' | 'profile';
|
||||
type FriendsSubTab = 'list' | 'requests' | 'search';
|
||||
type TradesSubTab = 'pending' | 'history';
|
||||
|
||||
const VISIBILITY_OPTIONS = [
|
||||
{ value: 'public', label: 'Public', description: 'Anyone can view your collection' },
|
||||
{ value: 'friends', label: 'Friends Only', description: 'Only friends can view' },
|
||||
{ value: 'private', label: 'Private', description: 'Only you can view' },
|
||||
] as const;
|
||||
|
||||
export default function Community() {
|
||||
const { user } = useAuth();
|
||||
const [activeTab, setActiveTab] = useState<Tab>('public');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const toast = useToast();
|
||||
const [activeTab, setActiveTab] = useState<Tab>('browse');
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Browse state
|
||||
const [browseSearch, setBrowseSearch] = 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);
|
||||
|
||||
// Friends state
|
||||
const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list');
|
||||
const [friends, setFriends] = useState<Friend[]>([]);
|
||||
const [pendingRequests, setPendingRequests] = useState<Friend[]>([]);
|
||||
const [sentRequests, setSentRequests] = useState<Friend[]>([]);
|
||||
const [friendSearch, setFriendSearch] = useState('');
|
||||
const [friendSearchResults, setFriendSearchResults] = useState<{ id: string; username: string | null }[]>([]);
|
||||
const [searchingFriends, setSearchingFriends] = useState(false);
|
||||
|
||||
// Trades state
|
||||
const [tradesSubTab, setTradesSubTab] = useState<TradesSubTab>('pending');
|
||||
const [pendingTrades, setPendingTrades] = useState<Trade[]>([]);
|
||||
const [tradeHistory, setTradeHistory] = useState<Trade[]>([]);
|
||||
const [tradeCardDetails, setTradeCardDetails] = useState<Map<string, Card>>(new Map());
|
||||
const [processingTradeId, setProcessingTradeId] = useState<string | null>(null);
|
||||
|
||||
// Profile state
|
||||
const [username, setUsername] = useState('');
|
||||
const [collectionVisibility, setCollectionVisibility] = useState<'public' | 'friends' | 'private'>('private');
|
||||
const [savingProfile, setSavingProfile] = useState(false);
|
||||
|
||||
// Confirm modal state
|
||||
const [confirmModal, setConfirmModal] = useState<{
|
||||
isOpen: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
onConfirm: () => void;
|
||||
variant: 'danger' | 'warning' | 'info' | 'success';
|
||||
}>({ isOpen: false, title: '', message: '', onConfirm: () => {}, variant: 'danger' });
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
loadData();
|
||||
loadAllData();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const loadData = async () => {
|
||||
const loadAllData = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [publicData, friendsData] = await Promise.all([
|
||||
await Promise.all([
|
||||
loadPublicUsers(),
|
||||
getFriends(user.id),
|
||||
loadFriendsData(),
|
||||
loadTradesData(),
|
||||
loadProfile(),
|
||||
]);
|
||||
setPublicUsers(publicData);
|
||||
setFriends(friendsData);
|
||||
} catch (error) {
|
||||
console.error('Error loading community data:', error);
|
||||
console.error('Error loading data:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadPublicUsers = async (): Promise<UserProfile[]> => {
|
||||
// ============ BROWSE FUNCTIONS ============
|
||||
const loadPublicUsers = async () => {
|
||||
const { data, error } = await supabase
|
||||
.from('profiles')
|
||||
.select('id, username, collection_visibility')
|
||||
@@ -63,29 +125,25 @@ export default function Community() {
|
||||
.neq('id', user?.id)
|
||||
.order('username');
|
||||
|
||||
if (error) throw error;
|
||||
return data || [];
|
||||
if (!error && data) {
|
||||
setPublicUsers(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) => ({
|
||||
setSelectedUserCollection(cards.map((card) => ({
|
||||
card,
|
||||
quantity: collectionMap.get(card.id) || 0,
|
||||
}));
|
||||
|
||||
setSelectedUserCollection(collectionWithCards);
|
||||
})));
|
||||
} catch (error) {
|
||||
console.error('Error loading collection:', error);
|
||||
setSelectedUserCollection([]);
|
||||
@@ -94,24 +152,227 @@ export default function Community() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleViewCollection = async (userProfile: UserProfile) => {
|
||||
setSelectedUser(userProfile);
|
||||
await loadUserCollection(userProfile.id);
|
||||
// ============ FRIENDS FUNCTIONS ============
|
||||
const loadFriendsData = async () => {
|
||||
if (!user) return;
|
||||
const [friendsData, pendingData, sentData] = await Promise.all([
|
||||
getFriends(user.id),
|
||||
getPendingRequests(user.id),
|
||||
getSentRequests(user.id),
|
||||
]);
|
||||
setFriends(friendsData);
|
||||
setPendingRequests(pendingData);
|
||||
setSentRequests(sentData);
|
||||
};
|
||||
|
||||
const filteredPublicUsers = publicUsers.filter(
|
||||
(u) => !searchQuery || u.username?.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
const handleSearchFriends = async () => {
|
||||
if (!user || friendSearch.trim().length < 2) return;
|
||||
setSearchingFriends(true);
|
||||
try {
|
||||
const results = await searchUsers(friendSearch, user.id);
|
||||
setFriendSearchResults(results || []);
|
||||
} catch (error) {
|
||||
console.error('Error searching users:', error);
|
||||
} finally {
|
||||
setSearchingFriends(false);
|
||||
}
|
||||
};
|
||||
|
||||
const friendProfiles: UserProfile[] = friends.map((f) => ({
|
||||
id: f.id,
|
||||
username: f.username,
|
||||
collection_visibility: 'friends' as const,
|
||||
}));
|
||||
const handleSendRequest = async (addresseeId: string) => {
|
||||
if (!user) return;
|
||||
try {
|
||||
await sendFriendRequest(user.id, addresseeId);
|
||||
setFriendSearchResults((prev) => prev.filter((u) => u.id !== addresseeId));
|
||||
await loadFriendsData();
|
||||
toast.success('Friend request sent!');
|
||||
} catch (error) {
|
||||
toast.error('Failed to send friend request');
|
||||
}
|
||||
};
|
||||
|
||||
const filteredFriends = friendProfiles.filter(
|
||||
(f) => !searchQuery || f.username?.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
const handleAcceptRequest = async (friendshipId: string) => {
|
||||
try {
|
||||
await acceptFriendRequest(friendshipId);
|
||||
await loadFriendsData();
|
||||
toast.success('Friend request accepted!');
|
||||
} catch (error) {
|
||||
toast.error('Failed to accept request');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeclineRequest = async (friendshipId: string) => {
|
||||
try {
|
||||
await declineFriendRequest(friendshipId);
|
||||
await loadFriendsData();
|
||||
toast.info('Friend request declined');
|
||||
} catch (error) {
|
||||
toast.error('Failed to decline request');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveFriend = (friendshipId: string, friendName: string) => {
|
||||
setConfirmModal({
|
||||
isOpen: true,
|
||||
title: 'Remove Friend',
|
||||
message: `Are you sure you want to remove ${friendName} from your friends?`,
|
||||
variant: 'danger',
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await removeFriend(friendshipId);
|
||||
await loadFriendsData();
|
||||
toast.success('Friend removed');
|
||||
} catch (error) {
|
||||
toast.error('Failed to remove friend');
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const isAlreadyFriendOrPending = (userId: string) => {
|
||||
return friends.some((f) => f.id === userId) ||
|
||||
pendingRequests.some((f) => f.id === userId) ||
|
||||
sentRequests.some((f) => f.id === userId);
|
||||
};
|
||||
|
||||
// ============ TRADES FUNCTIONS ============
|
||||
const loadTradesData = async () => {
|
||||
if (!user) return;
|
||||
const [pending, history] = await Promise.all([
|
||||
getTrades(user.id).then((trades) => trades.filter((t) => t.status === 'pending')),
|
||||
getTradeHistory(user.id),
|
||||
]);
|
||||
|
||||
const allCardIds = new Set<string>();
|
||||
[...pending, ...history].forEach((trade) => {
|
||||
trade.items?.forEach((item) => allCardIds.add(item.card_id));
|
||||
});
|
||||
|
||||
if (allCardIds.size > 0) {
|
||||
const cards = await getCardsByIds(Array.from(allCardIds));
|
||||
const cardMap = new Map<string, Card>();
|
||||
cards.forEach((card) => cardMap.set(card.id, card));
|
||||
setTradeCardDetails(cardMap);
|
||||
}
|
||||
|
||||
setPendingTrades(pending);
|
||||
setTradeHistory(history);
|
||||
};
|
||||
|
||||
const handleAcceptTrade = async (tradeId: string) => {
|
||||
setProcessingTradeId(tradeId);
|
||||
try {
|
||||
const success = await acceptTrade(tradeId);
|
||||
if (success) {
|
||||
await loadTradesData();
|
||||
toast.success('Trade accepted! Cards have been exchanged.');
|
||||
} else {
|
||||
toast.error('Failed to execute trade. Check your collection.');
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Error accepting trade');
|
||||
} finally {
|
||||
setProcessingTradeId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeclineTrade = async (tradeId: string) => {
|
||||
setProcessingTradeId(tradeId);
|
||||
try {
|
||||
await declineTrade(tradeId);
|
||||
await loadTradesData();
|
||||
toast.info('Trade declined');
|
||||
} catch (error) {
|
||||
toast.error('Error declining trade');
|
||||
} finally {
|
||||
setProcessingTradeId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelTrade = (tradeId: string) => {
|
||||
setConfirmModal({
|
||||
isOpen: true,
|
||||
title: 'Cancel Trade',
|
||||
message: 'Are you sure you want to cancel this trade offer?',
|
||||
variant: 'warning',
|
||||
onConfirm: async () => {
|
||||
setProcessingTradeId(tradeId);
|
||||
try {
|
||||
await cancelTrade(tradeId);
|
||||
await loadTradesData();
|
||||
toast.info('Trade cancelled');
|
||||
} catch (error) {
|
||||
toast.error('Error cancelling trade');
|
||||
} finally {
|
||||
setProcessingTradeId(null);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// ============ PROFILE FUNCTIONS ============
|
||||
const loadProfile = async () => {
|
||||
if (!user) return;
|
||||
const { data } = await supabase
|
||||
.from('profiles')
|
||||
.select('username, collection_visibility')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
|
||||
if (data) {
|
||||
setUsername(data.username || '');
|
||||
setCollectionVisibility(data.collection_visibility || 'private');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveProfile = async () => {
|
||||
if (!user) return;
|
||||
setSavingProfile(true);
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('profiles')
|
||||
.upsert({
|
||||
id: user.id,
|
||||
username,
|
||||
collection_visibility: collectionVisibility,
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
toast.success('Profile updated!');
|
||||
} catch (error) {
|
||||
toast.error('Failed to update profile');
|
||||
} finally {
|
||||
setSavingProfile(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ============ RENDER HELPERS ============
|
||||
const renderTradeItems = (items: TradeItem[] | undefined, ownerId: string, 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 = tradeCardDetails.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>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -121,22 +382,18 @@ export default function Community() {
|
||||
);
|
||||
}
|
||||
|
||||
// If viewing a user's collection
|
||||
// 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([]);
|
||||
}}
|
||||
onClick={() => { setSelectedUser(null); setSelectedUserCollection([]); }}
|
||||
className="text-blue-400 hover:text-blue-300 mb-2"
|
||||
>
|
||||
← Back to Community
|
||||
← Back
|
||||
</button>
|
||||
<h1 className="text-3xl font-bold">{selectedUser.username}'s Collection</h1>
|
||||
</div>
|
||||
@@ -149,7 +406,6 @@ export default function Community() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Collection Grid */}
|
||||
{loadingCollection ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||
@@ -159,16 +415,10 @@ export default function Community() {
|
||||
) : (
|
||||
<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 key={card.id} className="relative">
|
||||
<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>
|
||||
<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>
|
||||
@@ -176,7 +426,6 @@ export default function Community() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Trade Creator Modal */}
|
||||
{showTradeCreator && (
|
||||
<TradeCreator
|
||||
receiverId={selectedUser.id}
|
||||
@@ -185,7 +434,7 @@ export default function Community() {
|
||||
onClose={() => setShowTradeCreator(false)}
|
||||
onTradeCreated={() => {
|
||||
setShowTradeCreator(false);
|
||||
alert('Trade proposal sent!');
|
||||
toast.success('Trade proposal sent!');
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -194,112 +443,354 @@ export default function Community() {
|
||||
);
|
||||
}
|
||||
|
||||
const filteredPublicUsers = publicUsers.filter(
|
||||
(u) => !browseSearch || u.username?.toLowerCase().includes(browseSearch.toLowerCase())
|
||||
);
|
||||
|
||||
const friendProfiles: UserProfile[] = friends.map((f) => ({
|
||||
id: f.id,
|
||||
username: f.username,
|
||||
collection_visibility: 'friends',
|
||||
}));
|
||||
|
||||
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">
|
||||
{/* Main Tabs */}
|
||||
<div className="flex flex-wrap gap-2 mb-6">
|
||||
{[
|
||||
{ id: 'browse' as Tab, label: 'Browse', icon: Globe },
|
||||
{ id: 'friends' as Tab, label: `Friends (${friends.length})`, icon: Users },
|
||||
{ id: 'trades' as Tab, label: `Trades (${pendingTrades.length})`, icon: ArrowLeftRight },
|
||||
{ id: 'profile' as Tab, label: 'Profile', icon: Settings },
|
||||
].map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
|
||||
activeTab === tab.id ? 'bg-blue-600 text-white' : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
<tab.icon size={18} />
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* ============ BROWSE TAB ============ */}
|
||||
{activeTab === 'browse' && (
|
||||
<div className="space-y-4">
|
||||
<div className="relative">
|
||||
<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"
|
||||
value={browseSearch}
|
||||
onChange={(e) => setBrowseSearch(e.target.value)}
|
||||
placeholder="Search public collections..."
|
||||
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"
|
||||
/>
|
||||
</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>
|
||||
<div className="flex gap-2 mb-4">
|
||||
<button className="px-3 py-1 bg-blue-600 rounded-lg text-sm">Public ({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'
|
||||
}`}
|
||||
className="px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded-lg text-sm"
|
||||
>
|
||||
<Users size={18} />
|
||||
Friends ({filteredFriends.length})
|
||||
Friends ({friendProfiles.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>
|
||||
<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="space-y-3">
|
||||
{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)}
|
||||
onClick={() => { setSelectedUser(userProfile); loadUserCollection(userProfile.id); }}
|
||||
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
|
||||
View
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ============ FRIENDS TAB ============ */}
|
||||
{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>
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2 mb-4">
|
||||
{(['list', 'requests', 'search'] as FriendsSubTab[]).map((tab) => (
|
||||
<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"
|
||||
key={tab}
|
||||
onClick={() => setFriendsSubTab(tab)}
|
||||
className={`px-3 py-1 rounded-lg text-sm capitalize ${
|
||||
friendsSubTab === tab ? 'bg-blue-600' : 'bg-gray-700 hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
<Eye size={16} />
|
||||
View Collection
|
||||
{tab === 'requests' ? `Requests (${pendingRequests.length})` : tab}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{friendsSubTab === 'list' && (
|
||||
<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>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => { setSelectedUser({ id: friend.id, username: friend.username, collection_visibility: 'friends' }); loadUserCollection(friend.id); }}
|
||||
className="p-2 text-blue-400 hover:bg-blue-400/20 rounded-lg transition"
|
||||
title="View collection"
|
||||
>
|
||||
<Eye size={20} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleRemoveFriend(friend.friendshipId, friend.username || 'this user')}
|
||||
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition"
|
||||
title="Remove friend"
|
||||
>
|
||||
<UserMinus size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{friendsSubTab === 'requests' && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3 text-gray-300">Received</h3>
|
||||
{pendingRequests.length === 0 ? (
|
||||
<p className="text-gray-500 text-sm">No pending requests</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{pendingRequests.map((req) => (
|
||||
<div key={req.id} className="flex items-center justify-between bg-gray-800 p-4 rounded-lg">
|
||||
<span className="font-medium">{req.username || 'Unknown'}</span>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => handleAcceptRequest(req.friendshipId)} className="p-2 text-green-400 hover:bg-green-400/20 rounded-lg"><Check size={20} /></button>
|
||||
<button onClick={() => handleDeclineRequest(req.friendshipId)} className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg"><X size={20} /></button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3 text-gray-300">Sent</h3>
|
||||
{sentRequests.length === 0 ? (
|
||||
<p className="text-gray-500 text-sm">No sent requests</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{sentRequests.map((req) => (
|
||||
<div key={req.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">{req.username || 'Unknown'}</span>
|
||||
</div>
|
||||
<span className="text-sm text-yellow-500">Pending</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{friendsSubTab === 'search' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={friendSearch}
|
||||
onChange={(e) => setFriendSearch(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSearchFriends()}
|
||||
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"
|
||||
/>
|
||||
<button
|
||||
onClick={handleSearchFriends}
|
||||
disabled={searchingFriends || friendSearch.trim().length < 2}
|
||||
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded-lg"
|
||||
>
|
||||
{searchingFriends ? <Loader2 className="animate-spin" size={20} /> : <Search size={20} />}
|
||||
</button>
|
||||
</div>
|
||||
{friendSearchResults.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
{friendSearchResults.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 text-sm">
|
||||
<UserPlus size={16} />
|
||||
Add
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ============ TRADES TAB ============ */}
|
||||
{activeTab === 'trades' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2 mb-4">
|
||||
<button
|
||||
onClick={() => setTradesSubTab('pending')}
|
||||
className={`flex items-center gap-2 px-3 py-1 rounded-lg text-sm ${tradesSubTab === 'pending' ? 'bg-blue-600' : 'bg-gray-700 hover:bg-gray-600'}`}
|
||||
>
|
||||
<Clock size={16} />
|
||||
Pending ({pendingTrades.length})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTradesSubTab('history')}
|
||||
className={`flex items-center gap-2 px-3 py-1 rounded-lg text-sm ${tradesSubTab === 'history' ? 'bg-blue-600' : 'bg-gray-700 hover:bg-gray-600'}`}
|
||||
>
|
||||
<History size={16} />
|
||||
History
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{(tradesSubTab === 'pending' ? pendingTrades : tradeHistory).length === 0 ? (
|
||||
<p className="text-gray-400 text-center py-8">
|
||||
{tradesSubTab === 'pending' ? 'No pending trades' : 'No trade history'}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{(tradesSubTab === 'pending' ? pendingTrades : tradeHistory).map((trade) => {
|
||||
const isSender = trade.sender_id === user?.id;
|
||||
const otherUser = isSender ? trade.receiver : trade.sender;
|
||||
const statusColor = trade.status === 'accepted' ? 'text-green-400' : trade.status === 'declined' ? 'text-red-400' : trade.status === 'cancelled' ? 'text-gray-400' : 'text-yellow-400';
|
||||
|
||||
return (
|
||||
<div key={trade.id} className="bg-gray-800 rounded-lg p-4 space-y-4">
|
||||
<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 ${statusColor}`}>{trade.status}</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{renderTradeItems(trade.items, trade.sender_id, isSender ? 'You give' : 'They give')}
|
||||
{renderTradeItems(trade.items, trade.receiver_id, isSender ? 'You receive' : 'They receive')}
|
||||
</div>
|
||||
|
||||
{trade.message && <div className="text-gray-400 text-sm"><span className="text-gray-500">Message:</span> {trade.message}</div>}
|
||||
|
||||
{tradesSubTab === 'pending' && (
|
||||
<div className="flex gap-2 pt-2 border-t border-gray-700">
|
||||
{isSender ? (
|
||||
<button onClick={() => handleCancelTrade(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 text-sm">
|
||||
<X size={16} />
|
||||
Cancel
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<button onClick={() => handleAcceptTrade(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 text-sm">
|
||||
{processingTradeId === trade.id ? <Loader2 className="animate-spin" size={16} /> : <Check size={16} />}
|
||||
Accept
|
||||
</button>
|
||||
<button onClick={() => handleDeclineTrade(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 text-sm">
|
||||
<X size={16} />
|
||||
Decline
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-gray-500 text-xs">{new Date(trade.created_at || '').toLocaleDateString()}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ============ PROFILE TAB ============ */}
|
||||
{activeTab === 'profile' && (
|
||||
<div className="max-w-md space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">Username</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="Enter your username"
|
||||
/>
|
||||
</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) => (
|
||||
<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'
|
||||
}`}
|
||||
>
|
||||
<div>
|
||||
<div className="font-medium">{option.label}</div>
|
||||
<div className="text-sm text-gray-400">{option.description}</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSaveProfile}
|
||||
disabled={savingProfile}
|
||||
className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-semibold py-3 px-4 rounded-lg transition"
|
||||
>
|
||||
{savingProfile ? <Loader2 className="animate-spin" size={20} /> : <><Save size={20} /> Save Changes</>}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
isOpen={confirmModal.isOpen}
|
||||
onClose={() => setConfirmModal({ ...confirmModal, isOpen: false })}
|
||||
onConfirm={confirmModal.onConfirm}
|
||||
title={confirmModal.title}
|
||||
message={confirmModal.message}
|
||||
variant={confirmModal.variant}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,312 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +1,19 @@
|
||||
import React, { useState, useRef, useEffect } from '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';
|
||||
import { Library, LogOut, ChevronDown, Search, Heart, Users } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { supabase } from '../lib/supabase';
|
||||
|
||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'profile' | 'search' | 'life-counter' | 'friends' | 'trades' | 'community';
|
||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'search' | 'life-counter' | 'community';
|
||||
|
||||
interface NavigationProps {
|
||||
interface NavigationProps {
|
||||
currentPage: Page;
|
||||
setCurrentPage: (page: Page) => void;
|
||||
}
|
||||
}
|
||||
|
||||
export default function Navigation({ currentPage, setCurrentPage }: NavigationProps) {
|
||||
export default function Navigation({ currentPage, setCurrentPage }: NavigationProps) {
|
||||
const { user, signOut } = useAuth();
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const [showMobileMenu, setShowMobileMenu] = useState(false);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const mobileMenuRef = useRef<HTMLDivElement>(null);
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -41,9 +39,6 @@ import React, { useState, useRef, useEffect } from 'react';
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setShowDropdown(false);
|
||||
}
|
||||
if (mobileMenuRef.current && !mobileMenuRef.current.contains(event.target as Node)) {
|
||||
setShowMobileMenu(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
@@ -53,9 +48,7 @@ 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: 'community' as const, label: 'Community', icon: Users },
|
||||
{ id: 'search' as const, label: 'Search', icon: Search },
|
||||
{ id: 'life-counter' as const, label: 'Life', icon: Heart },
|
||||
];
|
||||
@@ -115,16 +108,6 @@ import React, { useState, useRef, useEffect } from 'react';
|
||||
|
||||
{showDropdown && (
|
||||
<div className="absolute right-0 mt-2 w-48 bg-gray-800 rounded-md shadow-lg py-1 border border-gray-700 animate-scale-in glass-effect">
|
||||
<button
|
||||
onClick={() => {
|
||||
setCurrentPage('profile');
|
||||
setShowDropdown(false);
|
||||
}}
|
||||
className="flex items-center space-x-2 w-full px-4 py-2 text-sm text-gray-300 hover:bg-gray-700 transition-smooth"
|
||||
>
|
||||
<Settings size={16} />
|
||||
<span>Profile Settings</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSignOut}
|
||||
className="flex items-center space-x-2 w-full px-4 py-2 text-sm text-gray-300 hover:bg-gray-700 transition-smooth"
|
||||
@@ -159,47 +142,16 @@ import React, { useState, useRef, useEffect } from 'react';
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Settings with dropdown */}
|
||||
<div className="relative flex-1 h-full" ref={mobileMenuRef}>
|
||||
{/* Sign Out button for mobile */}
|
||||
<button
|
||||
onClick={() => setShowMobileMenu(!showMobileMenu)}
|
||||
className={`flex flex-col items-center justify-center w-full h-full transition-colors ${
|
||||
currentPage === 'profile' || showMobileMenu
|
||||
? 'text-blue-500'
|
||||
: 'text-gray-400 hover:text-gray-200'
|
||||
}`}
|
||||
onClick={handleSignOut}
|
||||
className="flex flex-col items-center justify-center flex-1 h-full text-gray-400 hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<Settings size={20} />
|
||||
<span className="text-xs mt-1">Settings</span>
|
||||
<LogOut size={20} />
|
||||
<span className="text-xs mt-1">Logout</span>
|
||||
</button>
|
||||
|
||||
{showMobileMenu && (
|
||||
<div className="absolute right-0 bottom-full mb-2 w-48 bg-gray-800 rounded-lg shadow-xl py-1 border border-gray-700 animate-scale-in">
|
||||
<button
|
||||
onClick={() => {
|
||||
setCurrentPage('profile');
|
||||
setShowMobileMenu(false);
|
||||
}}
|
||||
className="flex items-center space-x-3 w-full px-4 py-3 text-sm text-gray-300 hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
<Settings size={18} />
|
||||
<span>Profile</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
handleSignOut();
|
||||
setShowMobileMenu(false);
|
||||
}}
|
||||
className="flex items-center space-x-3 w-full px-4 py-3 text-sm text-red-400 hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
<LogOut size={18} />
|
||||
<span>Sign Out</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
import React, { useState, useEffect } from '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);
|
||||
|
||||
useEffect(() => {
|
||||
const loadProfile = async () => {
|
||||
if (user) {
|
||||
const { data, error } = await supabase
|
||||
.from('profiles')
|
||||
.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);
|
||||
}
|
||||
};
|
||||
|
||||
loadProfile();
|
||||
}, [user]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!user) return;
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('profiles')
|
||||
.upsert({
|
||||
id: user.id,
|
||||
username,
|
||||
theme_color: themeColor,
|
||||
collection_visibility: collectionVisibility,
|
||||
updated_at: new Date()
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
alert('Profile updated successfully!');
|
||||
} catch (error) {
|
||||
console.error('Error updating profile:', error);
|
||||
alert('Failed to update profile');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
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-8">Profile Settings</h1>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder="Enter your username"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Theme Color
|
||||
</label>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 sm:gap-4">
|
||||
{THEME_COLORS.map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
type="button"
|
||||
onClick={() => setThemeColor(color)}
|
||||
className={`h-12 sm:h-14 rounded-lg border-2 transition-all capitalize text-sm sm:text-base
|
||||
${themeColor === color
|
||||
? 'border-white scale-105'
|
||||
: 'border-transparent hover:border-gray-600'
|
||||
}`}
|
||||
style={{ backgroundColor: `var(--color-${color}-primary)` }}
|
||||
>
|
||||
{color}
|
||||
</button>
|
||||
))}
|
||||
</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}
|
||||
className="w-full min-h-[44px] flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-semibold py-3 px-4 rounded-lg transition duration-200"
|
||||
>
|
||||
{saving ? (
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-white"></div>
|
||||
) : (
|
||||
<>
|
||||
<Save size={20} />
|
||||
Save Changes
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { X, ArrowLeftRight, Plus, Minus, Send, Gift } from 'lucide-react';
|
||||
import { X, ArrowLeftRight, Plus, Minus, Send, Gift, Loader2 } from 'lucide-react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
||||
import { createTrade } from '../services/tradesService';
|
||||
import { Card } from '../types';
|
||||
@@ -32,6 +33,7 @@ export default function TradeCreator({
|
||||
onTradeCreated,
|
||||
}: TradeCreatorProps) {
|
||||
const { user } = useAuth();
|
||||
const toast = useToast();
|
||||
const [myCollection, setMyCollection] = useState<CollectionItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
@@ -133,7 +135,7 @@ export default function TradeCreator({
|
||||
|
||||
// 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');
|
||||
toast.warning('Please select at least one card to trade or gift');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -160,7 +162,7 @@ export default function TradeCreator({
|
||||
onTradeCreated();
|
||||
} catch (error) {
|
||||
console.error('Error creating trade:', error);
|
||||
alert('Failed to create trade');
|
||||
toast.error('Failed to create trade');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -1,326 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -35,8 +35,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
.from('profiles')
|
||||
.upsert(
|
||||
{
|
||||
id: session.user.id,
|
||||
theme_color: 'blue' // Default theme color
|
||||
id: session.user.id
|
||||
},
|
||||
{ onConflict: 'id' }
|
||||
);
|
||||
@@ -65,8 +64,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const { error: profileError } = await supabase
|
||||
.from('profiles')
|
||||
.insert({
|
||||
id: data.user!.id,
|
||||
theme_color: 'blue' // Default theme color
|
||||
id: data.user!.id
|
||||
});
|
||||
|
||||
if (profileError) {
|
||||
|
||||
100
src/contexts/ToastContext.tsx
Normal file
100
src/contexts/ToastContext.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import React, { createContext, useContext, useState, useCallback } from 'react';
|
||||
import { CheckCircle, XCircle, AlertCircle, Info, X } from 'lucide-react';
|
||||
|
||||
type ToastType = 'success' | 'error' | 'warning' | 'info';
|
||||
|
||||
interface Toast {
|
||||
id: string;
|
||||
message: string;
|
||||
type: ToastType;
|
||||
}
|
||||
|
||||
interface ToastContextType {
|
||||
showToast: (message: string, type?: ToastType) => void;
|
||||
success: (message: string) => void;
|
||||
error: (message: string) => void;
|
||||
warning: (message: string) => void;
|
||||
info: (message: string) => void;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastContextType | undefined>(undefined);
|
||||
|
||||
export function useToast() {
|
||||
const context = useContext(ToastContext);
|
||||
if (!context) {
|
||||
throw new Error('useToast must be used within a ToastProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export function ToastProvider({ children }: { children: React.ReactNode }) {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
|
||||
const removeToast = useCallback((id: string) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
}, []);
|
||||
|
||||
const showToast = useCallback((message: string, type: ToastType = 'info') => {
|
||||
const id = Math.random().toString(36).substring(7);
|
||||
setToasts((prev) => [...prev, { id, message, type }]);
|
||||
|
||||
// Auto remove after 4 seconds
|
||||
setTimeout(() => removeToast(id), 4000);
|
||||
}, [removeToast]);
|
||||
|
||||
const success = useCallback((message: string) => showToast(message, 'success'), [showToast]);
|
||||
const error = useCallback((message: string) => showToast(message, 'error'), [showToast]);
|
||||
const warning = useCallback((message: string) => showToast(message, 'warning'), [showToast]);
|
||||
const info = useCallback((message: string) => showToast(message, 'info'), [showToast]);
|
||||
|
||||
const getIcon = (type: ToastType) => {
|
||||
switch (type) {
|
||||
case 'success':
|
||||
return <CheckCircle size={20} />;
|
||||
case 'error':
|
||||
return <XCircle size={20} />;
|
||||
case 'warning':
|
||||
return <AlertCircle size={20} />;
|
||||
case 'info':
|
||||
return <Info size={20} />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStyles = (type: ToastType) => {
|
||||
switch (type) {
|
||||
case 'success':
|
||||
return 'bg-green-600';
|
||||
case 'error':
|
||||
return 'bg-red-600';
|
||||
case 'warning':
|
||||
return 'bg-yellow-600';
|
||||
case 'info':
|
||||
return 'bg-blue-600';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ showToast, success, error, warning, info }}>
|
||||
{children}
|
||||
|
||||
{/* Toast Container */}
|
||||
<div className="fixed bottom-4 right-4 z-[100] flex flex-col gap-2">
|
||||
{toasts.map((toast) => (
|
||||
<div
|
||||
key={toast.id}
|
||||
className={`${getStyles(toast.type)} text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 min-w-[280px] animate-slide-in-right`}
|
||||
>
|
||||
{getIcon(toast.type)}
|
||||
<span className="flex-1">{toast.message}</span>
|
||||
<button
|
||||
onClick={() => removeToast(toast.id)}
|
||||
className="text-white/80 hover:text-white"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -140,7 +140,6 @@ export type Database = {
|
||||
Row: {
|
||||
created_at: string | null
|
||||
id: string
|
||||
theme_color: string | null
|
||||
updated_at: string | null
|
||||
username: string | null
|
||||
collection_visibility: 'public' | 'friends' | 'private' | null
|
||||
@@ -148,7 +147,6 @@ export type Database = {
|
||||
Insert: {
|
||||
created_at?: string | null
|
||||
id: string
|
||||
theme_color?: string | null
|
||||
updated_at?: string | null
|
||||
username?: string | null
|
||||
collection_visibility?: 'public' | 'friends' | 'private' | null
|
||||
@@ -156,7 +154,6 @@ export type Database = {
|
||||
Update: {
|
||||
created_at?: string | null
|
||||
id?: string
|
||||
theme_color?: string | null
|
||||
updated_at?: string | null
|
||||
username?: string | null
|
||||
collection_visibility?: 'public' | 'friends' | 'private' | null
|
||||
|
||||
Reference in New Issue
Block a user