'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Users,
  Trophy,
  Search,
  Plus,
  ChevronLeft,
  ChevronRight,
  Sparkles,
  Filter,
  Flame,
  Target,
  Star,
  TrendingUp,
  Shield,
  Zap,
  Award,
  Crown,
  UserPlus,
} 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 CategoryId =
  | 'all'
  | 'recruiting'
  | 'popular'
  | 'new'
  | 'pro'
  | 'advanced'
  | 'intermediate'
  | 'beginner'
  | 'endurance'
  | 'sprint';

interface Category {
  id: CategoryId;
  label: string;
  icon: React.ElementType;
  description: string;
  filter: (team: TeamDisplayData) => boolean;
  color?: string;
}

interface TeamDisplayData {
  id: string;
  name: string;
  memberCount: number;
  rating: number | null;
  totalWins: number;
  totalRaces: number;
  performanceLevel: 'beginner' | 'intermediate' | 'advanced' | 'pro';
  isRecruiting: boolean;
  createdAt: Date;
  description?: string;
  specialization?: 'endurance' | 'sprint' | 'mixed';
}

// ============================================================================
// 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',
  },
  {
    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',
  },
  {
    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',
  },
  // 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',
  },
  {
    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',
  },
  {
    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',
  },
  // 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',
  },
  {
    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',
  },
  {
    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',
  },
  // 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',
  },
  {
    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',
  },
  {
    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',
  },
  // 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',
  },
  {
    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',
  },
];

// ============================================================================
// CATEGORIES
// ============================================================================

const CATEGORIES: Category[] = [
  {
    id: 'all',
    label: 'All',
    icon: Users,
    description: 'Browse all teams',
    filter: () => true,
  },
  {
    id: 'recruiting',
    label: 'Recruiting',
    icon: UserPlus,
    description: 'Teams looking for drivers',
    filter: (team) => team.isRecruiting,
    color: 'text-performance-green',
  },
  {
    id: 'popular',
    label: 'Popular',
    icon: Flame,
    description: 'Most active teams',
    filter: (team) => team.totalRaces >= 50,
    color: 'text-orange-400',
  },
  {
    id: 'new',
    label: 'New',
    icon: Sparkles,
    description: 'Recently formed teams',
    filter: (team) => {
      const oneWeekAgo = new Date();
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
      return team.createdAt > oneWeekAgo;
    },
    color: 'text-neon-aqua',
  },
  {
    id: 'pro',
    label: 'Pro',
    icon: Crown,
    description: 'Professional-level teams',
    filter: (team) => team.performanceLevel === 'pro',
    color: 'text-yellow-400',
  },
  {
    id: 'advanced',
    label: 'Advanced',
    icon: Star,
    description: 'High-skill teams',
    filter: (team) => team.performanceLevel === 'advanced',
    color: 'text-purple-400',
  },
  {
    id: 'intermediate',
    label: 'Intermediate',
    icon: TrendingUp,
    description: 'Growing teams',
    filter: (team) => team.performanceLevel === 'intermediate',
    color: 'text-primary-blue',
  },
  {
    id: 'beginner',
    label: 'Beginner',
    icon: Shield,
    description: 'New racer friendly',
    filter: (team) => team.performanceLevel === 'beginner',
    color: 'text-green-400',
  },
  {
    id: 'endurance',
    label: 'Endurance',
    icon: Trophy,
    description: 'Long-distance specialists',
    filter: (team) => team.specialization === 'endurance',
  },
  {
    id: 'sprint',
    label: 'Sprint',
    icon: Zap,
    description: 'Short race experts',
    filter: (team) => team.specialization === 'sprint',
  },
];

// ============================================================================
// TEAM SLIDER COMPONENT
// ============================================================================

interface TeamSliderProps {
  title: string;
  icon: React.ElementType;
  description: string;
  teams: TeamDisplayData[];
  onTeamClick: (id: string) => void;
  autoScroll?: boolean;
  iconColor?: string;
  scrollSpeedMultiplier?: number;
  scrollDirection?: 'left' | 'right';
}

