'use client';

import Breadcrumbs from '@/components/layout/Breadcrumbs';
import EndRaceModal from '@/components/leagues/EndRaceModal';
import FileProtestModal from '@/components/races/FileProtestModal';
import SponsorInsightsCard, { MetricBuilders, SlotTemplates, useSponsorMode } from '@/components/sponsors/SponsorInsightsCard';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Heading from '@/components/ui/Heading';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useRaceDetail, useRegisterForRace, useWithdrawFromRace, useCancelRace, useCompleteRace, useReopenRace } from '@/hooks/useRaceService';
import { useLeagueMembership } from '@/hooks/useLeagueMembershipService';
import { LeagueMembershipUtility } from '@/lib/utilities/LeagueMembershipUtility';
import { RaceDetailEntryViewModel } from '@/lib/view-models/RaceDetailEntryViewModel';
import { RaceDetailUserResultViewModel } from '@/lib/view-models/RaceDetailUserResultViewModel';
import {
  AlertTriangle,
  ArrowLeft,
  ArrowRight,
  Calendar,
  Car,
  CheckCircle2,
  Clock,
  Flag,
  PlayCircle,
  Scale,
  Trophy,
  UserMinus,
  UserPlus,
  Users,
  XCircle,
  Zap,
} from 'lucide-react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';

