Compare commits
11 Commits
feature/tr
...
feature/bg
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf4c346e2d | ||
|
|
60bbeb9737 | ||
|
|
2acf50e46f | ||
|
|
1d77b6fb8e | ||
|
|
239a2c9591 | ||
|
|
64c48da05a | ||
|
|
2d7641cc20 | ||
|
|
24023570c7 | ||
|
|
359cc61115 | ||
|
|
71891a29be | ||
| 613db069b8 |
10
src/App.tsx
10
src/App.tsx
@@ -11,6 +11,7 @@ import Community from './components/Community';
|
|||||||
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
import PWAInstallPrompt from './components/PWAInstallPrompt';
|
||||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||||
import { ToastProvider } from './contexts/ToastContext';
|
import { ToastProvider } from './contexts/ToastContext';
|
||||||
|
import CardMosaicBackground from "./components/CardMosaicBackground.tsx";
|
||||||
|
|
||||||
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'search' | 'life-counter' | 'community';
|
type Page = 'home' | 'deck' | 'login' | 'collection' | 'edit-deck' | 'search' | 'life-counter' | 'community';
|
||||||
|
|
||||||
@@ -40,7 +41,7 @@ function AppContent() {
|
|||||||
switch (currentPage) {
|
switch (currentPage) {
|
||||||
case 'home':
|
case 'home':
|
||||||
return (
|
return (
|
||||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 animate-fade-in md:min-h-screen">
|
<div className="relative text-white p-3 sm:p-6 animate-fade-in md:min-h-screen">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6 animate-slide-in-left">My Decks</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6 animate-slide-in-left">My Decks</h1>
|
||||||
<DeckList
|
<DeckList
|
||||||
@@ -78,9 +79,12 @@ function AppContent() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-900 flex flex-col">
|
<div className="min-h-screen bg-gray-900 flex flex-col relative">
|
||||||
|
{/* Animated card mosaic overlay */}
|
||||||
|
<CardMosaicBackground />
|
||||||
|
|
||||||
<Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} />
|
<Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} />
|
||||||
<main className="relative flex-1 overflow-y-auto">
|
<main className="relative flex-1 overflow-y-auto z-20">
|
||||||
<div className="relative min-h-full md:min-h-0 pt-0 md:pt-16 pb-20 md:pb-0">
|
<div className="relative min-h-full md:min-h-0 pt-0 md:pt-16 pb-20 md:pb-0">
|
||||||
{renderPage()}
|
{renderPage()}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
155
src/components/CardMosaicBackground.tsx
Normal file
155
src/components/CardMosaicBackground.tsx
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
import React, { useEffect, useState, useRef } from 'react';
|
||||||
|
import { getRandomCards } from '../services/api';
|
||||||
|
import { Card } from '../types';
|
||||||
|
|
||||||
|
export default function CardMosaicBackground() {
|
||||||
|
const [cards, setCards] = useState<Card[]>([]);
|
||||||
|
const [offset, setOffset] = useState({ x: 0, y: 0 });
|
||||||
|
const animationRef = useRef<number>();
|
||||||
|
|
||||||
|
// Grid configuration - large grid to cover entire screen
|
||||||
|
const cardsPerRow = 18;
|
||||||
|
const cardsPerCol = 15;
|
||||||
|
// Spacing adjusted for card transforms: w-64 = 256px
|
||||||
|
// With rotateZ(15deg) and rotateX(60deg), cards need more space
|
||||||
|
const cardWidth = 130; // Horizontal spacing to avoid overlap
|
||||||
|
const cardHeight = 85; // Vertical spacing to avoid overlap
|
||||||
|
const gridWidth = cardsPerRow * cardWidth;
|
||||||
|
const gridHeight = cardsPerCol * cardHeight;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchCards = async () => {
|
||||||
|
try {
|
||||||
|
// Fetch enough cards for one grid
|
||||||
|
const totalCards = cardsPerRow * cardsPerCol;
|
||||||
|
const randomCards = await getRandomCards(totalCards);
|
||||||
|
setCards(randomCards);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching background cards:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchCards();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Diagonal infinite scroll animation
|
||||||
|
useEffect(() => {
|
||||||
|
if (cards.length === 0) return;
|
||||||
|
|
||||||
|
const speed = 0.5; // Pixels per frame (diagonal speed)
|
||||||
|
let lastTime = Date.now();
|
||||||
|
|
||||||
|
const animate = () => {
|
||||||
|
const now = Date.now();
|
||||||
|
const delta = now - lastTime;
|
||||||
|
lastTime = now;
|
||||||
|
|
||||||
|
setOffset((prev) => {
|
||||||
|
// Move diagonally: right and up
|
||||||
|
let newX = prev.x + (speed * delta) / 16;
|
||||||
|
let newY = prev.y - (speed * delta) / 16;
|
||||||
|
|
||||||
|
// Loop seamlessly when we've moved one full grid
|
||||||
|
if (newX >= gridWidth) newX = newX % gridWidth;
|
||||||
|
if (newY <= -gridHeight) newY = newY % gridHeight;
|
||||||
|
|
||||||
|
return { x: newX, y: newY };
|
||||||
|
});
|
||||||
|
|
||||||
|
animationRef.current = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
|
animationRef.current = requestAnimationFrame(animate);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (animationRef.current) {
|
||||||
|
cancelAnimationFrame(animationRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [cards.length, gridWidth, gridHeight]);
|
||||||
|
|
||||||
|
if (cards.length === 0) return null;
|
||||||
|
|
||||||
|
// Render the card grid (will be duplicated 4 times for infinite effect)
|
||||||
|
const renderGrid = (offsetX: number, offsetY: number, key: string) => (
|
||||||
|
<div
|
||||||
|
key={key}
|
||||||
|
className="absolute"
|
||||||
|
style={{
|
||||||
|
left: `${offsetX}px`,
|
||||||
|
top: `${offsetY}px`,
|
||||||
|
width: `${gridWidth}px`,
|
||||||
|
height: `${gridHeight}px`,
|
||||||
|
perspective: '2000px', // Apply perspective to parent for uniform card sizes
|
||||||
|
transformStyle: 'preserve-3d',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{cards.map((card, index) => {
|
||||||
|
const col = index % cardsPerRow;
|
||||||
|
const row = Math.floor(index / cardsPerRow);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={`${key}-${card.id}-${index}`}
|
||||||
|
className="absolute"
|
||||||
|
style={{
|
||||||
|
left: `${col * cardWidth}px`,
|
||||||
|
top: `${row * cardHeight}px`,
|
||||||
|
transform: `
|
||||||
|
perspective(1000px)
|
||||||
|
rotateX(60deg)
|
||||||
|
rotateY(5deg)
|
||||||
|
rotateZ(15deg)
|
||||||
|
`,
|
||||||
|
opacity: 1.0, // Full opacity - gradient overlay handles the fade
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={card.image_uris?.normal || card.image_uris?.large}
|
||||||
|
alt=""
|
||||||
|
className="w-64 h-auto rounded-lg shadow-2xl"
|
||||||
|
draggable={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 overflow-hidden pointer-events-none z-10">
|
||||||
|
{/* Scrolling grid container */}
|
||||||
|
<div
|
||||||
|
className="absolute"
|
||||||
|
style={{
|
||||||
|
transform: `translate(${offset.x}px, ${offset.y}px)`,
|
||||||
|
willChange: 'transform',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Duplicate grids in 2x2 pattern for seamless infinite scroll */}
|
||||||
|
{/* Position grids to cover entire viewport and beyond */}
|
||||||
|
{renderGrid(-gridWidth, window.innerHeight - gridHeight / 2, 'grid-tl')}
|
||||||
|
{renderGrid(0, window.innerHeight - gridHeight / 2, 'grid-tr')}
|
||||||
|
{renderGrid(-gridWidth, window.innerHeight - gridHeight / 2 + gridHeight, 'grid-bl')}
|
||||||
|
{renderGrid(0, window.innerHeight - gridHeight / 2 + gridHeight, 'grid-br')}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Fixed gradient overlay - cards pass UNDER and fade naturally */}
|
||||||
|
<div
|
||||||
|
className="absolute inset-0 pointer-events-none z-10"
|
||||||
|
style={{
|
||||||
|
background: `
|
||||||
|
linear-gradient(to top,
|
||||||
|
transparent 0%,
|
||||||
|
transparent 25%,
|
||||||
|
rgba(3, 7, 18, 0.3) 40%,
|
||||||
|
rgba(3, 7, 18, 0.6) 55%,
|
||||||
|
rgba(3, 7, 18, 0.85) 70%,
|
||||||
|
rgb(3, 7, 18) 85%
|
||||||
|
)
|
||||||
|
`
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -201,7 +201,7 @@ const CardSearch = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Card Search</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Card Search</h1>
|
||||||
<form onSubmit={handleSearch} className="mb-8 space-y-4">
|
<form onSubmit={handleSearch} className="mb-8 space-y-4">
|
||||||
|
|||||||
@@ -1,17 +1,25 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
import { Search, Loader2, Trash2, CheckCircle, XCircle, RefreshCw, Plus, Minus, X } from 'lucide-react';
|
import { Search, Loader2, Trash2, CheckCircle, XCircle, RefreshCw, Plus, Minus, X } from 'lucide-react';
|
||||||
import { Card } from '../types';
|
import { Card } from '../types';
|
||||||
import { getUserCollection, getCardsByIds, addCardToCollection } from '../services/api';
|
import { getUserCollectionPaginated, getCardsByIds, addCardToCollection, getCollectionTotalValue } from '../services/api';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { supabase } from '../lib/supabase';
|
import { supabase } from '../lib/supabase';
|
||||||
import ConfirmModal from './ConfirmModal';
|
import ConfirmModal from './ConfirmModal';
|
||||||
|
|
||||||
|
const PAGE_SIZE = 50;
|
||||||
|
|
||||||
export default function Collection() {
|
export default function Collection() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [collection, setCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
const [collection, setCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
||||||
const [filteredCollection, setFilteredCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
const [filteredCollection, setFilteredCollection] = useState<{ card: Card; quantity: number }[]>([]);
|
||||||
const [isLoadingCollection, setIsLoadingCollection] = useState(true);
|
const [isLoadingCollection, setIsLoadingCollection] = useState(true);
|
||||||
|
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
||||||
|
const [hasMore, setHasMore] = useState(false);
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const [totalCount, setTotalCount] = useState(0);
|
||||||
|
const [totalCollectionValue, setTotalCollectionValue] = useState<number>(0);
|
||||||
|
const [isLoadingTotalValue, setIsLoadingTotalValue] = useState(true);
|
||||||
const [hoveredCard, setHoveredCard] = useState<Card | null>(null);
|
const [hoveredCard, setHoveredCard] = useState<Card | null>(null);
|
||||||
const [selectedCard, setSelectedCard] = useState<{ card: Card; quantity: number } | null>(null);
|
const [selectedCard, setSelectedCard] = useState<{ card: Card; quantity: number } | null>(null);
|
||||||
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
|
const [cardFaceIndex, setCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||||
@@ -22,6 +30,7 @@ export default function Collection() {
|
|||||||
cardId: string;
|
cardId: string;
|
||||||
cardName: string;
|
cardName: string;
|
||||||
}>({ isOpen: false, cardId: '', cardName: '' });
|
}>({ isOpen: false, cardId: '', cardName: '' });
|
||||||
|
const observerTarget = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
// Helper function to check if a card has an actual back face (not adventure/split/etc)
|
// Helper function to check if a card has an actual back face (not adventure/split/etc)
|
||||||
const isDoubleFaced = (card: Card) => {
|
const isDoubleFaced = (card: Card) => {
|
||||||
@@ -62,6 +71,58 @@ export default function Collection() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Calculate total collection value (lightweight query from database)
|
||||||
|
useEffect(() => {
|
||||||
|
const calculateTotalValue = async () => {
|
||||||
|
if (!user) {
|
||||||
|
setIsLoadingTotalValue(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsLoadingTotalValue(true);
|
||||||
|
// Get total value directly from database (no need to fetch all cards!)
|
||||||
|
const totalValue = await getCollectionTotalValue(user.id);
|
||||||
|
setTotalCollectionValue(totalValue);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error calculating total collection value:', error);
|
||||||
|
setTotalCollectionValue(0);
|
||||||
|
} finally {
|
||||||
|
setIsLoadingTotalValue(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
calculateTotalValue();
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
// Subscribe to realtime updates for collection total value
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
const profileChannel = supabase
|
||||||
|
.channel('profile-total-value-changes')
|
||||||
|
.on(
|
||||||
|
'postgres_changes',
|
||||||
|
{
|
||||||
|
event: 'UPDATE',
|
||||||
|
schema: 'public',
|
||||||
|
table: 'profiles',
|
||||||
|
filter: `id=eq.${user.id}`,
|
||||||
|
},
|
||||||
|
(payload: any) => {
|
||||||
|
if (payload.new?.collection_total_value !== undefined) {
|
||||||
|
console.log('Collection total value updated:', payload.new.collection_total_value);
|
||||||
|
setTotalCollectionValue(payload.new.collection_total_value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.subscribe();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
supabase.removeChannel(profileChannel);
|
||||||
|
};
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
// Load user's collection from Supabase on mount
|
// Load user's collection from Supabase on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadCollection = async () => {
|
const loadCollection = async () => {
|
||||||
@@ -72,26 +133,33 @@ export default function Collection() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
setIsLoadingCollection(true);
|
setIsLoadingCollection(true);
|
||||||
// Get collection from Supabase (returns Map<card_id, quantity>)
|
setOffset(0);
|
||||||
const collectionMap = await getUserCollection(user.id);
|
|
||||||
|
|
||||||
if (collectionMap.size === 0) {
|
|
||||||
setCollection([]);
|
setCollection([]);
|
||||||
|
|
||||||
|
// Get paginated collection from Supabase
|
||||||
|
const result = await getUserCollectionPaginated(user.id, PAGE_SIZE, 0);
|
||||||
|
setTotalCount(result.totalCount);
|
||||||
|
setHasMore(result.hasMore);
|
||||||
|
|
||||||
|
if (result.items.size === 0) {
|
||||||
|
setCollection([]);
|
||||||
|
setFilteredCollection([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the actual card data from Scryfall for all cards in collection
|
// Get the actual card data from Scryfall for all cards in this page
|
||||||
const cardIds = Array.from(collectionMap.keys());
|
const cardIds = Array.from(result.items.keys());
|
||||||
const cards = await getCardsByIds(cardIds);
|
const cards = await getCardsByIds(cardIds);
|
||||||
|
|
||||||
// Combine card data with quantities
|
// Combine card data with quantities
|
||||||
const collectionWithCards = cards.map(card => ({
|
const collectionWithCards = cards.map(card => ({
|
||||||
card,
|
card,
|
||||||
quantity: collectionMap.get(card.id) || 0,
|
quantity: result.items.get(card.id) || 0,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setCollection(collectionWithCards);
|
setCollection(collectionWithCards);
|
||||||
setFilteredCollection(collectionWithCards);
|
setFilteredCollection(collectionWithCards);
|
||||||
|
setOffset(PAGE_SIZE);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading collection:', error);
|
console.error('Error loading collection:', error);
|
||||||
setSnackbar({ message: 'Failed to load collection', type: 'error' });
|
setSnackbar({ message: 'Failed to load collection', type: 'error' });
|
||||||
@@ -103,6 +171,70 @@ export default function Collection() {
|
|||||||
loadCollection();
|
loadCollection();
|
||||||
}, [user]);
|
}, [user]);
|
||||||
|
|
||||||
|
// Load more cards for infinite scroll
|
||||||
|
const loadMoreCards = useCallback(async () => {
|
||||||
|
if (!user || isLoadingMore || !hasMore) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsLoadingMore(true);
|
||||||
|
|
||||||
|
// Get next page of collection
|
||||||
|
const result = await getUserCollectionPaginated(user.id, PAGE_SIZE, offset);
|
||||||
|
setHasMore(result.hasMore);
|
||||||
|
|
||||||
|
if (result.items.size === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get card data from Scryfall
|
||||||
|
const cardIds = Array.from(result.items.keys());
|
||||||
|
const cards = await getCardsByIds(cardIds);
|
||||||
|
|
||||||
|
// Combine card data with quantities
|
||||||
|
const newCards = cards.map(card => ({
|
||||||
|
card,
|
||||||
|
quantity: result.items.get(card.id) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Deduplicate: only add cards that aren't already in the collection
|
||||||
|
setCollection(prev => {
|
||||||
|
const existingIds = new Set(prev.map(item => item.card.id));
|
||||||
|
const uniqueNewCards = newCards.filter(item => !existingIds.has(item.card.id));
|
||||||
|
return [...prev, ...uniqueNewCards];
|
||||||
|
});
|
||||||
|
|
||||||
|
setOffset(prev => prev + PAGE_SIZE);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading more cards:', error);
|
||||||
|
setSnackbar({ message: 'Failed to load more cards', type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setIsLoadingMore(false);
|
||||||
|
}
|
||||||
|
}, [user, offset, hasMore, isLoadingMore]);
|
||||||
|
|
||||||
|
// Intersection Observer for infinite scroll
|
||||||
|
useEffect(() => {
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
if (entries[0].isIntersecting && hasMore && !isLoadingMore) {
|
||||||
|
loadMoreCards();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.1 }
|
||||||
|
);
|
||||||
|
|
||||||
|
const currentTarget = observerTarget.current;
|
||||||
|
if (currentTarget) {
|
||||||
|
observer.observe(currentTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (currentTarget) {
|
||||||
|
observer.unobserve(currentTarget);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [hasMore, isLoadingMore, loadMoreCards]);
|
||||||
|
|
||||||
// Filter collection based on search query
|
// Filter collection based on search query
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!searchQuery.trim()) {
|
if (!searchQuery.trim()) {
|
||||||
@@ -189,7 +321,7 @@ export default function Collection() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">My Collection</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">My Collection</h1>
|
||||||
|
|
||||||
@@ -209,9 +341,31 @@ export default function Collection() {
|
|||||||
|
|
||||||
{/* Collection */}
|
{/* Collection */}
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-xl font-semibold mb-4">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
|
||||||
|
<h2 className="text-xl font-semibold">
|
||||||
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
|
{searchQuery ? `Found ${filteredCollection.length} card(s)` : `My Cards (${collection.length} unique, ${collection.reduce((acc, c) => acc + c.quantity, 0)} total)`}
|
||||||
</h2>
|
</h2>
|
||||||
|
{/* Collection Value Summary */}
|
||||||
|
<div className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2">
|
||||||
|
<div className="text-xs text-gray-400 mb-0.5">
|
||||||
|
{searchQuery ? 'Filtered Value' : 'Total Collection Value'}
|
||||||
|
</div>
|
||||||
|
<div className="text-lg font-bold text-green-400">
|
||||||
|
{isLoadingTotalValue ? (
|
||||||
|
<Loader2 className="animate-spin" size={20} />
|
||||||
|
) : searchQuery ? (
|
||||||
|
// For search results, calculate from filtered collection
|
||||||
|
`$${filteredCollection.reduce((total, { card, quantity }) => {
|
||||||
|
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
|
||||||
|
return total + (price * quantity);
|
||||||
|
}, 0).toFixed(2)}`
|
||||||
|
) : (
|
||||||
|
// For full collection, use pre-calculated total
|
||||||
|
`$${totalCollectionValue.toFixed(2)}`
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{isLoadingCollection ? (
|
{isLoadingCollection ? (
|
||||||
<div className="flex items-center justify-center py-12">
|
<div className="flex items-center justify-center py-12">
|
||||||
@@ -255,6 +409,12 @@ export default function Collection() {
|
|||||||
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs sm:text-sm font-bold px-2 py-1 rounded-full shadow-lg">
|
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs sm:text-sm font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
x{quantity}
|
x{quantity}
|
||||||
</div>
|
</div>
|
||||||
|
{/* Price badge */}
|
||||||
|
{card.prices?.usd && (
|
||||||
|
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-[10px] sm:text-xs font-bold px-1.5 py-0.5 rounded shadow-lg">
|
||||||
|
${card.prices.usd}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{/* Flip button for double-faced cards */}
|
{/* Flip button for double-faced cards */}
|
||||||
{isMultiFaced && (
|
{isMultiFaced && (
|
||||||
<button
|
<button
|
||||||
@@ -279,6 +439,25 @@ export default function Collection() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Infinite scroll loading indicator */}
|
||||||
|
{!searchQuery && isLoadingMore && (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<Loader2 className="animate-spin text-blue-500" size={32} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Observer target for infinite scroll */}
|
||||||
|
{!searchQuery && hasMore && !isLoadingMore && (
|
||||||
|
<div ref={observerTarget} className="h-20" />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* End of collection indicator */}
|
||||||
|
{!searchQuery && !hasMore && collection.length > 0 && (
|
||||||
|
<div className="text-center py-8 text-gray-500 text-sm">
|
||||||
|
End of collection • {totalCount} total cards
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft } from 'lucide-react';
|
import { Search, Globe, Users, Eye, ArrowLeftRight, Loader2, Clock, History, UserPlus, UserMinus, Check, X, Send, Settings, Save, ChevronLeft, RefreshCw, Plus, Minus, AlertTriangle } from 'lucide-react';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { useToast } from '../contexts/ToastContext';
|
import { useToast } from '../contexts/ToastContext';
|
||||||
import { supabase } from '../lib/supabase';
|
import { supabase } from '../lib/supabase';
|
||||||
@@ -23,7 +23,7 @@ import {
|
|||||||
Trade,
|
Trade,
|
||||||
TradeItem,
|
TradeItem,
|
||||||
} from '../services/tradesService';
|
} from '../services/tradesService';
|
||||||
import { getUserCollection, getCardsByIds } from '../services/api';
|
import { getUserCollectionPaginated, getCardsByIds, getCollectionTotalValue } from '../services/api';
|
||||||
import { Card } from '../types';
|
import { Card } from '../types';
|
||||||
import TradeCreator from './TradeCreator';
|
import TradeCreator from './TradeCreator';
|
||||||
import TradeDetail from './TradeDetail';
|
import TradeDetail from './TradeDetail';
|
||||||
@@ -50,6 +50,8 @@ const VISIBILITY_OPTIONS = [
|
|||||||
{ value: 'private', label: 'Private', description: 'Only you' },
|
{ value: 'private', label: 'Private', description: 'Only you' },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
const PAGE_SIZE = 50;
|
||||||
|
|
||||||
export default function Community() {
|
export default function Community() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
@@ -62,8 +64,18 @@ export default function Community() {
|
|||||||
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
|
const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
|
||||||
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
|
const [selectedUserCollection, setSelectedUserCollection] = useState<CollectionItem[]>([]);
|
||||||
const [loadingCollection, setLoadingCollection] = useState(false);
|
const [loadingCollection, setLoadingCollection] = useState(false);
|
||||||
|
const [isLoadingMoreUserCards, setIsLoadingMoreUserCards] = useState(false);
|
||||||
|
const [hasMoreUserCards, setHasMoreUserCards] = useState(false);
|
||||||
|
const [userCollectionOffset, setUserCollectionOffset] = useState(0);
|
||||||
|
const [userCollectionTotalCount, setUserCollectionTotalCount] = useState(0);
|
||||||
|
const [userCollectionTotalValue, setUserCollectionTotalValue] = useState<number>(0);
|
||||||
|
const [isLoadingUserTotalValue, setIsLoadingUserTotalValue] = useState(true);
|
||||||
const [showTradeCreator, setShowTradeCreator] = useState(false);
|
const [showTradeCreator, setShowTradeCreator] = useState(false);
|
||||||
const [userCollectionSearch, setUserCollectionSearch] = useState('');
|
const [userCollectionSearch, setUserCollectionSearch] = useState('');
|
||||||
|
const [hoveredUserCard, setHoveredUserCard] = useState<Card | null>(null);
|
||||||
|
const [selectedUserCard, setSelectedUserCard] = useState<CollectionItem | null>(null);
|
||||||
|
const [userCardFaceIndex, setUserCardFaceIndex] = useState<Map<string, number>>(new Map());
|
||||||
|
const userCollectionObserverTarget = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
// Friends state
|
// Friends state
|
||||||
const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list');
|
const [friendsSubTab, setFriendsSubTab] = useState<FriendsSubTab>('list');
|
||||||
@@ -196,6 +208,7 @@ export default function Community() {
|
|||||||
}, [user]);
|
}, [user]);
|
||||||
|
|
||||||
// Subscribe to collection changes when viewing someone's collection
|
// Subscribe to collection changes when viewing someone's collection
|
||||||
|
// Auto-price trigger is disabled, so no more infinite loops!
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!user || !selectedUser) return;
|
if (!user || !selectedUser) return;
|
||||||
|
|
||||||
@@ -209,10 +222,11 @@ export default function Community() {
|
|||||||
table: 'collections',
|
table: 'collections',
|
||||||
},
|
},
|
||||||
(payload: any) => {
|
(payload: any) => {
|
||||||
// Filter for the selected user's collections
|
|
||||||
const data = payload.new || payload.old;
|
const data = payload.new || payload.old;
|
||||||
if (data && data.user_id === selectedUser.id) {
|
if (data && data.user_id === selectedUser.id) {
|
||||||
console.log('Collection change for viewed user:', payload);
|
console.log('Collection change for viewed user:', payload.eventType);
|
||||||
|
// Reload on any change (INSERT/UPDATE/DELETE)
|
||||||
|
// No more infinite loops since auto-price trigger is disabled
|
||||||
loadUserCollection(selectedUser.id);
|
loadUserCollection(selectedUser.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,6 +238,44 @@ export default function Community() {
|
|||||||
};
|
};
|
||||||
}, [user, selectedUser]);
|
}, [user, selectedUser]);
|
||||||
|
|
||||||
|
// Helper function to check if a card has an actual back face
|
||||||
|
const isDoubleFaced = (card: Card) => {
|
||||||
|
const backFaceLayouts = ['transform', 'modal_dfc', 'double_faced_token', 'reversible_card'];
|
||||||
|
return card.card_faces && card.card_faces.length > 1 && backFaceLayouts.includes(card.layout);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get the current face index for a card
|
||||||
|
const getCurrentFaceIndex = (cardId: string) => {
|
||||||
|
return userCardFaceIndex.get(cardId) || 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get the image URI for a card
|
||||||
|
const getCardImageUri = (card: Card, faceIndex: number = 0) => {
|
||||||
|
if (isDoubleFaced(card) && card.card_faces) {
|
||||||
|
return card.card_faces[faceIndex]?.image_uris?.normal || card.card_faces[faceIndex]?.image_uris?.small;
|
||||||
|
}
|
||||||
|
return card.image_uris?.normal || card.image_uris?.small;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper function to get the large image URI for hover preview
|
||||||
|
const getCardLargeImageUri = (card: Card, faceIndex: number = 0) => {
|
||||||
|
if (isDoubleFaced(card) && card.card_faces) {
|
||||||
|
return card.card_faces[faceIndex]?.image_uris?.large || card.card_faces[faceIndex]?.image_uris?.normal;
|
||||||
|
}
|
||||||
|
return card.image_uris?.large || card.image_uris?.normal;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Toggle card face
|
||||||
|
const toggleCardFace = (cardId: string, totalFaces: number) => {
|
||||||
|
setUserCardFaceIndex(prev => {
|
||||||
|
const newMap = new Map(prev);
|
||||||
|
const currentIndex = prev.get(cardId) || 0;
|
||||||
|
const nextIndex = (currentIndex + 1) % totalFaces;
|
||||||
|
newMap.set(cardId, nextIndex);
|
||||||
|
return newMap;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const loadAllData = async () => {
|
const loadAllData = async () => {
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -257,26 +309,138 @@ export default function Community() {
|
|||||||
|
|
||||||
const loadUserCollection = async (userId: string) => {
|
const loadUserCollection = async (userId: string) => {
|
||||||
setLoadingCollection(true);
|
setLoadingCollection(true);
|
||||||
try {
|
setIsLoadingUserTotalValue(true);
|
||||||
const collectionMap = await getUserCollection(userId);
|
|
||||||
if (collectionMap.size === 0) {
|
|
||||||
setSelectedUserCollection([]);
|
setSelectedUserCollection([]);
|
||||||
|
setUserCollectionOffset(0);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Load paginated collection for display
|
||||||
|
const result = await getUserCollectionPaginated(userId, PAGE_SIZE, 0);
|
||||||
|
setUserCollectionTotalCount(result.totalCount);
|
||||||
|
setHasMoreUserCards(result.hasMore);
|
||||||
|
|
||||||
|
if (result.items.size === 0) {
|
||||||
|
setSelectedUserCollection([]);
|
||||||
|
setUserCollectionTotalValue(0);
|
||||||
|
setIsLoadingUserTotalValue(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const cardIds = Array.from(collectionMap.keys());
|
|
||||||
|
const cardIds = Array.from(result.items.keys());
|
||||||
const cards = await getCardsByIds(cardIds);
|
const cards = await getCardsByIds(cardIds);
|
||||||
setSelectedUserCollection(cards.map((card) => ({
|
setSelectedUserCollection(cards.map((card) => ({
|
||||||
card,
|
card,
|
||||||
quantity: collectionMap.get(card.id) || 0,
|
quantity: result.items.get(card.id) || 0,
|
||||||
})));
|
})));
|
||||||
|
setUserCollectionOffset(PAGE_SIZE);
|
||||||
|
|
||||||
|
// Calculate total value (lightweight query from database)
|
||||||
|
const totalValue = await getCollectionTotalValue(userId);
|
||||||
|
setUserCollectionTotalValue(totalValue);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading collection:', error);
|
console.error('Error loading collection:', error);
|
||||||
setSelectedUserCollection([]);
|
setSelectedUserCollection([]);
|
||||||
|
setUserCollectionTotalValue(0);
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingCollection(false);
|
setLoadingCollection(false);
|
||||||
|
setIsLoadingUserTotalValue(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Load more cards for infinite scroll in user collection view
|
||||||
|
const loadMoreUserCards = useCallback(async () => {
|
||||||
|
if (!selectedUser || isLoadingMoreUserCards || !hasMoreUserCards) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsLoadingMoreUserCards(true);
|
||||||
|
|
||||||
|
const result = await getUserCollectionPaginated(
|
||||||
|
selectedUser.id,
|
||||||
|
PAGE_SIZE,
|
||||||
|
userCollectionOffset
|
||||||
|
);
|
||||||
|
setHasMoreUserCards(result.hasMore);
|
||||||
|
|
||||||
|
if (result.items.size === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardIds = Array.from(result.items.keys());
|
||||||
|
const cards = await getCardsByIds(cardIds);
|
||||||
|
|
||||||
|
const newCards = cards.map(card => ({
|
||||||
|
card,
|
||||||
|
quantity: result.items.get(card.id) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Deduplicate: only add cards that aren't already in the collection
|
||||||
|
setSelectedUserCollection(prev => {
|
||||||
|
const existingIds = new Set(prev.map(item => item.card.id));
|
||||||
|
const uniqueNewCards = newCards.filter(item => !existingIds.has(item.card.id));
|
||||||
|
return [...prev, ...uniqueNewCards];
|
||||||
|
});
|
||||||
|
|
||||||
|
setUserCollectionOffset(prev => prev + PAGE_SIZE);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading more cards:', error);
|
||||||
|
} finally {
|
||||||
|
setIsLoadingMoreUserCards(false);
|
||||||
|
}
|
||||||
|
}, [selectedUser, userCollectionOffset, hasMoreUserCards, isLoadingMoreUserCards]);
|
||||||
|
|
||||||
|
// Intersection Observer for infinite scroll in user collection view
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedUser) return;
|
||||||
|
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
if (entries[0].isIntersecting && hasMoreUserCards && !isLoadingMoreUserCards) {
|
||||||
|
loadMoreUserCards();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.1 }
|
||||||
|
);
|
||||||
|
|
||||||
|
const currentTarget = userCollectionObserverTarget.current;
|
||||||
|
if (currentTarget) {
|
||||||
|
observer.observe(currentTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (currentTarget) {
|
||||||
|
observer.unobserve(currentTarget);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [selectedUser, hasMoreUserCards, isLoadingMoreUserCards, loadMoreUserCards]);
|
||||||
|
|
||||||
|
// Subscribe to realtime updates for selected user's collection total value
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedUser) return;
|
||||||
|
|
||||||
|
const userProfileChannel = supabase
|
||||||
|
.channel(`user-profile-value-${selectedUser.id}`)
|
||||||
|
.on(
|
||||||
|
'postgres_changes',
|
||||||
|
{
|
||||||
|
event: 'UPDATE',
|
||||||
|
schema: 'public',
|
||||||
|
table: 'profiles',
|
||||||
|
filter: `id=eq.${selectedUser.id}`,
|
||||||
|
},
|
||||||
|
(payload: any) => {
|
||||||
|
if (payload.new?.collection_total_value !== undefined) {
|
||||||
|
console.log(`User ${selectedUser.username}'s collection total value updated:`, payload.new.collection_total_value);
|
||||||
|
setUserCollectionTotalValue(payload.new.collection_total_value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.subscribe();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
supabase.removeChannel(userProfileChannel);
|
||||||
|
};
|
||||||
|
}, [selectedUser]);
|
||||||
|
|
||||||
// ============ FRIENDS FUNCTIONS ============
|
// ============ FRIENDS FUNCTIONS ============
|
||||||
const loadFriendsData = async () => {
|
const loadFriendsData = async () => {
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
@@ -532,74 +696,313 @@ export default function Community() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-gray-900 text-white min-h-screen">
|
<div className="relative text-white min-h-screen">
|
||||||
{/* Header */}
|
<div className="max-w-7xl mx-auto p-3 sm:p-6">
|
||||||
<div className="sticky top-0 bg-gray-900/95 backdrop-blur border-b border-gray-800 p-3 z-10">
|
{/* Header with Back and Trade buttons */}
|
||||||
<div className="flex items-center justify-between gap-2 mb-3">
|
<div className="flex items-center justify-between gap-2 mb-4 md:mb-6">
|
||||||
<button
|
<button
|
||||||
onClick={() => { setSelectedUser(null); setSelectedUserCollection([]); setUserCollectionSearch(''); }}
|
onClick={() => {
|
||||||
className="flex items-center gap-1 text-blue-400 text-sm min-w-0"
|
setSelectedUser(null);
|
||||||
|
setSelectedUserCollection([]);
|
||||||
|
setUserCollectionSearch('');
|
||||||
|
setSelectedUserCard(null);
|
||||||
|
setHoveredUserCard(null);
|
||||||
|
}}
|
||||||
|
className="flex items-center gap-1 text-blue-400 hover:text-blue-300 text-sm"
|
||||||
>
|
>
|
||||||
<ChevronLeft size={20} />
|
<ChevronLeft size={20} />
|
||||||
<span className="hidden sm:inline">Back</span>
|
<span>Back</span>
|
||||||
</button>
|
</button>
|
||||||
<h1 className="text-lg font-bold truncate flex-1 text-center">{selectedUser.username}</h1>
|
<h1 className="text-2xl md:text-3xl font-bold truncate flex-1 text-center">{selectedUser.username}'s Collection</h1>
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowTradeCreator(true)}
|
onClick={() => setShowTradeCreator(true)}
|
||||||
className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm whitespace-nowrap"
|
className="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm whitespace-nowrap"
|
||||||
>
|
>
|
||||||
<ArrowLeftRight size={16} />
|
<ArrowLeftRight size={16} />
|
||||||
<span className="hidden sm:inline">Trade</span>
|
<span className="hidden sm:inline">Propose Trade</span>
|
||||||
|
<span className="sm:hidden">Trade</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Search input */}
|
{/* Search input */}
|
||||||
|
<div className="mb-8">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={userCollectionSearch}
|
value={userCollectionSearch}
|
||||||
onChange={(e) => setUserCollectionSearch(e.target.value)}
|
onChange={(e) => setUserCollectionSearch(e.target.value)}
|
||||||
placeholder="Search cards..."
|
placeholder="Search cards by name, type, or text..."
|
||||||
className="w-full pl-9 pr-8 py-2 bg-gray-700 border border-gray-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
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"
|
||||||
/>
|
/>
|
||||||
{userCollectionSearch && (
|
</div>
|
||||||
<button
|
</div>
|
||||||
onClick={() => setUserCollectionSearch('')}
|
|
||||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
|
{/* Collection */}
|
||||||
|
<div>
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-4">
|
||||||
|
<h2 className="text-xl font-semibold">
|
||||||
|
{userCollectionSearch
|
||||||
|
? `Found ${filteredUserCollection.length} card(s)`
|
||||||
|
: `Cards (${selectedUserCollection.length} unique, ${selectedUserCollection.reduce((acc, c) => acc + c.quantity, 0)} total)`
|
||||||
|
}
|
||||||
|
</h2>
|
||||||
|
{/* Collection Value Summary */}
|
||||||
|
<div className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2">
|
||||||
|
<div className="text-xs text-gray-400 mb-0.5">
|
||||||
|
{userCollectionSearch ? 'Filtered Value' : 'Total Collection Value'}
|
||||||
|
</div>
|
||||||
|
<div className="text-lg font-bold text-green-400">
|
||||||
|
{isLoadingUserTotalValue ? (
|
||||||
|
<Loader2 className="animate-spin" size={20} />
|
||||||
|
) : userCollectionSearch ? (
|
||||||
|
// For search results, calculate from filtered collection
|
||||||
|
`$${filteredUserCollection.reduce((total, { card, quantity }) => {
|
||||||
|
const price = card.prices?.usd ? parseFloat(card.prices.usd) : 0;
|
||||||
|
return total + (price * quantity);
|
||||||
|
}, 0).toFixed(2)}`
|
||||||
|
) : (
|
||||||
|
// For full collection, use pre-calculated total
|
||||||
|
`$${userCollectionTotalValue.toFixed(2)}`
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loadingCollection ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="animate-spin text-blue-500" size={48} />
|
||||||
|
</div>
|
||||||
|
) : selectedUserCollection.length === 0 ? (
|
||||||
|
<div className="text-center py-12 text-gray-400">
|
||||||
|
<p className="text-lg">Empty collection</p>
|
||||||
|
</div>
|
||||||
|
) : filteredUserCollection.length === 0 ? (
|
||||||
|
<div className="text-center py-12 text-gray-400">
|
||||||
|
<p className="text-lg mb-2">No cards found</p>
|
||||||
|
<p className="text-sm">Try a different search term</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 xl:grid-cols-10 gap-1.5 sm:gap-2">
|
||||||
|
{filteredUserCollection.map(({ card, quantity }) => {
|
||||||
|
const currentFaceIndex = getCurrentFaceIndex(card.id);
|
||||||
|
const isMultiFaced = isDoubleFaced(card);
|
||||||
|
const displayName = isMultiFaced && card.card_faces
|
||||||
|
? card.card_faces[currentFaceIndex]?.name || card.name
|
||||||
|
: card.name;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={card.id}
|
||||||
|
className="relative group cursor-pointer"
|
||||||
|
onMouseEnter={() => setHoveredUserCard(card)}
|
||||||
|
onMouseLeave={() => setHoveredUserCard(null)}
|
||||||
|
onClick={() => setSelectedUserCard({ card, quantity })}
|
||||||
>
|
>
|
||||||
<X size={16} />
|
{/* Card thumbnail */}
|
||||||
|
<div className="relative rounded-lg overflow-hidden shadow-lg transition-all group-hover:ring-2 group-hover:ring-blue-500">
|
||||||
|
<img
|
||||||
|
src={getCardImageUri(card, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-auto"
|
||||||
|
/>
|
||||||
|
{/* Quantity badge */}
|
||||||
|
<div className="absolute top-1 right-1 bg-blue-600 text-white text-xs sm:text-sm font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
|
x{quantity}
|
||||||
|
</div>
|
||||||
|
{/* Price badge */}
|
||||||
|
{card.prices?.usd && (
|
||||||
|
<div className="absolute bottom-1 left-1 bg-green-600 text-white text-[10px] sm:text-xs font-bold px-1.5 py-0.5 rounded shadow-lg">
|
||||||
|
${card.prices.usd}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* Flip button for double-faced cards */}
|
||||||
|
{isMultiFaced && (
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toggleCardFace(card.id, card.card_faces!.length);
|
||||||
|
}}
|
||||||
|
className="absolute bottom-1 right-1 bg-purple-600 hover:bg-purple-700 text-white p-1 rounded-full shadow-lg transition-all"
|
||||||
|
title="Flip card"
|
||||||
|
>
|
||||||
|
<RefreshCw size={12} />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Card name below thumbnail */}
|
||||||
|
<div className="mt-1 text-xs text-center truncate px-1">
|
||||||
|
{displayName}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Infinite scroll loading indicator */}
|
||||||
|
{!userCollectionSearch && isLoadingMoreUserCards && (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<Loader2 className="animate-spin text-blue-500" size={32} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Observer target for infinite scroll */}
|
||||||
|
{!userCollectionSearch && hasMoreUserCards && !isLoadingMoreUserCards && (
|
||||||
|
<div ref={userCollectionObserverTarget} className="h-20" />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* End of collection indicator */}
|
||||||
|
{!userCollectionSearch && !hasMoreUserCards && selectedUserCollection.length > 0 && (
|
||||||
|
<div className="text-center py-8 text-gray-500 text-sm">
|
||||||
|
End of collection • {userCollectionTotalCount} total cards
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Collection Grid */}
|
{/* Hover Card Preview - desktop only, only show if no card is selected */}
|
||||||
<div className="p-3">
|
{hoveredUserCard && !selectedUserCard && (() => {
|
||||||
{loadingCollection ? (
|
const currentFaceIndex = getCurrentFaceIndex(hoveredUserCard.id);
|
||||||
<div className="flex justify-center py-12">
|
const isMultiFaced = isDoubleFaced(hoveredUserCard);
|
||||||
<Loader2 className="animate-spin text-blue-500" size={32} />
|
const currentFace = isMultiFaced && hoveredUserCard.card_faces
|
||||||
</div>
|
? hoveredUserCard.card_faces[currentFaceIndex]
|
||||||
) : selectedUserCollection.length === 0 ? (
|
: null;
|
||||||
<p className="text-gray-400 text-center py-12">Empty collection</p>
|
|
||||||
) : filteredUserCollection.length === 0 ? (
|
const displayName = currentFace?.name || hoveredUserCard.name;
|
||||||
<p className="text-gray-400 text-center py-12">No cards match "{userCollectionSearch}"</p>
|
const displayTypeLine = currentFace?.type_line || hoveredUserCard.type_line;
|
||||||
) : (
|
const displayOracleText = currentFace?.oracle_text || hoveredUserCard.oracle_text;
|
||||||
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
|
|
||||||
{filteredUserCollection.map(({ card, quantity }) => (
|
return (
|
||||||
<div key={card.id} className="relative">
|
<div className="hidden lg:block fixed top-1/2 right-8 transform -translate-y-1/2 z-30 pointer-events-none">
|
||||||
|
<div className="bg-gray-800 rounded-lg shadow-2xl p-4 max-w-md">
|
||||||
|
<div className="relative">
|
||||||
<img
|
<img
|
||||||
src={card.image_uris?.small || card.image_uris?.normal}
|
src={getCardLargeImageUri(hoveredUserCard, currentFaceIndex)}
|
||||||
alt={card.name}
|
alt={displayName}
|
||||||
className="w-full h-auto rounded-lg"
|
className="w-full h-auto rounded-lg shadow-lg"
|
||||||
/>
|
/>
|
||||||
<span className="absolute top-1 right-1 bg-blue-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full">
|
{isMultiFaced && (
|
||||||
x{quantity}
|
<div className="absolute top-2 right-2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
</span>
|
Face {currentFaceIndex + 1}/{hoveredUserCard.card_faces!.length}
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="mt-3 space-y-2">
|
||||||
|
<h3 className="text-xl font-bold">{displayName}</h3>
|
||||||
|
<p className="text-sm text-gray-400">{displayTypeLine}</p>
|
||||||
|
{displayOracleText && (
|
||||||
|
<p className="text-sm text-gray-300 border-t border-gray-700 pt-2">
|
||||||
|
{displayOracleText}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{hoveredUserCard.prices?.usd && (
|
||||||
|
<div className="text-sm text-green-400 font-semibold border-t border-gray-700 pt-2">
|
||||||
|
${hoveredUserCard.prices.usd}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
|
{/* Card Detail Panel - slides in from right */}
|
||||||
|
{selectedUserCard && (() => {
|
||||||
|
const currentFaceIndex = getCurrentFaceIndex(selectedUserCard.card.id);
|
||||||
|
const isMultiFaced = isDoubleFaced(selectedUserCard.card);
|
||||||
|
const currentFace = isMultiFaced && selectedUserCard.card.card_faces
|
||||||
|
? selectedUserCard.card.card_faces[currentFaceIndex]
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const displayName = currentFace?.name || selectedUserCard.card.name;
|
||||||
|
const displayTypeLine = currentFace?.type_line || selectedUserCard.card.type_line;
|
||||||
|
const displayOracleText = currentFace?.oracle_text || selectedUserCard.card.oracle_text;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Backdrop */}
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black bg-opacity-50 z-[110] transition-opacity duration-300"
|
||||||
|
onClick={() => setSelectedUserCard(null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Sliding Panel */}
|
||||||
|
<div className="fixed top-0 right-0 h-full w-full md:w-96 bg-gray-800 shadow-2xl z-[120] overflow-y-auto animate-slide-in-right">
|
||||||
|
{/* Close button */}
|
||||||
|
<button
|
||||||
|
onClick={() => setSelectedUserCard(null)}
|
||||||
|
className="fixed top-4 right-4 bg-gray-700 hover:bg-gray-600 text-white p-2 md:p-1.5 rounded-full transition-colors z-[130] shadow-lg"
|
||||||
|
aria-label="Close"
|
||||||
|
>
|
||||||
|
<X size={24} className="md:w-5 md:h-5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="p-4 sm:p-6">
|
||||||
|
{/* Card Image */}
|
||||||
|
<div className="relative mb-4 max-w-sm mx-auto">
|
||||||
|
<img
|
||||||
|
src={getCardLargeImageUri(selectedUserCard.card, currentFaceIndex)}
|
||||||
|
alt={displayName}
|
||||||
|
className="w-full h-auto rounded-lg shadow-lg"
|
||||||
|
/>
|
||||||
|
{isMultiFaced && (
|
||||||
|
<>
|
||||||
|
<div className="absolute top-2 right-2 bg-purple-600 text-white text-xs font-bold px-2 py-1 rounded-full shadow-lg">
|
||||||
|
Face {currentFaceIndex + 1}/{selectedUserCard.card.card_faces!.length}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => toggleCardFace(selectedUserCard.card.id, selectedUserCard.card.card_faces!.length)}
|
||||||
|
className="absolute bottom-2 right-2 bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-lg transition-all"
|
||||||
|
title="Flip card"
|
||||||
|
>
|
||||||
|
<RefreshCw size={20} />
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Card Info */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl md:text-2xl font-bold text-white mb-2">{displayName}</h2>
|
||||||
|
<p className="text-xs sm:text-sm text-gray-400">{displayTypeLine}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{displayOracleText && (
|
||||||
|
<div className="border-t border-gray-700 pt-3">
|
||||||
|
<p className="text-sm text-gray-300">{displayOracleText}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedUserCard.card.prices?.usd && (
|
||||||
|
<div className="border-t border-gray-700 pt-3">
|
||||||
|
<div className="text-lg text-green-400 font-semibold">
|
||||||
|
${selectedUserCard.card.prices.usd} each
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-gray-400">
|
||||||
|
Total value: ${(parseFloat(selectedUserCard.card.prices.usd) * selectedUserCard.quantity).toFixed(2)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Quantity Display */}
|
||||||
|
<div className="border-t border-gray-700 pt-3">
|
||||||
|
<h3 className="text-lg font-semibold mb-3">Quantity in Collection</h3>
|
||||||
|
<div className="flex items-center justify-center bg-gray-900 rounded-lg p-4">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-3xl font-bold">{selectedUserCard.quantity}</div>
|
||||||
|
<div className="text-xs text-gray-400">copies</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
{showTradeCreator && (
|
{showTradeCreator && (
|
||||||
<TradeCreator
|
<TradeCreator
|
||||||
@@ -624,7 +1027,7 @@ export default function Community() {
|
|||||||
|
|
||||||
// ============ MAIN VIEW ============
|
// ============ MAIN VIEW ============
|
||||||
return (
|
return (
|
||||||
<div className="relative bg-gray-900 text-white p-3 sm:p-6 md:min-h-screen">
|
<div className="relative text-white p-3 sm:p-6 md:min-h-screen">
|
||||||
<div className="max-w-7xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Community</h1>
|
<h1 className="text-2xl md:text-3xl font-bold mb-4 md:mb-6">Community</h1>
|
||||||
@@ -1009,10 +1412,15 @@ export default function Community() {
|
|||||||
With: <strong>{otherUser?.username}</strong>
|
With: <strong>{otherUser?.username}</strong>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
{trade.status === 'pending' && !trade.is_valid && (
|
||||||
|
<AlertTriangle size={14} className="text-red-400" title="Trade no longer valid" />
|
||||||
|
)}
|
||||||
<span className={`text-xs capitalize ${statusColors[trade.status]}`}>
|
<span className={`text-xs capitalize ${statusColors[trade.status]}`}>
|
||||||
{trade.status}
|
{trade.status}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Items */}
|
{/* Items */}
|
||||||
<div className="grid grid-cols-2 gap-2 text-sm">
|
<div className="grid grid-cols-2 gap-2 text-sm">
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ const DeckList = ({ onDeckEdit, onCreateDeck }: DeckListProps) => {
|
|||||||
{/* Create New Deck Card */}
|
{/* Create New Deck Card */}
|
||||||
<button
|
<button
|
||||||
onClick={onCreateDeck}
|
onClick={onCreateDeck}
|
||||||
className="bg-gray-800 rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl border-2 border-dashed border-gray-600 hover:border-blue-500 transition-all duration-300 hover:scale-105 cursor-pointer group aspect-[5/7] flex flex-col items-center justify-center gap-3 p-4"
|
||||||
>
|
>
|
||||||
<PlusCircle size={48} className="text-gray-600 group-hover:text-blue-500 transition-colors" />
|
<PlusCircle size={48} className="text-gray-600 group-hover:text-blue-500 transition-colors" />
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History } from 'lucide-react';
|
import { X, Check, ArrowLeftRight, DollarSign, Loader2, Edit, RefreshCcw, History, AlertTriangle } from 'lucide-react';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { useToast } from '../contexts/ToastContext';
|
import { useToast } from '../contexts/ToastContext';
|
||||||
import { Trade, TradeHistoryEntry, getTradeVersionHistory } from '../services/tradesService';
|
import { Trade, TradeHistoryEntry, getTradeVersionHistory } from '../services/tradesService';
|
||||||
@@ -222,6 +222,18 @@ export default function TradeDetail({
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{/* Invalid Trade Warning */}
|
||||||
|
{trade.status === 'pending' && !trade.is_valid && (
|
||||||
|
<div className="bg-red-900/30 border border-red-600 rounded-lg p-3 flex items-start gap-2">
|
||||||
|
<AlertTriangle size={20} className="text-red-400 flex-shrink-0 mt-0.5" />
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold text-red-400 text-sm">Trade No Longer Valid</h4>
|
||||||
|
<p className="text-red-200 text-xs mt-1">
|
||||||
|
One or more cards in this trade are no longer available in the required quantities. This trade cannot be accepted until it is updated.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||||
{/* Your Side */}
|
{/* Your Side */}
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
@@ -367,8 +379,9 @@ export default function TradeDetail({
|
|||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={handleAccept}
|
onClick={handleAccept}
|
||||||
disabled={processing}
|
disabled={processing || !trade.is_valid}
|
||||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-medium transition"
|
||||||
|
title={!trade.is_valid ? 'This trade is no longer valid' : ''}
|
||||||
>
|
>
|
||||||
{processing ? (
|
{processing ? (
|
||||||
<Loader2 className="animate-spin" size={18} />
|
<Loader2 className="animate-spin" size={18} />
|
||||||
@@ -431,8 +444,9 @@ export default function TradeDetail({
|
|||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={handleAccept}
|
onClick={handleAccept}
|
||||||
disabled={processing}
|
disabled={processing || !trade.is_valid}
|
||||||
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 rounded-lg font-medium transition"
|
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed rounded-lg font-medium transition"
|
||||||
|
title={!trade.is_valid ? 'This trade is no longer valid' : ''}
|
||||||
>
|
>
|
||||||
{processing ? (
|
{processing ? (
|
||||||
<Loader2 className="animate-spin" size={18} />
|
<Loader2 className="animate-spin" size={18} />
|
||||||
|
|||||||
@@ -167,6 +167,34 @@
|
|||||||
animation: float 3s ease-in-out infinite;
|
animation: float 3s ease-in-out infinite;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Diagonal Carousel - Cards flow from bottom-left to top-right diagonally and loop */
|
||||||
|
@keyframes flowDiagonal {
|
||||||
|
0% {
|
||||||
|
translate: 0 0;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
60% {
|
||||||
|
translate: 600px -600px;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
75% {
|
||||||
|
translate: 900px -900px;
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
85% {
|
||||||
|
translate: 1100px -1100px;
|
||||||
|
opacity: 0.3;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
translate: 1400px -1400px;
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-flow-right {
|
||||||
|
animation: flowDiagonal 40s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
/* Gradient Animation */
|
/* Gradient Animation */
|
||||||
@keyframes gradientShift {
|
@keyframes gradientShift {
|
||||||
0% {
|
0% {
|
||||||
|
|||||||
@@ -75,10 +75,76 @@ export const getUserCollection = async (userId: string): Promise<Map<string, num
|
|||||||
return collectionMap;
|
return collectionMap;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Paginated collection API
|
||||||
|
export interface PaginatedCollectionResult {
|
||||||
|
items: Map<string, number>; // card_id -> quantity
|
||||||
|
totalCount: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get total collection value from user profile (pre-calculated by triggers)
|
||||||
|
export const getCollectionTotalValue = async (userId: string): Promise<number> => {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('profiles')
|
||||||
|
.select('collection_total_value')
|
||||||
|
.eq('id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error fetching collection total value:', error);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return data?.collection_total_value || 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUserCollectionPaginated = async (
|
||||||
|
userId: string,
|
||||||
|
pageSize: number = 50,
|
||||||
|
offset: number = 0
|
||||||
|
): Promise<PaginatedCollectionResult> => {
|
||||||
|
// First, get the total count
|
||||||
|
const { count: totalCount, error: countError } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('*', { count: 'exact', head: true })
|
||||||
|
.eq('user_id', userId);
|
||||||
|
|
||||||
|
if (countError) {
|
||||||
|
console.error('Error counting user collection:', countError);
|
||||||
|
throw countError;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then get the paginated data
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('collections')
|
||||||
|
.select('card_id, quantity')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.order('created_at', { ascending: false })
|
||||||
|
.range(offset, offset + pageSize - 1);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error fetching user collection:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a map of card_id to quantity for easy lookup
|
||||||
|
const collectionMap = new Map<string, number>();
|
||||||
|
data?.forEach((item) => {
|
||||||
|
collectionMap.set(item.card_id, item.quantity);
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
items: collectionMap,
|
||||||
|
totalCount: totalCount || 0,
|
||||||
|
hasMore: offset + pageSize < (totalCount || 0),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export const addCardToCollection = async (
|
export const addCardToCollection = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
cardId: string,
|
cardId: string,
|
||||||
quantity: number = 1
|
quantity: number = 1,
|
||||||
|
priceUsd: number = 0
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
// Check if card already exists in collection
|
// Check if card already exists in collection
|
||||||
const { data: existing, error: fetchError } = await supabase
|
const { data: existing, error: fetchError } = await supabase
|
||||||
@@ -94,11 +160,12 @@ export const addCardToCollection = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
// Update existing card quantity
|
// Update existing card quantity and price
|
||||||
const { error: updateError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from('collections')
|
.from('collections')
|
||||||
.update({
|
.update({
|
||||||
quantity: existing.quantity + quantity,
|
quantity: existing.quantity + quantity,
|
||||||
|
price_usd: priceUsd,
|
||||||
updated_at: new Date().toISOString()
|
updated_at: new Date().toISOString()
|
||||||
})
|
})
|
||||||
.eq('id', existing.id);
|
.eq('id', existing.id);
|
||||||
@@ -112,6 +179,7 @@ export const addCardToCollection = async (
|
|||||||
user_id: userId,
|
user_id: userId,
|
||||||
card_id: cardId,
|
card_id: cardId,
|
||||||
quantity: quantity,
|
quantity: quantity,
|
||||||
|
price_usd: priceUsd,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (insertError) throw insertError;
|
if (insertError) throw insertError;
|
||||||
@@ -120,7 +188,7 @@ export const addCardToCollection = async (
|
|||||||
|
|
||||||
export const addMultipleCardsToCollection = async (
|
export const addMultipleCardsToCollection = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
cards: { cardId: string; quantity: number }[]
|
cards: { cardId: string; quantity: number; priceUsd?: number }[]
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
// Fetch existing cards in collection
|
// Fetch existing cards in collection
|
||||||
const cardIds = cards.map(c => c.cardId);
|
const cardIds = cards.map(c => c.cardId);
|
||||||
@@ -146,6 +214,7 @@ export const addMultipleCardsToCollection = async (
|
|||||||
toUpdate.push({
|
toUpdate.push({
|
||||||
id: existing.id,
|
id: existing.id,
|
||||||
quantity: existing.quantity + card.quantity,
|
quantity: existing.quantity + card.quantity,
|
||||||
|
price_usd: card.priceUsd || 0,
|
||||||
updated_at: new Date().toISOString(),
|
updated_at: new Date().toISOString(),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -153,6 +222,7 @@ export const addMultipleCardsToCollection = async (
|
|||||||
user_id: userId,
|
user_id: userId,
|
||||||
card_id: card.cardId,
|
card_id: card.cardId,
|
||||||
quantity: card.quantity,
|
quantity: card.quantity,
|
||||||
|
price_usd: card.priceUsd || 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -170,7 +240,11 @@ export const addMultipleCardsToCollection = async (
|
|||||||
for (const update of toUpdate) {
|
for (const update of toUpdate) {
|
||||||
const { error: updateError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from('collections')
|
.from('collections')
|
||||||
.update({ quantity: update.quantity, updated_at: update.updated_at })
|
.update({
|
||||||
|
quantity: update.quantity,
|
||||||
|
price_usd: update.price_usd,
|
||||||
|
updated_at: update.updated_at
|
||||||
|
})
|
||||||
.eq('id', update.id);
|
.eq('id', update.id);
|
||||||
|
|
||||||
if (updateError) throw updateError;
|
if (updateError) throw updateError;
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export interface Trade {
|
|||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
version: number;
|
version: number;
|
||||||
editor_id: string | null;
|
editor_id: string | null;
|
||||||
|
is_valid: boolean;
|
||||||
user1?: { username: string | null };
|
user1?: { username: string | null };
|
||||||
user2?: { username: string | null };
|
user2?: { username: string | null };
|
||||||
items?: TradeItem[];
|
items?: TradeItem[];
|
||||||
@@ -160,6 +161,25 @@ export async function createTrade(params: CreateTradeParams): Promise<Trade> {
|
|||||||
|
|
||||||
// Accept a trade (executes the card transfer)
|
// Accept a trade (executes the card transfer)
|
||||||
export async function acceptTrade(tradeId: string): Promise<boolean> {
|
export async function acceptTrade(tradeId: string): Promise<boolean> {
|
||||||
|
// First check if the trade is valid
|
||||||
|
const { data: trade, error: tradeError } = await supabase
|
||||||
|
.from('trades')
|
||||||
|
.select('is_valid, status')
|
||||||
|
.eq('id', tradeId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (tradeError) throw tradeError;
|
||||||
|
|
||||||
|
// Prevent accepting invalid trades
|
||||||
|
if (!trade.is_valid) {
|
||||||
|
throw new Error('This trade is no longer valid. One or more cards are no longer available in the required quantities.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevent accepting non-pending trades
|
||||||
|
if (trade.status !== 'pending') {
|
||||||
|
throw new Error('This trade has already been processed.');
|
||||||
|
}
|
||||||
|
|
||||||
const { data, error } = await supabase.rpc('execute_trade', {
|
const { data, error } = await supabase.rpc('execute_trade', {
|
||||||
trade_id: tradeId,
|
trade_id: tradeId,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- Add price_usd column to collections table
|
||||||
|
ALTER TABLE collections
|
||||||
|
ADD COLUMN IF NOT EXISTS price_usd DECIMAL(10, 2) DEFAULT 0;
|
||||||
|
|
||||||
|
-- Create index for faster price calculations
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_collections_price ON collections(price_usd);
|
||||||
|
|
||||||
|
-- Add comment
|
||||||
|
COMMENT ON COLUMN collections.price_usd IS 'USD price of the card at time of addition/update';
|
||||||
101
supabase/migrations/20250127000001_add_trade_validation.sql
Normal file
101
supabase/migrations/20250127000001_add_trade_validation.sql
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
-- Add is_valid column to trades table
|
||||||
|
ALTER TABLE public.trades
|
||||||
|
ADD COLUMN IF NOT EXISTS is_valid BOOLEAN DEFAULT true;
|
||||||
|
|
||||||
|
-- Create index for filtering by validity
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_trades_is_valid ON public.trades(is_valid);
|
||||||
|
|
||||||
|
-- Function to validate if a trade can still be executed based on current collections
|
||||||
|
CREATE OR REPLACE FUNCTION public.validate_trade(p_trade_id uuid)
|
||||||
|
RETURNS boolean
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
SECURITY DEFINER
|
||||||
|
AS $$
|
||||||
|
DECLARE
|
||||||
|
v_item RECORD;
|
||||||
|
v_collection_quantity integer;
|
||||||
|
BEGIN
|
||||||
|
-- Check each item in the trade
|
||||||
|
FOR v_item IN
|
||||||
|
SELECT owner_id, card_id, quantity
|
||||||
|
FROM public.trade_items
|
||||||
|
WHERE trade_id = p_trade_id
|
||||||
|
LOOP
|
||||||
|
-- Get the quantity of this card in the owner's collection
|
||||||
|
SELECT COALESCE(quantity, 0) INTO v_collection_quantity
|
||||||
|
FROM public.collections
|
||||||
|
WHERE user_id = v_item.owner_id
|
||||||
|
AND card_id = v_item.card_id;
|
||||||
|
|
||||||
|
-- If owner doesn't have enough of this card, trade is invalid
|
||||||
|
IF v_collection_quantity < v_item.quantity THEN
|
||||||
|
RETURN false;
|
||||||
|
END IF;
|
||||||
|
END LOOP;
|
||||||
|
|
||||||
|
-- All items are available, trade is valid
|
||||||
|
RETURN true;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Function to check and update validity of affected trades when collections change
|
||||||
|
CREATE OR REPLACE FUNCTION public.update_affected_trades_validity()
|
||||||
|
RETURNS TRIGGER
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
SECURITY DEFINER
|
||||||
|
AS $$
|
||||||
|
DECLARE
|
||||||
|
v_user_id uuid;
|
||||||
|
v_card_id text;
|
||||||
|
v_trade RECORD;
|
||||||
|
v_is_valid boolean;
|
||||||
|
BEGIN
|
||||||
|
-- Get the user_id and card_id from the changed row
|
||||||
|
IF (TG_OP = 'DELETE') THEN
|
||||||
|
v_user_id := OLD.user_id;
|
||||||
|
v_card_id := OLD.card_id;
|
||||||
|
ELSE
|
||||||
|
v_user_id := NEW.user_id;
|
||||||
|
v_card_id := NEW.card_id;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
-- Find all pending trades that involve this card from this user
|
||||||
|
FOR v_trade IN
|
||||||
|
SELECT DISTINCT t.id
|
||||||
|
FROM public.trades t
|
||||||
|
JOIN public.trade_items ti ON ti.trade_id = t.id
|
||||||
|
WHERE t.status = 'pending'
|
||||||
|
AND ti.owner_id = v_user_id
|
||||||
|
AND ti.card_id = v_card_id
|
||||||
|
LOOP
|
||||||
|
-- Validate the trade
|
||||||
|
v_is_valid := public.validate_trade(v_trade.id);
|
||||||
|
|
||||||
|
-- Update the trade's validity
|
||||||
|
UPDATE public.trades
|
||||||
|
SET is_valid = v_is_valid,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = v_trade.id;
|
||||||
|
END LOOP;
|
||||||
|
|
||||||
|
IF (TG_OP = 'DELETE') THEN
|
||||||
|
RETURN OLD;
|
||||||
|
ELSE
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Create trigger to auto-update trade validity when collections change
|
||||||
|
CREATE TRIGGER update_trades_on_collection_change
|
||||||
|
AFTER UPDATE OR DELETE ON public.collections
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION public.update_affected_trades_validity();
|
||||||
|
|
||||||
|
-- Add comment
|
||||||
|
COMMENT ON COLUMN public.trades.is_valid IS 'Indicates if the trade can still be executed based on current collections. Auto-updated when collections change.';
|
||||||
|
|
||||||
|
-- Initial validation: set is_valid for all existing pending trades
|
||||||
|
UPDATE public.trades
|
||||||
|
SET is_valid = public.validate_trade(id)
|
||||||
|
WHERE status = 'pending';
|
||||||
Reference in New Issue
Block a user