Refactor code structure and remove redundant changes

This commit is contained in:
pacnpal
2025-11-09 16:31:34 -05:00
parent 2884bc23ce
commit eb68cf40c6
1080 changed files with 27361 additions and 56687 deletions

View File

@@ -0,0 +1,193 @@
import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { AutocompleteSearch } from '@/components/search/AutocompleteSearch';
import { supabase } from '@/lib/supabaseClient';
import { toast } from 'sonner';
import { getErrorMessage } from '@/lib/errorHandler';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar as CalendarIcon } from 'lucide-react';
import { format } from 'date-fns';
import { cn } from '@/lib/utils';
interface AddRideCreditDialogProps {
userId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: (newCreditId: string) => void;
}
export function AddRideCreditDialog({ userId, open, onOpenChange, onSuccess }: AddRideCreditDialogProps) {
const [selectedRideId, setSelectedRideId] = useState<string>('');
const [selectedRideName, setSelectedRideName] = useState<string>('');
const [firstRideDate, setFirstRideDate] = useState<Date | undefined>(undefined);
const [rideCount, setRideCount] = useState(1);
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedRideId) {
toast.error('Please select a ride');
return;
}
try {
setSubmitting(true);
// Check if credit already exists
const { data: existing } = await supabase
.from('user_ride_credits')
.select('id')
.eq('user_id', userId)
.eq('ride_id', selectedRideId)
.maybeSingle();
if (existing) {
toast.error('You already have a credit for this ride');
return;
}
const { data, error } = await supabase
.from('user_ride_credits')
.insert({
user_id: userId,
ride_id: selectedRideId,
first_ride_date: firstRideDate ? format(firstRideDate, 'yyyy-MM-dd') : null,
ride_count: rideCount
})
.select('id')
.single();
if (error) throw error;
toast.success('Ride credit added!');
handleReset();
onSuccess(data.id); // Pass the new ID
onOpenChange(false);
} catch (error: unknown) {
toast.error(getErrorMessage(error));
} finally {
setSubmitting(false);
}
};
const handleReset = () => {
setSelectedRideId('');
setSelectedRideName('');
setFirstRideDate(undefined);
setRideCount(1);
};
return (
<Dialog
open={open}
onOpenChange={(newOpen) => {
if (!newOpen) {
handleReset();
}
onOpenChange(newOpen);
}}
>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Add Ride Credit</DialogTitle>
<DialogDescription>
Log a ride you've experienced
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label>Search for a Ride</Label>
{!selectedRideId ? (
<AutocompleteSearch
onResultSelect={(result) => {
if (result.type === 'ride') {
setSelectedRideId(result.id);
setSelectedRideName(result.title);
}
}}
types={['ride']}
placeholder="Search rides..."
className="w-full"
/>
) : (
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/50">
<div>
<p className="font-medium">{selectedRideName}</p>
<p className="text-sm text-muted-foreground">Selected ride</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setSelectedRideId('');
setSelectedRideName('');
}}
>
Change
</Button>
</div>
)}
</div>
<div className="space-y-2">
<Label>First Ride Date (Optional)</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
'w-full justify-start text-left font-normal',
!firstRideDate && 'text-muted-foreground'
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{firstRideDate ? format(firstRideDate, 'PPP') : 'Pick a date'}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={firstRideDate}
onSelect={setFirstRideDate}
initialFocus
disabled={(date) => date > new Date()}
/>
</PopoverContent>
</Popover>
</div>
<div className="space-y-2">
<Label htmlFor="ride-count">Number of Rides</Label>
<Input
id="ride-count"
type="number"
min="1"
value={rideCount}
onChange={(e) => setRideCount(parseInt(e.target.value) || 1)}
/>
</div>
<div className="flex gap-2 justify-end">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
Cancel
</Button>
<Button type="submit" loading={submitting} loadingText="Adding..." disabled={!selectedRideId}>
Add Credit
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,22 @@
import { MapPin } from 'lucide-react';
interface LocationDisplayProps {
location: {
city?: string;
country: string;
} | null | undefined;
}
export function LocationDisplay({ location }: LocationDisplayProps) {
// get_filtered_profile() already handles privacy - if location is present, it's viewable
if (!location) {
return null;
}
return (
<div className="flex items-center gap-1">
<MapPin className="w-4 h-4" />
{location.city ? `${location.city}, ${location.country}` : location.country}
</div>
);
}

View File

@@ -0,0 +1,19 @@
import { MapPin } from 'lucide-react';
interface PersonalLocationDisplayProps {
personalLocation: string | null | undefined;
}
export function PersonalLocationDisplay({ personalLocation }: PersonalLocationDisplayProps) {
// get_filtered_profile() already handles privacy - if personalLocation is present, it's viewable
if (!personalLocation) {
return null;
}
return (
<div className="flex items-center gap-1">
<MapPin className="w-4 h-4" />
{personalLocation}
</div>
);
}

View File

