'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import JoinLeagueButton from '@/components/leagues/JoinLeagueButton';
import LeagueActivityFeed from '@/components/leagues/LeagueActivityFeed';
import EndRaceModal from '@/components/leagues/EndRaceModal';
import DriverIdentity from '@/components/drivers/DriverIdentity';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import SponsorInsightsCard, {
  useSponsorMode,
  MetricBuilders,
  SlotTemplates,
  type SponsorMetric,
} from '@/components/sponsors/SponsorInsightsCard';
import {
  League,
  Driver,
  EntityMappers,
  type DriverDTO,
  type LeagueScoringConfigDTO,
  Race,
} from '@core/racing';
import { LeagueScoringConfigPresenter } from '@/lib/presenters/LeagueScoringConfigPresenter';
import { Trophy, Star, ExternalLink, Calendar, Users } from 'lucide-react';
import { getMembership, getLeagueMembers } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { getLeagueRoleDisplay } from '@/lib/leagueRoles';

// Sponsor info type
interface SponsorInfo {
  id: string;
  name: string;
  logoUrl?: string;
  websiteUrl?: string;
  tier: 'main' | 'secondary';
  tagline?: string;
}

export default function LeagueDetailPage() {
  const router = useRouter();
  const params = useParams();
  const leagueId = params.id as string;
  const isSponsor = useSponsorMode();

  const [league, setLeague] = useState<League | null>(null);
  const [owner, setOwner] = useState<Driver | null>(null);
  const [drivers, setDrivers] = useState<DriverDTO[]>([]);
  const [scoringConfig, setScoringConfig] = useState<LeagueScoringConfigDTO | null>(null);
  const [averageSOF, setAverageSOF] = useState<number | null>(null);
  const [completedRacesCount, setCompletedRacesCount] = useState<number>(0);
  const [sponsors, setSponsors] = useState<SponsorInfo[]>([]);
  const [runningRaces, setRunningRaces] = useState<Race[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);
  const [endRaceModalRaceId, setEndRaceModalRaceId] = useState<string | null>(null);

  const currentDriverId = useEffectiveDriverId();
  const membership = getMembership(leagueId, currentDriverId);
  const leagueMemberships = getLeagueMembers(leagueId);

  // Sponsor insights data - uses leagueMemberships and averageSOF
  const sponsorInsights = useMemo(() => {
    const memberCount = leagueMemberships?.length || 20;
    const mainSponsorTaken = sponsors.some(s => s.tier === 'main');
    const secondaryTaken = sponsors.filter(s => s.tier === 'secondary').length;
    
    return {
      avgViewsPerRace: 5400 + memberCount * 50,
      totalImpressions: 45000 + memberCount * 500,
      engagementRate: (3.5 + (memberCount / 50)).toFixed(1),
      estimatedReach: memberCount * 150,
      mainSponsorAvailable: !mainSponsorTaken,
      secondarySlotsAvailable: Math.max(0, 2 - secondaryTaken),
      mainSponsorPrice: 800 + Math.floor(memberCount * 10),
      secondaryPrice: 250 + Math.floor(memberCount * 3),
      tier: (averageSOF && averageSOF > 3000 ? 'premium' : averageSOF && averageSOF > 2000 ? 'standard' : 'starter') as 'premium' | 'standard' | 'starter',
      trustScore: Math.min(100, 60 + memberCount + completedRacesCount),
      discordMembers: memberCount * 3,
      monthlyActivity: Math.min(100, 40 + completedRacesCount * 2),
    };
  }, [averageSOF, leagueMemberships?.length, sponsors, completedRacesCount]);
  
  // Build metrics for SponsorInsightsCard
  const leagueMetrics: SponsorMetric[] = useMemo(() => [
    MetricBuilders.views(sponsorInsights.avgViewsPerRace, 'Avg Views/Race'),
    MetricBuilders.engagement(sponsorInsights.engagementRate),
    MetricBuilders.reach(sponsorInsights.estimatedReach),
    MetricBuilders.sof(averageSOF ?? '—'),
  ], [sponsorInsights, averageSOF]);

  const loadLeagueData = async () => {
    try {
      const leagueRepo = getLeagueRepository();
      const raceRepo = getRaceRepository();
      const driverRepo = getDriverRepository();
      const leagueStatsUseCase = getGetLeagueStatsUseCase();
      const seasonRepo = getSeasonRepository();
      const sponsorRepo = getSponsorRepository();
      const sponsorshipRepo = getSeasonSponsorshipRepository();

      const leagueData = await leagueRepo.findById(leagueId);
      
      if (!leagueData) {
        setError('League not found');
        setLoading(false);
        return;
      }

      setLeague(leagueData);

      // Load owner data
      const ownerData = await driverRepo.findById(leagueData.ownerId);
      setOwner(ownerData);

      // Load scoring configuration for the active season
      const getLeagueScoringConfigUseCase = getGetLeagueScoringConfigUseCase();
      const scoringPresenter = new LeagueScoringConfigPresenter();
      await getLeagueScoringConfigUseCase.execute({ leagueId }, scoringPresenter);
      const scoringViewModel = scoringPresenter.getViewModel();
      setScoringConfig(scoringViewModel as unknown as LeagueScoringConfigDTO);

      // Load all drivers for standings and map to DTOs for UI components
      const allDrivers = await driverRepo.findAll();
      const driverDtos: DriverDTO[] = allDrivers
        .map((driver) => EntityMappers.toDriverDTO(driver))
        .filter((dto): dto is DriverDTO => dto !== null);

      setDrivers(driverDtos);
      
      // Load all races for this league to find running ones
      const leagueRaces = await raceRepo.findByLeagueId(leagueId);
      const runningRaces = leagueRaces.filter(r => r.status === 'running');
      setRunningRaces(runningRaces);

      // Load league stats including average SOF from application use case
      await leagueStatsUseCase.execute({ leagueId });
      const leagueStatsViewModel = leagueStatsUseCase.presenter.getViewModel();
      if (leagueStatsViewModel) {
        setAverageSOF(leagueStatsViewModel.averageSOF);
        setCompletedRacesCount(leagueStatsViewModel.completedRaces);
      } else {
        // Fallback: count completed races manually
        const completedRaces = leagueRaces.filter(r => r.status === 'completed');
        setCompletedRacesCount(completedRaces.length);
      }

      // Load sponsors for this league
      try {
        const seasons = await seasonRepo.findByLeagueId(leagueId);
        const activeSeason = seasons.find((s: { status: string }) => s.status === 'active') ?? seasons[0];
        
        if (activeSeason) {
          const sponsorships = await sponsorshipRepo.findBySeasonId(activeSeason.id);
          const activeSponsorships = sponsorships.filter((s) => s.status === 'active');
          
          const sponsorInfos: SponsorInfo[] = [];
          for (const sponsorship of activeSponsorships) {
            const sponsor = await sponsorRepo.findById(sponsorship.sponsorId);
            if (sponsor) {
              const testingSupportModule = await import('@gridpilot/testing-support');
              const demoSponsors = testingSupportModule.sponsors as Array<{ id: string; tagline?: string }>;
              const demoSponsor = demoSponsors.find((demo) => demo.id === sponsor.id);
              
              sponsorInfos.push({
                id: sponsor.id,
                name: sponsor.name,
                logoUrl: sponsor.logoUrl ?? '',
                websiteUrl: sponsor.websiteUrl ?? '',
                tier: sponsorship.tier,
                tagline: demoSponsor?.tagline ?? '',
              });
            }
          }
          
          // Sort: main sponsors first, then secondary
          sponsorInfos.sort((a, b) => {
            if (a.tier === 'main' && b.tier !== 'main') return -1;
            if (a.tier !== 'main' && b.tier === 'main') return 1;
            return 0;
          });
          
          setSponsors(sponsorInfos);
        }
      } catch (sponsorError) {
        console.warn('Failed to load sponsors:', sponsorError);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load league');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadLeagueData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [leagueId]);

  const handleMembershipChange = () => {
    setRefreshKey(prev => prev + 1);
    loadLeagueData();
  };

  const driversById = useMemo(() => {
    const map: Record<string, DriverDTO> = {};
    for (const d of drivers) {
      map[d.id] = d;
    }
    return map;
  }, [drivers]);

  const ownerMembership = leagueMemberships.find((m) => m.role === 'owner') ?? null;
  const adminMemberships = leagueMemberships.filter((m) => m.role === 'admin');
  const stewardMemberships = leagueMemberships.filter((m) => m.role === 'steward');

  const buildDriverSummary = (driverId: string) => {
    const driverDto = driversById[driverId];
    if (!driverDto) {
      return null;
    }

    const stats = getDriverStats(driverDto.id);
    const allRankings = getAllDriverRankings();

    let rating: number | null = stats?.rating ?? null;
    let rank: number | null = null;

    if (stats) {
      if (typeof stats.overallRank === 'number' && stats.overallRank > 0) {
        rank = stats.overallRank;
      } else {
        const indexInGlobal = allRankings.findIndex(
          (stat) => stat.driverId === stats.driverId,
        );
        if (indexInGlobal !== -1) {
          rank = indexInGlobal + 1;
        }
      }

      if (rating === null) {
        const globalEntry = allRankings.find(
          (stat) => stat.driverId === stats.driverId,
        );
        if (globalEntry) {
          rating = globalEntry.rating;
        }
      }
    }

    return {
      driver: driverDto,
      rating,
      rank,
    };
  };

  return loading ? (
    <div className="text-center text-gray-400">Loading league...</div>
  ) : error || !league ? (
    <Card className="text-center py-12">
      <div className="text-warning-amber mb-4">
        {error || 'League not found'}
      </div>
      <Button
        variant="secondary"
        onClick={() => router.push('/leagues')}
      >
        Back to Leagues
      </Button>
    </Card>
  ) : (
    <>
      {/* Sponsor Insights Card - Only shown to sponsors, at top of page */}
      {isSponsor && league && (
        <SponsorInsightsCard
          entityType="league"
          entityId={leagueId}
          entityName={league.name}
          tier={sponsorInsights.tier}
          metrics={leagueMetrics}
          slots={SlotTemplates.league(
            sponsorInsights.mainSponsorAvailable,
            sponsorInsights.secondarySlotsAvailable,
            sponsorInsights.mainSponsorPrice,
            sponsorInsights.secondaryPrice
          )}
          trustScore={sponsorInsights.trustScore}
          discordMembers={sponsorInsights.discordMembers}
          monthlyActivity={sponsorInsights.monthlyActivity}
          additionalStats={{
            label: 'League Stats',
            items: [
              { label: 'Total Races', value: completedRacesCount },
              { label: 'Active Members', value: leagueMemberships.length },
              { label: 'Total Impressions', value: sponsorInsights.totalImpressions },
            ],
          }}
        />
      )}

      {/* Live Race Card - Prominently show running races */}
      {runningRaces.length > 0 && (
        <Card className="border-2 border-performance-green/50 bg-gradient-to-r from-performance-green/10 to-performance-green/5 mb-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-3 h-3 bg-performance-green rounded-full animate-pulse"></div>
            <h2 className="text-xl font-bold text-white">🏁 Live Race in Progress</h2>
          </div>

          <div className="space-y-3">
            {runningRaces.map((race) => (
              <div
                key={race.id}
                className="p-4 rounded-lg bg-deep-graphite border border-performance-green/30"
              >
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-3">
                  <div className="flex items-center gap-3">
                    <div className="px-3 py-1 bg-performance-green/20 border border-performance-green/40 rounded-full">
                      <span className="text-sm font-semibold text-performance-green">LIVE</span>
                    </div>
                    <h3 className="text-lg font-semibold text-white">
                      {race.track} - {race.car}
                    </h3>
                  </div>
                  <div className="flex flex-col sm:flex-row gap-2">
                    <Button
                      variant="primary"
                      onClick={() => router.push(`/races/${race.id}`)}
                      className="bg-performance-green hover:bg-performance-green/80 text-white"
                    >
                      View Live Race
                    </Button>
                    {membership?.role === 'admin' && (
                      <Button
                        variant="secondary"
                        onClick={() => setEndRaceModalRaceId(race.id)}
                        className="border-performance-green/50 text-performance-green hover:bg-performance-green/10"
                      >
                        End Race & Process Results
                      </Button>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm text-gray-400">
                  <div className="flex items-center gap-2">
                    <Calendar className="w-4 h-4" />
                    <span>Started {new Date(race.scheduledAt).toLocaleDateString()}</span>
                  </div>
                  {race.registeredCount && (
                    <div className="flex items-center gap-2">
                      <Users className="w-4 h-4" />
                      <span>{race.registeredCount} drivers registered</span>
                    </div>
                  )}
                  {race.strengthOfField && (
                    <div className="flex items-center gap-2">
                      <Trophy className="w-4 h-4" />
                      <span>SOF: {race.strengthOfField}</span>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Action Card */}
      {!membership && !isSponsor && (
        <Card className="mb-6">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-semibold text-white mb-2">Join This League</h3>
              <p className="text-gray-400 text-sm">Become a member to participate in races and track your progress</p>
            </div>
            <div className="w-48">
              <JoinLeagueButton
                leagueId={leagueId}
                onMembershipChange={handleMembershipChange}
              />
            </div>
          </div>
        </Card>
      )}

      {/* League Overview - Activity Center with Info Sidebar */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Center - Activity Feed */}
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <h2 className="text-xl font-semibold text-white mb-6">Recent Activity</h2>
            <LeagueActivityFeed leagueId={leagueId} limit={20} />
          </Card>
        </div>

        {/* Right Sidebar - League Info */}
        <div className="space-y-6">
          {/* League Info - Combined */}
          <Card>
            <h3 className="text-lg font-semibold text-white mb-4">About</h3>
            
            {/* Stats Grid */}
            <div className="grid grid-cols-3 gap-3 mb-4">
              <div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
                <div className="text-xl font-bold text-white">{leagueMemberships.length}</div>
                <div className="text-xs text-gray-500">Members</div>
              </div>
              <div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
                <div className="text-xl font-bold text-white">{completedRacesCount}</div>
                <div className="text-xs text-gray-500">Races</div>
              </div>
              <div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
                <div className="text-xl font-bold text-warning-amber">{averageSOF ?? '—'}</div>
                <div className="text-xs text-gray-500">Avg SOF</div>
              </div>
            </div>

            {/* Details */}
            <div className="space-y-2 text-sm">
              <div className="flex items-center justify-between py-1.5 border-b border-charcoal-outline/50">
                <span className="text-gray-500">Structure</span>
                <span className="text-white">Solo • {league.settings.maxDrivers ?? 32} max</span>
              </div>
              <div className="flex items-center justify-between py-1.5 border-b border-charcoal-outline/50">
                <span className="text-gray-500">Scoring</span>
                <span className="text-white">{scoringConfig?.scoringPresetName ?? 'Standard'}</span>
              </div>
              <div className="flex items-center justify-between py-1.5">
                <span className="text-gray-500">Created</span>
                <span className="text-white">
                  {new Date(league.createdAt).toLocaleDateString('en-US', {
                    month: 'short',
                    year: 'numeric'
                  })}
                </span>
              </div>
            </div>

            {league.socialLinks && (
              <div className="mt-4 pt-4 border-t border-charcoal-outline">
                <div className="flex flex-wrap gap-2">
                  {league.socialLinks.discordUrl && (
                    <a
                      href={league.socialLinks.discordUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-1 rounded-full border border-primary-blue/40 bg-primary-blue/10 px-2 py-1 text-xs text-primary-blue hover:bg-primary-blue/20 transition-colors"
                    >
                      Discord
                    </a>
                  )}
                  {league.socialLinks.youtubeUrl && (
                    <a
                      href={league.socialLinks.youtubeUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-1 rounded-full border border-red-500/40 bg-red-500/10 px-2 py-1 text-xs text-red-400 hover:bg-red-500/20 transition-colors"
                    >
                      YouTube
                    </a>
                  )}
                  {league.socialLinks.websiteUrl && (
                    <a
                      href={league.socialLinks.websiteUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-1 rounded-full border border-charcoal-outline bg-iron-gray/70 px-2 py-1 text-xs text-gray-100 hover:bg-iron-gray transition-colors"
                    >
                      Website
                    </a>
                  )}
                </div>
              </div>
            )}
          </Card>

          {/* Sponsors Section - Show sponsor logos */}
          {sponsors.length > 0 && (
            <Card>
              <h3 className="text-lg font-semibold text-white mb-4">
                {sponsors.find(s => s.tier === 'main') ? 'Presented by' : 'Sponsors'}
              </h3>
              <div className="space-y-3">
                {/* Main Sponsor - Featured prominently */}
                {sponsors.filter(s => s.tier === 'main').map(sponsor => (
                  <div
                    key={sponsor.id}
                    className="p-3 rounded-lg bg-gradient-to-r from-yellow-500/10 to-transparent border border-yellow-500/30"
                  >
                    <div className="flex items-center gap-3">
                      {sponsor.logoUrl ? (
                        <div className="w-12 h-12 rounded-lg bg-white flex items-center justify-center overflow-hidden">
                          <img
                            src={sponsor.logoUrl}
                            alt={sponsor.name}
                            className="w-10 h-10 object-contain"
                          />
                        </div>
                      ) : (
                        <div className="w-12 h-12 rounded-lg bg-yellow-500/20 flex items-center justify-center">
                          <Trophy className="w-6 h-6 text-yellow-400" />
                        </div>
                      )}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="font-semibold text-white truncate">{sponsor.name}</span>
                          <span className="px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/20 text-yellow-400 border border-yellow-500/30">
                            Main
                          </span>
                        </div>
                        {sponsor.tagline && (
                          <p className="text-xs text-gray-400 truncate mt-0.5">{sponsor.tagline}</p>
                        )}
                      </div>
                      {sponsor.websiteUrl && (
                        <a
                          href={sponsor.websiteUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="p-1.5 rounded-lg bg-iron-gray hover:bg-charcoal-outline transition-colors"
                        >
                          <ExternalLink className="w-4 h-4 text-gray-400" />
                        </a>
                      )}
                    </div>
                  </div>
                ))}

                {/* Secondary Sponsors - Smaller display */}
                {sponsors.filter(s => s.tier === 'secondary').length > 0 && (
                  <div className="grid grid-cols-2 gap-2">
                    {sponsors.filter(s => s.tier === 'secondary').map(sponsor => (
                      <div
                        key={sponsor.id}
                        className="p-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline"
                      >
                        <div className="flex items-center gap-2">
                          {sponsor.logoUrl ? (
                            <div className="w-8 h-8 rounded bg-white flex items-center justify-center overflow-hidden flex-shrink-0">
                              <img
                                src={sponsor.logoUrl}
                                alt={sponsor.name}
                                className="w-6 h-6 object-contain"
                              />
                            </div>
                          ) : (
                            <div className="w-8 h-8 rounded bg-purple-500/20 flex items-center justify-center flex-shrink-0">
                              <Star className="w-4 h-4 text-purple-400" />
                            </div>
                          )}
                          <div className="flex-1 min-w-0">
                            <span className="text-sm text-white truncate block">{sponsor.name}</span>
                          </div>
                          {sponsor.websiteUrl && (
                            <a
                              href={sponsor.websiteUrl}
                              target="_blank"
                              rel="noreferrer"
                              className="p-1 rounded hover:bg-charcoal-outline transition-colors"
                            >
                              <ExternalLink className="w-3 h-3 text-gray-500" />
                            </a>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </Card>
          )}

          {/* Management */}
          {(ownerMembership || adminMemberships.length > 0 || stewardMemberships.length > 0) && (
            <Card>
              <h3 className="text-lg font-semibold text-white mb-4">Management</h3>
              <div className="space-y-2">
                {ownerMembership && (() => {
                  const driverDto = driversById[ownerMembership.driverId];
                  const summary = buildDriverSummary(ownerMembership.driverId);
                  const roleDisplay = getLeagueRoleDisplay('owner');
                  const meta = summary && summary.rating !== null
                    ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                    : null;

                  return driverDto ? (
                    <div className="flex items-center gap-2">
                      <div className="flex-1">
                        <DriverIdentity
                          driver={driverDto}
                          href={`/drivers/${ownerMembership.driverId}?from=league-management&leagueId=${leagueId}`}
                          meta={meta}
                          size="sm"
                        />
                      </div>
                      <span className={`px-2 py-1 text-xs font-medium rounded border ${roleDisplay.badgeClasses}`}>
                        {roleDisplay.text}
                      </span>
                    </div>
                  ) : null;
                })()}

                {adminMemberships.slice(0, 3).map((membership) => {
                  const driverDto = driversById[membership.driverId];
                  const summary = buildDriverSummary(membership.driverId);
                  const roleDisplay = getLeagueRoleDisplay('admin');
                  const meta = summary && summary.rating !== null
                    ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                    : null;

                  return driverDto ? (
                    <div key={membership.driverId} className="flex items-center gap-2">
                      <div className="flex-1">
                        <DriverIdentity
                          driver={driverDto}
                          href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
                          meta={meta}
                          size="sm"
                        />
                      </div>
                      <span className={`px-2 py-1 text-xs font-medium rounded border ${roleDisplay.badgeClasses}`}>
                        {roleDisplay.text}
                      </span>
                    </div>
                  ) : null;
                })}

                {stewardMemberships.slice(0, 3).map((membership) => {
                  const driverDto = driversById[membership.driverId];
                  const summary = buildDriverSummary(membership.driverId);
                  const roleDisplay = getLeagueRoleDisplay('steward');
                  const meta = summary && summary.rating !== null
                    ? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
                    : null;

                  return driverDto ? (
                    <div key={membership.driverId} className="flex items-center gap-2">
                      <div className="flex-1">
                        <DriverIdentity
                          driver={driverDto}
                          href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
                          meta={meta}
                          size="sm"
                        />
                      </div>
                      <span className={`px-2 py-1 text-xs font-medium rounded border ${roleDisplay.badgeClasses}`}>
                        {roleDisplay.text}
                      </span>
                    </div>
                  ) : null;
                })}
              </div>
            </Card>
          )}
        </div>
      </div>

      {/* End Race Modal */}
      {endRaceModalRaceId && (() => {
        const race = runningRaces.find(r => r.id === endRaceModalRaceId);
        return race ? (
          <EndRaceModal
            raceId={race.id}
            raceName={race.track}
            onConfirm={async () => {
              try {
                const completeRace = getCompleteRaceUseCase();
                await completeRace.execute({ raceId: race.id });
                await loadLeagueData();
                setEndRaceModalRaceId(null);
              } catch (err) {
                alert(err instanceof Error ? err.message : 'Failed to complete race');
              }
            }}
            onCancel={() => setEndRaceModalRaceId(null)}
          />
        ) : null;
      })()}
    </>
  );
}