'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Users,
  Trophy,
  Search,
  Plus,
  Sparkles,
  Crown,
  Star,
  TrendingUp,
  Shield,
  Zap,
  UserPlus,
  ChevronRight,
  Timer,
  Target,
  Award,
  Handshake,
  MessageCircle,
  Calendar,
} from 'lucide-react';
import TeamCard from '@/components/teams/TeamCard';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
import CreateTeamForm from '@/components/teams/CreateTeamForm';
import { getGetAllTeamsQuery, getGetTeamMembersQuery, getDriverStats } from '@/lib/di-container';
import type { Team } from '@gridpilot/racing';

// ============================================================================
// TYPES
// ============================================================================

type SkillLevel = 'beginner' | 'intermediate' | 'advanced' | 'pro';

interface TeamDisplayData {
  id: string;
  name: string;
  memberCount: number;
  rating: number | null;
  totalWins: number;
  totalRaces: number;
  performanceLevel: SkillLevel;
  isRecruiting: boolean;
  createdAt: Date;
  description?: string;
  specialization?: 'endurance' | 'sprint' | 'mixed';
  region?: string;
  languages?: string[];
}

// ============================================================================
// DEMO TEAMS DATA
// ============================================================================

const DEMO_TEAMS: TeamDisplayData[] = [
  // Pro Teams
  {
    id: 'demo-team-1',
    name: 'Apex Predators Racing',
    description: 'Elite GT3 team competing at the highest level. Multiple championship winners seeking consistent drivers.',
    memberCount: 8,
    rating: 4850,
    totalWins: 47,
    totalRaces: 156,
    performanceLevel: 'pro',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000),
    specialization: 'mixed',
    region: '🇺🇸 North America',
    languages: ['English'],
  },
  {
    id: 'demo-team-2',
    name: 'Velocity Esports',
    description: 'Professional sim racing team with sponsors. Competing in major endurance events worldwide.',
    memberCount: 12,
    rating: 5200,
    totalWins: 63,
    totalRaces: 198,
    performanceLevel: 'pro',
    isRecruiting: false,
    createdAt: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000),
    specialization: 'endurance',
    region: '🇬🇧 Europe',
    languages: ['English', 'German'],
  },
  {
    id: 'demo-team-3',
    name: 'Nitro Motorsport',
    description: 'Championship-winning sprint specialists. Fast, consistent, and always fighting for podiums.',
    memberCount: 6,
    rating: 4720,
    totalWins: 38,
    totalRaces: 112,
    performanceLevel: 'pro',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000),
    specialization: 'sprint',
    region: '🇩🇪 Germany',
    languages: ['German', 'English'],
  },
  // Advanced Teams
  {
    id: 'demo-team-4',
    name: 'Horizon Racing Collective',
    description: 'Ambitious team on the rise. Building towards professional competition with dedicated drivers.',
    memberCount: 10,
    rating: 3800,
    totalWins: 24,
    totalRaces: 89,
    performanceLevel: 'advanced',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000),
    specialization: 'mixed',
    region: '🇳🇱 Netherlands',
    languages: ['Dutch', 'English'],
  },
  {
    id: 'demo-team-5',
    name: 'Phoenix Rising eSports',
    description: 'From the ashes to the podium. A team built on improvement and teamwork.',
    memberCount: 7,
    rating: 3650,
    totalWins: 19,
    totalRaces: 76,
    performanceLevel: 'advanced',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 45 * 24 * 60 * 60 * 1000),
    specialization: 'endurance',
    region: '🇫🇷 France',
    languages: ['French', 'English'],
  },
  {
    id: 'demo-team-6',
    name: 'Thunderbolt Racing',
    description: 'Fast and furious sprint racing. We live for wheel-to-wheel battles.',
    memberCount: 5,
    rating: 3420,
    totalWins: 15,
    totalRaces: 54,
    performanceLevel: 'advanced',
    isRecruiting: false,
    createdAt: new Date(Date.now() - 120 * 24 * 60 * 60 * 1000),
    specialization: 'sprint',
    region: '🇮🇹 Italy',
    languages: ['Italian', 'English'],
  },
  // Intermediate Teams
  {
    id: 'demo-team-7',
    name: 'Grid Starters',
    description: 'Growing together as racers. Friendly competition with a focus on learning and fun.',
    memberCount: 9,
    rating: 2800,
    totalWins: 11,
    totalRaces: 67,
    performanceLevel: 'intermediate',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
    specialization: 'mixed',
    region: '🇪🇸 Spain',
    languages: ['Spanish', 'English'],
  },
  {
    id: 'demo-team-8',
    name: 'Midnight Racers',
    description: 'Night owls who love endurance racing. Join us for late-night stints and good vibes.',
    memberCount: 6,
    rating: 2650,
    totalWins: 8,
    totalRaces: 42,
    performanceLevel: 'intermediate',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
    specialization: 'endurance',
    region: '🌍 International',
    languages: ['English'],
  },
  {
    id: 'demo-team-9',
    name: 'Casual Speedsters',
    description: 'Racing for fun, improving together. No pressure, just clean racing.',
    memberCount: 4,
    rating: 2400,
    totalWins: 5,
    totalRaces: 31,
    performanceLevel: 'intermediate',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    specialization: 'sprint',
    region: '🇵🇱 Poland',
    languages: ['Polish', 'English'],
  },
  // Beginner Teams
  {
    id: 'demo-team-10',
    name: 'Fresh Rubber Racing',
    description: 'New team for new racers! Learn the basics together in a supportive environment.',
    memberCount: 3,
    rating: 1800,
    totalWins: 2,
    totalRaces: 18,
    performanceLevel: 'beginner',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
    specialization: 'mixed',
    region: '🇧🇷 Brazil',
    languages: ['Portuguese', 'English'],
  },
  {
    id: 'demo-team-11',
    name: 'Rookie Revolution',
    description: 'First time racers welcome! We all start somewhere.',
    memberCount: 5,
    rating: 1650,
    totalWins: 1,
    totalRaces: 12,
    performanceLevel: 'beginner',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
    specialization: 'sprint',
    region: '🇦🇺 Australia',
    languages: ['English'],
  },
  {
    id: 'demo-team-12',
    name: 'Pit Lane Pioneers',
    description: 'Learning endurance racing from scratch. Long races, longer friendships.',
    memberCount: 4,
    rating: 1500,
    totalWins: 0,
    totalRaces: 8,
    performanceLevel: 'beginner',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
    specialization: 'endurance',
    region: '🇯🇵 Japan',
    languages: ['Japanese', 'English'],
  },
  // Recently Added
  {
    id: 'demo-team-13',
    name: 'Shadow Squadron',
    description: 'Elite drivers emerging from the shadows. Watch out for us this season.',
    memberCount: 6,
    rating: 4100,
    totalWins: 12,
    totalRaces: 34,
    performanceLevel: 'advanced',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
    specialization: 'mixed',
    region: '🇸🇪 Scandinavia',
    languages: ['Swedish', 'Norwegian', 'English'],
  },
  {
    id: 'demo-team-14',
    name: 'Turbo Collective',
    description: 'Fast, furious, and friendly. Sprint racing specialists looking for quick racers.',
    memberCount: 4,
    rating: 3200,
    totalWins: 7,
    totalRaces: 28,
    performanceLevel: 'intermediate',
    isRecruiting: true,
    createdAt: new Date(Date.now() - 12 * 60 * 60 * 1000),
    specialization: 'sprint',
    region: '🇨🇦 Canada',
    languages: ['English', 'French'],
  },
];