@@ -0,0 +1,502 @@
import { useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Calendar, MapPin, Edit, Trash2, Plus, Minus, Check, X, Star, Factory, Gauge, Ruler, Zap } from 'lucide-react';
import { Link } from 'react-router-dom';
import { format } from 'date-fns';
import { supabase } from '@/lib/supabaseClient';
import { toast } from 'sonner';
import { getErrorMessage } from '@/lib/errorHandler';
import { UserRideCredit } from '@/types/database';
import { convertValueFromMetric, getDisplayUnit } from '@/lib/units';
import { parseDateForDisplay } from '@/lib/dateUtils';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
interface RideCreditCardProps {
credit: UserRideCredit;
position: number;
maxPosition?: number;
viewMode: 'grid' | 'list';
isEditMode?: boolean;
onUpdate: (creditId: string, updates: Partial<UserRideCredit>) => void;
onDelete: () => void;
onReorder?: (creditId: string, newPosition: number) => Promise<void>;
}
export function RideCreditCard({ credit, position, maxPosition, viewMode, isEditMode, onUpdate, onDelete, onReorder }: RideCreditCardProps) {
const [isEditing, setIsEditing] = useState(false);
const [editCount, setEditCount] = useState(credit.ride_count);
const [editPosition, setEditPosition] = useState(position);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [updating, setUpdating] = useState(false);
const rideName = credit.rides?.name || 'Unknown Ride';
const parkName = credit.rides?.parks?.name || 'Unknown Park';
const parkSlug = credit.rides?.parks?.slug || '';
const rideSlug = credit.rides?.slug || '';
const imageUrl = credit.rides?.card_image_url;
const category = credit.rides?.category || '';
const location = credit.rides?.parks?.locations;
const manufacturer = credit.rides?.manufacturer;
const coasterType = credit.rides?.coaster_type;
const maxSpeed = credit.rides?.max_speed_kmh;
const maxHeight = credit.rides?.max_height_meters;
const inversions = credit.rides?.inversions || 0;
const intensityLevel = credit.rides?.intensity_level;
const handleUpdateCount = async () => {
try {
setUpdating(true);
const { error } = await supabase
.from('user_ride_credits')
.update({ ride_count: editCount })
.eq('id', credit.id);
if (error) throw error;
toast.success('Ride count updated');
setIsEditing(false);
// Optimistic update - pass specific changes
onUpdate(credit.id, { ride_count: editCount });
} catch (error: unknown) {
toast.error(getErrorMessage(error));
} finally {
setUpdating(false);
}
};
const handleQuickIncrement = async () => {
try {
const newCount = credit.ride_count + 1;
// Optimistic update first
onUpdate(credit.id, { ride_count: newCount });
const { error } = await supabase
.from('user_ride_credits')
.update({ ride_count: newCount })
.eq('id', credit.id);
if (error) throw error;
toast.success('Ride count increased');
} catch (error: unknown) {
toast.error(getErrorMessage(error));
// Rollback on error
onUpdate(credit.id, { ride_count: credit.ride_count });
}
};
const handlePositionChange = async () => {
if (editPosition === position || !onReorder || !maxPosition) return;
if (editPosition < 1 || editPosition > maxPosition) {
toast.error(`Position must be between 1 and ${maxPosition}`);
setEditPosition(position);
return;
}
try {
await onReorder(credit.id, editPosition);
toast.success('Position updated');
} catch (error: unknown) {
toast.error(getErrorMessage(error));
setEditPosition(position);
}
};
const getCategoryBadge = (category: string) => {
const categoryMap: Record<string, { label: string; variant: 'default' | 'secondary' | 'outline' }> = {
roller_coaster: { label: 'Coaster', variant: 'default' },
flat_ride: { label: 'Flat Ride', variant: 'secondary' },
water_ride: { label: 'Water Ride', variant: 'outline' },
dark_ride: { label: 'Dark Ride', variant: 'outline' },
};
const info = categoryMap[category] || { label: category, variant: 'outline' as const };
return <Badge variant={info.variant}>{info.label}</Badge>;
};
const ridePath = parkSlug && rideSlug
? `/parks/${parkSlug}/rides/${rideSlug}`
: '#';
if (viewMode === 'list') {
return (
<Card>
<CardContent className="p-4">
<div className="flex items-start gap-4">
{imageUrl && (
<img
src={imageUrl}
alt={rideName}
className="w-24 h-24 object-cover rounded flex-shrink-0"
/>
)}
<div className="flex-1 min-w-0 space-y-2">
{/* Header Row */}
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<Link
to={ridePath}
className="font-semibold hover:underline truncate"
>
{rideName}
</Link>
{isEditMode && maxPosition ? (
<div className="flex items-center gap-1">
<span className="text-xs text-muted-foreground">#</span>
<Input
type="number"
value={editPosition}
onChange={(e) => setEditPosition(parseInt(e.target.value) || 1)}
onBlur={handlePositionChange}
onKeyDown={(e) => e.key === 'Enter' && handlePositionChange()}
className="w-14 h-6 text-xs p-1"
min="1"
max={maxPosition}
/>
</div>
) : (
<Badge variant="secondary" className="text-xs font-semibold">
#{position}
</Badge>
)}
{getCategoryBadge(category)}
</div>
<Link
to={`/parks/${parkSlug}`}
className="text-sm text-muted-foreground hover:underline block truncate"
>
<MapPin className="w-3 h-3 inline mr-1" />
{parkName}
{location?.city && `, ${location.city}`}
{location?.state_province && `, ${location.state_province}`}
</Link>
</div>
</div>
{/* Stats Grid - Enhanced */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
{manufacturer && (
<div className="flex items-center gap-1">
<Factory className="w-3 h-3 text-muted-foreground" />
<span className="truncate">{manufacturer.name}</span>
</div>
)}
{coasterType && (
<div className="flex items-center gap-1">
<span className="text-muted-foreground">Type:</span>
<span className="truncate capitalize">{coasterType.replace('_', ' ')}</span>
</div>
)}
{maxSpeed && (
<div className="flex items-center gap-1">
<Gauge className="w-3 h-3 text-muted-foreground" />
<span>{Math.round(maxSpeed)} km/h</span>
</div>
)}
{maxHeight && (
<div className="flex items-center gap-1">
<Ruler className="w-3 h-3 text-muted-foreground" />
<span>{Math.round(maxHeight)} m</span>
</div>
)}
{inversions > 0 && (
<div className="flex items-center gap-1">
<Zap className="w-3 h-3 text-muted-foreground" />
<span>{inversions} inversions</span>
</div>
)}
{intensityLevel && (
<div className="flex items-center gap-1">
<span className="text-muted-foreground">Intensity:</span>
<Badge variant="outline" className="text-xs capitalize">{intensityLevel}</Badge>
</div>
)}
</div>
{/* Dates */}
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{credit.first_ride_date && (
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3" />
{/* ⚠️ Use parseDateForDisplay to prevent timezone shifts */}
<span>First: {format(parseDateForDisplay(credit.first_ride_date), 'MMM d, yyyy')}</span>
</div>
)}
{credit.last_ride_date && (
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3" />
<span>Last: {format(parseDateForDisplay(credit.last_ride_date), 'MMM d, yyyy')}</span>
</div>
)}
</div>
{/* Personal Rating */}
{credit.personal_rating && (
<div className="flex items-center gap-1">
{Array.from({ length: 5 }, (_, i) => (
<Star
key={i}
className={`w-3 h-3 ${
i < credit.personal_rating!
? 'fill-yellow-400 text-yellow-400'
: 'text-muted-foreground/30'
}`}
/>
))}
<span className="text-xs text-muted-foreground ml-1">Your Rating</span>
</div>
)}
{/* Personal Notes Preview */}
{credit.personal_notes && (
<p className="text-xs italic text-muted-foreground line-clamp-2 bg-muted/30 p-2 rounded">
"{credit.personal_notes}"
</p>
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{isEditing ? (
<>
<Input
type="number"
value={editCount}
onChange={(e) => setEditCount(parseInt(e.target.value) || 1)}
className="w-20"
min="1"
/>
<Button
size="icon"
variant="ghost"
onClick={handleUpdateCount}
disabled={updating}
>
<Check className="w-4 h-4" />
</Button>
<Button
size="icon"
variant="ghost"
onClick={() => {
setIsEditing(false);
setEditCount(credit.ride_count);
}}
>
<X className="w-4 h-4" />
</Button>
</>
) : (
<>
<div className="text-center">
<div className="text-2xl font-bold">{credit.ride_count}</div>
<div className="text-xs text-muted-foreground">
{credit.ride_count === 1 ? 'ride' : 'rides'}
</div>
</div>
<Button
size="icon"
variant="ghost"
onClick={handleQuickIncrement}
>
<Plus className="w-4 h-4" />
</Button>
<Button
size="icon"
variant="ghost"
onClick={() => setIsEditing(true)}
>
<Edit className="w-4 h-4" />
</Button>
<Button
size="icon"
variant="ghost"
onClick={() => setShowDeleteDialog(true)}
>
<Trash2 className="w-4 h-4" />
</Button>
</>
)}
</div>
</div>
</CardContent>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Ride Credit?</AlertDialogTitle>
<AlertDialogDescription>
This will remove {rideName} from your ride credits. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={onDelete}>Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
);
}
// Grid view
return (
<Card className="overflow-hidden">
{imageUrl && (
<div className="aspect-video relative">
<img
src={imageUrl}
alt={rideName}
className="w-full h-full object-cover"
/>
</div>
)}
<CardContent className="p-4">
<div className="space-y-3">
<div>
<div className="flex items-start justify-between gap-2 mb-1">
<Link
to={ridePath}
className="font-semibold hover:underline line-clamp-2"
>
{rideName}
</Link>
<div className="flex gap-1 flex-shrink-0">
{isEditMode && maxPosition ? (
<div className="flex items-center gap-1">
<span className="text-xs text-muted-foreground">#</span>
<Input
type="number"
value={editPosition}
onChange={(e) => setEditPosition(parseInt(e.target.value) || 1)}
onBlur={handlePositionChange}
onKeyDown={(e) => e.key === 'Enter' && handlePositionChange()}
className="w-14 h-6 text-xs p-1"
min="1"
max={maxPosition}
/>
</div>
) : (
<Badge variant="secondary" className="text-xs font-semibold">
#{position}
</Badge>
)}
{getCategoryBadge(category)}
</div>
</div>
<Link
to={`/parks/${parkSlug}`}
className="text-sm text-muted-foreground hover:underline block truncate"
>
<MapPin className="w-3 h-3 inline mr-1" />
{parkName}
</Link>
</div>
{credit.first_ride_date && (
<div className="text-xs text-muted-foreground">
<Calendar className="w-3 h-3 inline mr-1" />
{format(parseDateForDisplay(credit.first_ride_date), 'MMM d, yyyy')}
</div>
)}
<div className="flex items-center justify-between pt-2 border-t">
{isEditing ? (
<div className="flex items-center gap-2 flex-1">
<Input
type="number"
value={editCount}
onChange={(e) => setEditCount(parseInt(e.target.value) || 1)}
className="w-20"
min="1"
/>
<Button
size="sm"
variant="ghost"
onClick={handleUpdateCount}
disabled={updating}
>
<Check className="w-4 h-4" />
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => {
setIsEditing(false);
setEditCount(credit.ride_count);
}}
>
<X className="w-4 h-4" />
</Button>
</div>
) : (
<>
<div className="text-sm">
<span className="font-bold text-lg">{credit.ride_count}</span>
<span className="text-muted-foreground ml-1">
{credit.ride_count === 1 ? 'ride' : 'rides'}
</span>
</div>
<div className="flex gap-1">
<Button
size="sm"
variant="ghost"
onClick={handleQuickIncrement}
>
<Plus className="w-4 h-4" />
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setIsEditing(true)}
>
<Edit className="w-4 h-4" />
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setShowDeleteDialog(true)}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</>
)}
</div>
</div>
</CardContent>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Ride Credit?</AlertDialogTitle>
<AlertDialogDescription>
This will remove {rideName} from your ride credits. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={onDelete}>Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
);
}