function TeamSlider({
  title,
  icon: Icon,
  description,
  teams,
  onTeamClick,
  autoScroll = true,
  iconColor = 'text-primary-blue',
  scrollSpeedMultiplier = 1,
  scrollDirection = 'right',
}: TeamSliderProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);
  const [isHovering, setIsHovering] = useState(false);
  const animationRef = useRef<number | null>(null);
  const scrollPositionRef = useRef(0);

  const checkScrollButtons = useCallback(() => {
    if (scrollRef.current) {
      const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
      setCanScrollLeft(scrollLeft > 0);
      setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10);
    }
  }, []);

  const scroll = useCallback((direction: 'left' | 'right') => {
    if (scrollRef.current) {
      const cardWidth = 340;
      const scrollAmount = direction === 'left' ? -cardWidth : cardWidth;
      scrollPositionRef.current = scrollRef.current.scrollLeft + scrollAmount;
      scrollRef.current.scrollBy({ left: scrollAmount, behavior: 'smooth' });
    }
  }, []);

  // Initialize scroll position for left-scrolling sliders
  useEffect(() => {
    if (scrollDirection === 'left' && scrollRef.current) {
      const { scrollWidth, clientWidth } = scrollRef.current;
      scrollPositionRef.current = scrollWidth - clientWidth;
      scrollRef.current.scrollLeft = scrollPositionRef.current;
    }
  }, [scrollDirection, teams.length]);

  // Smooth continuous auto-scroll
  useEffect(() => {
    if (!autoScroll || teams.length <= 1) return;

    const scrollContainer = scrollRef.current;
    if (!scrollContainer) return;

    let lastTimestamp = 0;
    const baseSpeed = 0.025;
    const scrollSpeed = baseSpeed * scrollSpeedMultiplier;
    const directionMultiplier = scrollDirection === 'left' ? -1 : 1;

    const animate = (timestamp: number) => {
      if (!isHovering && scrollContainer) {
        const delta = lastTimestamp ? timestamp - lastTimestamp : 0;
        lastTimestamp = timestamp;

        scrollPositionRef.current += scrollSpeed * delta * directionMultiplier;

        const { scrollWidth, clientWidth } = scrollContainer;
        const maxScroll = scrollWidth - clientWidth;

        if (scrollDirection === 'right' && scrollPositionRef.current >= maxScroll) {
          scrollPositionRef.current = 0;
        } else if (scrollDirection === 'left' && scrollPositionRef.current <= 0) {
          scrollPositionRef.current = maxScroll;
        }

        scrollContainer.scrollLeft = scrollPositionRef.current;
      } else {
        lastTimestamp = timestamp;
      }

      animationRef.current = requestAnimationFrame(animate);
    };

    animationRef.current = requestAnimationFrame(animate);

    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
    };
  }, [autoScroll, teams.length, isHovering, scrollSpeedMultiplier, scrollDirection]);

  useEffect(() => {
    const scrollContainer = scrollRef.current;
    if (!scrollContainer) return;

    const handleScroll = () => {
      scrollPositionRef.current = scrollContainer.scrollLeft;
      checkScrollButtons();
    };

    scrollContainer.addEventListener('scroll', handleScroll);
    return () => scrollContainer.removeEventListener('scroll', handleScroll);
  }, [checkScrollButtons]);

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

  return (
    <div className="mb-10">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-iron-gray border border-charcoal-outline">
            <Icon className={`w-5 h-5 ${iconColor}`} />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-white">{title}</h2>
            <p className="text-xs text-gray-500">{description}</p>
          </div>
          <span className="ml-2 px-2 py-0.5 rounded-full text-xs bg-charcoal-outline/50 text-gray-400">
            {teams.length}
          </span>
        </div>

        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => scroll('left')}
            disabled={!canScrollLeft}
            className={`flex h-8 w-8 items-center justify-center rounded-lg transition-all ${
              canScrollLeft
                ? 'bg-iron-gray border border-charcoal-outline text-white hover:border-primary-blue hover:text-primary-blue'
                : 'bg-iron-gray/30 border border-charcoal-outline/30 text-gray-600 cursor-not-allowed'
            }`}
          >
            <ChevronLeft className="w-4 h-4" />
          </button>
          <button
            type="button"
            onClick={() => scroll('right')}
            disabled={!canScrollRight}
            className={`flex h-8 w-8 items-center justify-center rounded-lg transition-all ${
              canScrollRight
                ? 'bg-iron-gray border border-charcoal-outline text-white hover:border-primary-blue hover:text-primary-blue'
                : 'bg-iron-gray/30 border border-charcoal-outline/30 text-gray-600 cursor-not-allowed'
            }`}
          >
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      </div>

      <div className="relative">
        <div className="absolute left-0 top-0 bottom-4 w-12 bg-gradient-to-r from-deep-graphite to-transparent z-10 pointer-events-none" />
        <div className="absolute right-0 top-0 bottom-4 w-12 bg-gradient-to-l from-deep-graphite to-transparent z-10 pointer-events-none" />

        <div
          ref={scrollRef}
          onMouseEnter={() => setIsHovering(true)}
          onMouseLeave={() => setIsHovering(false)}
          className="flex gap-4 overflow-x-auto pb-4 px-4"
          style={{
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
          }}
        >
          <style jsx>{`
            div::-webkit-scrollbar {
              display: none;
            }
          `}</style>
          {teams.map((team) => (
            <div key={team.id} className="flex-shrink-0 w-[320px] h-full">
              <TeamCard
                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}
                onClick={() => onTeamClick(team.id)}
              />
            </div>
          ))}
        </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 [activeCategory, setActiveCategory] = useState<CategoryId>('all');
  const [showFilters, setShowFilters] = useState(false);
  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, // Default for now
            createdAt: new Date(), // Would need to be stored in Team entity
          });
        }),
      );

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

  // Combine real teams with demo teams
  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 searchFilteredTeams = teams.filter((team) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      team.name.toLowerCase().includes(query) ||
      (team.description ?? '').toLowerCase().includes(query)
    );
  });

  // Get teams for active category
  const activeCategoryData = CATEGORIES.find((c) => c.id === activeCategory);
  const categoryFilteredTeams = activeCategoryData
    ? searchFilteredTeams.filter(activeCategoryData.filter)
    : searchFilteredTeams;

  // Group teams by category for slider view
  const teamsByCategory = CATEGORIES.reduce(
    (acc, category) => {
      acc[category.id] = searchFilteredTeams.filter(category.filter);
      return acc;
    },
    {} as Record<CategoryId, TeamDisplayData[]>,
  );

  // Featured categories with different scroll speeds and directions
  const featuredCategoriesWithSpeed: { id: CategoryId; speed: number; direction: 'left' | 'right' }[] = [
    { id: 'recruiting', speed: 1.0, direction: 'right' },
    { id: 'pro', speed: 0.8, direction: 'left' },
    { id: 'advanced', speed: 1.1, direction: 'right' },
    { id: 'intermediate', speed: 0.9, direction: 'left' },
    { id: 'beginner', speed: 1.2, direction: 'right' },
    { id: 'new', speed: 1.0, direction: 'left' },
  ];

  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-primary-blue 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 */}
      <div className="relative mb-10 py-10 px-8 rounded-2xl bg-gradient-to-br from-iron-gray/80 via-deep-graphite to-iron-gray/60 border border-charcoal-outline/50 overflow-hidden">
        <div className="absolute top-0 right-0 w-96 h-96 bg-purple-500/5 rounded-full blur-3xl" />
        <div className="absolute bottom-0 left-0 w-64 h-64 bg-primary-blue/5 rounded-full blur-3xl" />

        <div className="relative z-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-8">
          <div className="max-w-2xl">
            <div className="flex items-center gap-3 mb-4">
              <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-purple-500/20 to-purple-500/5 border border-purple-500/20">
                <Users className="w-6 h-6 text-purple-400" />
              </div>
              <Heading level={1} className="text-3xl lg:text-4xl">
                Join a Team
              </Heading>
            </div>
            <p className="text-gray-400 text-lg leading-relaxed mb-6">
              Racing is better together. Find your crew, share strategies, and compete in endurance events as a team.
            </p>

            {/* Stats */}
            <div className="flex flex-wrap gap-6">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-performance-green animate-pulse" />
                <span className="text-sm text-gray-400">
                  <span className="text-white font-semibold">{teams.length}</span> active teams
                </span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-neon-aqua" />
                <span className="text-sm text-gray-400">
                  <span className="text-white font-semibold">{teamsByCategory.recruiting.length}</span> recruiting
                </span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-yellow-400" />
                <span className="text-sm text-gray-400">
                  <span className="text-white font-semibold">{teamsByCategory.pro.length}</span> pro teams
                </span>
              </div>
            </div>
          </div>

          {/* CTA */}
          <div className="flex flex-col gap-4">
            <Button
              variant="primary"
              onClick={() => setShowCreateForm(true)}
              className="flex items-center gap-2 px-6 py-3"
            >
              <Plus className="w-5 h-5" />
              <span>Create Team</span>
            </Button>
            <p className="text-xs text-gray-500 text-center">Start your own racing team</p>
          </div>
        </div>
      </div>

      {/* Search and Filter Bar */}
      <div className="mb-6">
        <div className="flex flex-col lg:flex-row gap-4">
          <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 or description..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-11"
            />
          </div>

          <Button
            type="button"
            variant="secondary"
            onClick={() => setShowFilters(!showFilters)}
            className="lg:hidden flex items-center gap-2"
          >
            <Filter className="w-4 h-4" />
            Filters
          </Button>
        </div>

        {/* Category Tabs */}
        <div className={`mt-4 ${showFilters ? 'block' : 'hidden lg:block'}`}>
          <div className="flex flex-wrap gap-2">
            {CATEGORIES.map((category) => {
              const Icon = category.icon;
              const count = teamsByCategory[category.id].length;
              const isActive = activeCategory === category.id;

              return (
                <button
                  key={category.id}
                  type="button"
                  onClick={() => setActiveCategory(category.id)}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-all duration-200 ${
                    isActive
                      ? 'bg-primary-blue text-white shadow-[0_0_15px_rgba(25,140,255,0.3)]'
                      : 'bg-iron-gray/60 text-gray-400 border border-charcoal-outline hover:border-gray-500 hover:text-white'
                  }`}
                >
                  <Icon className={`w-3.5 h-3.5 ${!isActive && category.color ? category.color : ''}`} />
                  <span>{category.label}</span>
                  {count > 0 && (
                    <span className={`px-1.5 py-0.5 rounded-full text-[10px] ${isActive ? 'bg-white/20' : 'bg-charcoal-outline/50'}`}>
                      {count}
                    </span>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Content */}
      {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"
            >
              <Sparkles className="w-4 h-4" />
              Create Your First Team
            </Button>
          </div>
        </Card>
      ) : activeCategory === 'all' && !searchQuery ? (
        /* Slider View */
        <div>
          {featuredCategoriesWithSpeed
            .map(({ id, speed, direction }) => {
              const category = CATEGORIES.find((c) => c.id === id)!;
              return { category, speed, direction };
            })
            .filter(({ category }) => teamsByCategory[category.id].length > 0)
            .map(({ category, speed, direction }) => (
              <TeamSlider
                key={category.id}
                title={category.label}
                icon={category.icon}
                description={category.description}
                teams={teamsByCategory[category.id]}
                onTeamClick={handleTeamClick}
                autoScroll={true}
                iconColor={category.color || 'text-primary-blue'}
                scrollSpeedMultiplier={speed}
                scrollDirection={direction}
              />
            ))}
        </div>
      ) : (
        /* Grid View */
        <div>
          {categoryFilteredTeams.length > 0 ? (
            <>
              <div className="flex items-center justify-between mb-6">
                <p className="text-sm text-gray-400">
                  Showing <span className="text-white font-medium">{categoryFilteredTeams.length}</span>{' '}
                  {categoryFilteredTeams.length === 1 ? 'team' : 'teams'}
                  {searchQuery && (
                    <span>
                      {' '}
                      for "<span className="text-primary-blue">{searchQuery}</span>"
                    </span>
                  )}
                </p>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {categoryFilteredTeams.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}
                    onClick={() => handleTeamClick(team.id)}
                  />
                ))}
              </div>
            </>
          ) : (
            <Card className="text-center py-12">
              <div className="flex flex-col items-center gap-4">
                <Search className="w-10 h-10 text-gray-600" />
                <p className="text-gray-400">
                  No teams found{searchQuery ? ` matching "${searchQuery}"` : ' in this category'}
                </p>
                <Button
                  variant="secondary"
                  onClick={() => {
                    setSearchQuery('');
                    setActiveCategory('all');
                  }}
                >
                  Clear filters
                </Button>
              </div>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}