'use client'; import Link from 'next/link'; import { useEffect, useMemo, useState } from 'react'; import { LogOut, Star } from 'lucide-react'; import { useAuth } from '@/lib/auth/AuthContext'; import { getDriverStats, getLeagueRankings, getAllDriverRankings, getDriverRepository, getImageService, } from '@/lib/di-container'; import { useEffectiveDriverId } from '@/lib/currentDriver'; import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO'; import { EntityMappers } from '@gridpilot/racing/application/mappers/EntityMappers'; import DriverSummaryPill from '@/components/profile/DriverSummaryPill'; export default function UserPill() { const { session, login } = useAuth(); const [driver, setDriver] = useState(null); const [isMenuOpen, setIsMenuOpen] = useState(false); const user = session?.user as | { id: string; displayName?: string; primaryDriverId?: string | null; avatarUrl?: string | null; } | undefined; const primaryDriverId = useEffectiveDriverId(); useEffect(() => { let cancelled = false; async function loadDriver() { if (!primaryDriverId) { if (!cancelled) { setDriver(null); } return; } const repo = getDriverRepository(); const entity = await repo.findById(primaryDriverId); if (!cancelled) { setDriver(EntityMappers.toDriverDTO(entity)); } } loadDriver(); return () => { cancelled = true; }; }, [primaryDriverId]); const data = useMemo(() => { if (!session?.user || !primaryDriverId || !driver) { return null; } const driverStats = getDriverStats(primaryDriverId); const allRankings = getAllDriverRankings(); let rating: number | null = driverStats?.rating ?? null; let rank: number | null = null; let totalDrivers: number | null = null; if (driverStats) { totalDrivers = allRankings.length || null; if (typeof driverStats.overallRank === 'number' && driverStats.overallRank > 0) { rank = driverStats.overallRank; } else { const indexInGlobal = allRankings.findIndex( (stat) => stat.driverId === driverStats.driverId, ); if (indexInGlobal !== -1) { rank = indexInGlobal + 1; } } if (rating === null) { const globalEntry = allRankings.find( (stat) => stat.driverId === driverStats.driverId, ); if (globalEntry) { rating = globalEntry.rating; } } } const avatarSrc = getImageService().getDriverAvatar(primaryDriverId); return { driver, avatarSrc, rating, rank, }; }, [session, driver, primaryDriverId]); if (!session) { const loginHref = '/auth/iracing/start?returnTo=/dashboard'; return (
Authenticate with iRacing
); } if (!data) { return null; } return (
setIsMenuOpen((open) => !open)} /> {isMenuOpen && (
setIsMenuOpen(false)} > Profile setIsMenuOpen(false)} > Manage leagues
)}
); }