This commit is contained in:
2026-01-15 01:26:30 +01:00
parent 4a2d7d15a5
commit c3b308e960
102 changed files with 2532 additions and 4744 deletions

View File

@@ -1,34 +0,0 @@
import Card from '@/ui/Card';
interface BonusPointsCardProps {
bonusSummary: string[];
}
export function BonusPointsCard({ bonusSummary }: BonusPointsCardProps) {
if (!bonusSummary || bonusSummary.length === 0) {
return null;
}
return (
<Card>
<div className="mb-4">
<h3 className="text-lg font-semibold text-white">Bonus Points</h3>
<p className="text-sm text-gray-400 mt-1">Additional points for special achievements</p>
</div>
<div className="space-y-3">
{bonusSummary.map((bonus, idx) => (
<div
key={idx}
className="flex items-center gap-4 p-4 bg-deep-graphite rounded-lg border border-charcoal-outline transition-colors hover:border-primary-blue/30"
>
<div className="w-10 h-10 rounded-full bg-performance-green/10 border border-performance-green/20 flex items-center justify-center shrink-0">
<span className="text-performance-green text-lg font-bold">+</span>
</div>
<p className="text-sm text-gray-300 flex-1">{bonus}</p>
</div>
))}
</div>
</Card>
);
}

View File

@@ -1,103 +0,0 @@
import Card from '@/ui/Card';
import type { LeagueScoringChampionshipViewModel } from '@/lib/view-models/LeagueScoringChampionshipViewModel';
type PointsPreviewRow = {
sessionType: string;
position: number;
points: number;
};
interface ChampionshipCardProps {
championship: LeagueScoringChampionshipViewModel;
}
export function ChampionshipCard({ championship }: ChampionshipCardProps) {
const pointsPreview = (championship.pointsPreview as unknown as PointsPreviewRow[]) ?? [];
const dropPolicyDescription = (championship as unknown as { dropPolicyDescription?: string }).dropPolicyDescription ?? '';
const getTypeLabel = (type: string): string => {
switch (type) {
case 'driver':
return 'Driver Championship';
case 'team':
return 'Team Championship';
case 'nations':
return 'Nations Championship';
case 'trophy':
return 'Trophy Championship';
default:
return 'Championship';
}
};
const getTypeBadgeStyle = (type: string): string => {
switch (type) {
case 'driver':
return 'bg-primary-blue/10 text-primary-blue border-primary-blue/20';
case 'team':
return 'bg-purple-500/10 text-purple-400 border-purple-500/20';
case 'nations':
return 'bg-performance-green/10 text-performance-green border-performance-green/20';
case 'trophy':
return 'bg-warning-amber/10 text-warning-amber border-warning-amber/20';
default:
return 'bg-gray-500/10 text-gray-400 border-gray-500/20';
}
};
return (
<Card>
<div className="flex items-center justify-between mb-6">
<div>
<h3 className="text-lg font-semibold text-white">{championship.name}</h3>
<span className={`inline-block mt-2 px-2.5 py-1 text-xs font-medium rounded border ${getTypeBadgeStyle(championship.type)}`}>
{getTypeLabel(championship.type)}
</span>
</div>
</div>
<div className="space-y-4">
{/* Session Types */}
{championship.sessionTypes.length > 0 && (
<div>
<h4 className="text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Scored Sessions</h4>
<div className="flex flex-wrap gap-2">
{championship.sessionTypes.map((session, idx) => (
<span
key={idx}
className="px-3 py-1.5 rounded bg-deep-graphite text-gray-300 text-sm font-medium border border-charcoal-outline capitalize"
>
{session}
</span>
))}
</div>
</div>
)}
{/* Points Preview */}
{pointsPreview.length > 0 && (
<div>
<h4 className="text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Points Distribution</h4>
<div className="bg-deep-graphite rounded-lg border border-charcoal-outline p-4">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3">
{pointsPreview.slice(0, 6).map((preview, idx) => (
<div key={idx} className="text-center">
<div className="text-xs text-gray-500 mb-1">P{preview.position}</div>
<div className="text-lg font-bold text-white tabular-nums">{preview.points}</div>
</div>
))}
</div>
</div>
</div>
)}
{/* Drop Policy */}
<div className="p-4 bg-deep-graphite rounded-lg border border-charcoal-outline">
<div className="flex items-center gap-2 mb-2">
<span className="text-xs font-medium text-gray-500 uppercase tracking-wider">Drop Policy</span>
</div>
<p className="text-sm text-gray-300">{dropPolicyDescription}</p>
</div>
</div>
</Card>
);
}

View File

@@ -1,192 +0,0 @@
'use client';
import { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import Input from '../ui/Input';
import Button from '../ui/Button';
import { useCreateLeague } from "@/lib/hooks/league/useCreateLeague";
import { useAuth } from '@/lib/auth/AuthContext';
import { useInject } from '@/lib/di/hooks/useInject';
import { DRIVER_SERVICE_TOKEN } from '@/lib/di/tokens';
interface FormErrors {
name?: string;
description?: string;
pointsSystem?: string;
sessionDuration?: string;
submit?: string;
}
export default function CreateLeagueForm() {
const router = useRouter();
const [errors, setErrors] = useState<FormErrors>({});
const [formData, setFormData] = useState({
name: '',
description: '',
pointsSystem: 'f1-2024' as 'f1-2024' | 'indycar',
sessionDuration: 60
});
const validateForm = (): boolean => {
const newErrors: FormErrors = {};
if (!formData.name.trim()) {
newErrors.name = 'Name is required';
} else if (formData.name.length > 100) {
newErrors.name = 'Name must be 100 characters or less';
}
if (!formData.description.trim()) {
newErrors.description = 'Description is required';
} else if (formData.description.length > 500) {
newErrors.description = 'Description must be 500 characters or less';
}
if (formData.sessionDuration < 1 || formData.sessionDuration > 240) {
newErrors.sessionDuration = 'Session duration must be between 1 and 240 minutes';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const { session } = useAuth();
const driverService = useInject(DRIVER_SERVICE_TOKEN);
const createLeagueMutation = useCreateLeague();
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
if (createLeagueMutation.isPending) return;
if (!validateForm()) return;
if (!session?.user.userId) {
setErrors({ submit: 'You must be logged in to create a league' });
return;
}
try {
// Get current driver
const currentDriver = await driverService.getDriverProfile(session.user.userId);
if (!currentDriver) {
setErrors({ submit: 'No driver profile found. Please create a profile first.' });
return;
}
// Create league using the league service
const input = {
name: formData.name.trim(),
description: formData.description.trim(),
visibility: 'public' as const,
ownerId: session.user.userId,
};
const result = await createLeagueMutation.mutateAsync(input);
router.push(`/leagues/${result.leagueId}`);
router.refresh();
} catch (error) {
setErrors({
submit: error instanceof Error ? error.message : 'Failed to create league'
});
}
};
return (
<>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="name" className="block text-sm font-medium text-gray-300 mb-2">
League Name *
</label>
<Input
id="name"
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
error={!!errors.name}
errorMessage={errors.name}
placeholder="European GT Championship"
maxLength={100}
disabled={createLeagueMutation.isPending}
/>
<p className="mt-1 text-xs text-gray-500 text-right">
{formData.name.length}/100
</p>
</div>
<div>
<label htmlFor="description" className="block text-sm font-medium text-gray-300 mb-2">
Description *
</label>
<textarea
id="description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Weekly GT3 racing with professional drivers"
maxLength={500}
rows={4}
disabled={createLeagueMutation.isPending}
className="block w-full rounded-md border-0 px-4 py-3 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm sm:leading-6 resize-none"
/>
<p className="mt-1 text-xs text-gray-500 text-right">
{formData.description.length}/500
</p>
{errors.description && (
<p className="mt-2 text-sm text-warning-amber">{errors.description}</p>
)}
</div>
<div>
<label htmlFor="pointsSystem" className="block text-sm font-medium text-gray-300 mb-2">
Points System *
</label>
<select
id="pointsSystem"
value={formData.pointsSystem}
onChange={(e) => setFormData({ ...formData, pointsSystem: e.target.value as 'f1-2024' | 'indycar' })}
disabled={createLeagueMutation.isPending}
className="block w-full rounded-md border-0 px-4 py-3 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm sm:leading-6"
>
<option value="f1-2024">F1 2024</option>
<option value="indycar">IndyCar</option>
</select>
</div>
<div>
<label htmlFor="sessionDuration" className="block text-sm font-medium text-gray-300 mb-2">
Session Duration (minutes) *
</label>
<Input
id="sessionDuration"
type="number"
value={formData.sessionDuration}
onChange={(e) => setFormData({ ...formData, sessionDuration: parseInt(e.target.value) || 60 })}
error={!!errors.sessionDuration}
errorMessage={errors.sessionDuration}
min={1}
max={240}
disabled={createLeagueMutation.isPending}
/>
</div>
{errors.submit && (
<div className="rounded-md bg-warning-amber/10 p-4 border border-warning-amber/20">
<p className="text-sm text-warning-amber">{errors.submit}</p>
</div>
)}
<Button
type="submit"
variant="primary"
disabled={createLeagueMutation.isPending}
className="w-full"
>
{createLeagueMutation.isPending ? 'Creating League...' : 'Create League'}
</Button>
</form>
</>
);
}

View File

@@ -1,985 +0,0 @@
'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 seasons 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>
);
}

