wip
This commit is contained in:
32
apps/website/app/admin/AdminDashboardWrapper.tsx
Normal file
32
apps/website/app/admin/AdminDashboardWrapper.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { AdminDashboardTemplate } from '@/templates/AdminDashboardTemplate';
|
||||
import { AdminDashboardViewData } from '@/lib/view-data/AdminDashboardViewData';
|
||||
|
||||
interface AdminDashboardWrapperProps {
|
||||
initialViewData: AdminDashboardViewData;
|
||||
}
|
||||
|
||||
export function AdminDashboardWrapper({ initialViewData }: AdminDashboardWrapperProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// UI state (not business logic)
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
setLoading(true);
|
||||
router.refresh();
|
||||
// Reset loading after a short delay to show the spinner
|
||||
setTimeout(() => setLoading(false), 1000);
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<AdminDashboardTemplate
|
||||
viewData={initialViewData}
|
||||
onRefresh={handleRefresh}
|
||||
isLoading={loading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
122
apps/website/app/admin/users/AdminUsersWrapper.tsx
Normal file
122
apps/website/app/admin/users/AdminUsersWrapper.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { AdminUsersTemplate } from '@/templates/AdminUsersTemplate';
|
||||
import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData';
|
||||
import { updateUserStatus, deleteUser } from '@/app/admin/actions';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
|
||||
interface AdminUsersWrapperProps {
|
||||
initialViewData: AdminUsersViewData;
|
||||
}
|
||||
|
||||
export function AdminUsersWrapper({ initialViewData }: AdminUsersWrapperProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// UI state (not business logic)
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deletingUser, setDeletingUser] = useState<string | null>(null);
|
||||
|
||||
// Current filter values from URL
|
||||
const search = searchParams.get('search') || '';
|
||||
const roleFilter = searchParams.get('role') || '';
|
||||
const statusFilter = searchParams.get('status') || '';
|
||||
|
||||
// Callbacks that update URL (triggers RSC re-render)
|
||||
const handleSearch = useCallback((newSearch: string) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (newSearch) params.set('search', newSearch);
|
||||
else params.delete('search');
|
||||
params.delete('page'); // Reset to page 1
|
||||
router.push(`${routes.admin.users}?${params.toString()}`);
|
||||
}, [router, searchParams]);
|
||||
|
||||
const handleFilterRole = useCallback((role: string) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (role) params.set('role', role);
|
||||
else params.delete('role');
|
||||
params.delete('page');
|
||||
router.push(`${routes.admin.users}?${params.toString()}`);
|
||||
}, [router, searchParams]);
|
||||
|
||||
const handleFilterStatus = useCallback((status: string) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (status) params.set('status', status);
|
||||
else params.delete('status');
|
||||
params.delete('page');
|
||||
router.push(`${routes.admin.users}?${params.toString()}`);
|
||||
}, [router, searchParams]);
|
||||
|
||||
const handleClearFilters = useCallback(() => {
|
||||
router.push(routes.admin.users);
|
||||
}, [router]);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
router.refresh();
|
||||
}, [router]);
|
||||
|
||||
// Mutation callbacks (call Server Actions)
|
||||
const handleUpdateStatus = useCallback(async (userId: string, newStatus: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await updateUserStatus(userId, newStatus);
|
||||
|
||||
if (result.isErr()) {
|
||||
setError(result.getError());
|
||||
return;
|
||||
}
|
||||
|
||||
// Revalidate data
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update status');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
const handleDeleteUser = useCallback(async (userId: string) => {
|
||||
if (!confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setDeletingUser(userId);
|
||||
const result = await deleteUser(userId);
|
||||
|
||||
if (result.isErr()) {
|
||||
setError(result.getError());
|
||||
return;
|
||||
}
|
||||
|
||||
// Revalidate data
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete user');
|
||||
} finally {
|
||||
setDeletingUser(null);
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<AdminUsersTemplate
|
||||
viewData={initialViewData}
|
||||
onRefresh={handleRefresh}
|
||||
onSearch={handleSearch}
|
||||
onFilterRole={handleFilterRole}
|
||||
onFilterStatus={handleFilterStatus}
|
||||
onClearFilters={handleClearFilters}
|
||||
onUpdateStatus={handleUpdateStatus}
|
||||
onDeleteUser={handleDeleteUser}
|
||||
search={search}
|
||||
roleFilter={roleFilter}
|
||||
statusFilter={statusFilter}
|
||||
loading={loading}
|
||||
error={error}
|
||||
deletingUser={deletingUser}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,36 +1,50 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { DriversTemplate } from '@/templates/DriversTemplate';
|
||||
import { useDriverSearch } from '@/lib/hooks/useDriverSearch';
|
||||
import type { DriverLeaderboardViewModel } from '@/lib/view-data/DriverLeaderboardViewModel';
|
||||
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
|
||||
|
||||
interface DriversPageClientProps {
|
||||
data: DriverLeaderboardViewModel | null;
|
||||
pageDto: DriverLeaderboardViewModel | null;
|
||||
error?: string;
|
||||
empty?: {
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function DriversPageClient({ data }: DriversPageClientProps) {
|
||||
const router = useRouter();
|
||||
const drivers = data?.drivers || [];
|
||||
const { searchQuery, setSearchQuery, filteredDrivers } = useDriverSearch(drivers);
|
||||
/**
|
||||
* DriversPageClient
|
||||
*
|
||||
* Client component that:
|
||||
* 1. Passes ViewModel directly to Template
|
||||
*
|
||||
* No business logic, filtering, or sorting here.
|
||||
* All data transformation happens in the PageQuery and ViewModelBuilder.
|
||||
*/
|
||||
export function DriversPageClient({ pageDto, error, empty }: DriversPageClientProps) {
|
||||
// Handle error/empty states
|
||||
if (error) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-12 text-center">
|
||||
<div className="text-red-400 mb-4">Error loading drivers</div>
|
||||
<p className="text-gray-400">Please try again later</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleDriverClick = (driverId: string) => {
|
||||
router.push(`/drivers/${driverId}`);
|
||||
};
|
||||
if (!pageDto || pageDto.drivers.length === 0) {
|
||||
if (empty) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-12 text-center">
|
||||
<h2 className="text-xl font-semibold text-white mb-2">{empty.title}</h2>
|
||||
<p className="text-gray-400">{empty.description}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleViewLeaderboard = () => {
|
||||
router.push('/leaderboards/drivers');
|
||||
};
|
||||
|
||||
return (
|
||||
<DriversTemplate
|
||||
data={data}
|
||||
searchQuery={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
filteredDrivers={filteredDrivers}
|
||||
onDriverClick={handleDriverClick}
|
||||
onViewLeaderboard={handleViewLeaderboard}
|
||||
/>
|
||||
);
|
||||
}
|
||||
// Pass ViewModel directly to template
|
||||
return <DriversTemplate data={pageDto} />;
|
||||
}
|
||||
88
apps/website/app/drivers/[id]/DriverProfilePageClient.tsx
Normal file
88
apps/website/app/drivers/[id]/DriverProfilePageClient.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
|
||||
import type { DriverProfileViewModel } from '@/lib/view-models/DriverProfileViewModel';
|
||||
|
||||
interface DriverProfilePageClientProps {
|
||||
pageDto: DriverProfileViewModel | null;
|
||||
error?: string;
|
||||
empty?: {
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* DriverProfilePageClient
|
||||
*
|
||||
* Client component that:
|
||||
* 1. Handles UI state (tabs, friend requests)
|
||||
* 2. Passes ViewModel directly to Template
|
||||
*
|
||||
* No business logic or data transformation here.
|
||||
* All data transformation happens in the PageQuery and ViewModelBuilder.
|
||||
*/
|
||||
export function DriverProfilePageClient({ pageDto, error, empty }: DriverProfilePageClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// UI State (UI-only concerns)
|
||||
const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
|
||||
const [friendRequestSent, setFriendRequestSent] = useState(false);
|
||||
|
||||
// Event handlers (UI-only concerns)
|
||||
const handleAddFriend = () => {
|
||||
setFriendRequestSent(true);
|
||||
};
|
||||
|
||||
const handleBackClick = () => {
|
||||
router.push('/drivers');
|
||||
};
|
||||
|
||||
// Handle error/empty states
|
||||
if (error) {
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-12 text-center">
|
||||
<div className="text-red-400 mb-4">Error loading driver profile</div>
|
||||
<p className="text-gray-400">Please try again later</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!pageDto || !pageDto.currentDriver) {
|
||||
if (empty) {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4">
|
||||
<div className="text-center py-12">
|
||||
<h2 className="text-xl font-semibold text-white mb-2">{empty.title}</h2>
|
||||
<p className="text-gray-400">{empty.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Pass ViewModel directly to template
|
||||
return (
|
||||
<DriverProfileTemplate
|
||||
driverProfile={pageDto}
|
||||
allTeamMemberships={pageDto.teamMemberships.map(m => ({
|
||||
team: {
|
||||
id: m.teamId,
|
||||
name: m.teamName,
|
||||
},
|
||||
role: m.role,
|
||||
joinedAt: new Date(m.joinedAt),
|
||||
}))}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
onBackClick={handleBackClick}
|
||||
onAddFriend={handleAddFriend}
|
||||
friendRequestSent={friendRequestSent}
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
/>
|
||||
);
|
||||
}
|
||||
673
apps/website/app/leagues/LeaguesClient.tsx
Normal file
673
apps/website/app/leagues/LeaguesClient.tsx
Normal file
@@ -0,0 +1,673 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useRef, useCallback } from 'react';
|
||||
import {
|
||||
Trophy,
|
||||
Users,
|
||||
Globe,
|
||||
Award,
|
||||
Search,
|
||||
Plus,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Sparkles,
|
||||
Flag,
|
||||
Filter,
|
||||
Flame,
|
||||
Clock,
|
||||
Target,
|
||||
Timer,
|
||||
} from 'lucide-react';
|
||||
import LeagueCard from '@/components/leagues/LeagueCard';
|
||||
import { Button } from '@/ui/Button';
|
||||
import { Card } from '@/ui/Card';
|
||||
import { Input } from '@/ui/Input';
|
||||
import { Heading } from '@/ui/Heading';
|
||||
import { Container } from '@/ui/Container';
|
||||
import { Box } from '@/ui/Box';
|
||||
import { Stack } from '@/ui/Stack';
|
||||
import { Text } from '@/ui/Text';
|
||||
import { Grid } from '@/ui/Grid';
|
||||
import { GridItem } from '@/ui/GridItem';
|
||||
import { HeroSection } from '@/components/shared/HeroSection';
|
||||
import type { LeaguesViewData } from '@/lib/view-data/LeaguesViewData';
|
||||
import type { LeagueSummaryViewModel } from '@/lib/view-models/LeagueSummaryViewModel';
|
||||
|
||||
// ============================================================================
|
||||
// TYPES
|
||||
// ============================================================================
|
||||
|
||||
type CategoryId =
|
||||
| 'all'
|
||||
| 'driver'
|
||||
| 'team'
|
||||
| 'nations'
|
||||
| 'trophy'
|
||||
| 'new'
|
||||
| 'popular'
|
||||
| 'iracing'
|
||||
| 'acc'
|
||||
| 'f1'
|
||||
| 'endurance'
|
||||
| 'sprint'
|
||||
| 'openSlots';
|
||||
|
||||
interface Category {
|
||||
id: CategoryId;
|
||||
label: string;
|
||||
icon: React.ElementType;
|
||||
description: string;
|
||||
filter: (league: LeaguesViewData['leagues'][number]) => boolean;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
interface LeagueSliderProps {
|
||||
title: string;
|
||||
icon: React.ElementType;
|
||||
description: string;
|
||||
leagues: LeaguesViewData['leagues'];
|
||||
autoScroll?: boolean;
|
||||
iconColor?: string;
|
||||
scrollSpeedMultiplier?: number;
|
||||
scrollDirection?: 'left' | 'right';
|
||||
}
|
||||
|
||||
interface LeaguesTemplateProps {
|
||||
viewData: LeaguesViewData;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CATEGORIES
|
||||
// ============================================================================
|
||||
|
||||
const CATEGORIES: Category[] = [
|
||||
{
|
||||
id: 'all',
|
||||
label: 'All',
|
||||
icon: Globe,
|
||||
description: 'Browse all available leagues',
|
||||
filter: () => true,
|
||||
},
|
||||
{
|
||||
id: 'popular',
|
||||
label: 'Popular',
|
||||
icon: Flame,
|
||||
description: 'Most active leagues right now',
|
||||
filter: (league) => {
|
||||
const fillRate = (league.usedDriverSlots ?? 0) / (league.maxDrivers ?? 1);
|
||||
return fillRate > 0.7;
|
||||
},
|
||||
color: 'text-orange-400',
|
||||
},
|
||||
{
|
||||
id: 'new',
|
||||
label: 'New',
|
||||
icon: Sparkles,
|
||||
description: 'Fresh leagues looking for members',
|
||||
filter: (league) => {
|
||||
const oneWeekAgo = new Date();
|
||||
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
|
||||
return new Date(league.createdAt) > oneWeekAgo;
|
||||
},
|
||||
color: 'text-performance-green',
|
||||
},
|
||||
{
|
||||
id: 'openSlots',
|
||||
label: 'Open Slots',
|
||||
icon: Target,
|
||||
description: 'Leagues with available spots',
|
||||
filter: (league) => {
|
||||
// Check for team slots if it's a team league
|
||||
if (league.maxTeams && league.maxTeams > 0) {
|
||||
const usedTeams = league.usedTeamSlots ?? 0;
|
||||
return usedTeams < league.maxTeams;
|
||||
}
|
||||
// Otherwise check driver slots
|
||||
const used = league.usedDriverSlots ?? 0;
|
||||
const max = league.maxDrivers ?? 0;
|
||||
return max > 0 && used < max;
|
||||
},
|
||||
color: 'text-neon-aqua',
|
||||
},
|
||||
{
|
||||
id: 'driver',
|
||||
label: 'Driver',
|
||||
icon: Trophy,
|
||||
description: 'Compete as an individual',
|
||||
filter: (league) => league.scoring?.primaryChampionshipType === 'driver',
|
||||
},
|
||||
{
|
||||
id: 'team',
|
||||
label: 'Team',
|
||||
icon: Users,
|
||||
description: 'Race together as a team',
|
||||
filter: (league) => league.scoring?.primaryChampionshipType === 'team',
|
||||
},
|
||||
{
|
||||
id: 'nations',
|
||||
label: 'Nations',
|
||||
icon: Flag,
|
||||
description: 'Represent your country',
|
||||
filter: (league) => league.scoring?.primaryChampionshipType === 'nations',
|
||||
},
|
||||
{
|
||||
id: 'trophy',
|
||||
label: 'Trophy',
|
||||
icon: Award,
|
||||
description: 'Special championship events',
|
||||
filter: (league) => league.scoring?.primaryChampionshipType === 'trophy',
|
||||
},
|
||||
{
|
||||
id: 'endurance',
|
||||
label: 'Endurance',
|
||||
icon: Timer,
|
||||
description: 'Long-distance racing',
|
||||
filter: (league) =>
|
||||
league.scoring?.scoringPresetId?.includes('endurance') ??
|
||||
league.timingSummary?.includes('h Race') ??
|
||||
false,
|
||||
},
|
||||
{
|
||||
id: 'sprint',
|
||||
label: 'Sprint',
|
||||
icon: Clock,
|
||||
description: 'Quick, intense races',
|
||||
filter: (league) =>
|
||||
(league.scoring?.scoringPresetId?.includes('sprint') ?? false) &&
|
||||
!(league.scoring?.scoringPresetId?.includes('endurance') ?? false),
|
||||
},
|
||||
];
|
||||
|
||||
// ============================================================================
|
||||
// LEAGUE SLIDER COMPONENT
|
||||
// ============================================================================
|
||||
|
||||
function LeagueSlider({
|
||||
title,
|
||||
icon: Icon,
|
||||
description,
|
||||
leagues,
|
||||
autoScroll = true,
|
||||
iconColor = 'text-primary-blue',
|
||||
scrollSpeedMultiplier = 1,
|
||||
scrollDirection = 'right',
|
||||
}: LeagueSliderProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [canScrollLeft, setCanScrollLeft] = useState(false);
|
||||
const [canScrollRight, setCanScrollRight] = useState(true);
|
||||
const [isHovering, setIsHovering] = useState(false);
|
||||
const animationRef = useRef<number | null>(null);
|
||||
const scrollPositionRef = useRef(0);
|
||||
|
||||
const checkScrollButtons = useCallback(() => {
|
||||
if (scrollRef.current) {
|
||||
const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
|
||||
setCanScrollLeft(scrollLeft > 0);
|
||||
setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const scroll = useCallback((direction: 'left' | 'right') => {
|
||||
if (scrollRef.current) {
|
||||
const cardWidth = 340;
|
||||
const scrollAmount = direction === 'left' ? -cardWidth : cardWidth;
|
||||
// Update the ref so auto-scroll continues from new position
|
||||
scrollPositionRef.current = scrollRef.current.scrollLeft + scrollAmount;
|
||||
scrollRef.current.scrollBy({ left: scrollAmount, behavior: 'smooth' });
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Initialize scroll position for left-scrolling sliders
|
||||
const initializeScroll = useCallback(() => {
|
||||
if (scrollDirection === 'left' && scrollRef.current) {
|
||||
const { scrollWidth, clientWidth } = scrollRef.current;
|
||||
scrollPositionRef.current = scrollWidth - clientWidth;
|
||||
scrollRef.current.scrollLeft = scrollPositionRef.current;
|
||||
}
|
||||
}, [scrollDirection]);
|
||||
|
||||
// Smooth continuous auto-scroll using requestAnimationFrame with variable speed and direction
|
||||
const setupAutoScroll = useCallback(() => {
|
||||
// Allow scroll even with just 2 leagues (minimum threshold = 1)
|
||||
if (!autoScroll || leagues.length <= 1) return;
|
||||
|
||||
const scrollContainer = scrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
|
||||
let lastTimestamp = 0;
|
||||
// Base speed with multiplier for variation between sliders
|
||||
const baseSpeed = 0.025;
|
||||
const scrollSpeed = baseSpeed * scrollSpeedMultiplier;
|
||||
const directionMultiplier = scrollDirection === 'left' ? -1 : 1;
|
||||
|
||||
const animate = (timestamp: number) => {
|
||||
if (!isHovering && scrollContainer) {
|
||||
const delta = lastTimestamp ? timestamp - lastTimestamp : 0;
|
||||
lastTimestamp = timestamp;
|
||||
|
||||
scrollPositionRef.current += scrollSpeed * delta * directionMultiplier;
|
||||
|
||||
const { scrollWidth, clientWidth } = scrollContainer;
|
||||
const maxScroll = scrollWidth - clientWidth;
|
||||
|
||||
// Handle wrap-around for both directions
|
||||
if (scrollDirection === 'right' && scrollPositionRef.current >= maxScroll) {
|
||||
scrollPositionRef.current = 0;
|
||||
} else if (scrollDirection === 'left' && scrollPositionRef.current <= 0) {
|
||||
scrollPositionRef.current = maxScroll;
|
||||
}
|
||||
|
||||
scrollContainer.scrollLeft = scrollPositionRef.current;
|
||||
} else {
|
||||
lastTimestamp = timestamp;
|
||||
}
|
||||
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
|
||||
return () => {
|
||||
if (animationRef.current) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
}
|
||||
};
|
||||
}, [autoScroll, leagues.length, isHovering, scrollSpeedMultiplier, scrollDirection]);
|
||||
|
||||
// Sync scroll position when user manually scrolls
|
||||
const setupManualScroll = useCallback(() => {
|
||||
const scrollContainer = scrollRef.current;
|
||||
if (!scrollContainer) return;
|
||||
|
||||
const handleScroll = () => {
|
||||
scrollPositionRef.current = scrollContainer.scrollLeft;
|
||||
checkScrollButtons();
|
||||
};
|
||||
|
||||
scrollContainer.addEventListener('scroll', handleScroll);
|
||||
return () => scrollContainer.removeEventListener('scroll', handleScroll);
|
||||
}, [checkScrollButtons]);
|
||||
|
||||
// Initialize effects
|
||||
useState(() => {
|
||||
initializeScroll();
|
||||
});
|
||||
|
||||
// Setup auto-scroll effect
|
||||
useState(() => {
|
||||
setupAutoScroll();
|
||||
});
|
||||
|
||||
// Setup manual scroll effect
|
||||
useState(() => {
|
||||
setupManualScroll();
|
||||
});
|
||||
|
||||
if (leagues.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="mb-10">
|
||||
{/* Section header */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`flex h-10 w-10 items-center justify-center rounded-xl bg-iron-gray border border-charcoal-outline`}>
|
||||
<Icon className={`w-5 h-5 ${iconColor}`} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">{title}</h2>
|
||||
<p className="text-xs text-gray-500">{description}</p>
|
||||
</div>
|
||||
<span className="ml-2 px-2 py-0.5 rounded-full text-xs bg-charcoal-outline/50 text-gray-400">
|
||||
{leagues.length}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Navigation arrows */}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => scroll('left')}
|
||||
disabled={!canScrollLeft}
|
||||
className={`flex h-8 w-8 items-center justify-center rounded-lg transition-all ${
|
||||
canScrollLeft
|
||||
? 'bg-iron-gray border border-charcoal-outline text-white hover:border-primary-blue hover:text-primary-blue'
|
||||
: 'bg-iron-gray/30 border border-charcoal-outline/30 text-gray-600 cursor-not-allowed'
|
||||
}`}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => scroll('right')}
|
||||
disabled={!canScrollRight}
|
||||
className={`flex h-8 w-8 items-center justify-center rounded-lg transition-all ${
|
||||
canScrollRight
|
||||
? 'bg-iron-gray border border-charcoal-outline text-white hover:border-primary-blue hover:text-primary-blue'
|
||||
: 'bg-iron-gray/30 border border-charcoal-outline/30 text-gray-600 cursor-not-allowed'
|
||||
}`}
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scrollable container with fade edges */}
|
||||
<div className="relative">
|
||||
{/* Left fade gradient */}
|
||||
<div className="absolute left-0 top-0 bottom-4 w-12 bg-gradient-to-r from-deep-graphite to-transparent z-10 pointer-events-none" />
|
||||
{/* Right fade gradient */}
|
||||
<div className="absolute right-0 top-0 bottom-4 w-12 bg-gradient-to-l from-deep-graphite to-transparent z-10 pointer-events-none" />
|
||||
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onMouseEnter={() => setIsHovering(true)}
|
||||
onMouseLeave={() => setIsHovering(false)}
|
||||
className="flex gap-4 overflow-x-auto pb-4 px-4"
|
||||
style={{
|
||||
scrollbarWidth: 'none',
|
||||
msOverflowStyle: 'none',
|
||||
}}
|
||||
>
|
||||
<style jsx>{`
|
||||
div::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
`}</style>
|
||||
{leagues.map((league) => {
|
||||
// Convert ViewData to ViewModel for LeagueCard
|
||||
const viewModel: LeagueSummaryViewModel = {
|
||||
id: league.id,
|
||||
name: league.name,
|
||||
description: league.description ?? '',
|
||||
logoUrl: league.logoUrl,
|
||||
ownerId: league.ownerId,
|
||||
createdAt: league.createdAt,
|
||||
maxDrivers: league.maxDrivers,
|
||||
usedDriverSlots: league.usedDriverSlots,
|
||||
maxTeams: league.maxTeams ?? 0,
|
||||
usedTeamSlots: league.usedTeamSlots ?? 0,
|
||||
structureSummary: league.structureSummary,
|
||||
timingSummary: league.timingSummary,
|
||||
category: league.category ?? undefined,
|
||||
scoring: league.scoring ? {
|
||||
...league.scoring,
|
||||
primaryChampionshipType: league.scoring.primaryChampionshipType as 'driver' | 'team' | 'nations' | 'trophy',
|
||||
} : undefined,
|
||||
};
|
||||
|
||||
return (
|
||||
<div key={league.id} className="flex-shrink-0 w-[320px] h-full">
|
||||
<a href={`/leagues/${league.id}`} className="block h-full">
|
||||
<LeagueCard league={viewModel} />
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MAIN TEMPLATE COMPONENT
|
||||
// ============================================================================
|
||||
|
||||
export function LeaguesClient({
|
||||
viewData,
|
||||
}: LeaguesTemplateProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [activeCategory, setActiveCategory] = useState<CategoryId>('all');
|
||||
const [showFilters, setShowFilters] = useState(false);
|
||||
|
||||
// Filter by search query
|
||||
const searchFilteredLeagues = viewData.leagues.filter((league) => {
|
||||
if (!searchQuery) return true;
|
||||
const query = searchQuery.toLowerCase();
|
||||
return (
|
||||
league.name.toLowerCase().includes(query) ||
|
||||
(league.description ?? '').toLowerCase().includes(query) ||
|
||||
(league.scoring?.gameName ?? '').toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
|
||||
// Get leagues for active category
|
||||
const activeCategoryData = CATEGORIES.find((c) => c.id === activeCategory);
|
||||
const categoryFilteredLeagues = activeCategoryData
|
||||
? searchFilteredLeagues.filter(activeCategoryData.filter)
|
||||
: searchFilteredLeagues;
|
||||
|
||||
// Group leagues by category for slider view
|
||||
const leaguesByCategory = CATEGORIES.reduce(
|
||||
(acc, category) => {
|
||||
// First try to use the dedicated category field, fall back to scoring-based filtering
|
||||
acc[category.id] = searchFilteredLeagues.filter((league) => {
|
||||
// If league has a category field, use it directly
|
||||
if (league.category) {
|
||||
return league.category === category.id;
|
||||
}
|
||||
// Otherwise fall back to the existing scoring-based filter
|
||||
return category.filter(league);
|
||||
});
|
||||
return acc;
|
||||
},
|
||||
{} as Record<CategoryId, LeaguesViewData['leagues']>,
|
||||
);
|
||||
|
||||
// Featured categories to show as sliders with different scroll speeds and alternating directions
|
||||
const featuredCategoriesWithSpeed: { id: CategoryId; speed: number; direction: 'left' | 'right' }[] = [
|
||||
{ id: 'popular', speed: 1.0, direction: 'right' },
|
||||
{ id: 'new', speed: 1.3, direction: 'left' },
|
||||
{ id: 'driver', speed: 0.8, direction: 'right' },
|
||||
{ id: 'team', speed: 1.1, direction: 'left' },
|
||||
{ id: 'nations', speed: 0.9, direction: 'right' },
|
||||
{ id: 'endurance', speed: 0.7, direction: 'left' },
|
||||
{ id: 'sprint', speed: 1.2, direction: 'right' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Container size="lg" pb={12}>
|
||||
{/* Hero Section */}
|
||||
<HeroSection
|
||||
title="Find Your Grid"
|
||||
description="From casual sprints to epic endurance battles — discover the perfect league for your racing style."
|
||||
icon={Trophy}
|
||||
stats={[
|
||||
{ value: viewData.leagues.length, label: 'active leagues', color: 'bg-performance-green', animate: true },
|
||||
{ value: leaguesByCategory.new.length, label: 'new this week', color: 'bg-primary-blue' },
|
||||
{ value: leaguesByCategory.openSlots.length, label: 'with open slots', color: 'bg-neon-aqua' },
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
label: 'Create League',
|
||||
onClick: () => { window.location.href = '/leagues/create'; },
|
||||
icon: Plus,
|
||||
description: 'Set up your own racing series'
|
||||
}
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* Search and Filter Bar */}
|
||||
<Box mb={6}>
|
||||
<Stack direction="row" gap={4} wrap>
|
||||
{/* Search */}
|
||||
<Box display="flex" position="relative" style={{ flex: 1 }}>
|
||||
<Box position="absolute" style={{ left: '0.75rem', top: '50%', transform: 'translateY(-50%)', zIndex: 10 }}>
|
||||
<Search className="w-5 h-5 text-gray-500" />
|
||||
</Box>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search leagues by name, description, or game..."
|
||||
value={searchQuery}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchQuery(e.target.value)}
|
||||
className="pl-11"
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{/* Filter toggle (mobile) */}
|
||||
<Box display="none" className="lg:hidden">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => setShowFilters(!showFilters)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<Filter className="w-4 h-4" />
|
||||
Filters
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
{/* Category Tabs */}
|
||||
<Box mt={4} display={showFilters ? 'block' : 'none'} className="lg:block">
|
||||
<Stack direction="row" gap={2} wrap>
|
||||
{CATEGORIES.map((category) => {
|
||||
const Icon = category.icon;
|
||||
const count = leaguesByCategory[category.id].length;
|
||||
const isActive = activeCategory === category.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={category.id}
|
||||
type="button"
|
||||
onClick={() => setActiveCategory(category.id)}
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-all duration-200 ${
|
||||
isActive
|
||||
? 'bg-primary-blue text-white shadow-[0_0_15px_rgba(25,140,255,0.3)]'
|
||||
: 'bg-iron-gray/60 text-gray-400 border border-charcoal-outline hover:border-gray-500 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
<Icon className={`w-3.5 h-3.5 ${!isActive && category.color ? category.color : ''}`} />
|
||||
<span>{category.label}</span>
|
||||
{count > 0 && (
|
||||
<span className={`px-1.5 py-0.5 rounded-full text-[10px] ${isActive ? 'bg-white/20' : 'bg-charcoal-outline/50'}`}>
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Content */}
|
||||
{viewData.leagues.length === 0 ? (
|
||||
/* Empty State */
|
||||
<Card className="text-center py-16">
|
||||
<Box maxWidth="28rem" mx="auto">
|
||||
<Box display="flex" center mb={6} rounded="2xl" p={4} className="bg-primary-blue/10 border border-primary-blue/20 mx-auto w-16 h-16">
|
||||
<Trophy className="w-8 h-8 text-primary-blue" />
|
||||
</Box>
|
||||
<Heading level={2} className="text-2xl mb-3">
|
||||
No leagues yet
|
||||
</Heading>
|
||||
<Text color="text-gray-400" mb={8} block>
|
||||
Be the first to create a racing series. Start your own league and invite drivers to compete for glory.
|
||||
</Text>
|
||||
<Button
|
||||
onClick={() => { window.location.href = '/leagues/create'; }}
|
||||
className="inline-flex items-center gap-2 px-6 py-3 bg-primary-blue text-white rounded-lg hover:bg-blue-600 transition-colors"
|
||||
>
|
||||
<Sparkles className="w-4 h-4" />
|
||||
Create Your First League
|
||||
</Button>
|
||||
</Box>
|
||||
</Card>
|
||||
) : activeCategory === 'all' && !searchQuery ? (
|
||||
/* Slider View - Show featured categories with sliders at different speeds and directions */
|
||||
<Box>
|
||||
{featuredCategoriesWithSpeed
|
||||
.map(({ id, speed, direction }) => {
|
||||
const category = CATEGORIES.find((c) => c.id === id)!;
|
||||
return { category, speed, direction };
|
||||
})
|
||||
.filter(({ category }) => leaguesByCategory[category.id].length > 0)
|
||||
.map(({ category, speed, direction }) => (
|
||||
<LeagueSlider
|
||||
key={category.id}
|
||||
title={category.label}
|
||||
icon={category.icon}
|
||||
description={category.description}
|
||||
leagues={leaguesByCategory[category.id]}
|
||||
autoScroll={true}
|
||||
iconColor={category.color || 'text-primary-blue'}
|
||||
scrollSpeedMultiplier={speed}
|
||||
scrollDirection={direction}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
) : (
|
||||
/* Grid View - Filtered by category or search */
|
||||
<Box>
|
||||
{categoryFilteredLeagues.length > 0 ? (
|
||||
<>
|
||||
<Box display="flex" align="center" justify="between" mb={6}>
|
||||
<Text size="sm" color="text-gray-400">
|
||||
Showing <Text color="text-white" weight="medium">{categoryFilteredLeagues.length}</Text>{' '}
|
||||
{categoryFilteredLeagues.length === 1 ? 'league' : 'leagues'}
|
||||
{searchQuery && (
|
||||
<span>
|
||||
{' '}
|
||||
for "<Text color="text-primary-blue">{searchQuery}</Text>"
|
||||
</span>
|
||||
)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Grid cols={1} mdCols={2} lgCols={3} gap={6}>
|
||||
{categoryFilteredLeagues.map((league) => {
|
||||
// Convert ViewData to ViewModel for LeagueCard
|
||||
const viewModel: LeagueSummaryViewModel = {
|
||||
id: league.id,
|
||||
name: league.name,
|
||||
description: league.description ?? '',
|
||||
logoUrl: league.logoUrl,
|
||||
ownerId: league.ownerId,
|
||||
createdAt: league.createdAt,
|
||||
maxDrivers: league.maxDrivers,
|
||||
usedDriverSlots: league.usedDriverSlots,
|
||||
maxTeams: league.maxTeams ?? 0,
|
||||
usedTeamSlots: league.usedTeamSlots ?? 0,
|
||||
structureSummary: league.structureSummary,
|
||||
timingSummary: league.timingSummary,
|
||||
category: league.category ?? undefined,
|
||||
scoring: league.scoring ? {
|
||||
...league.scoring,
|
||||
primaryChampionshipType: league.scoring.primaryChampionshipType as 'driver' | 'team' | 'nations' | 'trophy',
|
||||
} : undefined,
|
||||
};
|
||||
|
||||
return (
|
||||
<GridItem key={league.id}>
|
||||
<a href={`/leagues/${league.id}`} className="block h-full">
|
||||
<LeagueCard league={viewModel} />
|
||||
</a>
|
||||
</GridItem>
|
||||
);
|
||||
})}
|
||||
</Grid>
|
||||
</>
|
||||
) : (
|
||||
<Card className="text-center py-12">
|
||||
<Stack align="center" gap={4}>
|
||||
<Search className="w-10 h-10 text-gray-600" />
|
||||
<Text color="text-gray-400">
|
||||
No leagues found{searchQuery ? ` matching "${searchQuery}"` : ' in this category'}
|
||||
</Text>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setSearchQuery('');
|
||||
setActiveCategory('all');
|
||||
}}
|
||||
>
|
||||
Clear filters
|
||||
</Button>
|
||||
</Stack>
|
||||
</Card>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import PenaltyFAB from '@/components/leagues/PenaltyFAB';
|
||||
import QuickPenaltyModal from '@/components/leagues/QuickPenaltyModal';
|
||||
import { ReviewProtestModal } from '@/components/leagues/ReviewProtestModal';
|
||||
import StewardingStats from '@/components/leagues/StewardingStats';
|
||||
import Button from '@/ui/Button';
|
||||
import Card from '@/ui/Card';
|
||||
import { useLeagueStewardingMutations } from "@/lib/hooks/league/useLeagueStewardingMutations";
|
||||
import { Button } from '@/ui/Button';
|
||||
import { Card } from '@/ui/Card';
|
||||
import { useLeagueStewardingMutations } from "@/hooks/league/useLeagueStewardingMutations";
|
||||
import {
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
@@ -19,13 +19,15 @@ import {
|
||||
} from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { PendingProtestsList } from '@/components/leagues/PendingProtestsList';
|
||||
import { PenaltyHistoryList } from '@/components/leagues/PenaltyHistoryList';
|
||||
|
||||
interface StewardingData {
|
||||
totalPending: number;
|
||||
totalResolved: number;
|
||||
totalPenalties: number;
|
||||
racesWithData: Array<{
|
||||
race: { id: string; track: string; scheduledAt: Date };
|
||||
race: { id: string; track: string; scheduledAt: Date; car?: string };
|
||||
pendingProtests: any[];
|
||||
resolvedProtests: any[];
|
||||
penalties: any[];
|
||||
@@ -44,16 +46,27 @@ interface StewardingTemplateProps {
|
||||
export function StewardingTemplate({ data, leagueId, currentDriverId, onRefetch }: StewardingTemplateProps) {
|
||||
const [activeTab, setActiveTab] = useState<'pending' | 'history'>('pending');
|
||||
const [selectedProtest, setSelectedProtest] = useState<any | null>(null);
|
||||
const [expandedRaces, setExpandedRaces] = useState<Set<string>>(new Set());
|
||||
const [showQuickPenaltyModal, setShowQuickPenaltyModal] = useState(false);
|
||||
|
||||
// Mutations using domain hook
|
||||
const { acceptProtestMutation, rejectProtestMutation } = useLeagueStewardingMutations(onRefetch);
|
||||
|
||||
// Filter races based on active tab
|
||||
const filteredRaces = useMemo(() => {
|
||||
return activeTab === 'pending' ? data.racesWithData.filter(r => r.pendingProtests.length > 0) : data.racesWithData.filter(r => r.resolvedProtests.length > 0 || r.penalties.length > 0);
|
||||
}, [data, activeTab]);
|
||||
// Flatten protests for the specialized list components
|
||||
const allPendingProtests = useMemo(() => {
|
||||
return data.racesWithData.flatMap(r => r.pendingProtests);
|
||||
}, [data]);
|
||||
|
||||
const allResolvedProtests = useMemo(() => {
|
||||
return data.racesWithData.flatMap(r => r.resolvedProtests);
|
||||
}, [data]);
|
||||
|
||||
const racesMap = useMemo(() => {
|
||||
const map: Record<string, any> = {};
|
||||
data.racesWithData.forEach(r => {
|
||||
map[r.race.id] = r.race;
|
||||
});
|
||||
return map;
|
||||
}, [data]);
|
||||
|
||||
const handleAcceptProtest = async (
|
||||
protestId: string,
|
||||
@@ -89,34 +102,6 @@ export function StewardingTemplate({ data, leagueId, currentDriverId, onRefetch
|
||||
});
|
||||
};
|
||||
|
||||
const toggleRaceExpanded = (raceId: string) => {
|
||||
setExpandedRaces(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(raceId)) {
|
||||
next.delete(raceId);
|
||||
} else {
|
||||
next.add(raceId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
case 'under_review':
|
||||
return <span className="px-2 py-0.5 text-xs font-medium bg-warning-amber/20 text-warning-amber rounded-full">Pending</span>;
|
||||
case 'upheld':
|
||||
return <span className="px-2 py-0.5 text-xs font-medium bg-red-500/20 text-red-400 rounded-full">Upheld</span>;
|
||||
case 'dismissed':
|
||||
return <span className="px-2 py-0.5 text-xs font-medium bg-gray-500/20 text-gray-400 rounded-full">Dismissed</span>;
|
||||
case 'withdrawn':
|
||||
return <span className="px-2 py-0.5 text-xs font-medium bg-blue-500/20 text-blue-400 rounded-full">Withdrawn</span>;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
@@ -168,168 +153,21 @@ export function StewardingTemplate({ data, leagueId, currentDriverId, onRefetch
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{filteredRaces.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<div className="w-16 h-16 mx-auto mb-4 rounded-full bg-performance-green/10 flex items-center justify-center">
|
||||
<Flag className="w-8 h-8 text-performance-green" />
|
||||
</div>
|
||||
<p className="font-semibold text-lg text-white mb-2">
|
||||
{activeTab === 'pending' ? 'All Clear!' : 'No History Yet'}
|
||||
</p>
|
||||
<p className="text-sm text-gray-400">
|
||||
{activeTab === 'pending'
|
||||
? 'No pending protests to review'
|
||||
: 'No resolved protests or penalties'}
|
||||
</p>
|
||||
</div>
|
||||
{activeTab === 'pending' ? (
|
||||
<PendingProtestsList
|
||||
protests={allPendingProtests}
|
||||
races={racesMap}
|
||||
drivers={data.driverMap}
|
||||
leagueId={leagueId}
|
||||
onReviewProtest={setSelectedProtest}
|
||||
onProtestReviewed={onRefetch}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{filteredRaces.map(({ race, pendingProtests, resolvedProtests, penalties }) => {
|
||||
const isExpanded = expandedRaces.has(race.id);
|
||||
const displayProtests = activeTab === 'pending' ? pendingProtests : resolvedProtests;
|
||||
|
||||
return (
|
||||
<div key={race.id} className="rounded-lg border border-charcoal-outline overflow-hidden">
|
||||
{/* Race Header */}
|
||||
<button
|
||||
onClick={() => toggleRaceExpanded(race.id)}
|
||||
className="w-full px-4 py-3 bg-iron-gray/30 hover:bg-iron-gray/50 transition-colors flex items-center justify-between"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<MapPin className="w-4 h-4 text-gray-400" />
|
||||
<span className="font-medium text-white">{race.track}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-gray-400 text-sm">
|
||||
<Calendar className="w-4 h-4" />
|
||||
<span>{race.scheduledAt.toLocaleDateString()}</span>
|
||||
</div>
|
||||
{activeTab === 'pending' && pendingProtests.length > 0 && (
|
||||
<span className="px-2 py-0.5 text-xs font-medium bg-warning-amber/20 text-warning-amber rounded-full">
|
||||
{pendingProtests.length} pending
|
||||
</span>
|
||||
)}
|
||||
{activeTab === 'history' && (
|
||||
<span className="px-2 py-0.5 text-xs font-medium bg-gray-500/20 text-gray-400 rounded-full">
|
||||
{resolvedProtests.length} protests, {penalties.length} penalties
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<ChevronRight className={`w-5 h-5 text-gray-400 transition-transform ${isExpanded ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
|
||||
{/* Expanded Content */}
|
||||
{isExpanded && (
|
||||
<div className="p-4 space-y-3 bg-deep-graphite/50">
|
||||
{displayProtests.length === 0 && penalties.length === 0 ? (
|
||||
<p className="text-sm text-gray-400 text-center py-4">No items to display</p>
|
||||
) : (
|
||||
<>
|
||||
{displayProtests.map((protest) => {
|
||||
const protester = data.driverMap[protest.protestingDriverId];
|
||||
const accused = data.driverMap[protest.accusedDriverId];
|
||||
const daysSinceFiled = Math.floor((Date.now() - new Date(protest.filedAt).getTime()) / (1000 * 60 * 60 * 24));
|
||||
const isUrgent = daysSinceFiled > 2 && (protest.status === 'pending' || protest.status === 'under_review');
|
||||
|
||||
return (
|
||||
<div
|
||||
key={protest.id}
|
||||
className={`rounded-lg border border-charcoal-outline bg-iron-gray/30 p-4 ${isUrgent ? 'border-l-4 border-l-red-500' : ''}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<AlertCircle className="w-4 h-4 text-warning-amber flex-shrink-0" />
|
||||
<span className="font-medium text-white">
|
||||
{protester?.name || 'Unknown'} vs {accused?.name || 'Unknown'}
|
||||
</span>
|
||||
{getStatusBadge(protest.status)}
|
||||
{isUrgent && (
|
||||
<span className="px-2 py-0.5 text-xs font-medium bg-red-500/20 text-red-400 rounded-full flex items-center gap-1">
|
||||
<AlertTriangle className="w-3 h-3" />
|
||||
{daysSinceFiled}d old
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-sm text-gray-400 mb-2">
|
||||
<span>Lap {protest.incident.lap}</span>
|
||||
<span>•</span>
|
||||
<span>Filed {new Date(protest.filedAt).toLocaleDateString()}</span>
|
||||
{protest.proofVideoUrl && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span className="flex items-center gap-1 text-primary-blue">
|
||||
<Video className="w-3 h-3" />
|
||||
Video
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-300 line-clamp-2">
|
||||
{protest.incident.description}
|
||||
</p>
|
||||
{protest.decisionNotes && (
|
||||
<div className="mt-2 p-2 rounded bg-iron-gray/50 border border-charcoal-outline/50">
|
||||
<p className="text-xs text-gray-400">
|
||||
<span className="font-medium">Steward:</span> {protest.decisionNotes}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{(protest.status === 'pending' || protest.status === 'under_review') && (
|
||||
<Link href={`/leagues/${leagueId}/stewarding/protests/${protest.id}`}>
|
||||
<Button variant="primary">
|
||||
Review
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{activeTab === 'history' && penalties.map((penalty) => {
|
||||
const driver = data.driverMap[penalty.driverId];
|
||||
return (
|
||||
<div
|
||||
key={penalty.id}
|
||||
className="rounded-lg border border-charcoal-outline bg-iron-gray/30 p-4"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0">
|
||||
<Gavel className="w-4 h-4 text-red-400" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-white">{driver?.name || 'Unknown'}</span>
|
||||
<span className="px-2 py-0.5 text-xs font-medium bg-red-500/20 text-red-400 rounded-full">
|
||||
{penalty.type.replace('_', ' ')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-400">{penalty.reason}</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className="text-lg font-bold text-red-400">
|
||||
{penalty.type === 'time_penalty' && `+${penalty.value}s`}
|
||||
{penalty.type === 'grid_penalty' && `+${penalty.value} grid`}
|
||||
{penalty.type === 'points_deduction' && `-${penalty.value} pts`}
|
||||
{penalty.type === 'disqualification' && 'DSQ'}
|
||||
{penalty.type === 'warning' && 'Warning'}
|
||||
{penalty.type === 'license_points' && `${penalty.value} LP`}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<PenaltyHistoryList
|
||||
protests={allResolvedProtests}
|
||||
races={racesMap}
|
||||
drivers={data.driverMap}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
|
||||
985
apps/website/app/leagues/create/CreateLeagueWizard.tsx
Normal file
985
apps/website/app/leagues/create/CreateLeagueWizard.tsx
Normal file
@@ -0,0 +1,985 @@
|
||||
'use client';
|
||||
|
||||
import LeagueReviewSummary from '@/components/leagues/LeagueReviewSummary';
|
||||
import Button from '@/ui/Button';
|
||||
import Card from '@/ui/Card';
|
||||
import Heading from '@/ui/Heading';
|
||||
import Input from '@/ui/Input';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import {
|
||||
AlertCircle,
|
||||
Award,
|
||||
Calendar,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
FileText,
|
||||
Loader2,
|
||||
Scale,
|
||||
Sparkles,
|
||||
Trophy,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { FormEvent, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { LeagueWizardCommandModel } from '@/lib/command-models/leagues/LeagueWizardCommandModel';
|
||||
|
||||
import { useCreateLeagueWizard } from "@/lib/hooks/useLeagueWizardService";
|
||||
import { useLeagueScoringPresets } from "@/lib/hooks/useLeagueScoringPresets";
|
||||
import { LeagueBasicsSection } from './LeagueBasicsSection';
|
||||
import { LeagueDropSection } from './LeagueDropSection';
|
||||
import {
|
||||
ChampionshipsSection,
|
||||
ScoringPatternSection
|
||||
} from './LeagueScoringSection';
|
||||
import { LeagueStewardingSection } from './LeagueStewardingSection';
|
||||
import { LeagueStructureSection } from './LeagueStructureSection';
|
||||
import { LeagueTimingsSection } from './LeagueTimingsSection';
|
||||
import { LeagueVisibilitySection } from './LeagueVisibilitySection';
|
||||
import type { LeagueConfigFormModel } from '@/lib/types/LeagueConfigFormModel';
|
||||
import type { LeagueScoringPresetViewModel } from '@/lib/view-models/LeagueScoringPresetViewModel';
|
||||
import type { Weekday } from '@/lib/types/Weekday';
|
||||
import type { WizardErrors } from '@/lib/types/WizardErrors';
|
||||
|
||||
// ============================================================================
|
||||
// LOCAL STORAGE PERSISTENCE
|
||||
// ============================================================================
|
||||
|
||||
const STORAGE_KEY = 'gridpilot_league_wizard_draft';
|
||||
const STORAGE_HIGHEST_STEP_KEY = 'gridpilot_league_wizard_highest_step';
|
||||
|
||||
// TODO there is a better place for this
|
||||
function saveFormToStorage(form: LeagueWizardFormModel): void {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(form));
|
||||
} catch {
|
||||
// Ignore storage errors (quota exceeded, etc.)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO there is a better place for this
|
||||
function loadFormFromStorage(): LeagueWizardFormModel | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored) as LeagueWizardFormModel;
|
||||
if (!parsed.seasonName) {
|
||||
const seasonStartDate = parsed.timings?.seasonStartDate;
|
||||
parsed.seasonName = getDefaultSeasonName(seasonStartDate);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function clearFormStorage(): void {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
localStorage.removeItem(STORAGE_HIGHEST_STEP_KEY);
|
||||
} catch {
|
||||
// Ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function saveHighestStep(step: number): void {
|
||||
try {
|
||||
const current = getHighestStep();
|
||||
if (step > current) {
|
||||
localStorage.setItem(STORAGE_HIGHEST_STEP_KEY, String(step));
|
||||
}
|
||||
} catch {
|
||||
// Ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function getHighestStep(): number {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_HIGHEST_STEP_KEY);
|
||||
return stored ? parseInt(stored, 10) : 1;
|
||||
} catch {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
type Step = 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
||||
|
||||
type StepName = 'basics' | 'visibility' | 'structure' | 'schedule' | 'scoring' | 'stewarding' | 'review';
|
||||
|
||||
type LeagueWizardFormModel = LeagueConfigFormModel & {
|
||||
seasonName?: string;
|
||||
};
|
||||
|
||||
interface CreateLeagueWizardProps {
|
||||
stepName: StepName;
|
||||
onStepChange: (stepName: StepName) => void;
|
||||
}
|
||||
|
||||
function stepNameToStep(stepName: StepName): Step {
|
||||
switch (stepName) {
|
||||
case 'basics':
|
||||
return 1;
|
||||
case 'visibility':
|
||||
return 2;
|
||||
case 'structure':
|
||||
return 3;
|
||||
case 'schedule':
|
||||
return 4;
|
||||
case 'scoring':
|
||||
return 5;
|
||||
case 'stewarding':
|
||||
return 6;
|
||||
case 'review':
|
||||
return 7;
|
||||
}
|
||||
}
|
||||
|
||||
function stepToStepName(step: Step): StepName {
|
||||
switch (step) {
|
||||
case 1:
|
||||
return 'basics';
|
||||
case 2:
|
||||
return 'visibility';
|
||||
case 3:
|
||||
return 'structure';
|
||||
case 4:
|
||||
return 'schedule';
|
||||
case 5:
|
||||
return 'scoring';
|
||||
case 6:
|
||||
return 'stewarding';
|
||||
case 7:
|
||||
return 'review';
|
||||
}
|
||||
}
|
||||
|
||||
function getDefaultSeasonStartDate(): string {
|
||||
// Default to next Saturday
|
||||
const now = new Date();
|
||||
const daysUntilSaturday = (6 - now.getDay() + 7) % 7 || 7;
|
||||
const nextSaturday = new Date(now);
|
||||
nextSaturday.setDate(now.getDate() + daysUntilSaturday);
|
||||
const [datePart] = nextSaturday.toISOString().split('T');
|
||||
return datePart ?? '';
|
||||
}
|
||||
|
||||
function getDefaultSeasonName(seasonStartDate?: string): string {
|
||||
if (seasonStartDate) {
|
||||
const parsed = new Date(seasonStartDate);
|
||||
if (!Number.isNaN(parsed.getTime())) {
|
||||
const year = parsed.getFullYear();
|
||||
return `Season 1 (${year})`;
|
||||
}
|
||||
}
|
||||
const fallbackYear = new Date().getFullYear();
|
||||
return `Season 1 (${fallbackYear})`;
|
||||
}
|
||||
|
||||
function createDefaultForm(): LeagueWizardFormModel {
|
||||
const defaultPatternId = 'sprint-main-driver';
|
||||
const defaultSeasonStartDate = getDefaultSeasonStartDate();
|
||||
|
||||
return {
|
||||
basics: {
|
||||
name: '',
|
||||
description: '',
|
||||
visibility: 'public',
|
||||
gameId: 'iracing',
|
||||
},
|
||||
structure: {
|
||||
mode: 'solo',
|
||||
maxDrivers: 24,
|
||||
multiClassEnabled: false,
|
||||
},
|
||||
championships: {
|
||||
enableDriverChampionship: true,
|
||||
enableTeamChampionship: false,
|
||||
enableNationsChampionship: false,
|
||||
enableTrophyChampionship: false,
|
||||
},
|
||||
scoring: {
|
||||
patternId: defaultPatternId,
|
||||
customScoringEnabled: false,
|
||||
},
|
||||
dropPolicy: {
|
||||
strategy: 'bestNResults',
|
||||
n: 6,
|
||||
},
|
||||
timings: {
|
||||
practiceMinutes: 20,
|
||||
qualifyingMinutes: 30,
|
||||
sprintRaceMinutes: 20,
|
||||
mainRaceMinutes: 40,
|
||||
sessionCount: 2,
|
||||
roundsPlanned: 8,
|
||||
// Default to Saturday races, weekly, starting next week
|
||||
weekdays: ['Sat'] as Weekday[],
|
||||
recurrenceStrategy: 'weekly' as const,
|
||||
timezoneId: 'UTC',
|
||||
seasonStartDate: defaultSeasonStartDate,
|
||||
},
|
||||
stewarding: {
|
||||
decisionMode: 'admin_only',
|
||||
requiredVotes: 2,
|
||||
requireDefense: false,
|
||||
defenseTimeLimit: 48,
|
||||
voteTimeLimit: 72,
|
||||
protestDeadlineHours: 48,
|
||||
stewardingClosesHours: 168,
|
||||
notifyAccusedOnProtest: true,
|
||||
notifyOnVoteRequired: true,
|
||||
},
|
||||
seasonName: getDefaultSeasonName(defaultSeasonStartDate),
|
||||
};
|
||||
}
|
||||
|
||||
export default function CreateLeagueWizard({ stepName, onStepChange }: CreateLeagueWizardProps) {
|
||||
const router = useRouter();
|
||||
const { session } = useAuth();
|
||||
|
||||
const step = stepNameToStep(stepName);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [presetsLoading, setPresetsLoading] = useState(true);
|
||||
const [presets, setPresets] = useState<LeagueScoringPresetViewModel[]>([]);
|
||||
const [errors, setErrors] = useState<WizardErrors>({});
|
||||
const [highestCompletedStep, setHighestCompletedStep] = useState(1);
|
||||
const [isHydrated, setIsHydrated] = useState(false);
|
||||
|
||||
// Initialize form from localStorage or defaults
|
||||
const [form, setForm] = useState<LeagueWizardFormModel>(() =>
|
||||
createDefaultForm(),
|
||||
);
|
||||
|
||||
// Hydrate from localStorage on mount
|
||||
useEffect(() => {
|
||||
const stored = loadFormFromStorage();
|
||||
if (stored) {
|
||||
setForm(stored);
|
||||
}
|
||||
setHighestCompletedStep(getHighestStep());
|
||||
setIsHydrated(true);
|
||||
}, []);
|
||||
|
||||
// Save form to localStorage whenever it changes (after hydration)
|
||||
useEffect(() => {
|
||||
if (isHydrated) {
|
||||
saveFormToStorage(form);
|
||||
}
|
||||
}, [form, isHydrated]);
|
||||
|
||||
// Track highest step reached
|
||||
useEffect(() => {
|
||||
if (isHydrated) {
|
||||
saveHighestStep(step);
|
||||
setHighestCompletedStep((prev) => Math.max(prev, step));
|
||||
}
|
||||
}, [step, isHydrated]);
|
||||
|
||||
// Use the react-query hook for scoring presets
|
||||
const { data: queryPresets, error: presetsError } = useLeagueScoringPresets();
|
||||
|
||||
// Sync presets from query to local state
|
||||
useEffect(() => {
|
||||
if (queryPresets) {
|
||||
setPresets(queryPresets);
|
||||
const firstPreset = queryPresets[0];
|
||||
if (firstPreset && !form.scoring?.patternId) {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
scoring: {
|
||||
...prev.scoring,
|
||||
patternId: firstPreset.id,
|
||||
customScoringEnabled: false,
|
||||
},
|
||||
}));
|
||||
}
|
||||
setPresetsLoading(false);
|
||||
}
|
||||
}, [queryPresets, form.scoring?.patternId]);
|
||||
|
||||
// Handle presets error
|
||||
useEffect(() => {
|
||||
if (presetsError) {
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
submit: presetsError instanceof Error ? presetsError.message : 'Failed to load scoring presets',
|
||||
}));
|
||||
}
|
||||
}, [presetsError]);
|
||||
|
||||
// Use the create league mutation
|
||||
const createLeagueMutation = useCreateLeagueWizard();
|
||||
|
||||
const validateStep = (currentStep: Step): boolean => {
|
||||
// Convert form to LeagueWizardFormData for validation
|
||||
const formData: LeagueWizardCommandModel.LeagueWizardFormData = {
|
||||
leagueId: form.leagueId || '',
|
||||
basics: {
|
||||
name: form.basics?.name || '',
|
||||
description: form.basics?.description || '',
|
||||
visibility: (form.basics?.visibility as 'public' | 'private' | 'unlisted') || 'public',
|
||||
gameId: form.basics?.gameId || 'iracing',
|
||||
},
|
||||
structure: {
|
||||
mode: (form.structure?.mode as 'solo' | 'fixedTeams') || 'solo',
|
||||
maxDrivers: form.structure?.maxDrivers || 0,
|
||||
maxTeams: form.structure?.maxTeams || 0,
|
||||
driversPerTeam: form.structure?.driversPerTeam || 0,
|
||||
},
|
||||
championships: {
|
||||
enableDriverChampionship: form.championships?.enableDriverChampionship ?? true,
|
||||
enableTeamChampionship: form.championships?.enableTeamChampionship ?? false,
|
||||
enableNationsChampionship: form.championships?.enableNationsChampionship ?? false,
|
||||
enableTrophyChampionship: form.championships?.enableTrophyChampionship ?? false,
|
||||
},
|
||||
scoring: {
|
||||
patternId: form.scoring?.patternId || '',
|
||||
customScoringEnabled: form.scoring?.customScoringEnabled ?? false,
|
||||
},
|
||||
dropPolicy: {
|
||||
strategy: (form.dropPolicy?.strategy as 'none' | 'bestNResults' | 'dropWorstN') || 'bestNResults',
|
||||
n: form.dropPolicy?.n || 6,
|
||||
},
|
||||
timings: {
|
||||
practiceMinutes: form.timings?.practiceMinutes || 0,
|
||||
qualifyingMinutes: form.timings?.qualifyingMinutes || 0,
|
||||
sprintRaceMinutes: form.timings?.sprintRaceMinutes || 0,
|
||||
mainRaceMinutes: form.timings?.mainRaceMinutes || 0,
|
||||
sessionCount: form.timings?.sessionCount || 0,
|
||||
roundsPlanned: form.timings?.roundsPlanned || 0,
|
||||
},
|
||||
stewarding: {
|
||||
decisionMode: (form.stewarding?.decisionMode as 'owner_only' | 'admin_vote' | 'steward_panel') || 'admin_only',
|
||||
requiredVotes: form.stewarding?.requiredVotes || 0,
|
||||
requireDefense: form.stewarding?.requireDefense ?? false,
|
||||
defenseTimeLimit: form.stewarding?.defenseTimeLimit || 0,
|
||||
voteTimeLimit: form.stewarding?.voteTimeLimit || 0,
|
||||
protestDeadlineHours: form.stewarding?.protestDeadlineHours || 0,
|
||||
stewardingClosesHours: form.stewarding?.stewardingClosesHours || 0,
|
||||
notifyAccusedOnProtest: form.stewarding?.notifyAccusedOnProtest ?? true,
|
||||
notifyOnVoteRequired: form.stewarding?.notifyOnVoteRequired ?? true,
|
||||
},
|
||||
};
|
||||
|
||||
const stepErrors = LeagueWizardCommandModel.validateLeagueWizardStep(formData, currentStep);
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
...stepErrors,
|
||||
}));
|
||||
return !LeagueWizardCommandModel.hasWizardErrors(stepErrors);
|
||||
};
|
||||
|
||||
const goToNextStep = () => {
|
||||
if (!validateStep(step)) {
|
||||
return;
|
||||
}
|
||||
const nextStep = (step < 7 ? ((step + 1) as Step) : step);
|
||||
saveHighestStep(nextStep);
|
||||
setHighestCompletedStep((prev) => Math.max(prev, nextStep));
|
||||
onStepChange(stepToStepName(nextStep));
|
||||
};
|
||||
|
||||
const goToPreviousStep = () => {
|
||||
const prevStep = (step > 1 ? ((step - 1) as Step) : step);
|
||||
onStepChange(stepToStepName(prevStep));
|
||||
};
|
||||
|
||||
// Navigate to a specific step (only if it's been reached before)
|
||||
const goToStep = useCallback((targetStep: Step) => {
|
||||
if (targetStep <= highestCompletedStep) {
|
||||
onStepChange(stepToStepName(targetStep));
|
||||
}
|
||||
}, [highestCompletedStep, onStepChange]);
|
||||
|
||||
const handleSubmit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (loading) return;
|
||||
|
||||
const ownerId = session?.user.userId;
|
||||
if (!ownerId) {
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
submit: 'You must be logged in to create a league',
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert form to LeagueWizardFormData for validation
|
||||
const formData: LeagueWizardCommandModel.LeagueWizardFormData = {
|
||||
leagueId: form.leagueId || '',
|
||||
basics: {
|
||||
name: form.basics?.name || '',
|
||||
description: form.basics?.description || '',
|
||||
visibility: (form.basics?.visibility as 'public' | 'private' | 'unlisted') || 'public',
|
||||
gameId: form.basics?.gameId || 'iracing',
|
||||
},
|
||||
structure: {
|
||||
mode: (form.structure?.mode as 'solo' | 'fixedTeams') || 'solo',
|
||||
maxDrivers: form.structure?.maxDrivers || 0,
|
||||
maxTeams: form.structure?.maxTeams || 0,
|
||||
driversPerTeam: form.structure?.driversPerTeam || 0,
|
||||
},
|
||||
championships: {
|
||||
enableDriverChampionship: form.championships?.enableDriverChampionship ?? true,
|
||||
enableTeamChampionship: form.championships?.enableTeamChampionship ?? false,
|
||||
enableNationsChampionship: form.championships?.enableNationsChampionship ?? false,
|
||||
enableTrophyChampionship: form.championships?.enableTrophyChampionship ?? false,
|
||||
},
|
||||
scoring: {
|
||||
patternId: form.scoring?.patternId || '',
|
||||
customScoringEnabled: form.scoring?.customScoringEnabled ?? false,
|
||||
},
|
||||
dropPolicy: {
|
||||
strategy: (form.dropPolicy?.strategy as 'none' | 'bestNResults' | 'dropWorstN') || 'bestNResults',
|
||||
n: form.dropPolicy?.n || 6,
|
||||
},
|
||||
timings: {
|
||||
practiceMinutes: form.timings?.practiceMinutes || 0,
|
||||
qualifyingMinutes: form.timings?.qualifyingMinutes || 0,
|
||||
sprintRaceMinutes: form.timings?.sprintRaceMinutes || 0,
|
||||
mainRaceMinutes: form.timings?.mainRaceMinutes || 0,
|
||||
sessionCount: form.timings?.sessionCount || 0,
|
||||
roundsPlanned: form.timings?.roundsPlanned || 0,
|
||||
},
|
||||
stewarding: {
|
||||
decisionMode: (form.stewarding?.decisionMode as 'owner_only' | 'admin_vote' | 'steward_panel') || 'admin_only',
|
||||
requiredVotes: form.stewarding?.requiredVotes || 0,
|
||||
requireDefense: form.stewarding?.requireDefense ?? false,
|
||||
defenseTimeLimit: form.stewarding?.defenseTimeLimit || 0,
|
||||
voteTimeLimit: form.stewarding?.voteTimeLimit || 0,
|
||||
protestDeadlineHours: form.stewarding?.protestDeadlineHours || 0,
|
||||
stewardingClosesHours: form.stewarding?.stewardingClosesHours || 0,
|
||||
notifyAccusedOnProtest: form.stewarding?.notifyAccusedOnProtest ?? true,
|
||||
notifyOnVoteRequired: form.stewarding?.notifyOnVoteRequired ?? true,
|
||||
},
|
||||
};
|
||||
|
||||
const allErrors = LeagueWizardCommandModel.validateAllLeagueWizardSteps(formData);
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
...allErrors,
|
||||
}));
|
||||
|
||||
if (LeagueWizardCommandModel.hasWizardErrors(allErrors)) {
|
||||
onStepChange('basics');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setErrors((prev) => {
|
||||
const { submit, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
|
||||
try {
|
||||
// Use the mutation to create the league
|
||||
const result = await createLeagueMutation.mutateAsync({ form, ownerId });
|
||||
|
||||
// Clear the draft on successful creation
|
||||
clearFormStorage();
|
||||
|
||||
// Navigate to the new league
|
||||
router.push(`/leagues/${result.leagueId}`);
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : 'Failed to create league';
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
submit: message,
|
||||
}));
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handler for scoring preset selection (timings default from API)
|
||||
const handleScoringPresetChange = (patternId: string) => {
|
||||
setForm((prev) => {
|
||||
const selectedPreset = presets.find((p) => p.id === patternId);
|
||||
|
||||
return {
|
||||
...prev,
|
||||
scoring: {
|
||||
...prev.scoring,
|
||||
patternId,
|
||||
customScoringEnabled: false,
|
||||
},
|
||||
timings: selectedPreset
|
||||
? {
|
||||
...prev.timings,
|
||||
practiceMinutes: prev.timings?.practiceMinutes ?? selectedPreset.defaultTimings.practiceMinutes,
|
||||
qualifyingMinutes: prev.timings?.qualifyingMinutes ?? selectedPreset.defaultTimings.qualifyingMinutes,
|
||||
sprintRaceMinutes: prev.timings?.sprintRaceMinutes ?? selectedPreset.defaultTimings.sprintRaceMinutes,
|
||||
mainRaceMinutes: prev.timings?.mainRaceMinutes ?? selectedPreset.defaultTimings.mainRaceMinutes,
|
||||
sessionCount: selectedPreset.defaultTimings.sessionCount,
|
||||
}
|
||||
: prev.timings,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const steps = [
|
||||
{ id: 1 as Step, label: 'Basics', icon: FileText, shortLabel: 'Name' },
|
||||
{ id: 2 as Step, label: 'Visibility', icon: Award, shortLabel: 'Type' },
|
||||
{ id: 3 as Step, label: 'Structure', icon: Users, shortLabel: 'Mode' },
|
||||
{ id: 4 as Step, label: 'Schedule', icon: Calendar, shortLabel: 'Time' },
|
||||
{ id: 5 as Step, label: 'Scoring', icon: Trophy, shortLabel: 'Points' },
|
||||
{ id: 6 as Step, label: 'Stewarding', icon: Scale, shortLabel: 'Rules' },
|
||||
{ id: 7 as Step, label: 'Review', icon: CheckCircle2, shortLabel: 'Done' },
|
||||
];
|
||||
|
||||
const getStepTitle = (currentStep: Step): string => {
|
||||
switch (currentStep) {
|
||||
case 1:
|
||||
return 'Name your league';
|
||||
case 2:
|
||||
return 'Choose your destiny';
|
||||
case 3:
|
||||
return 'Choose the structure';
|
||||
case 4:
|
||||
return 'Set the schedule';
|
||||
case 5:
|
||||
return 'Scoring & championships';
|
||||
case 6:
|
||||
return 'Stewarding & protests';
|
||||
case 7:
|
||||
return 'Review & create';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const getStepSubtitle = (currentStep: Step): string => {
|
||||
switch (currentStep) {
|
||||
case 1:
|
||||
return 'Give your league a memorable name and tell your story.';
|
||||
case 2:
|
||||
return 'Will you compete for global rankings or race with friends?';
|
||||
case 3:
|
||||
return 'Define how races in this season will run.';
|
||||
case 4:
|
||||
return 'Plan when this season’s races happen.';
|
||||
case 5:
|
||||
return 'Choose how points and drop scores work for this season.';
|
||||
case 6:
|
||||
return 'Set how protests and stewarding work for this season.';
|
||||
case 7:
|
||||
return 'Review your league and first season before launching.';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const getStepContextLabel = (currentStep: Step): string => {
|
||||
if (currentStep === 1 || currentStep === 2) {
|
||||
return 'League setup';
|
||||
}
|
||||
if (currentStep >= 3 && currentStep <= 6) {
|
||||
return 'Season setup';
|
||||
}
|
||||
return 'League & Season summary';
|
||||
};
|
||||
|
||||
const currentStepData = steps.find((s) => s.id === step);
|
||||
const CurrentStepIcon = currentStepData?.icon ?? FileText;
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl mx-auto pb-8">
|
||||
{/* Header with icon */}
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-primary-blue/5 border border-primary-blue/20">
|
||||
<Sparkles className="w-5 h-5 text-primary-blue" />
|
||||
</div>
|
||||
<div>
|
||||
<Heading level={1} className="text-2xl sm:text-3xl">
|
||||
Create a new league
|
||||
</Heading>
|
||||
<p className="text-sm text-gray-500">
|
||||
We'll also set up your first season in {steps.length} easy steps.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
A league is your long-term brand. Each season is a block of races you can run again and again.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Desktop Progress Bar */}
|
||||
<div className="hidden md:block mb-8">
|
||||
<div className="relative">
|
||||
{/* Background track */}
|
||||
<div className="absolute top-5 left-6 right-6 h-0.5 bg-charcoal-outline rounded-full" />
|
||||
{/* Progress fill */}
|
||||
<div
|
||||
className="absolute top-5 left-6 h-0.5 bg-gradient-to-r from-primary-blue to-neon-aqua rounded-full transition-all duration-500 ease-out"
|
||||
style={{ width: `calc(${((step - 1) / (steps.length - 1)) * 100}% - 48px)` }}
|
||||
/>
|
||||
|
||||
<div className="relative flex justify-between">
|
||||
{steps.map((wizardStep) => {
|
||||
const isCompleted = wizardStep.id < step;
|
||||
const isCurrent = wizardStep.id === step;
|
||||
const isAccessible = wizardStep.id <= highestCompletedStep;
|
||||
const StepIcon = wizardStep.icon;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={wizardStep.id}
|
||||
type="button"
|
||||
onClick={() => goToStep(wizardStep.id)}
|
||||
disabled={!isAccessible}
|
||||
className="flex flex-col items-center bg-transparent border-0 cursor-pointer disabled:cursor-not-allowed"
|
||||
>
|
||||
<div
|
||||
className={`
|
||||
relative z-10 flex h-10 w-10 items-center justify-center rounded-full
|
||||
transition-all duration-300 ease-out
|
||||
${isCurrent
|
||||
? 'bg-primary-blue text-white shadow-[0_0_24px_rgba(25,140,255,0.5)] scale-110'
|
||||
: isCompleted
|
||||
? 'bg-primary-blue text-white hover:scale-105'
|
||||
: isAccessible
|
||||
? 'bg-iron-gray text-gray-400 border-2 border-charcoal-outline hover:border-primary-blue/50'
|
||||
: 'bg-iron-gray text-gray-500 border-2 border-charcoal-outline opacity-60'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{isCompleted ? (
|
||||
<Check className="w-4 h-4" strokeWidth={3} />
|
||||
) : (
|
||||
<StepIcon className="w-4 h-4" />
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2 text-center">
|
||||
<p
|
||||
className={`text-xs font-medium transition-colors duration-200 ${
|
||||
isCurrent
|
||||
? 'text-white'
|
||||
: isCompleted
|
||||
? 'text-primary-blue'
|
||||
: isAccessible
|
||||
? 'text-gray-400'
|
||||
: 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{wizardStep.label}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mobile Progress */}
|
||||
<div className="md:hidden mb-6">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<CurrentStepIcon className="w-4 h-4 text-primary-blue" />
|
||||
<span className="text-sm font-medium text-white">{currentStepData?.label}</span>
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">
|
||||
{step}/{steps.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 bg-charcoal-outline rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-gradient-to-r from-primary-blue to-neon-aqua rounded-full transition-all duration-500 ease-out"
|
||||
style={{ width: `${(step / steps.length) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
{/* Step dots */}
|
||||
<div className="flex justify-between mt-2 px-0.5">
|
||||
{steps.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`
|
||||
h-1.5 rounded-full transition-all duration-300
|
||||
${s.id === step
|
||||
? 'w-4 bg-primary-blue'
|
||||
: s.id < step
|
||||
? 'w-1.5 bg-primary-blue/60'
|
||||
: 'w-1.5 bg-charcoal-outline'
|
||||
}
|
||||
`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Card */}
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Top gradient accent */}
|
||||
<div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-primary-blue to-transparent" />
|
||||
|
||||
{/* Step header */}
|
||||
<div className="flex items-start gap-4 mb-6">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary-blue/10 shrink-0 transition-transform duration-300">
|
||||
<CurrentStepIcon className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<Heading level={2} className="text-xl sm:text-2xl text-white leading-tight">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span>{getStepTitle(step)}</span>
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-full border border-charcoal-outline bg-iron-gray/60 text-[11px] font-medium text-gray-300">
|
||||
{getStepContextLabel(step)}
|
||||
</span>
|
||||
</div>
|
||||
</Heading>
|
||||
<p className="text-sm text-gray-400 mt-1">
|
||||
{getStepSubtitle(step)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-deep-graphite border border-charcoal-outline">
|
||||
<span className="text-xs text-gray-500">Step</span>
|
||||
<span className="text-sm font-semibold text-white">{step}</span>
|
||||
<span className="text-xs text-gray-500">/ {steps.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-px bg-gradient-to-r from-transparent via-charcoal-outline to-transparent mb-6" />
|
||||
|
||||
{/* Step content with min-height for consistency */}
|
||||
<div className="min-h-[320px]">
|
||||
{step === 1 && (
|
||||
<div className="animate-fade-in space-y-8">
|
||||
<LeagueBasicsSection
|
||||
form={form}
|
||||
onChange={setForm}
|
||||
errors={errors.basics ?? {}}
|
||||
/>
|
||||
<div className="rounded-xl border border-charcoal-outline bg-iron-gray/40 p-4">
|
||||
<div className="flex items-center justify-between gap-2 mb-2">
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-gray-300 uppercase tracking-wide">
|
||||
First season
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Name the first season that will run in this league.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mt-2">
|
||||
<label className="text-sm font-medium text-gray-300">
|
||||
Season name
|
||||
</label>
|
||||
<Input
|
||||
value={form.seasonName ?? ''}
|
||||
onChange={(e) =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
seasonName: e.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder="e.g., Season 1 (2025)"
|
||||
/>
|
||||
<p className="text-xs text-gray-500">
|
||||
Seasons are the individual competitive runs inside your league. You can run Season 2, Season 3, or parallel seasons later.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<div className="animate-fade-in">
|
||||
<LeagueVisibilitySection
|
||||
form={form}
|
||||
onChange={setForm}
|
||||
errors={
|
||||
errors.basics?.visibility
|
||||
? { visibility: errors.basics.visibility }
|
||||
: {}
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<div className="animate-fade-in space-y-4">
|
||||
<div className="mb-2">
|
||||
<p className="text-xs text-gray-500">
|
||||
Applies to: First season of this league.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
These settings only affect this season. Future seasons can use different formats.
|
||||
</p>
|
||||
</div>
|
||||
<LeagueStructureSection
|
||||
form={form}
|
||||
onChange={setForm}
|
||||
readOnly={false}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 4 && (
|
||||
<div className="animate-fade-in space-y-4">
|
||||
<div className="mb-2">
|
||||
<p className="text-xs text-gray-500">
|
||||
Applies to: First season of this league.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
These settings only affect this season. Future seasons can use different formats.
|
||||
</p>
|
||||
</div>
|
||||
<LeagueTimingsSection
|
||||
form={form}
|
||||
onChange={setForm}
|
||||
errors={errors.timings ?? {}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 5 && (
|
||||
<div className="animate-fade-in space-y-8">
|
||||
<div className="mb-2">
|
||||
<p className="text-xs text-gray-500">
|
||||
Applies to: First season of this league.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
These settings only affect this season. Future seasons can use different formats.
|
||||
</p>
|
||||
</div>
|
||||
{/* Scoring Pattern Selection */}
|
||||
<ScoringPatternSection
|
||||
scoring={form.scoring || {}}
|
||||
presets={presets}
|
||||
readOnly={presetsLoading}
|
||||
patternError={errors.scoring?.patternId ?? ''}
|
||||
onChangePatternId={handleScoringPresetChange}
|
||||
onToggleCustomScoring={() =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
scoring: {
|
||||
...prev.scoring,
|
||||
customScoringEnabled: !(prev.scoring?.customScoringEnabled),
|
||||
},
|
||||
}))
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-px bg-gradient-to-r from-transparent via-charcoal-outline to-transparent" />
|
||||
|
||||
{/* Championships & Drop Rules side by side on larger screens */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<ChampionshipsSection form={form} onChange={setForm} readOnly={presetsLoading} />
|
||||
<LeagueDropSection form={form} onChange={setForm} readOnly={false} />
|
||||
</div>
|
||||
|
||||
{errors.submit && (
|
||||
<div className="flex items-start gap-3 rounded-lg bg-warning-amber/10 p-4 border border-warning-amber/20">
|
||||
<AlertCircle className="w-5 h-5 text-warning-amber shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-warning-amber">{errors.submit}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 6 && (
|
||||
<div className="animate-fade-in space-y-4">
|
||||
<div className="mb-2">
|
||||
<p className="text-xs text-gray-500">
|
||||
Applies to: First season of this league.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
These settings only affect this season. Future seasons can use different formats.
|
||||
</p>
|
||||
</div>
|
||||
<LeagueStewardingSection
|
||||
form={form}
|
||||
onChange={setForm}
|
||||
readOnly={false}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 7 && (
|
||||
<div className="animate-fade-in space-y-6">
|
||||
<LeagueReviewSummary form={form} presets={presets} />
|
||||
{errors.submit && (
|
||||
<div className="flex items-start gap-3 rounded-lg bg-warning-amber/10 p-4 border border-warning-amber/20">
|
||||
<AlertCircle className="w-5 h-5 text-warning-amber shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-warning-amber">{errors.submit}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex justify-between items-center mt-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={step === 1 || loading}
|
||||
onClick={goToPreviousStep}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Back</span>
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Mobile step dots */}
|
||||
<div className="flex sm:hidden items-center gap-1">
|
||||
{steps.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`
|
||||
h-1.5 rounded-full transition-all duration-300
|
||||
${s.id === step ? 'w-3 bg-primary-blue' : s.id < step ? 'w-1.5 bg-primary-blue/50' : 'w-1.5 bg-charcoal-outline'}
|
||||
`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{step < 7 ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={loading}
|
||||
onClick={goToNextStep}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<span>Continue</span>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2 min-w-[150px] justify-center"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>Creating…</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="w-4 h-4" />
|
||||
<span>Create League</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Helper text */}
|
||||
<p className="text-center text-xs text-gray-500 mt-4">
|
||||
This will create your league and its first season. You can edit both later.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
68
apps/website/app/onboarding/OnboardingWizardClient.tsx
Normal file
68
apps/website/app/onboarding/OnboardingWizardClient.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
import { OnboardingWizard } from './OnboardingWizard';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
import { completeOnboardingAction } from '@/app/onboarding/completeOnboardingAction';
|
||||
import { generateAvatarsAction } from '@/app/onboarding/generateAvatarsAction';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
|
||||
export function OnboardingWizardClient() {
|
||||
const { session } = useAuth();
|
||||
|
||||
const handleCompleteOnboarding = async (input: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
country: string;
|
||||
timezone?: string;
|
||||
}) => {
|
||||
try {
|
||||
const result = await completeOnboardingAction(input);
|
||||
|
||||
if (result.isErr()) {
|
||||
return { success: false, error: result.getError() };
|
||||
}
|
||||
|
||||
window.location.href = routes.protected.dashboard;
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: 'Failed to complete onboarding' };
|
||||
}
|
||||
};
|
||||
|
||||
const handleGenerateAvatars = async (params: {
|
||||
facePhotoData: string;
|
||||
suitColor: string;
|
||||
}) => {
|
||||
if (!session?.user?.userId) {
|
||||
return { success: false, error: 'Not authenticated' };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await generateAvatarsAction({
|
||||
userId: session.user.userId,
|
||||
facePhotoData: params.facePhotoData,
|
||||
suitColor: params.suitColor,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
return { success: false, error: result.getError() };
|
||||
}
|
||||
|
||||
const data = result.unwrap();
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
return { success: false, error: 'Failed to generate avatars' };
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<OnboardingWizard
|
||||
onCompleted={() => {
|
||||
window.location.href = routes.protected.dashboard;
|
||||
}}
|
||||
onCompleteOnboarding={handleCompleteOnboarding}
|
||||
onGenerateAvatars={handleGenerateAvatars}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +1,55 @@
|
||||
import Link from 'next/link';
|
||||
import Button from '@/ui/Button';
|
||||
import Card from '@/ui/Card';
|
||||
import Container from '@/ui/Container';
|
||||
import Heading from '@/ui/Heading';
|
||||
import { Button } from '@/ui/Button';
|
||||
import { Card } from '@/ui/Card';
|
||||
import { Container } from '@/ui/Container';
|
||||
import { Heading } from '@/ui/Heading';
|
||||
import { Grid } from '@/ui/Grid';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
import { LiveryCard } from '@/components/profile/LiveryCard';
|
||||
|
||||
export default async function ProfileLiveriesPage() {
|
||||
const mockLiveries = [
|
||||
{
|
||||
id: '1',
|
||||
carId: 'gt3-r',
|
||||
carName: 'Porsche 911 GT3 R (992)',
|
||||
thumbnailUrl: '',
|
||||
uploadedAt: new Date(),
|
||||
isValidated: true,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
carId: 'f3',
|
||||
carName: 'Dallara F3',
|
||||
thumbnailUrl: '',
|
||||
uploadedAt: new Date(),
|
||||
isValidated: false,
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<Container size="md">
|
||||
<Heading level={1}>Liveries</Heading>
|
||||
<Card>
|
||||
<p>Livery management is currently unavailable.</p>
|
||||
<Link href={routes.protected.profile}>
|
||||
<Button variant="secondary">Back to profile</Button>
|
||||
</Link>
|
||||
<Container size="lg" py={8}>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<Heading level={1}>My Liveries</Heading>
|
||||
<p className="text-gray-400 mt-1">Manage your custom car liveries</p>
|
||||
</div>
|
||||
<Link href={routes.protected.profileLiveryUpload}>
|
||||
<Button variant="primary">Upload livery</Button>
|
||||
</Link>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Grid cols={3} gap={6}>
|
||||
{mockLiveries.map((livery) => (
|
||||
<LiveryCard key={livery.id} livery={livery} />
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
<div className="mt-12">
|
||||
<Link href={routes.protected.profile}>
|
||||
<Button variant="secondary">Back to profile</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user