// ============================================================================
// SKILL LEVEL CONFIG
// ============================================================================

const SKILL_LEVELS: {
  id: SkillLevel;
  label: string;
  icon: React.ElementType;
  color: string;
  bgColor: string;
  borderColor: string;
  description: string;
}[] = [
  {
    id: 'pro',
    label: 'Pro',
    icon: Crown,
    color: 'text-yellow-400',
    bgColor: 'bg-yellow-400/10',
    borderColor: 'border-yellow-400/30',
    description: 'Elite competition, sponsored teams',
  },
  {
    id: 'advanced',
    label: 'Advanced',
    icon: Star,
    color: 'text-purple-400',
    bgColor: 'bg-purple-400/10',
    borderColor: 'border-purple-400/30',
    description: 'Competitive racing, high consistency',
  },
  {
    id: 'intermediate',
    label: 'Intermediate',
    icon: TrendingUp,
    color: 'text-primary-blue',
    bgColor: 'bg-primary-blue/10',
    borderColor: 'border-primary-blue/30',
    description: 'Growing skills, regular practice',
  },
  {
    id: 'beginner',
    label: 'Beginner',
    icon: Shield,
    color: 'text-green-400',
    bgColor: 'bg-green-400/10',
    borderColor: 'border-green-400/30',
    description: 'Learning the basics, friendly environment',
  },
];