View File

@@ -1,31 +0,0 @@
import Card from '@/ui/Card';
interface DropRulesExplanationProps {
dropPolicyDescription: string;
}
export function DropRulesExplanation({ dropPolicyDescription }: DropRulesExplanationProps) {
// Don't show if all results count
const hasDropRules = !dropPolicyDescription.toLowerCase().includes('all results count');
if (!hasDropRules) {
return null;
}
return (
<Card>
<div className="mb-4">
<h3 className="text-lg font-semibold text-white">Drop Score Rules</h3>
<p className="text-sm text-gray-400 mt-1">How your worst results are handled</p>
</div>
<div className="p-4 bg-deep-graphite rounded-lg border border-charcoal-outline">
<p className="text-sm text-gray-300">{dropPolicyDescription}</p>
</div>
<p className="mt-4 text-xs text-gray-500">
Drop rules are applied automatically when calculating championship standings. Focus on racing the system handles the rest.
</p>
</Card>
);
}

View File

@@ -1,13 +1,17 @@
import { Trophy, Sparkles, Search } from 'lucide-react';
import Heading from '@/ui/Heading';
import Button from '@/ui/Button';
import Card from '@/ui/Card';
import { Trophy, Sparkles, LucideIcon } from 'lucide-react';
import { Heading } from '@/ui/Heading';
import { Button } from '@/ui/Button';
import { Card } from '@/ui/Card';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Icon } from '@/ui/Icon';
interface EmptyStateProps {
title: string;
description: string;
icon?: React.ElementType;
actionIcon?: React.ElementType;
icon?: LucideIcon;
actionIcon?: LucideIcon;
actionLabel?: string;
onAction?: () => void;
children?: React.ReactNode;
@@ -17,37 +21,43 @@ interface EmptyStateProps {
export function EmptyState({
title,
description,
icon: Icon = Trophy,
actionIcon: ActionIcon = Sparkles,
icon = Trophy,
actionIcon = Sparkles,
actionLabel,
onAction,
children,
className,
}: EmptyStateProps) {
return (
<Card className={`text-center py-16 ${className || ''}`}>
<div className="max-w-md mx-auto">
<div className="flex h-16 w-16 mx-auto items-center justify-center rounded-2xl bg-primary-blue/10 border border-primary-blue/20 mb-6">
<Icon className="w-8 h-8 text-primary-blue" />
</div>
<Heading level={2} className="text-2xl mb-3">
{title}
</Heading>
<p className="text-gray-400 mb-8">
{description}
</p>
{children}
{actionLabel && onAction && (
<Button
variant="primary"
onClick={onAction}
className="flex items-center gap-2 mx-auto"
>
<ActionIcon className="w-4 h-4" />
{actionLabel}
</Button>
)}
</div>
<Card className={className}>
<Box textAlign="center" py={16}>
<Box maxWidth="md" mx="auto">
<Box height={16} width={16} mx="auto" display="flex" center rounded="2xl" backgroundColor="primary-blue" opacity={0.1} border borderColor="primary-blue" mb={6}>
<Icon icon={icon} size={8} color="text-primary-blue" />
</Box>
<Box mb={3}>
<Heading level={2}>
{title}
</Heading>
</Box>
<Box mb={8}>
<Text color="text-gray-400">
{description}
</Text>
</Box>
{children}
{actionLabel && onAction && (
<Button
variant="primary"
onClick={onAction}
icon={<Icon icon={actionIcon} size={4} />}
className="mx-auto"
>
{actionLabel}
</Button>
)}
</Box>
</Box>
</Card>
);
}
}

View File

@@ -1,85 +0,0 @@
import { Trophy, Plus } from 'lucide-react';
import Heading from '@/ui/Heading';
import Button from '@/ui/Button';
interface StatItem {
value: number;
label: string;
color: string;
animate?: boolean;
}
interface HeroSectionProps {
icon?: React.ElementType;
title: string;
description: string;
stats?: StatItem[];
ctaLabel?: string;
ctaDescription?: string;
onCtaClick?: () => void;
className?: string;
}
export function HeroSection({
icon: Icon = Trophy,
title,
description,
stats = [],
ctaLabel = "Create League",
ctaDescription = "Set up your own racing series",
onCtaClick,
className,
}: HeroSectionProps) {
return (
<div className={`relative mb-10 py-10 px-8 rounded-2xl bg-gradient-to-br from-iron-gray/80 via-deep-graphite to-iron-gray/60 border border-charcoal-outline/50 overflow-hidden ${className || ''}`}>
{/* Background decoration */}
<div className="absolute top-0 right-0 w-96 h-96 bg-primary-blue/5 rounded-full blur-3xl" />
<div className="absolute bottom-0 left-0 w-64 h-64 bg-neon-aqua/5 rounded-full blur-3xl" />
<div className="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-8">
<div className="max-w-2xl">
<div className="flex items-center gap-3 mb-4">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-primary-blue/5 border border-primary-blue/20">
<Icon className="w-6 h-6 text-primary-blue" />
</div>
<Heading level={1} className="text-3xl lg:text-4xl">
{title}
</Heading>
</div>
<p className="text-gray-400 text-lg leading-relaxed mb-6">
{description}
</p>
{/* Stats */}
{stats.length > 0 && (
<div className="flex flex-wrap gap-6">
{stats.map((stat, index) => (
<div key={index} className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${stat.color} ${stat.animate ? 'animate-pulse' : ''}`} />
<span className="text-sm text-gray-400">
<span className="text-white font-semibold">{stat.value}</span> {stat.label}
</span>
</div>
))}
</div>
)}
</div>
{/* CTA */}
{onCtaClick && (
<div className="flex flex-col gap-4">
<Button
variant="primary"
onClick={onCtaClick}
className="flex items-center gap-2 px-6 py-3"
>
<Plus className="w-5 h-5" />
<span>{ctaLabel}</span>
</Button>
<p className="text-xs text-gray-500 text-center">{ctaDescription}</p>
</div>
)}
</div>
</div>
);
}

View File

@@ -2,8 +2,16 @@
import React from 'react';
import { FileText, Gamepad2, AlertCircle, Check } from 'lucide-react';
import Input from '@/ui/Input';
import { Input } from '@/ui/Input';
import type { LeagueConfigFormModel } from '@/lib/types/LeagueConfigFormModel';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Heading } from '@/ui/Heading';
import { Icon } from '@/ui/Icon';
import { Grid } from '@/ui/Grid';
import { Surface } from '@/ui/Surface';
import { Button } from '@/ui/Button';
interface LeagueBasicsSectionProps {
form: LeagueConfigFormModel;
@@ -36,126 +44,135 @@ export function LeagueBasicsSection({
};
return (
<div className="space-y-8">
<Stack gap={8}>
{/* Emotional header for the step */}
<div className="text-center pb-2">
<h3 className="text-lg font-semibold text-white mb-2">
Every great championship starts with a name
</h3>
<p className="text-sm text-gray-400 max-w-lg mx-auto">
This is where legends begin. Give your league an identity that drivers will remember.
</p>
</div>
<Box textAlign="center" pb={2}>
<Box mb={2}>
<Heading level={3}>
Every great championship starts with a name
</Heading>
</Box>
<Box maxWidth="lg" mx="auto">
<Text size="sm" color="text-gray-400">
This is where legends begin. Give your league an identity that drivers will remember.
</Text>
</Box>
</Box>
{/* League name */}
<div className="space-y-3">
<label className="flex items-center gap-2 text-sm font-medium text-gray-300">
<FileText className="w-4 h-4 text-primary-blue" />
League name *
</label>
<Stack gap={3}>
<Text as="label" size="sm" weight="medium" color="text-gray-300">
<Stack direction="row" align="center" gap={2}>
<Icon icon={FileText} size={4} color="text-primary-blue" />
League name *
</Stack>
</Text>
<Input
value={basics.name}
onChange={(e) => updateBasics({ name: e.target.value })}
placeholder="e.g., GridPilot Sprint Series"
error={!!errors?.name}
variant={errors?.name ? 'error' : 'default'}
errorMessage={errors?.name}
disabled={disabled}
autoFocus
/>
<div className="space-y-2">
<p className="text-xs text-gray-500">
<Stack gap={2}>
<Text size="xs" color="text-gray-500">
Make it memorable this is what drivers will see first
</p>
<div className="flex flex-wrap gap-2">
<span className="text-xs text-gray-500">Try:</span>
<button
type="button"
onClick={() => updateBasics({ name: 'Sunday Showdown Series' })}
className="text-xs px-2 py-0.5 rounded-full bg-primary-blue/10 text-primary-blue hover:bg-primary-blue/20 transition-colors"
disabled={disabled}
>
Sunday Showdown Series
</button>
<button
type="button"
onClick={() => updateBasics({ name: 'Midnight Endurance League' })}
className="text-xs px-2 py-0.5 rounded-full bg-primary-blue/10 text-primary-blue hover:bg-primary-blue/20 transition-colors"
disabled={disabled}
>
Midnight Endurance League
</button>
<button
type="button"
onClick={() => updateBasics({ name: 'GT Masters Championship' })}
className="text-xs px-2 py-0.5 rounded-full bg-primary-blue/10 text-primary-blue hover:bg-primary-blue/20 transition-colors"
disabled={disabled}
>
GT Masters Championship
</button>
</div>
</div>
</div>
</Text>
<Stack direction="row" wrap gap={2}>
<Text size="xs" color="text-gray-500">Try:</Text>
{[
'Sunday Showdown Series',
'Midnight Endurance League',
'GT Masters Championship'
].map(name => (
<Button
key={name}
type="button"
onClick={() => updateBasics({ name })}
variant="secondary"
size="sm"
className="h-auto py-0.5 px-2 rounded-full text-xs"
disabled={disabled}
>
{name}
</Button>
))}
</Stack>
</Stack>
</Stack>
{/* Description - Now Required */}
<div className="space-y-3">
<label className="flex items-center gap-2 text-sm font-medium text-gray-300">
<FileText className="w-4 h-4 text-primary-blue" />
Tell your story *
</label>
<textarea
value={basics.description ?? ''}
onChange={(e) =>
updateBasics({
description: e.target.value,
})
}
rows={4}
disabled={disabled}
className={`block w-full rounded-md border-0 px-4 py-3 bg-iron-gray text-white shadow-sm ring-1 ring-inset placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue text-sm disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-150 ${
errors?.description ? 'ring-warning-amber' : 'ring-charcoal-outline'
}`}
placeholder="What makes your league special? Tell drivers what to expect..."
/>
<Stack gap={3}>
<Text as="label" size="sm" weight="medium" color="text-gray-300">
<Stack direction="row" align="center" gap={2}>
<Icon icon={FileText} size={4} color="text-primary-blue" />
Tell your story *
</Stack>
</Text>
<Box position="relative">
<textarea
value={basics.description ?? ''}
onChange={(e) =>
updateBasics({
description: e.target.value,
})
}
rows={4}
disabled={disabled}
className={`block w-full rounded-md border-0 px-4 py-3 bg-iron-gray text-white shadow-sm ring-1 ring-inset placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue text-sm disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-150 ${
errors?.description ? 'ring-warning-amber' : 'ring-charcoal-outline'
}`}
placeholder="What makes your league special? Tell drivers what to expect..."
/>
</Box>
{errors?.description && (
<p className="text-xs text-warning-amber flex items-center gap-1.5">
<AlertCircle className="w-3 h-3" />
{errors.description}
</p>
<Text size="xs" color="text-warning-amber">
<Stack direction="row" align="center" gap={1.5}>
<Icon icon={AlertCircle} size={3} />
{errors.description}
</Stack>
</Text>
)}
<div className="rounded-lg bg-iron-gray/50 border border-charcoal-outline/50 p-4 space-y-3">
<p className="text-xs text-gray-400">
<span className="font-medium text-gray-300">Great descriptions include:</span>
</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="flex items-start gap-2">
<Check className="w-3.5 h-3.5 text-performance-green shrink-0 mt-0.5" />
<span className="text-xs text-gray-400">Racing style & pace</span>
</div>
<div className="flex items-start gap-2">
<Check className="w-3.5 h-3.5 text-performance-green shrink-0 mt-0.5" />
<span className="text-xs text-gray-400">Schedule & timezone</span>
</div>
<div className="flex items-start gap-2">
<Check className="w-3.5 h-3.5 text-performance-green shrink-0 mt-0.5" />
<span className="text-xs text-gray-400">Community vibe</span>
</div>
</div>
</div>
</div>
<Surface variant="muted" rounded="lg" border padding={4}>
<Box mb={3}>
<Text size="xs" color="text-gray-400">
<Text weight="medium" color="text-gray-300">Great descriptions include:</Text>
</Text>
</Box>
<Grid cols={3} gap={3}>
{[
'Racing style & pace',
'Schedule & timezone',
'Community vibe'
].map(item => (
<Stack key={item} direction="row" align="start" gap={2}>
<Icon icon={Check} size={3.5} color="text-performance-green" className="mt-0.5" />
<Text size="xs" color="text-gray-400">{item}</Text>
</Stack>
))}
</Grid>
</Surface>
</Stack>
{/* Game Platform */}
<div className="space-y-2">
<label className="flex items-center gap-2 text-sm font-medium text-gray-300">
<Gamepad2 className="w-4 h-4 text-gray-400" />
Game platform
</label>
<div className="relative">
<Stack gap={2}>
<Text as="label" size="sm" weight="medium" color="text-gray-300">
<Stack direction="row" align="center" gap={2}>
<Icon icon={Gamepad2} size={4} color="text-gray-400" />
Game platform
</Stack>
</Text>
<Box position="relative">
<Input value="iRacing" disabled />
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-500">
More platforms soon
</div>
</div>
</div>
</div>
<Box position="absolute" right={3} top="50%" style={{ transform: 'translateY(-50%)' }}>
<Text size="xs" color="text-gray-500">
More platforms soon
</Text>
</Box>
</Box>
</Stack>
</Stack>
);
}
}

View File

@@ -0,0 +1,27 @@
/**
* LeagueCover
*
* Pure UI component for displaying league cover images.
* Renders an image with fallback on error.
*/
export interface LeagueCoverProps {
leagueId: string;
alt: string;
className?: string;
}
export function LeagueCover({ leagueId, alt, className = '' }: LeagueCoverProps) {
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={`/media/leagues/${leagueId}/cover`}
alt={alt}
className={`w-full h-48 object-cover ${className}`}
onError={(e) => {
// Fallback to default cover
(e.target as HTMLImageElement).src = '/default-league-cover.png';
}}
/>
);
}

View File

@@ -1,8 +1,8 @@
'use client';
import { useState, useRef, useCallback } from 'react';
import Card from '@/ui/Card';
import Button from '@/ui/Button';
import { Card } from '@/ui/Card';
import { Button } from '@/ui/Button';
import {
Move,
RotateCw,

View File

@@ -0,0 +1,30 @@
/**
* LeagueLogo
*
* Pure UI component for displaying league logos.
* Renders an optimized image with fallback on error.
*/
import Image from 'next/image';
export interface LeagueLogoProps {
leagueId: string;
alt: string;
className?: string;
}
export function LeagueLogo({ leagueId, alt, className = '' }: LeagueLogoProps) {
return (
<Image
src={`/media/leagues/${leagueId}/logo`}
alt={alt}
width={100}
height={100}
className={`object-contain ${className}`}
onError={(e) => {
// Fallback to default logo
(e.target as HTMLImageElement).src = '/default-league-logo.png';
}}
/>
);
}

View File

@@ -1,8 +1,8 @@
'use client';
import { useState } from 'react';
import Button from '../ui/Button';
import Input from '../ui/Input';
import { Button } from '@/ui/Button';
import { Input } from '@/ui/Input';
import { DollarSign, Calendar, User, TrendingUp } from 'lucide-react';
type FeeType = 'season' | 'monthly' | 'per_race';

View File

@@ -1,9 +1,16 @@
import React, { useState } from 'react';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import Button from '@/ui/Button';
import { DriverSummaryPill } from '@/components/profile/DriverSummaryPill';
import { Button } from '@/ui/Button';
import { UserCog } from 'lucide-react';
import { LeagueSettingsViewModel } from '@/lib/view-models/LeagueSettingsViewModel';
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Heading } from '@/ui/Heading';
import { Surface } from '@/ui/Surface';
import { Select } from '@/ui/Select';
import { Icon } from '@/ui/Icon';
interface LeagueOwnershipTransferProps {
settings: LeagueSettingsViewModel;
@@ -11,7 +18,7 @@ interface LeagueOwnershipTransferProps {
onTransferOwnership: (newOwnerId: string) => Promise<void>;
}
export default function LeagueOwnershipTransfer({
export function LeagueOwnershipTransfer({
settings,
currentDriverId,
onTransferOwnership
@@ -39,10 +46,12 @@ export default function LeagueOwnershipTransfer({
const ownerSummary = settings.owner;
return (
<div className="space-y-4">
<Stack gap={4}>
{/* League Owner */}
<div className="rounded-xl border border-charcoal-outline bg-gradient-to-br from-iron-gray/40 to-iron-gray/20 p-5">
<h3 className="text-sm font-semibold text-gray-400 mb-3">League Owner</h3>
<Surface variant="muted" rounded="xl" border padding={5}>
<Box mb={3}>
<Heading level={3}>League Owner</Heading>
</Box>
{ownerSummary ? (
<DriverSummaryPill
driver={new DriverViewModel({
@@ -58,20 +67,22 @@ export default function LeagueOwnershipTransfer({
rank={ownerSummary.rank}
/>
) : (
<p className="text-sm text-gray-500">Loading owner details...</p>
<Text size="sm" color="text-gray-500">Loading owner details...</Text>
)}
</div>
</Surface>
{/* Transfer Ownership - Owner Only */}
{settings.league.ownerId === currentDriverId && settings.members.length > 0 && (
<div className="rounded-xl border border-charcoal-outline bg-gradient-to-br from-iron-gray/40 to-iron-gray/20 p-5">
<div className="flex items-center gap-2 mb-3">
<UserCog className="w-4 h-4 text-gray-400" />
<h3 className="text-sm font-semibold text-gray-400">Transfer Ownership</h3>
</div>
<p className="text-xs text-gray-500 mb-4">
Transfer league ownership to another active member. You will become an admin.
</p>
<Surface variant="muted" rounded="xl" border padding={5}>
<Stack direction="row" align="center" gap={2} mb={3}>
<Icon icon={UserCog} size={4} color="text-gray-400" />
<Heading level={3}>Transfer Ownership</Heading>
</Stack>
<Box mb={4}>
<Text size="xs" color="text-gray-500">
Transfer league ownership to another active member. You will become an admin.
</Text>
</Box>
{!showTransferDialog ? (
<Button
@@ -81,21 +92,20 @@ export default function LeagueOwnershipTransfer({
Transfer Ownership
</Button>
) : (
<div className="space-y-3">
<select
<Stack gap={3}>
<Select
value={selectedNewOwner}
onChange={(e) => setSelectedNewOwner(e.target.value)}
className="w-full rounded-lg border border-charcoal-outline bg-charcoal-card px-3 py-2 text-sm text-white focus:border-primary-blue focus:outline-none"
>
<option value="">Select new owner...</option>
{settings.members.map((member) => (
<option key={member.driver.id} value={member.driver.id}>
{member.driver.name}
</option>
))}
</select>
options={[
{ value: '', label: 'Select new owner...' },
...settings.members.map((member) => ({
value: member.driver.id,
label: member.driver.name,
})),
]}
/>
<div className="flex gap-2">
<Stack direction="row" gap={2}>
<Button
variant="primary"
onClick={handleTransferOwnership}
@@ -113,11 +123,11 @@ export default function LeagueOwnershipTransfer({
>
Cancel
</Button>
</div>
</div>
</Stack>
</Stack>
)}
</div>
</Surface>
)}
</div>
</Stack>
);
}
}

View File

@@ -1,8 +1,8 @@
'use client';
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
import { useRegisterForRace } from "@/lib/hooks/race/useRegisterForRace";
import { useWithdrawFromRace } from "@/lib/hooks/race/useWithdrawFromRace";
import { useEffectiveDriverId } from "@/hooks/useEffectiveDriverId";
import { useRegisterForRace } from "@/hooks/race/useRegisterForRace";
import { useWithdrawFromRace } from "@/hooks/race/useWithdrawFromRace";
import { useRouter } from 'next/navigation';
import { useMemo, useState } from 'react';
import type { LeagueScheduleRaceViewModel } from '@/lib/view-models/LeagueScheduleViewModel';
@@ -10,7 +10,7 @@ import type { LeagueScheduleRaceViewModel } from '@/lib/view-models/LeagueSchedu
// Shared state components
import { StateContainer } from '@/components/shared/state/StateContainer';
import { EmptyState } from '@/components/shared/state/EmptyState';
import { useLeagueSchedule } from "@/lib/hooks/league/useLeagueSchedule";
import { useLeagueSchedule } from "@/hooks/league/useLeagueSchedule";
import { Calendar } from 'lucide-react';
interface LeagueScheduleProps {

File diff suppressed because it is too large Load Diff

View File

@@ -1,237 +0,0 @@
'use client';
import type { LeagueScoringConfigViewModel } from '@/lib/view-models/LeagueScoringConfigViewModel';
import { Trophy, Clock, Target, Zap, Info } from 'lucide-react';
type LeagueScoringConfigUi = LeagueScoringConfigViewModel & {
scoringPresetName?: string;
dropPolicySummary?: string;
championships?: Array<{
id: string;
name: string;
type: 'driver' | 'team' | 'nations' | 'trophy' | string;
sessionTypes: string[];
pointsPreview: Array<{ sessionType: string; position: number; points: number }>;
bonusSummary: string[];
dropPolicyDescription?: string;
}>;
};
interface LeagueScoringTabProps {
scoringConfig: LeagueScoringConfigViewModel | null;
practiceMinutes?: number;
qualifyingMinutes?: number;
sprintRaceMinutes?: number;
mainRaceMinutes?: number;
}
export default function LeagueScoringTab({
scoringConfig,
practiceMinutes,
qualifyingMinutes,
sprintRaceMinutes,
mainRaceMinutes,
}: LeagueScoringTabProps) {
if (!scoringConfig) {
return (
<div className="p-12 text-center">
<div className="w-16 h-16 mx-auto mb-4 rounded-full bg-purple-500/10 flex items-center justify-center">
<Target className="w-8 h-8 text-purple-400" />
</div>
<h3 className="text-lg font-semibold text-white mb-2">No Scoring System</h3>
<p className="text-sm text-gray-400">
Scoring configuration is not available for this league yet
</p>
</div>
);
}
const ui = scoringConfig as unknown as LeagueScoringConfigUi;
const championships = ui.championships ?? [];
const primaryChampionship =
championships.find((c) => c.type === 'driver') ??
championships[0];
const resolvedPractice = practiceMinutes ?? 20;
const resolvedQualifying = qualifyingMinutes ?? 30;
const resolvedSprint = sprintRaceMinutes;
const resolvedMain = mainRaceMinutes ?? 40;
return (
<div className="space-y-6">
<div className="border-b border-charcoal-outline pb-4 space-y-3">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-primary-blue/10 flex items-center justify-center">
<Trophy className="w-5 h-5 text-primary-blue" />
</div>
<div>
<h2 className="text-xl font-semibold text-white">
Scoring overview
</h2>
<p className="text-sm text-gray-400">
{scoringConfig.gameName}{' '}
{ui.scoringPresetName
? `${ui.scoringPresetName}`
: '• Custom scoring'}{' '}
{ui.dropPolicySummary ? `${ui.dropPolicySummary}` : ''}
</p>
</div>
</div>
{primaryChampionship && (
<div className="space-y-3 pt-3">
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-gray-400" />
<h3 className="text-sm font-medium text-gray-200">
Weekend structure & timings
</h3>
</div>
<div className="flex flex-wrap gap-2 text-xs">
{primaryChampionship.sessionTypes.map((session: string) => (
<span
key={session}
className="px-3 py-1 rounded-full bg-primary-blue/10 text-primary-blue border border-primary-blue/20 font-medium"
>
{session}
</span>
))}
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<div className="p-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
<p className="text-xs text-gray-400 mb-1">Practice</p>
<p className="text-sm font-medium text-white">
{resolvedPractice ? `${resolvedPractice} min` : '—'}
</p>
</div>
<div className="p-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
<p className="text-xs text-gray-400 mb-1">Qualifying</p>
<p className="text-sm font-medium text-white">{resolvedQualifying} min</p>
</div>
<div className="p-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
<p className="text-xs text-gray-400 mb-1">Sprint</p>
<p className="text-sm font-medium text-white">
{resolvedSprint ? `${resolvedSprint} min` : '—'}
</p>
</div>
<div className="p-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
<p className="text-xs text-gray-400 mb-1">Main race</p>
<p className="text-sm font-medium text-white">{resolvedMain} min</p>
</div>
</div>
</div>
)}
</div>
{championships.map((championship) => (
<div
key={championship.id}
className="border border-charcoal-outline rounded-lg bg-iron-gray/40 p-4 space-y-4"
>
<div className="flex items-center justify-between gap-4">
<div>
<h3 className="text-lg font-semibold text-white">
{championship.name}
</h3>
<p className="text-xs uppercase tracking-wide text-gray-500">
{championship.type === 'driver'
? 'Driver championship'
: championship.type === 'team'
? 'Team championship'
: championship.type === 'nations'
? 'Nations championship'
: 'Trophy championship'}
</p>
</div>
{championship.sessionTypes.length > 0 && (
<div className="flex flex-wrap gap-1 justify-end">
{championship.sessionTypes.map((session: string) => (
<span
key={session}
className="px-2 py-0.5 rounded-full bg-charcoal-outline/60 text-xs text-gray-200"
>
{session}
</span>
))}
</div>
)}
</div>
{championship.pointsPreview.length > 0 && (
<div>
<h4 className="text-xs font-semibold text-gray-400 mb-2">
Points preview (top positions)
</h4>
<div className="overflow-x-auto">
<table className="w-full text-xs">
<thead>
<tr className="border-b border-charcoal-outline/60">
<th className="text-left py-2 pr-2 text-gray-400">
Session
</th>
<th className="text-left py-2 px-2 text-gray-400">
Position
</th>
<th className="text-left py-2 px-2 text-gray-400">
Points
</th>
</tr>
</thead>
<tbody>
{championship.pointsPreview.map((row, index: number) => {
const typedRow = row as { sessionType: string; position: number; points: number };
return (
<tr
key={`${typedRow.sessionType}-${typedRow.position}-${index}`}
className="border-b border-charcoal-outline/30"
>
<td className="py-1.5 pr-2 text-gray-200">
{typedRow.sessionType}
</td>
<td className="py-1.5 px-2 text-gray-200">
P{typedRow.position}
</td>
<td className="py-1.5 px-2 text-white">
{typedRow.points}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
{championship.bonusSummary.length > 0 && (
<div className="p-3 bg-yellow-500/5 border border-yellow-500/20 rounded-lg">
<div className="flex items-center gap-2 mb-2">
<Zap className="w-4 h-4 text-yellow-400" />
<h4 className="text-xs font-semibold text-yellow-400">
Bonus points
</h4>
</div>
<ul className="list-disc list-inside text-xs text-gray-300 space-y-1">
{championship.bonusSummary.map((item: string, index: number) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
)}
<div className="p-3 bg-primary-blue/5 border border-primary-blue/20 rounded-lg">
<div className="flex items-center gap-2 mb-2">
<Info className="w-4 h-4 text-primary-blue" />
<h4 className="text-xs font-semibold text-primary-blue">
Drop score policy
</h4>
</div>
<p className="text-xs text-gray-300">
{championship.dropPolicyDescription ?? ''}
</p>
</div>
</div>
))}
</div>
);
}

View File

@@ -1,204 +0,0 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import type { LeagueSummaryViewModel } from '@/lib/view-models/LeagueSummaryViewModel';
import LeagueCard from '@/components/leagues/LeagueCard';
interface LeagueSliderProps {
title: string;
icon: React.ElementType;
description: string;
leagues: LeagueSummaryViewModel[];
onLeagueClick: (id: string) => void;
autoScroll?: boolean;
iconColor?: string;
scrollSpeedMultiplier?: number;
scrollDirection?: 'left' | 'right';
}
export const LeagueSlider = ({
title,
icon: Icon,
description,
leagues,
onLeagueClick,
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
useEffect(() => {
if (scrollDirection === 'left' && scrollRef.current) {
const { scrollWidth, clientWidth } = scrollRef.current;
scrollPositionRef.current = scrollWidth - clientWidth;
scrollRef.current.scrollLeft = scrollPositionRef.current;
}
}, [scrollDirection, leagues.length]);
// Smooth continuous auto-scroll using requestAnimationFrame with variable speed and direction
useEffect(() => {
// 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
useEffect(() => {
const scrollContainer = scrollRef.current;
if (!scrollContainer) return;
const handleScroll = () => {
scrollPositionRef.current = scrollContainer.scrollLeft;
checkScrollButtons();
};
scrollContainer.addEventListener('scroll', handleScroll);
return () => scrollContainer.removeEventListener('scroll', handleScroll);
}, [checkScrollButtons]);
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="league-slider__scroll flex gap-4 overflow-x-auto pb-4 px-4"
style={{
scrollbarWidth: 'none',
msOverflowStyle: 'none',
}}
>
<style>{`
.league-slider__scroll::-webkit-scrollbar {
display: none;
}
`}</style>
{leagues.map((league) => (
<div key={league.id} className="flex-shrink-0 w-[320px] h-full">
<LeagueCard league={league} onClick={() => onLeagueClick(league.id)} />
</div>
))}
</div>
</div>
</div>
);
};

View File

@@ -1,691 +0,0 @@
'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 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 (
<div className="max-w-7xl mx-auto px-4 pb-12">
{/* Hero Section */}
<div className="relative mb-10 py-10 px-8 rounded-2xl bg-gradient-to-br from-iron-gray/80 via-deep-graphite to-iron-gray/60 border border-charcoal-outline/50 overflow-hidden">
{/* Background decoration */}
<div className="absolute top-0 right-0 w-96 h-96 bg-primary-blue/5 rounded-full blur-3xl" />
<div className="absolute bottom-0 left-0 w-64 h-64 bg-neon-aqua/5 rounded-full blur-3xl" />
<div className="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-8">
<div className="max-w-2xl">
<div className="flex items-center gap-3 mb-4">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-primary-blue/5 border border-primary-blue/20">
<Trophy className="w-6 h-6 text-primary-blue" />
</div>
<Heading level={1} className="text-3xl lg:text-4xl">
Find Your Grid
</Heading>
</div>
<p className="text-gray-400 text-lg leading-relaxed mb-6">
From casual sprints to epic endurance battles discover the perfect league for your racing style.
</p>
{/* Stats */}
<div className="flex flex-wrap gap-6">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-performance-green animate-pulse" />
<span className="text-sm text-gray-400">
<span className="text-white font-semibold">{viewData.leagues.length}</span> active leagues
</span>
</div>
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-primary-blue" />
<span className="text-sm text-gray-400">
<span className="text-white font-semibold">{leaguesByCategory.new.length}</span> new this week
</span>
</div>
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-neon-aqua" />
<span className="text-sm text-gray-400">
<span className="text-white font-semibold">{leaguesByCategory.openSlots.length}</span> with open slots
</span>
</div>
</div>
</div>
{/* CTA */}
<div className="flex flex-col gap-4">
<a href=routes.league.detail('create') className="flex items-center gap-2 px-6 py-3 bg-primary-blue text-white rounded-lg hover:bg-blue-600 transition-colors">
<Plus className="w-5 h-5" />
<span>Create League</span>
</a>
<p className="text-xs text-gray-500 text-center">Set up your own racing series</p>
</div>
</div>
</div>
{/* Search and Filter Bar */}
<div className="mb-6">
<div className="flex flex-col lg:flex-row gap-4">
{/* Search */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
<Input
type="text"
placeholder="Search leagues by name, description, or game..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-11"
/>
</div>
{/* Filter toggle (mobile) */}
<Button
type="button"
variant="secondary"
onClick={() => setShowFilters(!showFilters)}
className="lg:hidden flex items-center gap-2"
>
<Filter className="w-4 h-4" />
Filters
</Button>
</div>
{/* Category Tabs */}
<div className={`mt-4 ${showFilters ? 'block' : 'hidden lg:block'}`}>
<div className="flex flex-wrap gap-2">
{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>
);
})}
</div>
</div>
</div>
{/* Content */}
{viewData.leagues.length === 0 ? (
/* Empty State */
<Card className="text-center py-16">
<div className="max-w-md mx-auto">
<div className="flex h-16 w-16 mx-auto items-center justify-center rounded-2xl bg-primary-blue/10 border border-primary-blue/20 mb-6">
<Trophy className="w-8 h-8 text-primary-blue" />
</div>
<Heading level={2} className="text-2xl mb-3">
No leagues yet
</Heading>
<p className="text-gray-400 mb-8">
Be the first to create a racing series. Start your own league and invite drivers to compete for glory.
</p>
<a href=routes.league.detail('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
</a>
</div>
</Card>
) : activeCategory === 'all' && !searchQuery ? (
/* Slider View - Show featured categories with sliders at different speeds and directions */
<div>
{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}
/>
))}
</div>
) : (
/* Grid View - Filtered by category or search */
<div>
{categoryFilteredLeagues.length > 0 ? (
<>
<div className="flex items-center justify-between mb-6">
<p className="text-sm text-gray-400">
Showing <span className="text-white font-medium">{categoryFilteredLeagues.length}</span>{' '}
{categoryFilteredLeagues.length === 1 ? 'league' : 'leagues'}
{searchQuery && (
<span>
{' '}
for "<span className="text-primary-blue">{searchQuery}</span>"
</span>
)}
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-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 (
<a key={league.id} href={`/leagues/${league.id}`} className="block h-full">
<LeagueCard league={viewModel} />
</a>
);
})}
</div>
</>
) : (
<Card className="text-center py-12">
<div className="flex flex-col items-center gap-4">
<Search className="w-10 h-10 text-gray-600" />
<p className="text-gray-400">
No leagues found{searchQuery ? ` matching "${searchQuery}"` : ' in this category'}
</p>
<Button
variant="secondary"
onClick={() => {
setSearchQuery('');
setActiveCategory('all');
}}
>
Clear filters
</Button>
</div>
</Card>
)}
</div>
)}
</div>
);
}

View File

@@ -1,45 +0,0 @@
import { Search } from 'lucide-react';
import Button from '@/ui/Button';
import Card from '@/ui/Card';
interface NoResultsStateProps {
icon?: React.ElementType;
message?: string;
searchQuery?: string;
actionLabel?: string;
onAction?: () => void;
children?: React.ReactNode;
className?: string;
}
export function NoResultsState({
icon: Icon = Search,
message,
searchQuery,
actionLabel = "Clear filters",
onAction,
children,
className
}: NoResultsStateProps) {
const defaultMessage = message || `No leagues found${searchQuery ? ` matching "${searchQuery}"` : ' in this category'}`;
return (
<Card className={`text-center py-12 ${className || ''}`}>
<div className="flex flex-col items-center gap-4">
<Icon className="w-10 h-10 text-gray-600" />
<p className="text-gray-400">
{defaultMessage}
</p>
{children}
{actionLabel && onAction && (
<Button
variant="secondary"
onClick={onAction}
>
{actionLabel}
</Button>
)}
</div>
</Card>
);
}

View File

@@ -1,57 +0,0 @@
'use client';
import { useState } from 'react';
import { MoreVertical, Edit, Trash2 } from 'lucide-react';
import Button from '../ui/Button';
interface PenaltyCardMenuProps {
onEdit: () => void;
onVoid: () => void;
}
export default function PenaltyCardMenu({ onEdit, onVoid }: PenaltyCardMenuProps) {
const [isOpen, setIsOpen] = useState(false);
return (
<div className="relative">
<Button
variant="secondary"
className="p-2 w-8 h-8"
onClick={() => setIsOpen(!isOpen)}
>
<MoreVertical className="w-4 h-4" />
</Button>
{isOpen && (
<>
<div
className="fixed inset-0 z-10"
onClick={() => setIsOpen(false)}
/>
<div className="absolute right-0 mt-1 w-32 bg-deep-graphite border border-charcoal-outline rounded-lg shadow-lg z-20">
<button
onClick={() => {
onEdit();
setIsOpen(false);
}}
className="w-full px-3 py-2 text-left text-sm text-white hover:bg-iron-gray/50 flex items-center gap-2"
>
<Edit className="w-4 h-4" />
Edit
</button>
<button
onClick={() => {
onVoid();
setIsOpen(false);
}}
className="w-full px-3 py-2 text-left text-sm text-red-400 hover:bg-iron-gray/50 flex items-center gap-2"
>
<Trash2 className="w-4 h-4" />
Void
</button>
</div>
</>
)}
</div>
);
}

View File

@@ -1,11 +1,11 @@
"use client";
import { useState, useEffect } from "react";
import { ProtestViewModel } from "../../lib/view-models/ProtestViewModel";
import { RaceViewModel } from "../../lib/view-models/RaceViewModel";
import { DriverViewModel } from "../../lib/view-models/DriverViewModel";
import Card from "../ui/Card";
import Button from "../ui/Button";
import { ProtestViewModel } from "@/lib/view-models/ProtestViewModel";
import { RaceViewModel } from "@/lib/view-models/RaceViewModel";
import { DriverViewModel } from "@/lib/view-models/DriverViewModel";
import { Card } from "@/ui/Card";
import { Button } from "@/ui/Button";
import { Clock, Grid3x3, TrendingDown, AlertCircle, Filter, Flag } from "lucide-react";
interface PenaltyHistoryListProps {

View File

@@ -1,10 +1,10 @@
"use client";
import { ProtestViewModel } from "../../lib/view-models/ProtestViewModel";
import { RaceViewModel } from "../../lib/view-models/RaceViewModel";
import { DriverViewModel } from "../../lib/view-models/DriverViewModel";
import Card from "../ui/Card";
import Button from "../ui/Button";
import { ProtestViewModel } from "@/lib/view-models/ProtestViewModel";
import { RaceViewModel } from "@/lib/view-models/RaceViewModel";
import { DriverViewModel } from "@/lib/view-models/DriverViewModel";
import { Card } from "@/ui/Card";
import { Button } from "@/ui/Button";
import Link from "next/link";
import { AlertCircle, Video, ChevronRight, Flag, Clock, AlertTriangle } from "lucide-react";

View File

@@ -1,73 +0,0 @@
import Card from '@/ui/Card';
interface PointsBreakdownTableProps {
positionPoints: Array<{ position: number; points: number }>;
}
export function PointsBreakdownTable({ positionPoints }: PointsBreakdownTableProps) {
const getPositionStyle = (position: number): string => {
if (position === 1) return 'bg-yellow-500 text-black';
if (position === 2) return 'bg-gray-400 text-black';
if (position === 3) return 'bg-amber-600 text-white';
return 'bg-charcoal-outline text-white';
};
const getRowHighlight = (position: number): string => {
if (position === 1) return 'bg-yellow-500/5 border-l-2 border-l-yellow-500';
if (position === 2) return 'bg-gray-400/5 border-l-2 border-l-gray-400';
if (position === 3) return 'bg-amber-600/5 border-l-2 border-l-amber-600';
return 'border-l-2 border-l-transparent';
};
const formatPosition = (position: number): string => {
if (position === 1) return '1st';
if (position === 2) return '2nd';
if (position === 3) return '3rd';
return `${position}th`;
};
return (
<Card className="overflow-hidden">
<div className="mb-4">
<h3 className="text-lg font-semibold text-white">Position Points</h3>
<p className="text-sm text-gray-400 mt-1">Points awarded by finishing position</p>
</div>
<div className="overflow-x-auto -mx-6 -mb-6">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-charcoal-outline bg-deep-graphite">
<th className="text-left py-3 px-6 font-medium text-gray-400 uppercase text-xs tracking-wider">
Position
</th>
<th className="text-right py-3 px-6 font-medium text-gray-400 uppercase text-xs tracking-wider">
Points
</th>
</tr>
</thead>
<tbody>
{positionPoints.map(({ position, points }) => (
<tr
key={position}
className={`border-b border-charcoal-outline/50 transition-colors hover:bg-iron-gray/30 ${getRowHighlight(position)}`}
>
<td className="py-3 px-6">
<div className="flex items-center gap-3">
<div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold ${getPositionStyle(position)}`}>
{position}
</div>
<span className="text-white font-medium">{formatPosition(position)}</span>
</div>
</td>
<td className="py-3 px-6 text-right">
<span className="text-white font-semibold tabular-nums">{points}</span>
<span className="text-gray-500 ml-1">pts</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
);
}

View File

@@ -1,314 +0,0 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Button from '../ui/Button';
import Input from '../ui/Input';
import { useAllLeagues } from "@/lib/hooks/league/useAllLeagues";
import type { LeagueSummaryViewModel } from '@/lib/view-models/LeagueSummaryViewModel';
interface ScheduleRaceFormData {
leagueId: string;
track: string;
car: string;
sessionType: 'practice' | 'qualifying' | 'race';
scheduledDate: string;
scheduledTime: string;
}
interface ScheduledRaceViewModel {
id: string;
track: string;
car: string;
scheduledAt: string;
}
interface ScheduleRaceFormProps {
preSelectedLeagueId?: string;
onSuccess?: (race: ScheduledRaceViewModel) => void;
onCancel?: () => void;
}
export default function ScheduleRaceForm({
preSelectedLeagueId,
onSuccess,
onCancel
}: ScheduleRaceFormProps) {
const router = useRouter();
const { data: leagues = [], isLoading, error } = useAllLeagues();
const [formData, setFormData] = useState<ScheduleRaceFormData>({
leagueId: preSelectedLeagueId || '',
track: '',
car: '',
sessionType: 'race',
scheduledDate: '',
scheduledTime: '',
});
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
const validateForm = (): boolean => {
const errors: Record<string, string> = {};
if (!formData.leagueId) {
errors.leagueId = 'League is required';
}
if (!formData.track.trim()) {
errors.track = 'Track is required';
}
if (!formData.car.trim()) {
errors.car = 'Car is required';
}
if (!formData.scheduledDate) {
errors.scheduledDate = 'Date is required';
}
if (!formData.scheduledTime) {
errors.scheduledTime = 'Time is required';
}
// Validate future date
if (formData.scheduledDate && formData.scheduledTime) {
const scheduledDateTime = new Date(`${formData.scheduledDate}T${formData.scheduledTime}`);
const now = new Date();
if (scheduledDateTime <= now) {
errors.scheduledDate = 'Date must be in the future';
}
}
setValidationErrors(errors);
return Object.keys(errors).length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateForm()) {
return;
}
try {
// Create race using the race service
// Note: This assumes the race service has a create method
// If not available, we'll need to implement it or use an alternative approach
const raceData = {
leagueId: formData.leagueId,
track: formData.track,
car: formData.car,
sessionType: formData.sessionType,
scheduledAt: new Date(`${formData.scheduledDate}T${formData.scheduledTime}`).toISOString(),
};
// For now, we'll simulate race creation since the race service may not have create method
// In a real implementation, this would call raceService.createRace(raceData)
const createdRace: ScheduledRaceViewModel = {
id: `race-${Date.now()}`,
track: formData.track,
car: formData.car,
scheduledAt: new Date(`${formData.scheduledDate}T${formData.scheduledTime}`).toISOString(),
};
if (onSuccess) {
onSuccess(createdRace);
} else {
router.push(`/races/${createdRace.id}`);
}
} catch (err) {
// Error handling is now done through the component state
console.error('Failed to create race:', err);
}
};
const handleChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
// Clear validation error for this field
if (validationErrors[field]) {
setValidationErrors(prev => {
const newErrors = { ...prev };
delete newErrors[field];
return newErrors;
});
}
};
return (
<>
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
<div className="p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400">
{error.message}
</div>
)}
{/* Companion App Notice */}
<div className="p-4 rounded-lg bg-iron-gray border border-charcoal-outline">
<div className="flex items-start gap-3">
<div className="flex items-center gap-2 flex-1">
<input
type="checkbox"
disabled
className="w-4 h-4 rounded border-charcoal-outline bg-deep-graphite text-primary-blue opacity-50 cursor-not-allowed"
/>
<label className="text-sm text-gray-400">
Use Companion App
</label>
<button
type="button"
className="text-gray-500 hover:text-gray-400 transition-colors"
title="Companion automation available in production. For alpha, races are created manually."
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
</div>
</div>
<p className="text-xs text-gray-500 mt-2 ml-6">
Companion automation available in production. For alpha, races are created manually.
</p>
</div>
{/* League Selection */}
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
League *
</label>
<select
value={formData.leagueId}
onChange={(e) => handleChange('leagueId', e.target.value)}
disabled={!!preSelectedLeagueId}
className={`
w-full px-4 py-2 bg-deep-graphite border rounded-lg text-white
focus:outline-none focus:ring-2 focus:ring-primary-blue
disabled:opacity-50 disabled:cursor-not-allowed
${validationErrors.leagueId ? 'border-red-500' : 'border-charcoal-outline'}
`}
>
<option value="">Select a league</option>
{leagues.map((league) => (
<option key={league.id} value={league.id}>
{league.name}
</option>
))}
</select>
{validationErrors.leagueId && (
<p className="mt-1 text-sm text-red-400">{validationErrors.leagueId}</p>
)}
</div>
{/* Track */}
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Track *
</label>
<Input
type="text"
value={formData.track}
onChange={(e) => handleChange('track', e.target.value)}
placeholder="e.g., Spa-Francorchamps"
className={validationErrors.track ? 'border-red-500' : ''}
/>
{validationErrors.track && (
<p className="mt-1 text-sm text-red-400">{validationErrors.track}</p>
)}
<p className="mt-1 text-xs text-gray-500">Enter the iRacing track name</p>
</div>
{/* Car */}
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Car *
</label>
<Input
type="text"
value={formData.car}
onChange={(e) => handleChange('car', e.target.value)}
placeholder="e.g., Porsche 911 GT3 R"
className={validationErrors.car ? 'border-red-500' : ''}
/>
{validationErrors.car && (
<p className="mt-1 text-sm text-red-400">{validationErrors.car}</p>
)}
<p className="mt-1 text-xs text-gray-500">Enter the iRacing car name</p>
</div>
{/* Session Type */}
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Session Type *
</label>
<select
value={formData.sessionType}
onChange={(e) => handleChange('sessionType', e.target.value)}
className="w-full px-4 py-2 bg-deep-graphite border border-charcoal-outline rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary-blue"
>
<option value="practice">Practice</option>
<option value="qualifying">Qualifying</option>
<option value="race">Race</option>
</select>
</div>
{/* Date and Time */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Date *
</label>
<Input
type="date"
value={formData.scheduledDate}
onChange={(e) => handleChange('scheduledDate', e.target.value)}
className={validationErrors.scheduledDate ? 'border-red-500' : ''}
/>
{validationErrors.scheduledDate && (
<p className="mt-1 text-sm text-red-400">{validationErrors.scheduledDate}</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Time *
</label>
<Input
type="time"
value={formData.scheduledTime}
onChange={(e) => handleChange('scheduledTime', e.target.value)}
className={validationErrors.scheduledTime ? 'border-red-500' : ''}
/>
{validationErrors.scheduledTime && (
<p className="mt-1 text-sm text-red-400">{validationErrors.scheduledTime}</p>
)}
</div>
</div>
{/* Actions */}
<div className="flex gap-3">
<Button
type="submit"
variant="primary"
disabled={isLoading}
className="flex-1"
>
{isLoading ? 'Creating...' : 'Schedule Race'}
</Button>
{onCancel && (
<Button
type="button"
variant="secondary"
onClick={onCancel}
disabled={isLoading}
>
Cancel
</Button>
)}
</div>
</form>
</>
);
}

View File

@@ -1,54 +0,0 @@
import Card from '@/ui/Card';
interface ScoringOverviewCardProps {
gameName: string;
scoringPresetName?: string;
dropPolicySummary: string;
totalChampionships: number;
}
export function ScoringOverviewCard({
gameName,
scoringPresetName,
dropPolicySummary,
totalChampionships
}: ScoringOverviewCardProps) {
return (
<Card>
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-xl font-semibold text-white">Scoring System</h2>
<p className="text-sm text-gray-400 mt-1">Points allocation and championship rules</p>
</div>
<div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-primary-blue/10 border border-primary-blue/20">
<span className="text-sm font-medium text-primary-blue">{scoringPresetName || 'Custom'}</span>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<div className="bg-deep-graphite rounded-lg p-4 border border-charcoal-outline">
<p className="text-xs text-gray-500 uppercase tracking-wider mb-1 font-medium">Platform</p>
<p className="text-lg font-semibold text-white">{gameName}</p>
</div>
<div className="bg-deep-graphite rounded-lg p-4 border border-charcoal-outline">
<p className="text-xs text-gray-500 uppercase tracking-wider mb-1 font-medium">Championships</p>
<p className="text-lg font-semibold text-white">{totalChampionships}</p>
</div>
<div className="bg-deep-graphite rounded-lg p-4 border border-charcoal-outline">
<p className="text-xs text-gray-500 uppercase tracking-wider mb-1 font-medium">Drop Policy</p>
<p className="text-lg font-semibold text-white truncate" title={dropPolicySummary}>
{dropPolicySummary.includes('Best') ? dropPolicySummary.split(' ').slice(0, 3).join(' ') :
dropPolicySummary.includes('Worst') ? dropPolicySummary.split(' ').slice(0, 3).join(' ') :
'All count'}
</p>
</div>
</div>
<div className="p-4 bg-deep-graphite rounded-lg border border-charcoal-outline">
<p className="text-sm text-gray-400">{dropPolicySummary}</p>
</div>
</Card>
);
}

View File

@@ -1,95 +0,0 @@
import { useState } from 'react';
import { Search, Filter } from 'lucide-react';
import Input from '@/ui/Input';
import Button from '@/ui/Button';
interface Category {
id: string;
label: string;
icon: React.ElementType;
description: string;
color?: string;
}
interface SearchAndFilterBarProps {
searchQuery: string;
onSearchChange: (query: string) => void;
activeCategory: string;
onCategoryChange: (category: string) => void;
categories: Category[];
leaguesByCategory: Record<string, any[]>;
className?: string;
}
export function SearchAndFilterBar({
searchQuery,
onSearchChange,
activeCategory,
onCategoryChange,
categories,
leaguesByCategory,
className,
}: SearchAndFilterBarProps) {
const [showFilters, setShowFilters] = useState(false);
return (
<div className={`mb-6 ${className || ''}`}>
<div className="flex flex-col lg:flex-row gap-4">
{/* Search */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
<Input
type="text"
placeholder="Search leagues by name, description, or game..."
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
className="pl-11"
/>
</div>
{/* Filter toggle (mobile) */}
<Button
type="button"
variant="secondary"
onClick={() => setShowFilters(!showFilters)}
className="lg:hidden flex items-center gap-2"
>
<Filter className="w-4 h-4" />
Filters
</Button>
</div>
{/* Category Tabs */}
<div className={`mt-4 ${showFilters ? 'block' : 'hidden lg:block'}`}>
<div className="flex flex-wrap gap-2">
{categories.map((category) => {
const Icon = category.icon;
const count = leaguesByCategory[category.id]?.length || 0;
const isActive = activeCategory === category.id;
return (
<button
key={category.id}
type="button"
onClick={() => onCategoryChange(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>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -1,87 +0,0 @@
interface SeasonStatistics {
racesCompleted: number;
totalRaces: number;
averagePoints: number;
highestScore: number;
totalPoints: number;
}
interface SeasonStatsCardProps {
stats: SeasonStatistics;
}
export function SeasonStatsCard({ stats }: SeasonStatsCardProps) {
const completionPercentage = stats.totalRaces > 0
? Math.round((stats.racesCompleted / stats.totalRaces) * 100)
: 0;
if (stats.racesCompleted === 0) {
return null;
}
return (
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
📈 Season Statistics
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Your performance this season
</p>
</div>
<div className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
<div className="bg-gradient-to-br from-blue-50 to-cyan-50 dark:from-blue-950/20 dark:to-cyan-950/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
<p className="text-xs text-blue-600 dark:text-blue-400 uppercase tracking-wider mb-1 font-medium">
Races Completed
</p>
<p className="text-3xl font-bold text-gray-900 dark:text-white">
{stats.racesCompleted}
<span className="text-lg text-gray-500 dark:text-gray-400">/{stats.totalRaces}</span>
</p>
</div>
<div className="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/20 dark:to-emerald-950/20 rounded-lg p-4 border border-green-200 dark:border-green-800">
<p className="text-xs text-green-600 dark:text-green-400 uppercase tracking-wider mb-1 font-medium">
Average Points
</p>
<p className="text-3xl font-bold text-gray-900 dark:text-white">
{stats.averagePoints.toFixed(1)}
</p>
</div>
<div className="bg-gradient-to-br from-purple-50 to-pink-50 dark:from-purple-950/20 dark:to-pink-950/20 rounded-lg p-4 border border-purple-200 dark:border-purple-800">
<p className="text-xs text-purple-600 dark:text-purple-400 uppercase tracking-wider mb-1 font-medium">
Highest Score
</p>
<p className="text-3xl font-bold text-gray-900 dark:text-white">
{stats.highestScore}
</p>
</div>
<div className="bg-gradient-to-br from-orange-50 to-red-50 dark:from-orange-950/20 dark:to-red-950/20 rounded-lg p-4 border border-orange-200 dark:border-orange-800">
<p className="text-xs text-orange-600 dark:text-orange-400 uppercase tracking-wider mb-1 font-medium">
Total Points
</p>
<p className="text-3xl font-bold text-gray-900 dark:text-white">
{stats.totalPoints}
</p>
</div>
</div>
<div className="space-y-2">
<div className="flex justify-between items-center text-sm">
<span className="text-gray-600 dark:text-gray-400">Season Progress</span>
<span className="font-semibold text-gray-900 dark:text-white">{completionPercentage}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3 overflow-hidden">
<div
className="bg-gradient-to-r from-blue-500 to-purple-500 h-3 rounded-full transition-all duration-500 ease-out"
style={{ width: `${completionPercentage}%` }}
/>
</div>
</div>
</div>
</div>
);
}