import { useEffect, useCallback, useState, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Copy, Check, ExternalLink, Zap, Shield, Gamepad2,
  TrendingUp, TrendingDown, Target, Flame, Swords,
  Radio, Activity, BarChart3, Crosshair, Trophy, MapPin, Ghost,
} from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Button } from '@/components/ui/Button';
import { Avatar } from '@/components/ui/Avatar';
import { useToast } from '@/components/ui/Toast';
import { Modal } from '@/components/ui/Modal';
import { ServerProgress } from '@/components/queue/ServerProgress';
import { CountdownTimer } from '@/components/queue/CountdownTimer';
import { useQueueStore } from '@/stores/queueStore';
import { useAuthStore } from '@/stores/authStore';
import { useMockStore } from '@/stores/mockStore';
import { queueAPI, matchAPI, profileAPI } from '@/api/client';
import { MAPS, GAME_MODES, getRankTier, formatRelativeTime } from '@/lib/constants';
import { MockToggle } from '@/components/dev/MockToggle';
import { cn } from '@/lib/cn';

function generateMockStats() {
  return {
    mmr: 1450,
    wins: 87,
    losses: 63,
    matchesPlayed: 150,
    winRate: 58,
    streak: 3,
    avgKd: 1.24,
    avgAdr: 82.5,
    avgRating: 1.08,
    recentForm: ['W', 'W', 'L', 'W', 'W', 'L', 'W', 'W', 'W', 'L'] as string[],
    mmrHistory: [1380, 1395, 1370, 1410, 1405, 1430, 1425, 1440, 1435, 1450],
    mapStats: [
      { map: 'Dust II', wins: 24, losses: 12, winRate: 67 },
      { map: 'Mirage', wins: 18, losses: 14, winRate: 56 },
      { map: 'Inferno', wins: 20, losses: 11, winRate: 65 },
      { map: 'Nuke', wins: 12, losses: 10, winRate: 55 },
      { map: 'Anubis', wins: 8, losses: 9, winRate: 47 },
      { map: 'Ancient', wins: 5, losses: 7, winRate: 42 },
    ],
  };
}

function generateMockRecentMatches() {
  return [
    { id: '1', map: 'de_mirage', score: '16-12', result: 'win' as const, mmrDelta: 22, kda: '24/16/5', date: '2h ago' },
    { id: '2', map: 'de_dust2', score: '16-9', result: 'win' as const, mmrDelta: 25, kda: '20/12/8', date: '3h ago' },
    { id: '3', map: 'de_inferno', score: '12-16', result: 'loss' as const, mmrDelta: -18, kda: '15/19/3', date: '5h ago' },
    { id: '4', map: 'de_nuke', score: '16-14', result: 'win' as const, mmrDelta: 20, kda: '22/17/6', date: '1d ago' },
    { id: '5', map: 'de_anubis', score: '8-16', result: 'loss' as const, mmrDelta: -22, kda: '11/18/4', date: '1d ago' },
  ];
}

interface QueueStats {
  mmr: number;
  wins: number;
  losses: number;
  matchesPlayed: number;
  winRate: number;
  streak: number;
  avgKd: number;
  avgAdr: number;
  avgRating: number;
  recentForm: string[];
  mmrHistory: number[];
  mapStats: { map: string; wins: number; losses: number; winRate: number }[];
}

interface RecentMatch {
  id: string;
  map: string;
  score: string;
  result: 'win' | 'loss' | 'draw';
  mmrDelta: number;
  kda: string;
  date: string;
}

function buildStatsFromProfile(user: any, mmrHistoryRaw: any[]): Omit<QueueStats, 'avgKd' | 'avgAdr' | 'avgRating' | 'mapStats'> {
  const wins = user.wins || 0;
  const losses = user.losses || 0;
  const matchesPlayed = user.matches_played || (wins + losses);
  const winRate = matchesPlayed > 0 ? Math.round((wins / matchesPlayed) * 100) : 0;

  const historyEntries = (mmrHistoryRaw || []).slice().reverse();
  const mmrHistory = historyEntries.length > 0
    ? historyEntries.map((h: any) => h.new_mmr)
    : [user.mmr || 1000];

  return {
    mmr: user.mmr || 1000,
    wins,
    losses,
    matchesPlayed,
    winRate,
    streak: Math.abs(user.current_streak || 0),
    recentForm: [],
    mmrHistory,
  };
}

function buildFromMatchHistory(matchEntries: any[]): {
  recentForm: string[];
  avgKd: number;
  avgAdr: number;
  avgRating: number;
  mapStats: { map: string; wins: number; losses: number; winRate: number }[];
  recentMatches: RecentMatch[];
} {
  if (!matchEntries || matchEntries.length === 0) {
    return { recentForm: [], avgKd: 0, avgAdr: 0, avgRating: 0, mapStats: [], recentMatches: [] };
  }

  const recentForm: string[] = [];
  const recentMatches: RecentMatch[] = [];
  let totalKills = 0, totalDeaths = 0, totalDamage = 0, totalRounds = 0;
  const mapData: Record<string, { wins: number; losses: number }> = {};

  for (const entry of matchEntries.slice(0, 10)) {
    const match = entry.match || {};
    const player = entry.player || {};
    const stats = entry.stats;

    const playerTeam = player.team;
    const t1Score = match.team1_score || 0;
    const t2Score = match.team2_score || 0;
    const isWin = playerTeam === 1 ? t1Score > t2Score : t2Score > t1Score;
    const isDraw = t1Score === t2Score;
    const result: 'win' | 'loss' | 'draw' = isDraw ? 'draw' : isWin ? 'win' : 'loss';

    recentForm.push(isDraw ? 'D' : isWin ? 'W' : 'L');

    const mapName = (match.map || '').replace('de_', '');
    const capMap = mapName.charAt(0).toUpperCase() + mapName.slice(1);
    if (!mapData[capMap]) mapData[capMap] = { wins: 0, losses: 0 };
    if (isWin) mapData[capMap].wins++;
    else if (!isDraw) mapData[capMap].losses++;

    if (stats) {
      totalKills += stats.kills || 0;
      totalDeaths += stats.deaths || 0;
      totalDamage += stats.damage || 0;
      totalRounds += stats.rounds_played || 0;
    }

    const k = stats?.kills ?? 0;
    const d = stats?.deaths ?? 0;
    const a = stats?.assists ?? 0;

    recentMatches.push({
      id: match.id || '',
      map: match.map || '',
      score: `${t1Score}-${t2Score}`,
      result,
      mmrDelta: player.mmr_delta || 0,
      kda: `${k}/${d}/${a}`,
      date: match.finished_at ? formatRelativeTime(match.finished_at) : '',
    });
  }

  const avgKd = totalDeaths > 0 ? Math.round((totalKills / totalDeaths) * 100) / 100 : totalKills;
  const avgAdr = totalRounds > 0 ? Math.round((totalDamage / totalRounds) * 10) / 10 : 0;
  const avgRating = Math.round((avgKd * 0.6 + (avgAdr / 100) * 0.4) * 100) / 100;

  const mapStats = Object.entries(mapData).map(([map, d]) => ({
    map,
    wins: d.wins,
    losses: d.losses,
    winRate: (d.wins + d.losses) > 0 ? Math.round((d.wins / (d.wins + d.losses)) * 100) : 0,
  })).sort((a, b) => (b.wins + b.losses) - (a.wins + a.losses));

  return { recentForm, avgKd, avgAdr, avgRating, mapStats, recentMatches };
}