View File

@@ -0,0 +1,574 @@
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { MultiSelectCombobox } from '@/components/ui/multi-select-combobox';
import { RideCreditFilters as FilterTypes } from '@/types/ride-credits';
import { UserRideCredit } from '@/types/database';
import { X, ChevronDown, MapPin, Building2, Factory, Calendar, Star, MessageSquare, Image } from 'lucide-react';
import { useEffect, useMemo } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
interface RideCreditFiltersProps {
filters: FilterTypes;
onFilterChange: (key: keyof FilterTypes, value: any) => void;
onClearFilters: () => void;
credits: UserRideCredit[];
activeFilterCount: number;
resultCount: number;
totalCount: number;
compact?: boolean;
}
export function RideCreditFilters({
filters,
onFilterChange,
onClearFilters,
credits,
activeFilterCount,
resultCount,
totalCount,
compact = false,
}: RideCreditFiltersProps) {
const spacingClass = compact ? 'space-y-3' : 'space-y-4';
const sectionSpacing = compact ? 'space-y-2' : 'space-y-3';
const paddingClass = compact ? 'p-4' : 'pt-6';
// Extract unique values from credits for filter options
const filterOptions = useMemo(() => {
const countries = new Set<string>();
const states = new Set<string>();
const cities = new Set<string>();
const parks = new Map<string, string>();
const manufacturers = new Map<string, string>();
const coasterTypes = new Set<string>();
const seatingTypes = new Set<string>();
const intensityLevels = new Set<string>();
const trackMaterials = new Set<string>();
credits.forEach(credit => {
const location = credit.rides?.parks?.locations;
if (location?.country) countries.add(location.country);
if (location?.state_province) states.add(location.state_province);
if (location?.city) cities.add(location.city);
if (credit.rides?.parks?.id && credit.rides?.parks?.name) {
parks.set(credit.rides.parks.id, credit.rides.parks.name);
}
if (credit.rides?.manufacturer?.id && credit.rides?.manufacturer?.name) {
manufacturers.set(credit.rides.manufacturer.id, credit.rides.manufacturer.name);
}
if (credit.rides?.coaster_type) {
coasterTypes.add(credit.rides.coaster_type);
}
if (credit.rides?.seating_type) {
seatingTypes.add(credit.rides.seating_type);
}
if (credit.rides?.intensity_level) {
intensityLevels.add(credit.rides.intensity_level);
}
if (credit.rides?.track_material) {
trackMaterials.add(credit.rides.track_material);
}
});
return {
countries: Array.from(countries).sort(),
states: Array.from(states).sort(),
cities: Array.from(cities).sort(),
parks: Array.from(parks.entries()).map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name)),
manufacturers: Array.from(manufacturers.entries()).map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name)),
coasterTypes: Array.from(coasterTypes).sort(),
seatingTypes: Array.from(seatingTypes).sort(),
intensityLevels: Array.from(intensityLevels).sort(),
trackMaterials: Array.from(trackMaterials).sort(),
};
}, [credits]);
const searchOptions = useMemo(() => {
const rides = new Map<string, { name: string, park: string }>();
const parks = new Map<string, string>();
const manufacturers = new Map<string, string>();
credits.forEach(credit => {
// Rides with their park context
if (credit.rides?.id && credit.rides?.name) {
rides.set(credit.rides.id, {
name: credit.rides.name,
park: credit.rides.parks?.name || 'Unknown Park'
});
}
// Parks
if (credit.rides?.parks?.id && credit.rides?.parks?.name) {
parks.set(credit.rides.parks.id, credit.rides.parks.name);
}
// Manufacturers
if (credit.rides?.manufacturer?.id && credit.rides?.manufacturer?.name) {
manufacturers.set(credit.rides.manufacturer.id, credit.rides.manufacturer.name);
}
});
// Combine into single options array with type prefixes
return [
...Array.from(rides.entries()).map(([id, data]) => ({
label: `🎢 ${data.name} (at ${data.park})`,
value: `ride:${id}`,
})),
...Array.from(parks.entries()).map(([id, name]) => ({
label: `🏰 ${name}`,
value: `park:${id}`,
})),
...Array.from(manufacturers.entries()).map(([id, name]) => ({
label: `🏭 ${name}`,
value: `manufacturer:${id}`,
}))
].sort((a, b) => a.label.localeCompare(b.label));
}, [credits]);
const maxRideCount = useMemo(() => {
return Math.max(...credits.map(c => c.ride_count), 1);
}, [credits]);
const categoryOptions = [
{ value: 'roller_coaster', label: '🎢 Coasters', icon: '🎢' },
{ value: 'flat_ride', label: '🎪 Flat Rides', icon: '🎪' },
{ value: 'water_ride', label: '🌊 Water Rides', icon: '🌊' },
{ value: 'dark_ride', label: '🌑 Dark Rides', icon: '🌑' },
{ value: 'transport_ride', label: '🚂 Transport', icon: '🚂' },
];
const toggleCategory = (category: string) => {
const current = filters.categories || [];
const updated = current.includes(category)
? current.filter(c => c !== category)
: [...current, category];
onFilterChange('categories', updated.length > 0 ? updated : undefined);
};
const toggleArrayFilter = (key: keyof FilterTypes, value: string) => {
const current = (filters[key] as string[]) || [];
const updated = current.includes(value)
? current.filter(v => v !== value)
: [...current, value];
onFilterChange(key, updated.length > 0 ? updated : undefined);
};
const removeFilter = (key: keyof FilterTypes, value?: string) => {
if (value && Array.isArray(filters[key])) {
const updated = (filters[key] as string[]).filter(v => v !== value);
onFilterChange(key, updated.length > 0 ? updated : undefined);
} else {
onFilterChange(key, undefined);
}
};
return (
<div className={compact ? 'p-4' : ''}>
<div className={spacingClass}>
{/* Quick Search - Multi-select Combobox */}
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Quick Search</Label>
<MultiSelectCombobox
options={searchOptions}
value={filters.selectedSearchItems || []}
onValueChange={(values) =>
onFilterChange('selectedSearchItems', values.length > 0 ? values : undefined)
}
placeholder="Search for specific rides, parks, or manufacturers..."
searchPlaceholder="Type to search..."
emptyText="No matches found"
maxDisplay={3}
className={compact ? "h-9 text-sm" : ""}
/>
</div>
{/* Quick Category Chips */}
<div className="flex flex-wrap gap-2">
{categoryOptions.map(cat => (
<Badge
key={cat.value}
variant={(filters.categories || []).includes(cat.value) ? 'default' : 'outline'}
className="cursor-pointer hover:bg-accent transition-colors px-3 py-1.5"
onClick={() => toggleCategory(cat.value)}
>
{cat.label}
</Badge>
))}
</div>
{/* Collapsible Filter Sections */}
<div className={sectionSpacing}>
{/* Geographic Filters */}
<Collapsible>
<CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
<div className="flex items-center gap-2">
<MapPin className="w-4 h-4" />
<span className="font-medium">Location Filters</span>
{((filters.countries?.length || 0) + (filters.statesProvinces?.length || 0) + (filters.cities?.length || 0)) > 0 && (
<Badge variant="secondary" className="ml-2">
{(filters.countries?.length || 0) + (filters.statesProvinces?.length || 0) + (filters.cities?.length || 0)}
</Badge>
)}
</div>
<ChevronDown className="w-4 h-4" />
</CollapsibleTrigger>
<CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
{filterOptions.countries.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Countries</Label>
<MultiSelectCombobox
options={filterOptions.countries.map(c => ({ label: c, value: c }))}
value={filters.countries || []}
onValueChange={(values) =>
onFilterChange('countries', values.length > 0 ? values : undefined)
}
placeholder="Select countries..."
searchPlaceholder="Search countries..."
emptyText="No countries found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
{filterOptions.states.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">States/Provinces</Label>
<MultiSelectCombobox
options={filterOptions.states.map(s => ({ label: s, value: s }))}
value={filters.statesProvinces || []}
onValueChange={(values) =>
onFilterChange('statesProvinces', values.length > 0 ? values : undefined)
}
placeholder="Select states/provinces..."
searchPlaceholder="Search states/provinces..."
emptyText="No states/provinces found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
</CollapsibleContent>
</Collapsible>
{/* Park Filters */}
<Collapsible>
<CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
<div className="flex items-center gap-2">
<Building2 className="w-4 h-4" />
<span className="font-medium">Park Filters</span>
{(filters.parks?.length || 0) > 0 && (
<Badge variant="secondary" className="ml-2">{filters.parks?.length}</Badge>
)}
</div>
<ChevronDown className="w-4 h-4" />
</CollapsibleTrigger>
<CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
{filterOptions.parks.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Specific Parks</Label>
<MultiSelectCombobox
options={filterOptions.parks.map(p => ({ label: p.name, value: p.id }))}
value={filters.parks || []}
onValueChange={(values) =>
onFilterChange('parks', values.length > 0 ? values : undefined)
}
placeholder="Select parks..."
searchPlaceholder="Search parks..."
emptyText="No parks found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
</CollapsibleContent>
</Collapsible>
{/* Ride Detail Filters */}
<Collapsible>
<CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
<div className="flex items-center gap-2">
<Factory className="w-4 h-4" />
<span className="font-medium">Ride Details</span>
{(filters.manufacturers?.length || 0) > 0 && (
<Badge variant="secondary" className="ml-2">{filters.manufacturers?.length}</Badge>
)}
</div>
<ChevronDown className="w-4 h-4" />
</CollapsibleTrigger>
<CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
{filterOptions.manufacturers.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Manufacturers</Label>
<MultiSelectCombobox
options={filterOptions.manufacturers.map(m => ({ label: m.name, value: m.id }))}
value={filters.manufacturers || []}
onValueChange={(values) =>
onFilterChange('manufacturers', values.length > 0 ? values : undefined)
}
placeholder="Select manufacturers..."
searchPlaceholder="Search manufacturers..."
emptyText="No manufacturers found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
{filterOptions.coasterTypes.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Coaster Type</Label>
<MultiSelectCombobox
options={filterOptions.coasterTypes.map(type => ({
label: type.charAt(0).toUpperCase() + type.slice(1),
value: type
}))}
value={filters.coasterTypes || []}
onValueChange={(values) =>
onFilterChange('coasterTypes', values.length > 0 ? values : undefined)
}
placeholder="Select coaster types..."
searchPlaceholder="Search types..."
emptyText="No coaster types found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
{filterOptions.seatingTypes.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Seating Type</Label>
<MultiSelectCombobox
options={filterOptions.seatingTypes.map(type => ({
label: type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()),
value: type
}))}
value={filters.seatingTypes || []}
onValueChange={(values) =>
onFilterChange('seatingTypes', values.length > 0 ? values : undefined)
}
placeholder="Select seating types..."
searchPlaceholder="Search types..."
emptyText="No seating types found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
{filterOptions.intensityLevels.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Intensity Level</Label>
<MultiSelectCombobox
options={filterOptions.intensityLevels.map(level => ({
label: level.charAt(0).toUpperCase() + level.slice(1),
value: level
}))}
value={filters.intensityLevels || []}
onValueChange={(values) =>
onFilterChange('intensityLevels', values.length > 0 ? values : undefined)
}
placeholder="Select intensity levels..."
searchPlaceholder="Search intensity..."
emptyText="No intensity levels found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
{filterOptions.trackMaterials.length > 0 && (
<div className={sectionSpacing}>
<Label className="text-sm font-medium">Track Material</Label>
<MultiSelectCombobox
options={filterOptions.trackMaterials.map(tm => ({
label: tm.charAt(0).toUpperCase() + tm.slice(1),
value: tm
}))}
value={filters.trackMaterial || []}
onValueChange={(values) =>
onFilterChange('trackMaterial', values.length > 0 ? values : undefined)
}
placeholder="Select track materials..."
searchPlaceholder="Search materials..."
emptyText="No track materials found"
className={compact ? "h-9 text-sm" : ""}
/>
</div>
)}
<div className="space-y-2">
<Label>Inversions</Label>
<div className="flex items-center gap-2">
<Checkbox
checked={filters.hasInversions === true}
onCheckedChange={(checked) => onFilterChange('hasInversions', checked ? true : undefined)}
/>
<span className="text-sm">Has inversions</span>
</div>
</div>
</CollapsibleContent>
</Collapsible>
{/* Statistics Filters */}
<Collapsible>
<CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
<div className="flex items-center gap-2">
<Calendar className="w-4 h-4" />
<span className="font-medium">Statistics</span>
{((filters.minRideCount !== undefined) || (filters.minSpeed !== undefined) || (filters.minHeight !== undefined)) && (
<Badge variant="secondary" className="ml-2">Active</Badge>
)}
</div>
<ChevronDown className="w-4 h-4" />
</CollapsibleTrigger>
<CollapsibleContent className="p-4 space-y-4 bg-card border rounded-lg mt-1">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>Ride Count</Label>
<span className="text-sm text-muted-foreground">
{filters.minRideCount || 1} - {filters.maxRideCount || maxRideCount}
</span>
</div>
<Slider
value={[filters.minRideCount || 1, filters.maxRideCount || maxRideCount]}
min={1}
max={maxRideCount}
step={1}
onValueChange={([min, max]) => {
onFilterChange('minRideCount', min > 1 ? min : undefined);
onFilterChange('maxRideCount', max < maxRideCount ? max : undefined);
}}
className="w-full"
/>
</div>
</CollapsibleContent>
</Collapsible>
{/* Experience Filters */}
<Collapsible>
<CollapsibleTrigger className="flex items-center justify-between w-full p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
<div className="flex items-center gap-2">
<Star className="w-4 h-4" />
<span className="font-medium">My Experience</span>
{(filters.hasNotes !== undefined || filters.hasPhotos !== undefined || filters.hasRating !== undefined) && (
<Badge variant="secondary" className="ml-2">Active</Badge>
)}
</div>
<ChevronDown className="w-4 h-4" />
</CollapsibleTrigger>
<CollapsibleContent className="p-4 space-y-3 bg-card border rounded-lg mt-1">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<Checkbox
checked={filters.hasNotes === true}
onCheckedChange={(checked) => onFilterChange('hasNotes', checked ? true : undefined)}
/>
<MessageSquare className="w-4 h-4" />
<span className="text-sm">Has notes</span>
</div>
<div className="flex items-center gap-2">
<Checkbox
checked={filters.hasPhotos === true}
onCheckedChange={(checked) => onFilterChange('hasPhotos', checked ? true : undefined)}
/>
<Image className="w-4 h-4" />
<span className="text-sm">Has photos</span>
</div>
</div>
<div className="space-y-2">
<Label>Personal Rating</Label>
<div className="flex items-center gap-2">
<Checkbox
checked={filters.hasRating === true}
onCheckedChange={(checked) => onFilterChange('hasRating', checked ? true : undefined)}
/>
<span className="text-sm">Has rating</span>
</div>
{filters.hasRating && (
<Slider
value={[filters.minUserRating || 1]}
min={1}
max={5}
step={1}
onValueChange={([min]) => onFilterChange('minUserRating', min > 1 ? min : undefined)}
className="w-full"
/>
)}
</div>
</CollapsibleContent>
</Collapsible>
</div>
{/* Active Filters Display */}
{activeFilterCount > 0 && (
<div className={sectionSpacing}>
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
Showing <strong>{resultCount}</strong> of <strong>{totalCount}</strong> credits
{activeFilterCount > 0 && ` (${activeFilterCount} ${activeFilterCount === 1 ? 'filter' : 'filters'} active)`}
</span>
<Button variant="ghost" size="sm" onClick={onClearFilters}>
Clear All
</Button>
</div>
<div className="flex flex-wrap gap-2">
{filters.selectedSearchItems?.map(item => {
const option = searchOptions.find(opt => opt.value === item);
return option ? (
<Badge key={item} variant="secondary" className="gap-1">
{option.label}
<X
className="w-3 h-3 cursor-pointer"
onClick={() => {
const updated = filters.selectedSearchItems!.filter(i => i !== item);
onFilterChange('selectedSearchItems', updated.length > 0 ? updated : undefined);
}}
/>
</Badge>
) : null;
})}
{filters.categories?.map(cat => (
<Badge key={cat} variant="secondary" className="gap-1">
{categoryOptions.find(c => c.value === cat)?.icon} {cat}
<X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('categories', cat)} />
</Badge>
))}
{filters.countries?.map(country => (
<Badge key={country} variant="secondary" className="gap-1">
📍 {country}
<X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('countries', country)} />
</Badge>
))}
{filters.manufacturers?.map(mfrId => {
const mfr = filterOptions.manufacturers.find(m => m.id === mfrId);
return mfr && (
<Badge key={mfrId} variant="secondary" className="gap-1">
🏭 {mfr.name}
<X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('manufacturers', mfrId)} />
</Badge>
);
})}
{filters.minRideCount && filters.minRideCount > 1 && (
<Badge variant="secondary" className="gap-1">
{filters.minRideCount}+ rides
<X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('minRideCount')} />
</Badge>
)}
{filters.hasInversions && (
<Badge variant="secondary" className="gap-1">
Has inversions
<X className="w-3 h-3 cursor-pointer" onClick={() => removeFilter('hasInversions')} />
</Badge>
)}
</div>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,539 @@
import { useState, useEffect, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, LayoutGrid, List, GripVertical } from 'lucide-react';
import { supabase } from '@/lib/supabaseClient';
import { toast } from 'sonner';
import { handleError } from '@/lib/errorHandler';
import { AddRideCreditDialog } from './AddRideCreditDialog';
import { RideCreditCard } from './RideCreditCard';
import { SortableRideCreditCard } from './SortableRideCreditCard';
import { RideCreditFilters } from './RideCreditFilters';
import { UserRideCredit } from '@/types/database';
import { useRideCreditFilters } from '@/hooks/useRideCreditFilters';
import { useIsMobile } from '@/hooks/use-mobile';
import {
DndContext,
DragEndEvent,
closestCenter,
PointerSensor,
useSensor,
useSensors,
} from '@dnd-kit/core';
import {
SortableContext,
verticalListSortingStrategy,
arrayMove,
} from '@dnd-kit/sortable';
interface RideCreditsManagerProps {
userId: string;
}
export function RideCreditsManager({ userId }: RideCreditsManagerProps) {
const [credits, setCredits] = useState<UserRideCredit[]>([]);
const [loading, setLoading] = useState(true);
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [sortBy, setSortBy] = useState<'date' | 'count' | 'name' | 'custom'>('custom');
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [isEditMode, setIsEditMode] = useState(false);
const isMobile = useIsMobile();
// Use the filter hook
const {
filters,
updateFilter,
clearFilters,
filteredCredits,
activeFilterCount,
} = useRideCreditFilters(credits);
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
})
);
useEffect(() => {
fetchCredits();
}, [userId, sortBy]);
const fetchCredits = async () => {
try {
setLoading(true);
// Build main query with enhanced data
let query = supabase
.from('user_ride_credits')
.select(`
*,
rides:ride_id (
id,
name,
slug,
category,
status,
coaster_type,
seating_type,
intensity_level,
max_speed_kmh,
max_height_meters,
length_meters,
inversions,
card_image_url,
average_rating,
review_count,
parks:park_id (
id,
name,
slug,
park_type,
locations:location_id (
country,
state_province,
city
)
),
manufacturer:companies!rides_manufacturer_id_fkey (
id,
name
),
designer:companies!rides_designer_id_fkey (
id,
name
)
)
`)
.eq('user_id', userId);
// Apply sorting - default to sort_order when available
if (sortBy === 'date') {
query = query.order('first_ride_date', { ascending: false, nullsFirst: false });
} else if (sortBy === 'count') {
query = query.order('ride_count', { ascending: false });
} else if (sortBy === 'name') {
query = query.order('created_at', { ascending: false });
} else {
query = query.order('sort_order', { ascending: true, nullsFirst: false });
}
const { data, error } = await query;
if (error) throw error;
let processedData = data || [];
// Sort by name client-side if needed
if (sortBy === 'name') {
processedData.sort((a, b) => {
const nameA = a.rides?.name || '';
const nameB = b.rides?.name || '';
return nameA.localeCompare(nameB);
});
}
setCredits(processedData as UserRideCredit[]);
} catch (error: unknown) {
handleError(error, {
action: 'Fetch Ride Credits',
userId,
metadata: { sortBy }
});
} finally {
setLoading(false);
}
};
const handleCreditAdded = async (newCreditId: string) => {
try {
// Fetch just the new credit with all necessary joins
const { data, error } = await supabase
.from('user_ride_credits')
.select(`
*,
rides:ride_id (
id,
name,
slug,
category,
status,
coaster_type,
seating_type,
intensity_level,
max_speed_kmh,
max_height_meters,
length_meters,
inversions,
card_image_url,
parks:park_id (
id,
name,
slug,
park_type,
locations:location_id (
country,
state_province,
city
)
),
manufacturer:manufacturer_id (
id,
name
),
designer:designer_id (
id,
name
)
)
`)
.eq('id', newCreditId)
.single();
if (error) throw error;
// Type assertion for complex joined data
const newCredit = data as unknown as UserRideCredit;
// Add to existing array
setCredits(prev => [...prev, newCredit]);
setIsAddDialogOpen(false);
} catch (error: unknown) {
handleError(error, {
action: 'Add Ride Credit',
userId,
metadata: { creditId: newCreditId }
});
}
};
const handleCreditUpdated = (creditId: string, updates: Partial<UserRideCredit>) => {
// Optimistic update - update only the affected credit
setCredits(prev => prev.map(c =>
c.id === creditId ? { ...c, ...updates } : c
));
};
const handleCreditDeleted = async (creditId: string) => {
// Store for rollback
const deletedCredit = credits.find(c => c.id === creditId);
// Optimistic removal
setCredits(prev => prev.filter(c => c.id !== creditId));
try {
const { error } = await supabase
.from('user_ride_credits')
.delete()
.eq('id', creditId)
.eq('user_id', userId);
if (error) throw error;
toast.success('Ride credit removed');
} catch (error: unknown) {
handleError(error, {
action: 'Delete Ride Credit',
userId,
metadata: { creditId }
});
// Rollback on error
if (deletedCredit) {
setCredits(prev => [...prev, deletedCredit]);
}
}
};
const handleReorder = async (creditId: string, newPosition: number) => {
try {
const { error } = await supabase.rpc('reorder_ride_credit', {
p_credit_id: creditId,
p_new_position: newPosition
});
if (error) throw error;
// No refetch - optimistic update is already applied
} catch (error: unknown) {
handleError(error, {
action: 'Reorder Ride Credit',
userId,
metadata: { creditId, newPosition }
});
throw error;
}
};
const handleDragEnd = async (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const oldIndex = credits.findIndex(c => c.id === String(active.id));
const newIndex = credits.findIndex(c => c.id === String(over.id));
if (oldIndex === -1 || newIndex === -1) return;
// Store old order for rollback
const oldCredits = credits;
// Optimistic update
const newCredits = arrayMove(credits, oldIndex, newIndex);
setCredits(newCredits);
try {
await handleReorder(String(active.id), newIndex + 1);
toast.success('Order updated');
} catch (error: unknown) {
handleError(error, {
action: 'Drag Reorder Ride Credit',
userId,
metadata: {
activeId: String(active.id),
overId: String(over.id),
oldIndex,
newIndex
}
});
// Rollback to old order
setCredits(oldCredits);
}
};
// Memoize statistics to only recalculate when credits change
const stats = useMemo(() => ({
totalRides: credits.reduce((sum, c) => sum + c.ride_count, 0),
uniqueCredits: credits.length,
parksVisited: new Set(credits.map(c => c.rides?.parks?.id).filter(Boolean)).size,
coasters: credits.filter(c => c.rides?.category === 'roller_coaster').length
}), [credits]);
// Use filtered credits for display
const displayCredits = filteredCredits;
if (loading) {
return (
<div className="space-y-4">
{Array.from({ length: 6 }, (_, i) => (
<Card key={i} className="animate-pulse">
<CardContent className="p-6">
<div className="h-32 bg-muted rounded"></div>
</CardContent>
</Card>
))}
</div>
);
}
return (
<div className="space-y-6">
{/* Statistics */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.totalRides}</div>
<div className="text-sm text-muted-foreground">Total Rides</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.uniqueCredits}</div>
<div className="text-sm text-muted-foreground">Unique Credits</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.parksVisited}</div>
<div className="text-sm text-muted-foreground">Parks Visited</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.coasters}</div>
<div className="text-sm text-muted-foreground">Coasters</div>
</CardContent>
</Card>
</div>
{/* Main Content Area with Sidebar */}
<div className="flex gap-6 items-start">
{/* Left Sidebar - Desktop Only */}
{!isMobile && (
<aside className="w-80 flex-shrink-0">
<div className="sticky top-4">
<div className="rounded-lg border bg-card">
<RideCreditFilters
filters={filters}
onFilterChange={updateFilter}
onClearFilters={clearFilters}
credits={credits}
activeFilterCount={activeFilterCount}
resultCount={displayCredits.length}
totalCount={credits.length}
compact={true}
/>
</div>
</div>
</aside>
)}
{/* Right Content Area */}
<div className="flex-1 min-w-0 space-y-4">
{/* Mobile Filters - Collapsible Card */}
{isMobile && (
<Card>
<CardContent className="pt-6">
<RideCreditFilters
filters={filters}
onFilterChange={updateFilter}
onClearFilters={clearFilters}
credits={credits}
activeFilterCount={activeFilterCount}
resultCount={displayCredits.length}
totalCount={credits.length}
compact={false}
/>
</CardContent>
</Card>
)}
{/* Controls */}
<div className="flex flex-wrap gap-4 items-center justify-between">
<div className="flex gap-2">
<Button onClick={() => setIsAddDialogOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
Add Credit
</Button>
<Button
variant={isEditMode ? 'default' : 'outline'}
onClick={() => setIsEditMode(!isEditMode)}
>
<GripVertical className="w-4 h-4 mr-2" />
{isEditMode ? 'Done Editing' : 'Edit Order'}
</Button>
</div>
<div className="flex gap-2">
<Select value={sortBy} onValueChange={(value) => setSortBy(value as typeof sortBy)}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Sort by" />
</SelectTrigger>
<SelectContent>
<SelectItem value="custom">Custom Order</SelectItem>
<SelectItem value="date">Most Recent</SelectItem>
<SelectItem value="count">Most Ridden</SelectItem>
<SelectItem value="name">Ride Name</SelectItem>
</SelectContent>
</Select>
<div className="flex border rounded-md">
<Button
variant={viewMode === 'grid' ? 'default' : 'ghost'}
size="icon"
onClick={() => setViewMode('grid')}
>
<LayoutGrid className="w-4 h-4" />
</Button>
<Button
variant={viewMode === 'list' ? 'default' : 'ghost'}
size="icon"
onClick={() => setViewMode('list')}
>
<List className="w-4 h-4" />
</Button>
</div>
</div>
</div>
{/* Credits Display */}
{displayCredits.length === 0 ? (
<Card>
<CardContent className="py-12">
<div className="text-center">
{credits.length === 0 ? (
<>
<h3 className="text-xl font-semibold mb-2">No Ride Credits Yet</h3>
<p className="text-muted-foreground mb-4">
Start tracking your ride experiences
</p>
<Button onClick={() => setIsAddDialogOpen(true)}>
<Plus className="w-4 h-4 mr-2" />
Add Your First Credit
</Button>
</>
) : (
<>
<h3 className="text-xl font-semibold mb-2">No Results Found</h3>
<p className="text-muted-foreground mb-4">
Try adjusting your filters
</p>
<Button onClick={clearFilters} variant="outline">
Clear Filters
</Button>
</>
)}
</div>
</CardContent>
</Card>
) : isEditMode ? (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={displayCredits.map(c => c.id)}
strategy={verticalListSortingStrategy}
>
<div className={viewMode === 'grid'
? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4'
: 'space-y-4'
}>
{displayCredits.map((credit, index) => (
<SortableRideCreditCard
key={credit.id}
credit={credit}
position={index + 1}
maxPosition={displayCredits.length}
viewMode={viewMode}
onUpdate={handleCreditUpdated}
onDelete={() => handleCreditDeleted(credit.id)}
onReorder={handleReorder}
/>
))}
</div>
</SortableContext>
</DndContext>
) : (
<div className={viewMode === 'grid'
? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4'
: 'space-y-4'
}>
{displayCredits.map((credit, index) => (
<RideCreditCard
key={credit.id}
credit={credit}
position={index + 1}
viewMode={viewMode}
onUpdate={handleCreditUpdated}
onDelete={() => handleCreditDeleted(credit.id)}
/>
))}
</div>
)}
</div>
</div>
{/* Add Credit Dialog */}
<AddRideCreditDialog
userId={userId}
open={isAddDialogOpen}
onOpenChange={setIsAddDialogOpen}
onSuccess={handleCreditAdded}
/>
</div>
);
}