export default function RaceDetailPage() {
  const router = useRouter();
  const params = useParams();
  const raceId = params.id as string;
  const currentDriverId = useEffectiveDriverId();
  const isSponsorMode = useSponsorMode();

  const { data: viewModel, isLoading: loading, error } = useRaceDetail(raceId, currentDriverId);
  const { data: membership } = useLeagueMembership(viewModel?.league?.id || '', currentDriverId);

  const [ratingChange, setRatingChange] = useState<number | null>(null);
  const [animatedRatingChange, setAnimatedRatingChange] = useState(0);
  const [showProtestModal, setShowProtestModal] = useState(false);
  const [showEndRaceModal, setShowEndRaceModal] = useState(false);

  const registerMutation = useRegisterForRace();
  const withdrawMutation = useWithdrawFromRace();
  const cancelMutation = useCancelRace();
  const completeMutation = useCompleteRace();
  const reopenMutation = useReopenRace();

  // Set rating change when viewModel changes
  useEffect(() => {
    if (viewModel?.userResult?.ratingChange !== undefined) {
      setRatingChange(viewModel.userResult.ratingChange);
    }
  }, [viewModel?.userResult?.ratingChange]);

  // Animate rating change when it changes
  useEffect(() => {
    if (ratingChange !== null) {
      let start = 0;
      const end = ratingChange;
      const duration = 1000;
      const startTime = performance.now();

      const animate = (currentTime: number) => {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 3);
        const current = Math.round(start + (end - start) * eased);
        setAnimatedRatingChange(current);

        if (progress < 1) {
          requestAnimationFrame(animate);
        }
      };

      requestAnimationFrame(animate);
    }
  }, [ratingChange]);

  const handleCancelRace = async () => {
    const race = viewModel?.race;
    if (!race || race.status !== 'scheduled') return;

    const confirmed = window.confirm(
      'Are you sure you want to cancel this race? This action cannot be undone.',
    );

    if (!confirmed) return;

    try {
      await cancelMutation.mutateAsync(race.id);
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to cancel race');
    }
  };

  const handleRegister = async () => {
    const race = viewModel?.race;
    const league = viewModel?.league;
    if (!race || !league) return;

    const confirmed = window.confirm(
      `Register for ${race.track}?\n\nYou'll be added to the entry list for this race.`,
    );

    if (!confirmed) return;

    try {
      await registerMutation.mutateAsync({ raceId: race.id, leagueId: league.id, driverId: currentDriverId });
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to register for race');
    }
  };

  const handleWithdraw = async () => {
    const race = viewModel?.race;
    const league = viewModel?.league;
    if (!race || !league) return;

    const confirmed = window.confirm(
      'Withdraw from this race?\n\nYou can register again later if you change your mind.',
    );

    if (!confirmed) return;

    try {
      await withdrawMutation.mutateAsync({ raceId: race.id, driverId: currentDriverId });
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to withdraw from race');
    }
  };

  const handleReopenRace = async () => {
    const race = viewModel?.race;
    if (!race || !viewModel?.canReopenRace) return;

    const confirmed = window.confirm(
      'Re-open this race? This will allow re-registration and re-running. Results will be archived.',
    );

    if (!confirmed) return;

    try {
      await reopenMutation.mutateAsync(race.id);
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Failed to re-open race');
    }
  };

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('en-US', {
      weekday: 'long',
      month: 'long',
      day: 'numeric',
      year: 'numeric',
    });
  };

  const formatTime = (date: Date) => {
    return new Date(date).toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      timeZoneName: 'short',
    });
  };

  const getTimeUntil = (date: Date) => {
    const now = new Date();
    const target = new Date(date);
    const diffMs = target.getTime() - now.getTime();

    if (diffMs < 0) return null;

    const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

    if (days > 0) return `${days}d ${hours}h`;
    if (hours > 0) return `${hours}h ${minutes}m`;
    return `${minutes}m`;
  };

  const statusConfig = {
    scheduled: {
      icon: Clock,
      color: 'text-primary-blue',
      bg: 'bg-primary-blue/10',
      border: 'border-primary-blue/30',
      label: 'Scheduled',
      description: 'This race is scheduled and waiting to start',
    },
    running: {
      icon: PlayCircle,
      color: 'text-performance-green',
      bg: 'bg-performance-green/10',
      border: 'border-performance-green/30',
      label: 'LIVE NOW',
      description: 'This race is currently in progress',
    },
    completed: {
      icon: CheckCircle2,
      color: 'text-gray-400',
      bg: 'bg-gray-500/10',
      border: 'border-gray-500/30',
      label: 'Completed',
      description: 'This race has finished',
    },
    cancelled: {
      icon: XCircle,
      color: 'text-warning-amber',
      bg: 'bg-warning-amber/10',
      border: 'border-warning-amber/30',
      label: 'Cancelled',
      description: 'This race has been cancelled',
    },
  } as const;

  if (loading) {
    return (
      <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
        <div className="max-w-4xl mx-auto">
          <div className="animate-pulse space-y-6">
            <div className="h-6 bg-iron-gray rounded w-1/4" />
            <div className="h-48 bg-iron-gray rounded-xl" />
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 h-64 bg-iron-gray rounded-xl" />
              <div className="h-64 bg-iron-gray rounded-xl" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !viewModel || !viewModel.race) {
    return (
      <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
        <div className="max-w-4xl mx-auto">
          <Breadcrumbs items={[{ label: 'Races', href: '/races' }, { label: 'Error' }]} />

          <Card className="text-center py-12 mt-6">
            <div className="flex flex-col items-center gap-4">
              <div className="p-4 bg-warning-amber/10 rounded-full">
                <AlertTriangle className="w-8 h-8 text-warning-amber" />
              </div>
              <div>
                <p className="text-white font-medium mb-1">{error instanceof Error ? error.message : error || 'Race not found'}</p>
                <p className="text-sm text-gray-500">
                  The race you're looking for doesn't exist or has been removed.
                </p>
              </div>
              <Button
                variant="secondary"
                onClick={() => router.push('/races')}
                className="mt-4"
              >
                Back to Races
              </Button>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  const race = viewModel.race;
  const league = viewModel.league;
  const entryList: RaceDetailEntryViewModel[] = viewModel.entryList;
  const registration = viewModel.registration;
  const userResult: RaceDetailUserResultViewModel | null = viewModel.userResult;
  const raceSOF = null; // TODO: Add strength of field to race details response

  const config = statusConfig[race.status as keyof typeof statusConfig];
  const StatusIcon = config.icon;
  const timeUntil = race.status === 'scheduled' ? getTimeUntil(new Date(race.scheduledAt)) : null;

  const breadcrumbItems = [
    { label: 'Races', href: '/races' },
    ...(league ? [{ label: league.name, href: `/leagues/${league.id}` }] : []),
    { label: race.track },
  ];

  const getCountryFlag = (countryCode: string): string => {
    const codePoints = countryCode
      .toUpperCase()
      .split('')
      .map(char => 127397 + char.charCodeAt(0));
    return String.fromCodePoint(...codePoints);
  };

  const sponsorInsights = {
    tier: 'gold' as const,
    trustScore: 92,
    discordMembers: league ? 1847 : undefined,
    monthlyActivity: 156,
  };

  const raceMetrics = [
    MetricBuilders.views(entryList.length * 12),
    MetricBuilders.engagement(78),
    { label: 'SOF', value: raceSOF != null ? String(raceSOF) : '—', icon: Zap, color: 'text-warning-amber' as const },
    MetricBuilders.reach(entryList.length * 45),
  ];

  return (
    <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* Navigation Row: Breadcrumbs left, Back button right */}
        <div className="flex items-center justify-between">
          <Breadcrumbs items={breadcrumbItems} className="text-sm text-gray-400" />
          <Button
            variant="secondary"
            onClick={() => router.back()}
            className="flex items-center gap-2 text-sm"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
        </div>

        {/* Sponsor Insights Card - Consistent placement at top */}
        {isSponsorMode && race && league && (
          <SponsorInsightsCard
            entityType="race"
            entityId={raceId}
            entityName={race.track}
            tier="premium"
            metrics={raceMetrics}
            slots={SlotTemplates.race(true, 500)}
            trustScore={sponsorInsights.trustScore}
            monthlyActivity={sponsorInsights.monthlyActivity}
          />
        )}

        {/* User Result - Premium Achievement Card */}
        {userResult && (
          <div
            className={`
            relative overflow-hidden rounded-2xl p-1
            ${
              userResult.position === 1
                ? 'bg-gradient-to-r from-yellow-500 via-yellow-400 to-yellow-600'
                : userResult.isPodium
                ? 'bg-gradient-to-r from-gray-400 via-gray-300 to-gray-500'
                : 'bg-gradient-to-r from-primary-blue via-primary-blue/80 to-primary-blue'
            }
          `}
          >
            <div className="relative bg-deep-graphite rounded-xl p-6 sm:p-8">
              {/* Decorative elements */}
              <div className="absolute top-0 left-0 w-32 h-32 bg-gradient-to-br from-white/10 to-transparent rounded-full blur-2xl" />
              <div className="absolute bottom-0 right-0 w-48 h-48 bg-gradient-to-tl from-white/5 to-transparent rounded-full blur-3xl" />

              {/* Victory confetti effect for P1 */}
              {userResult.position === 1 && (
                <div className="absolute inset-0 overflow-hidden pointer-events-none">
                  <div className="absolute top-4 left-[10%] w-2 h-2 bg-yellow-400 rounded-full animate-pulse" />
                  <div className="absolute top-8 left-[25%] w-1.5 h-1.5 bg-yellow-300 rounded-full animate-pulse delay-100" />
                  <div className="absolute top-6 right-[20%] w-2 h-2 bg-yellow-500 rounded-full animate-pulse delay-200" />
                  <div className="absolute top-10 right-[35%] w-1 h-1 bg-yellow-400 rounded-full animate-pulse delay-300" />
                </div>
              )}

              <div className="relative z-10">
                {/* Main content grid */}
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
                  {/* Left: Position and achievement */}
                  <div className="flex items-center gap-5">
                    {/* Giant position badge */}
                    <div
                      className={`
                      relative flex items-center justify-center w-24 h-24 sm:w-28 sm:h-28 rounded-3xl font-black text-4xl sm:text-5xl
                      ${
                        userResult.position === 1
                          ? 'bg-gradient-to-br from-yellow-400 to-yellow-600 text-deep-graphite shadow-2xl shadow-yellow-500/30'
                          : userResult.position === 2
                          ? 'bg-gradient-to-br from-gray-300 to-gray-500 text-deep-graphite shadow-xl shadow-gray-400/20'
                          : userResult.position === 3
                          ? 'bg-gradient-to-br from-amber-600 to-amber-800 text-white shadow-xl shadow-amber-600/20'
                          : 'bg-gradient-to-br from-primary-blue to-primary-blue/70 text-white shadow-xl shadow-primary-blue/20'
                      }
                    `}
                    >
                      {userResult.position === 1 && (
                        <Trophy className="absolute -top-3 -right-2 w-8 h-8 text-yellow-300 drop-shadow-lg" />
                      )}
                      <span>P{userResult.position}</span>
                    </div>

                    {/* Achievement text */}
                    <div>
                      <p
                        className={`
                          text-2xl sm:text-3xl font-bold mb-1
                          ${
                            userResult.position === 1
                              ? 'text-yellow-400'
                              : userResult.isPodium
                              ? 'text-gray-300'
                              : 'text-white'
                          }
                        `}
                      >
                        {userResult.position === 1
                          ? '🏆 VICTORY!'
                          : userResult.position === 2
                          ? '🥈 Second Place'
                          : userResult.position === 3
                          ? '🥉 Podium Finish'
                          : userResult.position <= 5
                          ? '⭐ Top 5 Finish'
                          : userResult.position <= 10
                          ? 'Points Finish'
                          : `P${userResult.position} Finish`}
                      </p>
                      <div className="flex items-center gap-3 text-sm text-gray-400">
                        <span>Started P{userResult.startPosition}</span>
                        <span className="w-1 h-1 rounded-full bg-gray-600" />
                        <span className={userResult.isClean ? 'text-performance-green' : ''}>
                          {userResult.incidents}x incidents
                          {userResult.isClean && ' ✨'}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Right: Stats cards */}
                  <div className="flex flex-wrap gap-3">
                    {/* Position change */}
                    {userResult.positionChange !== 0 && (
                      <div
                        className={`
                        flex flex-col items-center px-5 py-3 rounded-2xl min-w-[100px]
                        ${
                          userResult.positionChange > 0
                            ? 'bg-gradient-to-br from-performance-green/30 to-performance-green/10 border border-performance-green/40'
                            : 'bg-gradient-to-br from-red-500/30 to-red-500/10 border border-red-500/40'
                        }
                      `}
                      >
                        <div
                          className={`
                          flex items-center gap-1 font-black text-2xl
                          ${
                            userResult.positionChange > 0
                              ? 'text-performance-green'
                              : 'text-red-400'
                          }
                        `}
                        >
                          {userResult.positionChange > 0 ? (
                            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                              <path
                                fillRule="evenodd"
                                d="M10 17a.75.75 0 01-.75-.75V5.612L5.29 9.77a.75.75 0 01-1.08-1.04l5.25-5.5a.75.75 0 011.08 0l5.25 5.5a.75.75 0 11-1.08 1.04l-3.96-4.158V16.25A.75.75 0 0110 17z"
                                clipRule="evenodd"
                              />
                            </svg>
                          ) : (
                            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                              <path
                                fillRule="evenodd"
                                d="M10 3a.75.75 0 01.75.75v10.638l3.96-4.158a.75.75 0 111.08 1.04l-5.25 5.5a.75.75 0 01-1.08 0l-5.25-5.5a.75.75 0 111.08-1.04l3.96 4.158V3.75A.75.75 0 0110 3z"
                                clipRule="evenodd"
                              />
                            </svg>
                          )}
                          {Math.abs(userResult.positionChange)}
                        </div>
                        <div className="text-xs text-gray-400 mt-0.5">
                          {userResult.positionChange > 0 ? 'Gained' : 'Lost'}
                        </div>
                      </div>
                    )}

                    {/* Rating change */}
                    {ratingChange !== null && (
                      <div
                        className={`
                        flex flex-col items-center px-5 py-3 rounded-2xl min-w-[100px]
                        ${
                          ratingChange > 0
                            ? 'bg-gradient-to-br from-warning-amber/30 to-warning-amber/10 border border-warning-amber/40'
                            : 'bg-gradient-to-br from-red-500/30 to-red-500/10 border border-red-500/40'
                        }
                      `}
                      >
                        <div
                          className={`
                          font-mono font-black text-2xl
                          ${ratingChange > 0 ? 'text-warning-amber' : 'text-red-400'}
                        `}
                        >
                          {animatedRatingChange > 0 ? '+' : ''}
                          {animatedRatingChange}
                        </div>
                        <div className="text-xs text-gray-400 mt-0.5">Rating</div>
                      </div>
                    )}

                    {/* Clean race bonus */}
                    {userResult.isClean && (
                      <div className="flex flex-col items-center px-5 py-3 rounded-2xl min-w-[100px] bg-gradient-to-br from-performance-green/30 to-performance-green/10 border border-performance-green/40">
                        <div className="text-2xl">✨</div>
                        <div className="text-xs text-performance-green mt-0.5 font-medium">
                          Clean Race
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Hero Header */}
        <div className={`relative overflow-hidden rounded-2xl ${config.bg} border ${config.border} p-6 sm:p-8`}>
          {/* Live indicator */}
          {race.status === 'running' && (
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-performance-green via-performance-green/50 to-performance-green animate-pulse" />
          )}

          <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full blur-3xl" />

          <div className="relative z-10">
            {/* Status Badge */}
            <div className="flex items-center gap-3 mb-4">
              <div className={`flex items-center gap-2 px-3 py-1.5 rounded-full ${config.bg} border ${config.border}`}>
                {race.status === 'running' && (
                  <span className="w-2 h-2 bg-performance-green rounded-full animate-pulse" />
                )}
                <StatusIcon className={`w-4 h-4 ${config.color}`} />
                <span className={`text-sm font-semibold ${config.color}`}>{config.label}</span>
              </div>
              {timeUntil && (
                <span className="text-sm text-gray-400">
                  Starts in <span className="text-white font-medium">{timeUntil}</span>
                </span>
              )}
            </div>

            {/* Title */}
            <Heading level={1} className="text-2xl sm:text-3xl font-bold text-white mb-2">
              {race.track}
            </Heading>

            {/* Meta */}
            <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-gray-400">
              <span className="flex items-center gap-2">
                <Calendar className="w-4 h-4" />
                {formatDate(new Date(race.scheduledAt))}
              </span>
              <span className="flex items-center gap-2">
                <Clock className="w-4 h-4" />
                {formatTime(new Date(race.scheduledAt))}
              </span>
              <span className="flex items-center gap-2">
                <Car className="w-4 h-4" />
                {race.car}
              </span>
            </div>
          </div>
          {/* Prominent SOF Badge - Electric Design */}
          {raceSOF != null && (
            <div className="absolute top-6 right-6 sm:top-8 sm:right-8">
              <div className="relative group">
                {/* Glow effect */}
                <div className="absolute inset-0 bg-warning-amber/40 rounded-2xl blur-xl group-hover:blur-2xl transition-all duration-300" />

                <div className="relative flex items-center gap-4 px-6 py-4 rounded-2xl bg-gradient-to-br from-warning-amber/30 via-warning-amber/20 to-orange-500/20 border border-warning-amber/50 shadow-2xl backdrop-blur-sm">
                  {/* Electric bolt with animation */}
                  <div className="relative">
                    <Zap className="w-8 h-8 text-warning-amber drop-shadow-lg" />
                    <Zap className="absolute inset-0 w-8 h-8 text-warning-amber animate-pulse opacity-50" />
                  </div>

                  <div>
                    <div className="text-[10px] text-warning-amber/90 uppercase tracking-widest font-bold mb-0.5">
                      Strength of Field
                    </div>
                    <div className="flex items-baseline gap-1">
                      <span className="text-3xl font-black text-warning-amber font-mono tracking-tight drop-shadow-lg">
                        {raceSOF}
                      </span>
                      <span className="text-sm text-warning-amber/70 font-medium">SOF</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Race Details */}
            <Card>
              <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <Flag className="w-5 h-5 text-primary-blue" />
                Race Details
              </h2>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Track</p>
                  <p className="text-white font-medium">{race.track}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Car</p>
                  <p className="text-white font-medium">{race.car}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Session Type</p>
                  <p className="text-white font-medium capitalize">{race.sessionType}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</p>
                  <p className={`font-medium ${config.color}`}>{config.label}</p>
                </div>
                <div className="p-4 bg-deep-graphite rounded-lg">
                  <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Strength of Field</p>
                  <p className="text-warning-amber font-medium flex items-center gap-1.5">
                    <Zap className="w-4 h-4" />
                    {raceSOF ?? '—'}
                  </p>
                </div>
                {/* TODO: Add registered count and max participants to race details response */}
                {/* {race.registeredCount !== undefined && (
                  <div className="p-4 bg-deep-graphite rounded-lg">
                    <p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Registered</p>
                    <p className="text-white font-medium">
                      {race.registeredCount}
                      {race.maxParticipants && ` / ${race.maxParticipants}`}
                    </p>
                  </div>
                )} */}
              </div>
            </Card>

            {/* Entry List */}
            <Card>
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-semibold text-white flex items-center gap-2">
                  <Users className="w-5 h-5 text-primary-blue" />
                  Entry List
                </h2>
                <span className="text-sm text-gray-400">
                  {entryList.length} driver{entryList.length !== 1 ? 's' : ''}
                </span>
              </div>

              {entryList.length === 0 ? (
                <div className="text-center py-8">
                  <div className="p-4 bg-iron-gray rounded-full inline-block mb-3">
                    <Users className="w-6 h-6 text-gray-500" />
                  </div>
                  <p className="text-gray-400">No drivers registered yet</p>
                  <p className="text-sm text-gray-500">Be the first to sign up!</p>
                </div>
              ) : (
                <div className="space-y-1">
                  {entryList.map((driver, index) => {
                    const isCurrentUser = driver.isCurrentUser;
                    const countryFlag = getCountryFlag(driver.country);

                    return (
                      <div
                        key={driver.id}
                        onClick={() => router.push(`/drivers/${driver.id}`)}
                        className={`
                          flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all duration-200
                          ${
                            isCurrentUser
                              ? 'bg-gradient-to-r from-primary-blue/20 via-primary-blue/10 to-transparent border border-primary-blue/40 shadow-lg shadow-primary-blue/10'
                              : 'bg-deep-graphite hover:bg-charcoal-outline/50 border border-transparent'
                          }
                        `}
                      >
                        {/* Position number */}
                        <div
                          className={`
                            flex items-center justify-center w-8 h-8 rounded-lg font-bold text-sm
                            ${
                              race.status === 'completed' && index === 0
                                ? 'bg-yellow-500/20 text-yellow-400'
                                : race.status === 'completed' && index === 1
                                ? 'bg-gray-400/20 text-gray-300'
                                : race.status === 'completed' && index === 2
                                ? 'bg-amber-600/20 text-amber-500'
                                : 'bg-iron-gray text-gray-500'
                            }
                          `}
                        >
                          {index + 1}
                        </div>

                        {/* Avatar with nation flag */}
                        <div className="relative flex-shrink-0">
                          <img
                            src={driver.avatarUrl}
                            alt={driver.name}
                            className={`
                              w-10 h-10 rounded-full object-cover
                              ${isCurrentUser ? 'ring-2 ring-primary-blue/50' : ''}
                            `}
                          />
                          {/* Nation flag */}
                          <div className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-deep-graphite border-2 border-deep-graphite flex items-center justify-center text-xs shadow-sm">
                            {countryFlag}
                          </div>
                        </div>

                        {/* Driver info */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <p
                              className={`text-sm font-semibold truncate ${
                                isCurrentUser ? 'text-primary-blue' : 'text-white'
                              }`}
                            >
                              {driver.name}
                            </p>
                            {isCurrentUser && (
                              <span className="px-2 py-0.5 text-[10px] font-bold bg-primary-blue text-white rounded-full uppercase tracking-wide">
                                You
                              </span>
                            )}
                          </div>
                          <p className="text-xs text-gray-500">{driver.country}</p>
                        </div>

                        {/* Rating badge */}
                        {driver.rating != null && (
                          <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-warning-amber/10 border border-warning-amber/20">
                            <Zap className="w-3 h-3 text-warning-amber" />
                            <span className="text-xs font-bold text-warning-amber font-mono">
                              {driver.rating}
                            </span>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </Card>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* League Card - Premium Design */}
            {league && (
              <Card className="overflow-hidden">
                <div className="flex items-center gap-4 mb-4">
                  <div className="w-14 h-14 rounded-xl overflow-hidden bg-iron-gray flex-shrink-0">
                    <img
                      src={`league-logo-${league.id}`}
                      alt={league.name}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs text-gray-500 uppercase tracking-wide mb-0.5">League</p>
                    <h3 className="text-white font-semibold truncate">{league.name}</h3>
                  </div>
                </div>

                {league.description && (
                  <p className="text-sm text-gray-400 mb-4 line-clamp-2">{league.description}</p>
                )}

                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className="p-3 rounded-lg bg-deep-graphite">
                    <p className="text-xs text-gray-500 mb-1">Max Drivers</p>
                    <p className="text-white font-medium">{(league.settings as any).maxDrivers ?? 32}</p>
                  </div>
                  <div className="p-3 rounded-lg bg-deep-graphite">
                    <p className="text-xs text-gray-500 mb-1">Format</p>
                    <p className="text-white font-medium capitalize">
                      {(league.settings as any).qualifyingFormat ?? 'Open'}
                    </p>
                  </div>
                </div>

                <Link
                  href={`/leagues/${league.id}`}
                  className="flex items-center justify-center gap-2 w-full py-2.5 rounded-lg bg-primary-blue/10 border border-primary-blue/30 text-primary-blue text-sm font-medium hover:bg-primary-blue/20 transition-colors"
                >
                  View League
                  <ArrowRight className="w-4 h-4" />
                </Link>
              </Card>
            )}

            {/* Quick Actions Card */}
            <Card>
              <h2 className="text-lg font-semibold text-white mb-4">Actions</h2>

              <div className="space-y-3">
                {/* Registration Actions */}
                {race.status === 'scheduled' && registration.canRegister && !registration.isUserRegistered && (
                  <Button
                    variant="primary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={handleRegister}
                    disabled={registerMutation.isPending}
                  >
                    <UserPlus className="w-4 h-4" />
                    {registerMutation.isPending ? 'Registering...' : 'Register for Race'}
                  </Button>
                )}

                {race.status === 'scheduled' && registration.isUserRegistered && (
                  <>
                    <div className="flex items-center gap-2 px-4 py-3 bg-performance-green/10 border border-performance-green/30 rounded-lg text-performance-green">
                      <CheckCircle2 className="w-5 h-5" />
                      <span className="font-medium">You're Registered</span>
                    </div>
                    <Button
                      variant="secondary"
                      className="w-full flex items-center justify-center gap-2"
                      onClick={handleWithdraw}
                      disabled={withdrawMutation.isPending}
                    >
                      <UserMinus className="w-4 h-4" />
                      {withdrawMutation.isPending ? 'Withdrawing...' : 'Withdraw'}
                    </Button>
                  </>
                )}

                {viewModel.canReopenRace &&
                  LeagueMembershipUtility.isOwnerOrAdmin(viewModel.league?.id || '', currentDriverId) && (
                  <Button
                    variant="secondary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={handleReopenRace}
                    disabled={reopenMutation.isPending}
                  >
                    <PlayCircle className="w-4 h-4" />
                    {reopenMutation.isPending ? 'Re-opening...' : 'Re-open Race'}
                  </Button>
                )}

                {race.status === 'completed' && (
                  <>
                    <Button
                      variant="primary"
                      className="w-full flex items-center justify-center gap-2"
                      onClick={() => router.push(`/races/${race.id}/results`)}
                    >
                      <Trophy className="w-4 h-4" />
                      View Results
                    </Button>
                    {userResult && (
                      <Button
                        variant="secondary"
                        className="w-full flex items-center justify-center gap-2"
                        onClick={() => setShowProtestModal(true)}
                      >
                        <Scale className="w-4 h-4" />
                        File Protest
                      </Button>
                    )}
                    <Button
                      variant="secondary"
                      className="w-full flex items-center justify-center gap-2"
                      onClick={() => router.push(`/races/${race.id}/stewarding`)}
                    >
                      <Scale className="w-4 h-4" />
                      Stewarding
                    </Button>
                  </>
                )}

                {viewModel.canReopenRace &&
                  LeagueMembershipUtility.isOwnerOrAdmin(viewModel.league?.id || '', currentDriverId) && (
                  <Button
                    variant="secondary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={handleReopenRace}
                    disabled={reopenMutation.isPending}
                  >
                    <PlayCircle className="w-4 h-4" />
                    {reopenMutation.isPending ? 'Re-opening...' : 'Re-open Race'}
                  </Button>
                )}

                {race.status === 'running' && LeagueMembershipUtility.isOwnerOrAdmin(viewModel.league?.id || '', currentDriverId) && (
                  <Button
                    variant="primary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={() => setShowEndRaceModal(true)}
                  >
                    <CheckCircle2 className="w-4 h-4" />
                    End Race & Process Results
                  </Button>
                )}

                {race.status === 'scheduled' && (
                  <Button
                    variant="secondary"
                    className="w-full flex items-center justify-center gap-2"
                    onClick={handleCancelRace}
                    disabled={cancelMutation.isPending}
                  >
                    <XCircle className="w-4 h-4" />
                    {cancelMutation.isPending ? 'Cancelling...' : 'Cancel Race'}
                  </Button>
                )}
              </div>
            </Card>

            {/* Status Info */}
            <Card className={`${config.bg} border ${config.border}`}>
              <div className="flex items-start gap-3">
                <div className={`p-2 rounded-lg ${config.bg}`}>
                  <StatusIcon className={`w-5 h-5 ${config.color}`} />
                </div>
                <div>
                  <p className={`font-medium ${config.color}`}>{config.label}</p>
                  <p className="text-sm text-gray-400 mt-1">{config.description}</p>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </div>

      {/* Protest Filing Modal */}
      <FileProtestModal
        isOpen={showProtestModal}
        onClose={() => setShowProtestModal(false)}
        raceId={race.id}
        leagueId={league ? league.id : ''}
        protestingDriverId={currentDriverId}
        participants={entryList.map(d => ({ id: d.id, name: d.name }))}
      />

      {/* End Race Modal */}
      {showEndRaceModal && (
        <EndRaceModal
          raceId={race.id}
          raceName={race.track}
          onConfirm={async () => {
            try {
              await completeMutation.mutateAsync(race.id);
              setShowEndRaceModal(false);
            } catch (err) {
              alert(err instanceof Error ? err.message : 'Failed to complete race');
            }
          }}
          onCancel={() => setShowEndRaceModal(false)}
        />
      )}
    </div>
  );
}