function MmrSparkline({ data, width = 280, height = 80 }: { data: number[]; width?: number; height?: number }) {
  if (data.length < 2) return null;
  const min = Math.min(...data) - 10;
  const max = Math.max(...data) + 10;
  const range = max - min || 1;

  const points = data.map((v, i) => ({
    x: (i / (data.length - 1)) * width,
    y: height - ((v - min) / range) * height,
  }));

  const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');
  const areaD = `${pathD} L ${width} ${height} L 0 ${height} Z`;

  return (
    <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-full" preserveAspectRatio="none">
      <defs>
        <linearGradient id="sparkFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#ff6b2c" stopOpacity="0.3" />
          <stop offset="100%" stopColor="#ff6b2c" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="sparkStroke" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#ff6b2c" stopOpacity="0.5" />
          <stop offset="50%" stopColor="#ff8a50" />
          <stop offset="100%" stopColor="#ff6b2c" />
        </linearGradient>
      </defs>
      <path d={areaD} fill="url(#sparkFill)" />
      <path d={pathD} fill="none" stroke="url(#sparkStroke)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={points[points.length - 1].x} cy={points[points.length - 1].y} r="3" fill="#ff6b2c" />
      <circle cx={points[points.length - 1].x} cy={points[points.length - 1].y} r="6" fill="#ff6b2c" opacity="0.3">
        <animate attributeName="r" values="4;8;4" dur="2s" repeatCount="indefinite" />
        <animate attributeName="opacity" values="0.4;0.1;0.4" dur="2s" repeatCount="indefinite" />
      </circle>
    </svg>
  );
}

function MapWinBar({ name, winRate, index }: { name: string; winRate: number; index: number }) {
  const color = winRate >= 60 ? '#10b981' : winRate >= 50 ? '#ff6b2c' : '#ef4444';
  return (
    <motion.div
      initial={{ opacity: 0, x: -20 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ delay: 0.8 + index * 0.08 }}
      className="flex items-center gap-3"
    >
      <span className="text-xs text-[#a0a0b8] w-16 text-right font-medium">{name}</span>
      <div className="flex-1 h-2 bg-[#1a1a28] rounded-full overflow-hidden">
        <motion.div
          initial={{ width: 0 }}
          animate={{ width: `${winRate}%` }}
          transition={{ delay: 1 + index * 0.1, duration: 0.6, ease: 'easeOut' }}
          className="h-full rounded-full"
          style={{ background: `linear-gradient(90deg, ${color}80, ${color})` }}
        />
      </div>
      <span className="text-xs font-mono font-bold w-10" style={{ color }}>{winRate}%</span>
    </motion.div>
  );
}

function EnhancedRadar({ startedAt }: { startedAt: number }) {
  const [elapsed, setElapsed] = useState(0);

  useEffect(() => {
    const tick = () => setElapsed(Math.floor((Date.now() - startedAt) / 1000));
    tick();
    const interval = setInterval(tick, 1000);
    return () => clearInterval(interval);
  }, [startedAt]);

  const minutes = Math.floor(elapsed / 60);
  const seconds = elapsed % 60;
  const timeStr = `${minutes}:${seconds.toString().padStart(2, '0')}`;

  return (
    <div className="relative w-36 h-36">
      <div className="absolute inset-0 rounded-full border border-[#ff6b2c]/15" />
      <div className="absolute inset-3 rounded-full border border-[#ff6b2c]/10" />
      <div className="absolute inset-6 rounded-full border border-[#ff6b2c]/5" />
      <motion.div
        className="absolute inset-0"
        animate={{ rotate: 360 }}
        transition={{ duration: 2.5, repeat: Infinity, ease: 'linear' }}
      >
        <div
          className="absolute top-1/2 left-1/2 w-1/2 h-0.5 origin-left"
          style={{ background: 'linear-gradient(90deg, #ff6b2c80, transparent)' }}
        />
      </motion.div>
      <motion.div
        className="absolute inset-0 rounded-full"
        animate={{ rotate: 360 }}
        transition={{ duration: 2.5, repeat: Infinity, ease: 'linear' }}
        style={{
          background: 'conic-gradient(from 0deg, transparent 0deg, rgba(255,107,44,0.08) 0deg, transparent 60deg)',
        }}
      />
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span className="text-2xl font-mono font-bold text-[#f0f0f5]">{timeStr}</span>
        <span className="text-[10px] text-[#5a5a72] uppercase tracking-widest mt-0.5">elapsed</span>
      </div>
      <motion.div
        className="absolute inset-0 rounded-full border border-[#ff6b2c]/30"
        animate={{ scale: [1, 1.15, 1], opacity: [0.3, 0, 0.3] }}
        transition={{ duration: 2, repeat: Infinity }}
      />
    </div>
  );
}