View File

@@ -0,0 +1,67 @@
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical } from 'lucide-react';
import { RideCreditCard } from './RideCreditCard';
import { UserRideCredit } from '@/types/database';
interface SortableRideCreditCardProps {
credit: UserRideCredit;
position: number;
maxPosition: number;
viewMode: 'grid' | 'list';
onUpdate: (creditId: string, updates: Partial<UserRideCredit>) => void;
onDelete: () => void;
onReorder: (creditId: string, newPosition: number) => Promise<void>;
}
export function SortableRideCreditCard({
credit,
position,
maxPosition,
viewMode,
onUpdate,
onDelete,
onReorder,
}: SortableRideCreditCardProps) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: credit.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<div ref={setNodeRef} style={style} className="flex gap-2 items-start">
{/* Drag handle - external to card */}
<div
{...attributes}
{...listeners}
className="flex-shrink-0 cursor-grab active:cursor-grabbing p-2 rounded-md bg-background border hover:bg-accent transition-colors self-stretch flex items-center"
>
<GripVertical className="w-4 h-4 text-muted-foreground" />
</div>
{/* Card takes remaining space */}
<div className="flex-1 min-w-0">
<RideCreditCard
credit={credit}
position={position}
maxPosition={maxPosition}
viewMode={viewMode}
isEditMode={true}
onUpdate={onUpdate}
onDelete={onDelete}
onReorder={onReorder}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,103 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { UserX } from 'lucide-react';
import { supabase } from '@/lib/supabaseClient';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
import { getErrorMessage } from '@/lib/errorHandler';
interface UserBlockButtonProps {
targetUserId: string;
targetUsername: string;
variant?: 'default' | 'outline' | 'ghost';
size?: 'default' | 'sm' | 'lg';
}
export function UserBlockButton({ targetUserId, targetUsername, variant = 'outline', size = 'sm' }: UserBlockButtonProps) {
const { user } = useAuth();
const { toast } = useToast();
const [reason, setReason] = useState('');
const [loading, setLoading] = useState(false);
const handleBlock = async () => {
if (!user) return;
setLoading(true);
try {
const { error } = await supabase
.from('user_blocks')
.insert({
blocker_id: user.id,
blocked_id: targetUserId,
reason: reason.trim() || null
});
if (error) throw error;
toast({
title: 'User blocked',
description: `You have blocked @${targetUsername}. They will no longer be able to interact with your content.`
});
setReason('');
} catch (error: unknown) {
toast({
title: 'Error',
description: getErrorMessage(error),
variant: 'destructive'
});
} finally {
setLoading(false);
}
};
// Don't show block button if user is not logged in or trying to block themselves
if (!user || user.id === targetUserId) {
return null;
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant={variant} size={size}>
<UserX className="w-4 h-4 mr-2" />
Block User
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Block @{targetUsername}</AlertDialogTitle>
<AlertDialogDescription>
This user will no longer be able to see your content or interact with you.
You can unblock them at any time from your privacy settings.
</AlertDialogDescription>
</AlertDialogHeader>
<div className="space-y-2">
<Label htmlFor="reason">Reason (optional)</Label>
<Input
id="reason"
placeholder="Why are you blocking this user?"
value={reason}
onChange={(e) => setReason(e.target.value)}
maxLength={200}
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleBlock}
disabled={loading}
className="bg-destructive hover:bg-destructive/90"
>
{loading ? 'Blocking...' : 'Block User'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}

View File

@@ -0,0 +1,270 @@
import { useState } from 'react';
import { useUserReviews } from '@/hooks/reviews/useUserReviews';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Star, Calendar, MapPin, Edit, Trash2, ThumbsUp } from 'lucide-react';
import { supabase } from '@/lib/supabaseClient';
import { StarRating } from '@/components/reviews/StarRating';
import { Button } from '@/components/ui/button';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import { getErrorMessage } from '@/lib/errorHandler';
interface ReviewWithEntity {
id: string;
rating: number;
title: string | null;
content: string | null;
visit_date: string | null;
wait_time_minutes: number | null;
helpful_votes: number;
moderation_status: string;
created_at: string;
parks?: {
id: string;
name: string;
slug: string;
} | null;
rides?: {
id: string;
name: string;
slug: string;
parks?: {
name: string;
slug: string;
} | null;
} | null;
}
interface UserReviewsListProps {
userId: string;
reviewCount: number;
}
export function UserReviewsList({ userId, reviewCount }: UserReviewsListProps) {
const [filter, setFilter] = useState<'all' | 'parks' | 'rides'>('all');
const [sortBy, setSortBy] = useState<'date' | 'rating'>('date');
// Use cached user reviews hook
const { data: reviews = [], isLoading: loading } = useUserReviews(userId, filter, sortBy);
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'approved':
return <Badge variant="default">Approved</Badge>;
case 'pending':
return <Badge variant="secondary">Pending Review</Badge>;
case 'rejected':
return <Badge variant="destructive">Rejected</Badge>;
default:
return null;
}
};
if (loading) {
return (
<div className="space-y-4">
{Array.from({ length: 3 }, (_, i) => (
<Card key={i} className="animate-pulse">
<CardContent className="p-6">
<div className="space-y-3">
<div className="h-4 bg-muted rounded w-1/4"></div>
<div className="h-4 bg-muted rounded w-1/6"></div>
<div className="h-20 bg-muted rounded"></div>
</div>
</CardContent>
</Card>
))}
</div>
);
}
if (reviewCount === 0) {
return (
<Card>
<CardContent className="py-12">
<div className="text-center">
<Star className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
<h3 className="text-xl font-semibold mb-2">No Reviews Yet</h3>
<p className="text-muted-foreground mb-4">
Start sharing your park and ride experiences
</p>
<div className="flex gap-2 justify-center">
<Button asChild>
<Link to="/parks">Browse Parks</Link>
</Button>
<Button variant="outline" asChild>
<Link to="/rides">Browse Rides</Link>
</Button>
</div>
</div>
</CardContent>
</Card>
);
}
const stats = {
total: reviews.length,
parks: reviews.filter(r => r.parks).length,
rides: reviews.filter(r => r.rides).length,
avgRating: reviews.length > 0
? (reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length).toFixed(1)
: '0'
};
return (
<div className="space-y-6">
{/* Statistics */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.total}</div>
<div className="text-sm text-muted-foreground">Total Reviews</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.parks}</div>
<div className="text-sm text-muted-foreground">Park Reviews</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold">{stats.rides}</div>
<div className="text-sm text-muted-foreground">Ride Reviews</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-2xl font-bold flex items-center gap-1">
<Star className="w-5 h-5 fill-primary text-primary" />
{stats.avgRating}
</div>
<div className="text-sm text-muted-foreground">Avg Rating</div>
</CardContent>
</Card>
</div>
{/* Filters */}
<div className="flex gap-4">
<Select value={filter} onValueChange={(value) => setFilter(value as typeof filter)}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Filter by type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Reviews</SelectItem>
<SelectItem value="parks">Parks Only</SelectItem>
<SelectItem value="rides">Rides Only</SelectItem>
</SelectContent>
</Select>
<Select value={sortBy} onValueChange={(value) => setSortBy(value as typeof sortBy)}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Sort by" />
</SelectTrigger>
<SelectContent>
<SelectItem value="date">Most Recent</SelectItem>
<SelectItem value="rating">Highest Rated</SelectItem>
</SelectContent>
</Select>
</div>
{/* Reviews List */}
<div className="space-y-4">
{reviews.map((review) => {
const entityName = review.parks?.name || review.rides?.name || 'Unknown';
const entitySlug = review.parks?.slug || review.rides?.slug || '';
const entityType = review.parks ? 'park' : 'ride';
const entityPath = review.parks
? `/parks/${entitySlug}`
: review.rides
? `/parks/${review.rides.parks?.slug}/rides/${entitySlug}`
: '#';
return (
<Card key={review.id}>
<CardContent className="p-6">
<div className="space-y-3">
{/* Header */}
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<Link
to={entityPath}
className="font-semibold hover:underline"
>
{entityName}
</Link>
<Badge variant="outline">
{entityType === 'park' ? 'Park' : 'Ride'}
</Badge>
{getStatusBadge(review.moderation_status)}
</div>
{review.rides?.parks && (
<Link
to={`/parks/${review.rides.parks.slug}`}
className="text-sm text-muted-foreground hover:underline"
>
at {review.rides.parks.name}
</Link>
)}
</div>
<div className="flex items-center gap-1">
<StarRating rating={review.rating} size="sm" />
<span className="ml-1 text-sm font-medium">
{review.rating}
</span>
</div>
</div>
{/* Title */}
{review.title && (
<h4 className="font-medium">{review.title}</h4>
)}
{/* Content */}
{review.content && (
<p className="text-muted-foreground leading-relaxed">
{review.content}
</p>
)}
{/* Metadata */}
<div className="flex items-center gap-4 text-sm text-muted-foreground">
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3" />
{formatDate(review.created_at)}
</div>
{review.visit_date && (
<div className="flex items-center gap-1">
<MapPin className="w-3 h-3" />
Visited {formatDate(review.visit_date)}
</div>
)}
{review.wait_time_minutes && (
<span>Wait: {review.wait_time_minutes} min</span>
)}
<div className="flex items-center gap-1">
<ThumbsUp className="w-3 h-3" />
{review.helpful_votes} helpful
</div>
</div>
</div>
</CardContent>
</Card>
);
})}
</div>
</div>
);
}