// ============================================================================
// WHY JOIN A TEAM SECTION
// ============================================================================

function WhyJoinTeamSection() {
  const benefits = [
    {
      icon: Handshake,
      title: 'Shared Strategy',
      description: 'Develop setups together, share telemetry, and coordinate pit strategies for endurance races.',
    },
    {
      icon: MessageCircle,
      title: 'Team Communication',
      description: 'Discord integration, voice chat during races, and dedicated team channels.',
    },
    {
      icon: Calendar,
      title: 'Coordinated Schedule',
      description: 'Team calendars, practice sessions, and organized race attendance.',
    },
    {
      icon: Trophy,
      title: 'Team Championships',
      description: 'Compete in team-based leagues and build your collective reputation.',
    },
  ];

  return (
    <div className="mb-12">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-white mb-2">Why Join a Team?</h2>
        <p className="text-gray-400">Racing is better when you have teammates to share the journey</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {benefits.map((benefit) => (
          <div
            key={benefit.title}
            className="p-5 rounded-xl bg-iron-gray/50 border border-charcoal-outline/50 hover:border-purple-500/30 transition-all duration-300"
          >
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-500/10 border border-purple-500/20 mb-3">
              <benefit.icon className="w-5 h-5 text-purple-400" />
            </div>
            <h3 className="text-white font-semibold mb-1">{benefit.title}</h3>
            <p className="text-sm text-gray-500">{benefit.description}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// SKILL LEVEL SECTION COMPONENT
// ============================================================================

interface SkillLevelSectionProps {
  level: typeof SKILL_LEVELS[0];
  teams: TeamDisplayData[];
  onTeamClick: (id: string) => void;
  defaultExpanded?: boolean;
}

function SkillLevelSection({ level, teams, onTeamClick, defaultExpanded = false }: SkillLevelSectionProps) {
  const [isExpanded, setIsExpanded] = useState(defaultExpanded);
  const recruitingTeams = teams.filter((t) => t.isRecruiting);
  const displayedTeams = isExpanded ? teams : teams.slice(0, 3);
  const Icon = level.icon;

  if (teams.length === 0) return null;

  return (
    <div className="mb-8">
      {/* Section Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`flex h-11 w-11 items-center justify-center rounded-xl ${level.bgColor} border ${level.borderColor}`}>
            <Icon className={`w-5 h-5 ${level.color}`} />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-xl font-bold text-white">{level.label}</h2>
              <span className="px-2 py-0.5 rounded-full text-xs bg-charcoal-outline/50 text-gray-400">
                {teams.length} {teams.length === 1 ? 'team' : 'teams'}
              </span>
              {recruitingTeams.length > 0 && (
                <span className="flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-performance-green/10 text-performance-green border border-performance-green/20">
                  <UserPlus className="w-3 h-3" />
                  {recruitingTeams.length} recruiting
                </span>
              )}
            </div>
            <p className="text-sm text-gray-500">{level.description}</p>
          </div>
        </div>

        {teams.length > 3 && (
          <button
            type="button"
            onClick={() => setIsExpanded(!isExpanded)}
            className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm text-gray-400 hover:text-white hover:bg-iron-gray/50 transition-all"
          >
            {isExpanded ? 'Show less' : `View all ${teams.length}`}
            <ChevronRight className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-90' : ''}`} />
          </button>
        )}
      </div>

      {/* Teams Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {displayedTeams.map((team) => (
          <TeamCard
            key={team.id}
            id={team.id}
            name={team.name}
            description={team.description}
            memberCount={team.memberCount}
            rating={team.rating}
            totalWins={team.totalWins}
            totalRaces={team.totalRaces}
            performanceLevel={team.performanceLevel}
            isRecruiting={team.isRecruiting}
            specialization={team.specialization}
            region={team.region}
            languages={team.languages}
            onClick={() => onTeamClick(team.id)}
          />
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// FEATURED RECRUITING TEAMS
// ============================================================================

interface FeaturedRecruitingProps {
  teams: TeamDisplayData[];
  onTeamClick: (id: string) => void;
}

function FeaturedRecruiting({ teams, onTeamClick }: FeaturedRecruitingProps) {
  const recruitingTeams = teams.filter((t) => t.isRecruiting).slice(0, 4);

  if (recruitingTeams.length === 0) return null;

  return (
    <div className="mb-10">
      <div className="flex items-center gap-3 mb-4">
        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-performance-green/10 border border-performance-green/20">
          <UserPlus className="w-5 h-5 text-performance-green" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-white">Looking for Drivers</h2>
          <p className="text-xs text-gray-500">Teams actively recruiting new members</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {recruitingTeams.map((team) => {
          const levelConfig = SKILL_LEVELS.find((l) => l.id === team.performanceLevel);
          const LevelIcon = levelConfig?.icon || Shield;

          return (
            <button
              key={team.id}
              type="button"
              onClick={() => onTeamClick(team.id)}
              className="p-4 rounded-xl bg-iron-gray/60 border border-charcoal-outline hover:border-performance-green/40 transition-all duration-200 text-left group"
            >
              <div className="flex items-start justify-between mb-3">
                <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${levelConfig?.bgColor} border ${levelConfig?.borderColor}`}>
                  <LevelIcon className={`w-4 h-4 ${levelConfig?.color}`} />
                </div>
                <span className="flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] bg-performance-green/10 text-performance-green border border-performance-green/20">
                  <div className="w-1.5 h-1.5 rounded-full bg-performance-green animate-pulse" />
                  Recruiting
                </span>
              </div>

              <h3 className="text-white font-semibold mb-1 group-hover:text-performance-green transition-colors line-clamp-1">
                {team.name}
              </h3>
              <p className="text-xs text-gray-500 line-clamp-2 mb-3">{team.description}</p>

              <div className="flex items-center gap-3 text-xs text-gray-400">
                <span className="flex items-center gap-1">
                  <Users className="w-3 h-3" />
                  {team.memberCount}
                </span>
                <span className="flex items-center gap-1">
                  <Trophy className="w-3 h-3" />
                  {team.totalWins} wins
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============================================================================
// TEAM LEADERBOARD PREVIEW COMPONENT (Top 5 + Link)
// ============================================================================

interface TeamLeaderboardPreviewProps {
  teams: TeamDisplayData[];
  onTeamClick: (id: string) => void;
}

function TeamLeaderboardPreview({ teams, onTeamClick }: TeamLeaderboardPreviewProps) {
  const router = useRouter();

  // Sort teams by rating and get top 5
  const topTeams = [...teams]
    .filter((t) => t.rating !== null)
    .sort((a, b) => (b.rating ?? 0) - (a.rating ?? 0))
    .slice(0, 5);

  const getMedalColor = (position: number) => {
    switch (position) {
      case 0:
        return 'text-yellow-400';
      case 1:
        return 'text-gray-300';
      case 2:
        return 'text-amber-600';
      default:
        return 'text-gray-500';
    }
  };

  const getMedalBg = (position: number) => {
    switch (position) {
      case 0:
        return 'bg-yellow-400/10 border-yellow-400/30';
      case 1:
        return 'bg-gray-300/10 border-gray-300/30';
      case 2:
        return 'bg-amber-600/10 border-amber-600/30';
      default:
        return 'bg-iron-gray/50 border-charcoal-outline';
    }
  };

  if (topTeams.length === 0) return null;

  return (
    <div className="mb-12">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-yellow-400/20 to-amber-600/10 border border-yellow-400/30">
            <Award className="w-5 h-5 text-yellow-400" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-white">Top Teams</h2>
            <p className="text-sm text-gray-500">Highest rated racing teams</p>
          </div>
        </div>

        <Button
          variant="secondary"
          onClick={() => router.push('/teams/leaderboard')}
          className="flex items-center gap-2 text-sm"
        >
          View Full Leaderboard
          <ChevronRight className="w-4 h-4" />
        </Button>
      </div>

      {/* Compact Leaderboard */}
      <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
        <div className="divide-y divide-charcoal-outline/50">
          {topTeams.map((team, index) => {
            const levelConfig = SKILL_LEVELS.find((l) => l.id === team.performanceLevel);
            const LevelIcon = levelConfig?.icon || Shield;

            return (
              <button
                key={team.id}
                type="button"
                onClick={() => onTeamClick(team.id)}
                className="flex items-center gap-4 px-4 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group"
              >
                {/* Position */}
                <div
                  className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${getMedalBg(index)} ${getMedalColor(index)}`}
                >
                  {index < 3 ? (
                    <Crown className="w-3.5 h-3.5" />
                  ) : (
                    index + 1
                  )}
                </div>

                {/* Team Info */}
                <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${levelConfig?.bgColor} border ${levelConfig?.borderColor}`}>
                  <LevelIcon className={`w-4 h-4 ${levelConfig?.color}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-white font-medium truncate group-hover:text-purple-400 transition-colors">
                    {team.name}
                  </p>
                  <div className="flex items-center gap-3 text-xs text-gray-500">
                    <span className="flex items-center gap-1">
                      <Users className="w-3 h-3" />
                      {team.memberCount}
                    </span>
                    <span className="flex items-center gap-1">
                      <Trophy className="w-3 h-3" />
                      {team.totalWins} wins
                    </span>
                    {team.isRecruiting && (
                      <span className="flex items-center gap-1 text-performance-green">
                        <div className="w-1.5 h-1.5 rounded-full bg-performance-green animate-pulse" />
                        Recruiting
                      </span>
                    )}
                  </div>
                </div>

                {/* Rating */}
                <div className="text-right">
                  <p className="text-purple-400 font-mono font-semibold">
                    {team.rating?.toLocaleString()}
                  </p>
                  <p className="text-xs text-gray-500">Rating</p>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// MAIN PAGE COMPONENT
// ============================================================================

export default function TeamsPage() {
  const router = useRouter();
  const [realTeams, setRealTeams] = useState<TeamDisplayData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [showCreateForm, setShowCreateForm] = useState(false);

  useEffect(() => {
    loadTeams();
  }, []);

  const loadTeams = async () => {
    try {
      const allTeamsQuery = getGetAllTeamsQuery();
      const teamMembersQuery = getGetTeamMembersQuery();

      const allTeams = await allTeamsQuery.execute();
      const teamData: TeamDisplayData[] = [];

      await Promise.all(
        allTeams.map(async (team: Team) => {
          const memberships = await teamMembersQuery.execute({ teamId: team.id });
          const memberCount = memberships.length;

          let ratingSum = 0;
          let ratingCount = 0;
          let totalWins = 0;
          let totalRaces = 0;

          for (const membership of memberships) {
            const stats = getDriverStats(membership.driverId);
            if (!stats) continue;

            if (typeof stats.rating === 'number') {
              ratingSum += stats.rating;
              ratingCount += 1;
            }

            totalWins += stats.wins ?? 0;
            totalRaces += stats.totalRaces ?? 0;
          }

          const averageRating = ratingCount > 0 ? ratingSum / ratingCount : null;

          let performanceLevel: TeamDisplayData['performanceLevel'] = 'beginner';
          if (averageRating !== null) {
            if (averageRating >= 4500) performanceLevel = 'pro';
            else if (averageRating >= 3000) performanceLevel = 'advanced';
            else if (averageRating >= 2000) performanceLevel = 'intermediate';
          }

          teamData.push({
            id: team.id,
            name: team.name,
            memberCount,
            rating: averageRating,
            totalWins,
            totalRaces,
            performanceLevel,
            isRecruiting: true,
            createdAt: new Date(),
          });
        }),
      );

      setRealTeams(teamData);
    } catch (error) {
      console.error('Failed to load teams:', error);
    } finally {
      setLoading(false);
    }
  };

  const teams = [...realTeams, ...DEMO_TEAMS];

  const handleTeamClick = (teamId: string) => {
    if (teamId.startsWith('demo-team-')) {
      return;
    }
    router.push(`/teams/${teamId}`);
  };

  const handleCreateSuccess = (teamId: string) => {
    setShowCreateForm(false);
    void loadTeams();
    router.push(`/teams/${teamId}`);
  };

  // Filter by search query
  const filteredTeams = teams.filter((team) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      team.name.toLowerCase().includes(query) ||
      (team.description ?? '').toLowerCase().includes(query) ||
      (team.region ?? '').toLowerCase().includes(query) ||
      (team.languages ?? []).some((lang) => lang.toLowerCase().includes(query))
    );
  });

  // Group teams by skill level
  const teamsByLevel = SKILL_LEVELS.reduce(
    (acc, level) => {
      acc[level.id] = filteredTeams.filter((t) => t.performanceLevel === level.id);
      return acc;
    },
    {} as Record<SkillLevel, TeamDisplayData[]>,
  );

  const recruitingCount = teams.filter((t) => t.isRecruiting).length;

  if (showCreateForm) {
    return (
      <div className="max-w-4xl mx-auto px-4">
        <div className="mb-6">
          <Button variant="secondary" onClick={() => setShowCreateForm(false)}>
            ← Back to Teams
          </Button>
        </div>

        <Card>
          <h2 className="text-2xl font-bold text-white mb-6">Create New Team</h2>
          <CreateTeamForm onCancel={() => setShowCreateForm(false)} onSuccess={handleCreateSuccess} />
        </Card>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="flex flex-col items-center gap-4">
            <div className="w-10 h-10 border-2 border-purple-400 border-t-transparent rounded-full animate-spin" />
            <p className="text-gray-400">Loading teams...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 pb-12">
      {/* Hero Section - Different from Leagues */}
      <div className="relative mb-10 overflow-hidden">
        {/* Main Hero Card */}
        <div className="relative py-12 px-8 rounded-2xl bg-gradient-to-br from-purple-900/30 via-iron-gray/80 to-deep-graphite border border-purple-500/20">
          {/* Background decorations */}
          <div className="absolute top-0 right-0 w-80 h-80 bg-purple-500/10 rounded-full blur-3xl" />
          <div className="absolute bottom-0 left-1/4 w-64 h-64 bg-neon-aqua/5 rounded-full blur-3xl" />
          <div className="absolute top-1/2 right-1/4 w-48 h-48 bg-yellow-400/5 rounded-full blur-2xl" />

          <div className="relative z-10">
            <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-8">
              <div className="max-w-xl">
                {/* Badge */}
                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-purple-500/10 border border-purple-500/20 text-purple-400 text-xs font-medium mb-4">
                  <Users className="w-3.5 h-3.5" />
                  Team Racing
                </div>

                <Heading level={1} className="text-4xl lg:text-5xl mb-4">
                  Find Your
                  <span className="text-purple-400"> Crew</span>
                </Heading>

                <p className="text-gray-400 text-lg leading-relaxed mb-6">
                  Solo racing is great. Team racing is unforgettable. Join a team that matches your skill level and ambitions.
                </p>

                {/* Quick Stats */}
                <div className="flex flex-wrap gap-4 mb-6">
                  <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
                    <Users className="w-4 h-4 text-purple-400" />
                    <span className="text-white font-semibold">{teams.length}</span>
                    <span className="text-gray-500 text-sm">Teams</span>
                  </div>
                  <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
                    <UserPlus className="w-4 h-4 text-performance-green" />
                    <span className="text-white font-semibold">{recruitingCount}</span>
                    <span className="text-gray-500 text-sm">Recruiting</span>
                  </div>
                </div>

                {/* CTA Buttons */}
                <div className="flex flex-wrap gap-3">
                  <Button
                    variant="primary"
                    onClick={() => setShowCreateForm(true)}
                    className="flex items-center gap-2 px-5 py-2.5 bg-purple-600 hover:bg-purple-500"
                  >
                    <Plus className="w-4 h-4" />
                    Create Team
                  </Button>
                  <Button
                    variant="secondary"
                    onClick={() => {
                      const element = document.getElementById('teams-list');
                      element?.scrollIntoView({ behavior: 'smooth' });
                    }}
                    className="flex items-center gap-2"
                  >
                    <Search className="w-4 h-4" />
                    Browse Teams
                  </Button>
                </div>
              </div>

              {/* Skill Level Quick Nav */}
              <div className="lg:w-72">
                <p className="text-xs text-gray-500 uppercase tracking-wider mb-3">Find Your Level</p>
                <div className="space-y-2">
                  {SKILL_LEVELS.map((level) => {
                    const LevelIcon = level.icon;
                    const count = teamsByLevel[level.id]?.length || 0;

                    return (
                      <button
                        key={level.id}
                        type="button"
                        onClick={() => {
                          const element = document.getElementById(`level-${level.id}`);
                          element?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }}
                        className={`w-full flex items-center justify-between p-3 rounded-lg ${level.bgColor} border ${level.borderColor} hover:scale-[1.02] transition-all duration-200`}
                      >
                        <div className="flex items-center gap-2">
                          <LevelIcon className={`w-4 h-4 ${level.color}`} />
                          <span className="text-white font-medium">{level.label}</span>
                        </div>
                        <span className="text-gray-400 text-sm">{count} teams</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Search and Filter Bar - Same style as Leagues */}
      <div id="teams-list" className="mb-6 scroll-mt-8">
        <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 teams by name, description, region, or language..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-11"
            />
          </div>
        </div>
      </div>

      {/* Why Join Section */}
      {!searchQuery && <WhyJoinTeamSection />}

      {/* Team Leaderboard Preview */}
      {!searchQuery && <TeamLeaderboardPreview teams={teams} onTeamClick={handleTeamClick} />}

      {/* Featured Recruiting */}
      {!searchQuery && <FeaturedRecruiting teams={teams} onTeamClick={handleTeamClick} />}

      {/* Teams by Skill Level */}
      {teams.length === 0 ? (
        <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-purple-500/10 border border-purple-500/20 mb-6">
              <Users className="w-8 h-8 text-purple-400" />
            </div>
            <Heading level={2} className="text-2xl mb-3">
              No teams yet
            </Heading>
            <p className="text-gray-400 mb-8">
              Be the first to create a racing team. Gather drivers and compete together in endurance events.
            </p>
            <Button
              variant="primary"
              onClick={() => setShowCreateForm(true)}
              className="flex items-center gap-2 mx-auto bg-purple-600 hover:bg-purple-500"
            >
              <Sparkles className="w-4 h-4" />
              Create Your First Team
            </Button>
          </div>
        </Card>
      ) : filteredTeams.length === 0 ? (
        <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 teams found matching "{searchQuery}"</p>
            <Button variant="secondary" onClick={() => setSearchQuery('')}>
              Clear search
            </Button>
          </div>
        </Card>
      ) : (
        <div>
          {SKILL_LEVELS.map((level, index) => (
            <div key={level.id} id={`level-${level.id}`} className="scroll-mt-8">
              <SkillLevelSection
                level={level}
                teams={teamsByLevel[level.id]}
                onTeamClick={handleTeamClick}
                defaultExpanded={index === 0}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}