function FormStrip({ form }: { form: string[] }) {
  if (form.length === 0) return <span className="text-xs text-[#3a3a4e]">No matches yet</span>;
  return (
    <div className="flex items-center gap-1">
      {form.map((r, i) => (
        <motion.div
          key={i}
          initial={{ scale: 0, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ delay: 0.6 + i * 0.05 }}
          className={cn(
            'w-5 h-5 rounded text-[10px] font-bold flex items-center justify-center',
            r === 'W'
              ? 'bg-emerald-500/15 text-emerald-400 border border-emerald-500/20'
              : r === 'L'
                ? 'bg-red-500/15 text-red-400 border border-red-500/20'
                : 'bg-[#5a5a72]/15 text-[#5a5a72] border border-[#5a5a72]/20'
          )}
        >
          {r}
        </motion.div>
      ))}
    </div>
  );
}

function PlayerSlots({ found, total = 10 }: { found: number; total?: number }) {
  return (
    <div className="flex items-center gap-1.5">
      {Array.from({ length: total }, (_, i) => {
        const isFilled = i < found;
        const isMiddle = i === 4;
        return (
          <div key={i} className={cn('flex items-center', isMiddle && 'mr-3')}>
            <motion.div
              initial={{ scale: 0.6, opacity: 0.3 }}
              animate={{ scale: isFilled ? 1 : 0.7, opacity: isFilled ? 1 : 0.25 }}
              transition={{ type: 'spring', stiffness: 400, damping: 20 }}
              className={cn('w-2.5 h-2.5 rounded-sm', isFilled ? 'bg-[#ff6b2c]' : 'bg-[#1e1e30]')}
            />
          </div>
        );
      })}
    </div>
  );
}

function EmptyState({ icon: Icon, title, subtitle }: { icon: any; title: string; subtitle: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-10 text-center">
      <div className="w-12 h-12 rounded-xl bg-[#1a1a28] border border-[#1e1e30] flex items-center justify-center mb-4">
        <Icon className="w-5 h-5 text-[#3a3a4e]" />
      </div>
      <p className="text-sm font-semibold text-[#5a5a72] mb-1">{title}</p>
      <p className="text-xs text-[#3a3a4e] max-w-xs">{subtitle}</p>
    </div>
  );
}

function normalizeQueuePlayer(p: any): { id: string; username: string; avatar?: string; connected: boolean } {
  return {
    id: p.user?.id || p.user_id || p.id,
    username: p.user?.username || p.username || 'player',
    avatar: p.user?.steam_avatar_url || p.steam_avatar_url,
    connected: Boolean(p.connected),
  };
}

const JOIN_WINDOW_SECONDS = 180;

function deriveJoinDeadline(match: any) {
  if (match.join_deadline) return match.join_deadline;

  const baseTime = match.started_at || match.created_at;
  if (!baseTime) {
    return new Date(Date.now() + JOIN_WINDOW_SECONDS * 1000).toISOString();
  }

  return new Date(new Date(baseTime).getTime() + JOIN_WINDOW_SECONDS * 1000).toISOString();
}

function serverStateForMatch(match: any) {
  if (match.connect_string) {
    return { phase: 'ready' as const, progress: 100, status: 'Server ready' };
  }

  switch (match.status) {
    case 'waiting_for_players':
      return { phase: 'server_loading' as const, progress: 85, status: 'Waiting for server...' };
    case 'live':
      return { phase: 'ready' as const, progress: 100, status: 'Live' };
    case 'matched':
      return { phase: 'found' as const, progress: 35, status: 'Allocating server...' };
    default:
      return { phase: 'server_loading' as const, progress: 50, status: 'Preparing match...' };
  }
}

function buildQueueMatchFromDetails(data: any) {
  const m = data.match || data;
  const flatPlayers = data.players || [];
  const team1Source = data.team1 || flatPlayers.filter((p: any) => p.team === 1);
  const team2Source = data.team2 || flatPlayers.filter((p: any) => p.team === 2);
  const serverState = serverStateForMatch(m);

  return {
    match: {
      id: m.id || m.match_id,
      map: m.map || 'de_dust2',
      game_mode: m.game_mode || 'competitive',
      team1: {
        name: m.team1_name || 'Team Alpha',
        players: team1Source.map(normalizeQueuePlayer),
      },
      team2: {
        name: m.team2_name || 'Team Beta',
        players: team2Source.map(normalizeQueuePlayer),
      },
      connect_string: m.connect_string || undefined,
      server_progress: serverState.progress,
      server_status: serverState.status,
      join_deadline: m.connect_string ? deriveJoinDeadline(m) : undefined,
    },
    phase: serverState.phase,
  };
}

export default function Queue() {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();
  const user = useAuthStore((s) => s.user);
  const {
    phase, gameMode, selectedMaps, searchStartedAt, playersFound, match,
    setPhase, setGameMode, toggleMap, startSearch, cancelSearch, setPlayersFound, setMatch, reset,
  } = useQueueStore();
  const [copied, setCopied] = useState(false);
  const [loading, setLoading] = useState(false);
  const [abortOpen, setAbortOpen] = useState(false);
  const [hiddenMatchIds, setHiddenMatchIds] = useState<Set<string>>(() => new Set());
  const useMock = useMockStore((s) => s.enabled);

  const [realStats, setRealStats] = useState<QueueStats | null>(null);
  const [realMatches, setRealMatches] = useState<RecentMatch[]>([]);
  const [dataLoading, setDataLoading] = useState(true);

  const mockStats = useMemo(() => generateMockStats(), []);
  const mockMatches = useMemo(() => generateMockRecentMatches(), []);

  const stats = useMock ? mockStats : realStats;
  const recentMatches = useMock ? mockMatches : realMatches;

  useEffect(() => {
    let cancelled = false;

    async function fetchData() {
      setDataLoading(true);
      try {
        const [profileRes, matchRes] = await Promise.all([
          profileAPI.me(),
          matchAPI.list({ page: 1, limit: 10 }),
        ]);

        if (cancelled) return;

        const profileData = profileRes.data;
        const matchEntries = matchRes.data?.matches || [];

        const baseStats = buildStatsFromProfile(profileData, profileData.mmr_history || []);
        const matchDerived = buildFromMatchHistory(matchEntries);

        setRealStats({
          ...baseStats,
          recentForm: matchDerived.recentForm,
          avgKd: matchDerived.avgKd,
          avgAdr: matchDerived.avgAdr,
          avgRating: matchDerived.avgRating,
          mapStats: matchDerived.mapStats,
        });
        setRealMatches(matchDerived.recentMatches);
      } catch {
        // empty state shown when stats null
      } finally {
        if (!cancelled) setDataLoading(false);
      }
    }

    fetchData();
    return () => { cancelled = true; };
  }, []);

  const isActive = phase === 'searching' || phase === 'found' || phase === 'server_loading' || phase === 'ready';

  useEffect(() => {
    async function poll() {
      try {
        const { data } = await queueAPI.status();
        if (data.in_queue) {
          const store = useQueueStore.getState();
          if (store.phase === 'idle') {
            setGameMode(data.game_mode);
            store.startSearch();
            useQueueStore.setState({ searchStartedAt: new Date(data.joined_at).getTime() });
          }
          setPlayersFound(data.players_in_queue || 1);
        } else if (data.matched && data.match_id) {
          if (hiddenMatchIds.has(data.match_id)) {
            const store = useQueueStore.getState();
            if (store.phase !== 'idle') store.reset();
            return;
          }

          // Active match in progress: fetch details before flipping the phase,
          // otherwise the "found" branch renders nothing (match is null).
          try {
            const detail = await matchAPI.get(data.match_id);
            const next = buildQueueMatchFromDetails(detail.data);
            if (next.match.join_deadline && new Date(next.match.join_deadline).getTime() <= Date.now()) {
              setHiddenMatchIds((ids) => new Set(ids).add(next.match.id));
              try {
                await matchAPI.leave(next.match.id);
              } catch {
                // If the backend already closed it, the local queue reset is still correct.
              }
              reset();
              toast('Join window expired. Returning to matchmaking.', 'warning');
              return;
            }
            setMatch(next.match);
            setPhase(next.phase);
          } catch {
            // If we can't load the match, stay in idle so the page renders.
          }
        } else {
          const store = useQueueStore.getState();
          if (store.phase !== 'idle') store.reset();
        }
        if (data.match) setMatch(data.match);
      } catch {
        // ignore poll errors
      }
    }
    poll();
    if (!isActive) return;
    const interval = setInterval(poll, 3000);
    return () => clearInterval(interval);
  }, [hiddenMatchIds, isActive, reset, setGameMode, setMatch, setPhase, setPlayersFound, toast]);

  useEffect(() => {
    const mode = searchParams.get('mode');
    if (mode === 'competitive' || mode === 'casual') setGameMode(mode);
  }, [searchParams, setGameMode]);

  const handleStartSearch = useCallback(async () => {
    if (!user?.steam_id) {
      toast('Link your Steam account before queueing.', 'warning');
      return;
    }
    if (selectedMaps.length === 0) {
      toast('Select at least one map.', 'warning');
      return;
    }
    setLoading(true);
    try {
      await queueAPI.join({ game_mode: gameMode });
      startSearch();
      toast('Searching for a match...', 'info');
    } catch (err: any) {
      const msg = err.response?.data?.error || 'Failed to join queue';
      toast(msg, 'error');
    } finally {
      setLoading(false);
    }
  }, [gameMode, selectedMaps, user, startSearch, toast]);

  const handleCancelSearch = useCallback(async () => {
    try {
      await queueAPI.leave();
      cancelSearch();
    } catch { /* */ }
  }, [cancelSearch]);

  const leaveMatchScreen = useCallback(async (message: string) => {
    const currentMatchId = useQueueStore.getState().match?.id;
    if (currentMatchId) {
      setHiddenMatchIds((ids) => new Set(ids).add(currentMatchId));
      try {
        await matchAPI.leave(currentMatchId);
      } catch {
        // The match may already be terminal; continue returning the user to matchmaking.
      }
    }
    setAbortOpen(false);
    reset();
    toast(message, 'warning');
  }, [reset, toast]);

  const handleJoinExpired = useCallback(() => {
    leaveMatchScreen('Join window expired. Returning to matchmaking.');
  }, [leaveMatchScreen]);

  const handleAbortMatch = useCallback(() => {
    leaveMatchScreen('Match screen closed. No penalty was applied in this demo.');
  }, [leaveMatchScreen]);

  const handleCopy = useCallback((text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, []);

  const rankTier = user ? getRankTier(user.mmr || 0, user.placement_done || false) : null;
  const hasData = stats !== null && stats.matchesPlayed > 0;

  return (
    <PageTransition className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <MockToggle />

      <AnimatePresence mode="wait">

        {phase === 'idle' && (
          <motion.div
            key="idle"
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -16 }}
            transition={{ duration: 0.35, ease: [0.25, 0.1, 0.25, 1] }}
          >
            <div className="flex items-center justify-between mb-8">
              <div>
                <div className="flex items-center gap-3 mb-1">
                  <motion.div
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                    transition={{ type: 'spring', stiffness: 300, damping: 20 }}
                    className="w-8 h-8 rounded-lg bg-[#ff6b2c]/10 border border-[#ff6b2c]/20 flex items-center justify-center"
                  >
                    <Crosshair className="w-4 h-4 text-[#ff6b2c]" />
                  </motion.div>
                  <h1 className="text-2xl font-black text-[#f0f0f5] tracking-tight font-display">
                    Find a Match
                  </h1>
                </div>
                <p className="text-sm text-[#5a5a72] ml-11">
                  Select mode and maps, then queue up
                </p>
              </div>
              {rankTier && (
                <div className="hidden sm:flex items-center gap-3 px-4 py-2 rounded-xl bg-[#0d0d14] border border-[#1e1e30]">
                  <div className="w-2 h-2 rounded-full" style={{ background: rankTier.color }} />
                  <span className="text-sm font-bold text-[#f0f0f5]">{rankTier.name}</span>
                  <span className="text-xs text-[#5a5a72] font-mono">{user?.mmr || 0} MMR</span>
                </div>
              )}
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 space-y-6">
                <div>
                  <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest mb-3">
                    Game Mode
                  </h3>
                  <div className="grid grid-cols-2 gap-3">
                    {GAME_MODES.map((mode) => {
                      const isSelected = gameMode === mode.id;
                      const Icon = mode.id === 'competitive' ? Shield : Gamepad2;
                      return (
                        <motion.button
                          key={mode.id}
                          onClick={() => setGameMode(mode.id)}
                          whileHover={{ scale: 1.01 }}
                          whileTap={{ scale: 0.99 }}
                          className={cn(
                            'relative p-5 rounded-xl border text-left transition-all duration-300 overflow-hidden group',
                            isSelected
                              ? 'border-[#ff6b2c]/40 bg-[#ff6b2c]/5'
                              : 'border-[#1e1e30] bg-[#0d0d14] hover:border-[#2a2a3e] hover:bg-[#0f0f18]'
                          )}
                        >
                          {isSelected && (
                            <div className="absolute inset-0 bg-gradient-to-br from-[#ff6b2c]/8 to-transparent pointer-events-none" />
                          )}
                          <div className="relative z-10 flex items-start gap-4">
                            <div className={cn(
                              'w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 transition-colors',
                              isSelected
                                ? 'bg-[#ff6b2c]/15 border border-[#ff6b2c]/25'
                                : 'bg-[#1a1a28] border border-[#1e1e30]'
                            )}>
                              <Icon className={cn('w-5 h-5', isSelected ? 'text-[#ff6b2c]' : 'text-[#5a5a72]')} />
                            </div>
                            <div className="min-w-0">
                              <h4 className={cn('text-sm font-bold', isSelected ? 'text-[#f0f0f5]' : 'text-[#a0a0b8]')}>
                                {mode.name}
                              </h4>
                              <p className="text-xs text-[#5a5a72] mt-0.5">{mode.description}</p>
                              <p className="text-[10px] text-[#3a3a4e] mt-1">
                                {mode.id === 'competitive' ? 'Elo rating \u2022 Rank progression' : 'No rank impact \u2022 Relaxed rules'}
                              </p>
                            </div>
                          </div>
                          {isSelected && (
                            <motion.div
                              layoutId="mode-indicator"
                              className="absolute top-3 right-3 w-2 h-2 rounded-full bg-[#ff6b2c]"
                              transition={{ type: 'spring', stiffness: 400, damping: 25 }}
                            />
                          )}
                        </motion.button>
                      );
                    })}
                  </div>
                </div>

                <div>
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest">Map Pool</h3>
                    <span className="text-[10px] text-[#3a3a4e] font-medium">{selectedMaps.length}/{MAPS.length} selected</span>
                  </div>
                  <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">
                    {MAPS.map((map, i) => {
                      const selected = selectedMaps.includes(map.id);
                      return (
                        <motion.button
                          key={map.id}
                          initial={{ opacity: 0, y: 8 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ delay: i * 0.04 }}
                          onClick={() => toggleMap(map.id)}
                          whileHover={{ scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                          className={cn(
                            'relative group rounded-xl overflow-hidden border transition-all duration-200 aspect-[16/9]',
                            selected
                              ? 'border-[#ff6b2c]/40 shadow-[0_0_16px_rgba(255,107,44,0.12)]'
                              : 'border-[#1e1e30] hover:border-[#2a2a3e]'
                          )}
                        >
                          <div className={cn(
                            'absolute inset-0 bg-gradient-to-br transition-all duration-300',
                            selected
                              ? 'from-[#ff6b2c]/15 to-[#0d0d14]'
                              : 'from-[#12121e] to-[#0a0a12] group-hover:from-[#16162a]'
                          )} />
                          <div className="absolute inset-0 flex flex-col items-center justify-center">
                            <MapPin className={cn(
                              'w-4 h-4 mb-1.5 transition-colors',
                              selected ? 'text-[#ff6b2c]' : 'text-[#3a3a4e] group-hover:text-[#5a5a72]'
                            )} />
                            <span className={cn(
                              'text-xs font-bold uppercase tracking-wider transition-colors',
                              selected ? 'text-[#f0f0f5]' : 'text-[#5a5a72]'
                            )}>
                              {map.name}
                            </span>
                          </div>
                          <div className="absolute top-2 right-2">
                            <div className={cn(
                              'w-4 h-4 rounded flex items-center justify-center border transition-all',
                              selected ? 'bg-[#ff6b2c] border-[#ff6b2c]' : 'bg-transparent border-[#2a2a3e]'
                            )}>
                              {selected && (
                                <motion.div
                                  initial={{ scale: 0 }}
                                  animate={{ scale: 1 }}
                                  transition={{ type: 'spring', stiffness: 500, damping: 25 }}
                                >
                                  <Check className="w-2.5 h-2.5 text-white" />
                                </motion.div>
                              )}
                            </div>
                          </div>
                        </motion.button>
                      );
                    })}
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5">
                  <div className="flex items-center gap-2 mb-4">
                    <Activity className="w-3.5 h-3.5 text-[#ff6b2c]" />
                    <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest">Your Stats</h3>
                  </div>

                  {dataLoading && !useMock ? (
                    <div className="space-y-3">
                      {[1,2,3,4].map(i => (
                        <div key={i} className="h-14 rounded-lg bg-[#0a0a12] border border-[#1a1a28] animate-pulse" />
                      ))}
                    </div>
                  ) : !hasData ? (
                    <EmptyState
                      icon={Ghost}
                      title="No stats yet"
                      subtitle="Play your first match to see your stats here"
                    />
                  ) : (
                    <>
                      <div className="grid grid-cols-2 gap-3 mb-4">
                        <div className="p-3 rounded-lg bg-[#0a0a12] border border-[#1a1a28]">
                          <p className="text-[10px] text-[#3a3a4e] uppercase tracking-wider mb-1">Win Rate</p>
                          <p className="text-lg font-bold text-emerald-400">{stats!.winRate}%</p>
                        </div>
                        <div className="p-3 rounded-lg bg-[#0a0a12] border border-[#1a1a28]">
                          <p className="text-[10px] text-[#3a3a4e] uppercase tracking-wider mb-1">Avg K/D</p>
                          <p className="text-lg font-bold text-[#f0f0f5]">{stats!.avgKd}</p>
                        </div>
                        <div className="p-3 rounded-lg bg-[#0a0a12] border border-[#1a1a28]">
                          <p className="text-[10px] text-[#3a3a4e] uppercase tracking-wider mb-1">Avg ADR</p>
                          <p className="text-lg font-bold text-[#f0f0f5]">{stats!.avgAdr}</p>
                        </div>
                        <div className="p-3 rounded-lg bg-[#0a0a12] border border-[#1a1a28]">
                          <p className="text-[10px] text-[#3a3a4e] uppercase tracking-wider mb-1">Streak</p>
                          <div className="flex items-center gap-1">
                            <Flame className="w-3.5 h-3.5 text-[#ff6b2c]" />
                            <p className="text-lg font-bold text-[#ff6b2c]">{stats!.streak}</p>
                          </div>
                        </div>
                      </div>
                      <div>
                        <p className="text-[10px] text-[#3a3a4e] uppercase tracking-wider mb-2">Recent Form</p>
                        <FormStrip form={stats!.recentForm} />
                      </div>
                    </>
                  )}
                </div>

                <div className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5">
                  <div className="space-y-3 mb-5">
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-[#5a5a72]">Mode</span>
                      <span className="text-xs font-bold text-[#f0f0f5] capitalize">{gameMode}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-[#5a5a72]">Maps</span>
                      <span className="text-xs font-bold text-[#f0f0f5]">{selectedMaps.length} selected</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-[#5a5a72]">Est. Wait</span>
                      <span className="text-xs font-bold text-emerald-400">~1-2 min</span>
                    </div>
                  </div>

                  <Button
                    size="lg"
                    onClick={handleStartSearch}
                    loading={loading}
                    disabled={selectedMaps.length === 0}
                    className="w-full text-sm font-bold tracking-wide relative overflow-hidden"
                  >
                    <motion.span
                      className="absolute inset-0 bg-[#ff8a50]/20 rounded-lg"
                      animate={{ opacity: [0, 0.3, 0] }}
                      transition={{ duration: 2, repeat: Infinity, ease: 'easeInOut' }}
                    />
                    <span className="relative z-10 flex items-center justify-center gap-2">
                      <Zap className="w-4 h-4" />
                      FIND MATCH
                    </span>
                  </Button>
                </div>
              </div>
            </div>
          </motion.div>
        )}

        {phase === 'searching' && searchStartedAt && (
          <motion.div
            key="searching"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0, scale: 1.02 }}
            transition={{ duration: 0.4 }}
          >
            <motion.div
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
              className="flex items-center justify-between p-4 rounded-xl border border-[#ff6b2c]/20 bg-[#ff6b2c]/5 mb-6"
            >
              <div className="flex items-center gap-4">
                <EnhancedRadar startedAt={searchStartedAt} />
                <div className="ml-2">
                  <div className="flex items-center gap-2 mb-1">
                    <Radio className="w-3.5 h-3.5 text-[#ff6b2c] animate-pulse" />
                    <h2 className="text-lg font-black text-[#f0f0f5] tracking-tight">
                      Searching for Match
                    </h2>
                  </div>
                  <p className="text-xs text-[#5a5a72]">
                    {gameMode === 'competitive' ? 'Competitive' : 'Casual'} &middot;{' '}
                    {selectedMaps.map((m) => m.replace('de_', '')).join(', ')}
                  </p>
                  <div className="flex items-center gap-3 mt-2">
                    <PlayerSlots found={playersFound} />
                    <span className="text-[10px] text-[#5a5a72] font-mono">{playersFound}/10</span>
                  </div>
                </div>
              </div>

              <Button
                variant="ghost"
                onClick={handleCancelSearch}
                className="flex-shrink-0"
              >
                Cancel
              </Button>
            </motion.div>

            {dataLoading && !useMock ? (
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                {[1,2,3,4].map(i => (
                  <div key={i} className={cn(
                    'rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5 animate-pulse',
                    i <= 1 ? 'lg:col-span-2' : '',
                    i === 3 ? 'lg:col-span-2' : ''
                  )}>
                    <div className="h-32" />
                  </div>
                ))}
              </div>
            ) : !hasData ? (
              <div className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-10">
                <EmptyState
                  icon={BarChart3}
                  title="No match data yet"
                  subtitle="Your stats, MMR chart, and recent matches will appear here after you play your first game. Sit tight while we find opponents!"
                />
              </div>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 items-start">
                <div className="lg:col-span-2 space-y-4">
                  <motion.div
                    initial={{ opacity: 0, y: 16 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2 }}
                    className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5"
                  >
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-2">
                        <TrendingUp className="w-3.5 h-3.5 text-[#ff6b2c]" />
                        <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest">MMR Trend</h3>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-[#3a3a4e]">Last {stats!.mmrHistory.length} changes</span>
                        <span className="text-sm font-bold text-[#ff6b2c] font-mono">{stats!.mmrHistory[stats!.mmrHistory.length - 1]}</span>
                      </div>
                    </div>
                    {stats!.mmrHistory.length >= 2 ? (
                      <>
                        <div className="h-28">
                          <MmrSparkline data={stats!.mmrHistory} />
                        </div>
                        <div className="flex items-center justify-between mt-2">
                          <span className="text-[10px] text-[#3a3a4e] font-mono">{Math.min(...stats!.mmrHistory)}</span>
                          <span className="text-[10px] text-[#3a3a4e] font-mono">{Math.max(...stats!.mmrHistory)}</span>
                        </div>
                      </>
                    ) : (
                      <div className="h-28 flex items-center justify-center">
                        <span className="text-xs text-[#3a3a4e]">Not enough data for chart</span>
                      </div>
                    )}
                  </motion.div>

                  {recentMatches.length > 0 && (
                    <motion.div
                      initial={{ opacity: 0, y: 16 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.5 }}
                      className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5"
                    >
                      <div className="flex items-center gap-2 mb-4">
                        <Swords className="w-3.5 h-3.5 text-[#ff6b2c]" />
                        <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest">Recent Matches</h3>
                      </div>
                      <div className="grid grid-cols-[60px_1fr_80px_70px_90px_60px] gap-2 mb-2 px-3">
                        <span className="text-[10px] text-[#3a3a4e] uppercase">Result</span>
                        <span className="text-[10px] text-[#3a3a4e] uppercase">Map</span>
                        <span className="text-[10px] text-[#3a3a4e] uppercase">Score</span>
                        <span className="text-[10px] text-[#3a3a4e] uppercase">MMR</span>
                        <span className="text-[10px] text-[#3a3a4e] uppercase">K/D/A</span>
                        <span className="text-[10px] text-[#3a3a4e] uppercase text-right">Time</span>
                      </div>
                      <div className="space-y-1">
                        {recentMatches.map((m, i) => (
                          <motion.div
                            key={m.id}
                            initial={{ opacity: 0, x: -10 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ delay: 0.6 + i * 0.08 }}
                            className="grid grid-cols-[60px_1fr_80px_70px_90px_60px] gap-2 items-center px-3 py-2.5 rounded-lg hover:bg-[#1a1a28]/40 transition-colors"
                          >
                            <span className={cn(
                              'text-[10px] font-bold uppercase px-2 py-0.5 rounded text-center',
                              m.result === 'win'
                                ? 'bg-emerald-500/15 text-emerald-400'
                                : m.result === 'loss'
                                  ? 'bg-red-500/15 text-red-400'
                                  : 'bg-[#5a5a72]/15 text-[#5a5a72]'
                            )}>
                              {m.result}
                            </span>
                            <span className="text-xs text-[#f0f0f5] font-medium">
                              {m.map.replace('de_', '')}
                            </span>
                            <span className="text-xs text-[#a0a0b8] font-mono">{m.score}</span>
                            <div className="flex items-center gap-1">
                              {m.mmrDelta > 0 ? (
                                <TrendingUp className="w-3 h-3 text-emerald-400" />
                              ) : m.mmrDelta < 0 ? (
                                <TrendingDown className="w-3 h-3 text-red-400" />
                              ) : null}
                              <span className={cn(
                                'text-xs font-bold font-mono',
                                m.mmrDelta > 0 ? 'text-emerald-400' : m.mmrDelta < 0 ? 'text-red-400' : 'text-[#5a5a72]'
                              )}>
                                {m.mmrDelta > 0 ? '+' : ''}{m.mmrDelta}
                              </span>
                            </div>
                            <span className="text-xs text-[#a0a0b8] font-mono">{m.kda}</span>
                            <span className="text-[10px] text-[#3a3a4e] text-right">{m.date}</span>
                          </motion.div>
                        ))}
                      </div>
                    </motion.div>
                  )}
                </div>

                <div className="space-y-4">
                  <motion.div
                    initial={{ opacity: 0, y: 16 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.3 }}
                    className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5"
                  >
                    <div className="flex items-center gap-2 mb-4">
                      <BarChart3 className="w-3.5 h-3.5 text-[#ff6b2c]" />
                      <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest">Performance</h3>
                    </div>
                    <div className="space-y-4">
                      {[
                        { label: 'Win Rate', value: `${stats!.winRate}%`, icon: Target, color: '#10b981' },
                        { label: 'K/D Ratio', value: `${stats!.avgKd}`, icon: Crosshair, color: '#ff6b2c' },
                        { label: 'Avg ADR', value: `${stats!.avgAdr}`, icon: Activity, color: '#6366f1' },
                        { label: 'Rating', value: `${stats!.avgRating}`, icon: Trophy, color: '#f59e0b' },
                      ].map((stat, i) => (
                        <motion.div
                          key={stat.label}
                          initial={{ opacity: 0, x: 10 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: 0.4 + i * 0.08 }}
                          className="flex items-center justify-between"
                        >
                          <div className="flex items-center gap-2">
                            <stat.icon className="w-3.5 h-3.5" style={{ color: stat.color }} />
                            <span className="text-xs text-[#5a5a72]">{stat.label}</span>
                          </div>
                          <span className="text-sm font-bold text-[#f0f0f5] font-mono">{stat.value}</span>
                        </motion.div>
                      ))}
                    </div>
                    <div className="mt-5 pt-4 border-t border-[#1a1a28]">
                      <p className="text-[10px] text-[#3a3a4e] uppercase tracking-wider mb-2">Recent Form</p>
                      <FormStrip form={stats!.recentForm} />
                    </div>
                  </motion.div>

                  {stats!.mapStats.length > 0 && (
                    <motion.div
                      initial={{ opacity: 0, y: 16 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.4 }}
                      className="rounded-xl border border-[#1e1e30] bg-[#0d0d14] p-5"
                    >
                      <div className="flex items-center gap-2 mb-4">
                        <MapPin className="w-3.5 h-3.5 text-[#ff6b2c]" />
                        <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest">Map Win Rates</h3>
                      </div>
                      <div className="space-y-3">
                        {stats!.mapStats.map((ms, i) => (
                          <MapWinBar key={ms.map} name={ms.map} winRate={ms.winRate} index={i} />
                        ))}
                      </div>
                    </motion.div>
                  )}
                </div>
              </div>
            )}
          </motion.div>
        )}

        {(phase === 'found' || phase === 'server_loading') && match && (
          <motion.div
            key="found"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="flex flex-col items-center py-8"
          >
            <motion.div
              initial={{ scale: 0, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ type: 'spring', stiffness: 150, damping: 12, delay: 0.1 }}
              className="relative mb-2"
            >
              <div className="absolute inset-0 blur-3xl bg-[#ff6b2c]/30 rounded-full scale-150" />
              <h1
                className="relative text-5xl sm:text-6xl font-black tracking-tighter font-display"
                style={{
                  background: 'linear-gradient(135deg, #ff8a50, #ff6b2c, #e85d1c)',
                  WebkitBackgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                }}
              >
                MATCH FOUND
              </h1>
            </motion.div>

            <motion.p
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
              className="text-[#a0a0b8] mb-8"
            >
              {match.map.replace('de_', '')} &middot;{' '}
              <span className="capitalize">{match.game_mode}</span>
            </motion.p>

            <motion.div
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
              className="w-full max-w-md mb-8"
            >
              <ServerProgress progress={match.server_progress || 0} status={match.server_status || ''} />
            </motion.div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 w-full max-w-2xl">
              {[match.team1, match.team2].map((team, teamIdx) => (
                <motion.div
                  key={teamIdx}
                  initial={{ opacity: 0, x: teamIdx === 0 ? -24 : 24 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.6 + teamIdx * 0.15, type: 'spring', stiffness: 200, damping: 20 }}
                  className={cn(
                    'rounded-xl border bg-[#0d0d14] p-5 relative overflow-hidden',
                    teamIdx === 0 ? 'border-blue-500/20' : 'border-yellow-500/20'
                  )}
                >
                  <div className={cn(
                    'absolute top-0 left-0 right-0 h-px',
                    teamIdx === 0
                      ? 'bg-gradient-to-r from-blue-500 to-transparent'
                      : 'bg-gradient-to-r from-transparent to-yellow-500'
                  )} />
                  <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest mb-3">{team.name}</h3>
                  <div className="space-y-2">
                    {team.players.map((p, pi) => (
                      <motion.div
                        key={p.id}
                        initial={{ opacity: 0, x: teamIdx === 0 ? -12 : 12 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: 0.8 + pi * 0.08 }}
                        className="flex items-center gap-2.5"
                      >
                        <span className={cn(
                          'w-2 h-2 rounded-full flex-shrink-0',
                          p.connected ? 'bg-emerald-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]' : 'bg-[#1e1e30]'
                        )} />
                        <Avatar src={p.avatar} username={p.username} size="sm" />
                        <span className={cn(
                          'text-sm truncate',
                          p.id === user?.id ? 'text-[#ff8a50] font-semibold' : 'text-[#f0f0f5]'
                        )}>
                          {p.username}
                          {p.id === user?.id && <span className="text-xs text-[#ff6b2c]/60 ml-1">(You)</span>}
                        </span>
                      </motion.div>
                    ))}
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>
        )}

        {phase === 'ready' && match?.connect_string && (
          <motion.div
            key="ready"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="flex flex-col items-center py-8"
          >
            <motion.div
              initial={{ scale: 0.85, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ type: 'spring', stiffness: 200, damping: 15 }}
              className="relative mb-2"
            >
              <div className="absolute inset-0 blur-3xl bg-emerald-500/20 rounded-full scale-150" />
              <h1 className="relative text-4xl sm:text-5xl font-black tracking-tight text-emerald-400 font-display">
                SERVER READY
              </h1>
            </motion.div>

            <motion.p
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.2 }}
              className="text-[#a0a0b8] mb-8"
            >
              Connect before the timer runs out
            </motion.p>

            {match.join_deadline && (
              <motion.div
                initial={{ scale: 0.8, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ delay: 0.3, type: 'spring', stiffness: 200, damping: 18 }}
                className="mb-8"
              >
                <CountdownTimer deadline={match.join_deadline} onExpire={handleJoinExpired} />
              </motion.div>
            )}

            <motion.div
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
              className="w-full max-w-lg"
            >
              <div className="rounded-xl border border-emerald-500/20 bg-[#0d0d14] p-6 text-center">
                <p className="text-xs text-[#5a5a72] uppercase tracking-widest mb-3">Connect Command</p>
                <p className="text-lg sm:text-xl font-mono font-bold text-[#f0f0f5] mb-5 select-all break-all">
                  {match.connect_string}
                </p>
                <div className="flex items-center justify-center gap-3">
                  <Button variant="ghost" onClick={() => handleCopy(match.connect_string!)}>
                    {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                    {copied ? 'Copied!' : 'Copy'}
                  </Button>
                  <Button
                    onClick={() =>
                      window.open(`steam://connect/${match.connect_string!.replace('connect ', '')}`, '_blank')
                    }
                  >
                    <ExternalLink className="w-4 h-4" />
                    Connect in CS2
                  </Button>
                  <Button variant="danger" onClick={() => setAbortOpen(true)}>
                    Abort
                  </Button>
                </div>
              </div>
            </motion.div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 w-full max-w-2xl mt-8">
              {[match.team1, match.team2].map((team, teamIdx) => (
                <motion.div
                  key={teamIdx}
                  initial={{ opacity: 0, x: teamIdx === 0 ? -24 : 24 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.5 + teamIdx * 0.12, type: 'spring', stiffness: 200, damping: 20 }}
                  className={cn(
                    'rounded-xl border bg-[#0d0d14] p-5 relative overflow-hidden',
                    teamIdx === 0 ? 'border-blue-500/20' : 'border-yellow-500/20'
                  )}
                >
                  <div className={cn(
                    'absolute top-0 left-0 right-0 h-px',
                    teamIdx === 0
                      ? 'bg-gradient-to-r from-blue-500 to-transparent'
                      : 'bg-gradient-to-r from-transparent to-yellow-500'
                  )} />
                  <h3 className="text-xs font-bold text-[#5a5a72] uppercase tracking-widest mb-3">{team.name}</h3>
                  <div className="space-y-2">
                    {team.players.map((p, pi) => (
                      <motion.div
                        key={p.id}
                        initial={{ opacity: 0, x: teamIdx === 0 ? -12 : 12 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: 0.65 + pi * 0.08 }}
                        className="flex items-center gap-2.5"
                      >
                        <span className={cn(
                          'w-2 h-2 rounded-full flex-shrink-0',
                          p.connected ? 'bg-emerald-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]' : 'bg-[#1e1e30]'
                        )} />
                        <Avatar src={p.avatar} username={p.username} size="sm" />
                        <span className={cn(
                          'text-sm truncate',
                          p.id === user?.id ? 'text-[#ff8a50] font-semibold' : 'text-[#f0f0f5]'
                        )}>
                          {p.username}
                          {p.id === user?.id && <span className="text-xs text-[#ff6b2c]/60 ml-1">(You)</span>}
                        </span>
                      </motion.div>
                    ))}
                  </div>
                </motion.div>
              ))}
            </div>

            <motion.div
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.6 }}
              className="mt-8 w-full max-w-lg"
            >
              <p className="text-xs text-[#5a5a72] uppercase tracking-widest mb-4 text-center">Waiting for Players</p>
              <div className="flex flex-wrap justify-center gap-2">
                {[...match.team1.players, ...match.team2.players].map((p) => (
                  <motion.div
                    key={p.id}
                    whileHover={{ y: -2 }}
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-[#0a0a12] border border-[#1e1e30]"
                  >
                    <span className={cn(
                      'w-2 h-2 rounded-full flex-shrink-0',
                      p.connected ? 'bg-emerald-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]' : 'bg-[#1e1e30]'
                    )} />
                    <span className={cn(
                      'text-xs font-medium',
                      p.id === user?.id ? 'text-[#ff8a50]' : 'text-[#a0a0b8]'
                    )}>
                      {p.username}
                    </span>
                  </motion.div>
                ))}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <Modal open={abortOpen} onClose={() => setAbortOpen(false)} title="Abort Match">
        <p className="text-sm text-[#a0a0b8] mb-5">
          If you cancel now, this would normally count as an abandon and apply a cooldown penalty.
          For this demo it only closes this match screen and returns you to matchmaking.
        </p>
        <div className="flex items-center justify-end gap-3">
          <Button variant="ghost" onClick={() => setAbortOpen(false)}>
            Stay
          </Button>
          <Button variant="danger" onClick={handleAbortMatch}>
            Abort Anyway
          </Button>
        </div>
      </Modal>
    </PageTransition>
  );
}
