import React, { useState } from 'react'; import { Team, User } from '../types'; import { Award, ShieldAlert, Sparkles, Trophy, Users, Star, Target, Check, Facebook, Twitter, Send, Globe, X, Scale, Newspaper } from 'lucide-react'; import { ResponsiveContainer, AreaChart, Area, Radar, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Legend, Tooltip } from 'recharts'; import { motion, AnimatePresence } from 'motion/react'; interface ProLeagueViewProps { teams: Team[]; currentUser: User | null; currentLanguage?: string; } // Helper to construct a realistic points progression history over time for the sparkline chart const getPointsHistory = (team: Team, lang: string = 'EN') => { const w = team.matchesWon ?? 0; const d = team.draws ?? 0; const l = team.losses ?? 0; const m = team.matchesPlayed ?? 0; // Base date representing mid-March start of typical Uzbekistan Pro Liga const baseDate = new Date(2026, 2, 14); // March 14, 2026 const formatDate = (idx: number) => { const d = new Date(baseDate); d.setDate(baseDate.getDate() + idx * 7); if (lang === 'UZ') { return d.toLocaleDateString('uz-UZ', { day: 'numeric', month: 'long', year: 'numeric' }); } else if (lang === 'RU') { return d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' }); } else { return d.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' }); } }; // If no matches played, render a flat line with slightly moving dummy starts to indicate presence if (m === 0) { return [ { day: 0, val: 0, date: formatDate(0) }, { day: 1, val: 0, date: formatDate(1) }, { day: 2, val: 0, date: formatDate(2) }, { day: 3, val: 0, date: formatDate(3) } ]; } // Interleave outcomes to form a realistic distribution of points over the match history const outcomes: number[] = []; let winsLeft = w; let drawsLeft = d; let lossesLeft = l; for (let i = 0; i < m; i++) { if (i % 3 === 0 && winsLeft > 0) { outcomes.push(3); winsLeft--; } else if (i % 3 === 1 && drawsLeft > 0) { outcomes.push(1); drawsLeft--; } else if (lossesLeft > 0) { outcomes.push(0); lossesLeft--; } else if (winsLeft > 0) { outcomes.push(3); winsLeft--; } else if (drawsLeft > 0) { outcomes.push(1); drawsLeft--; } else { outcomes.push(0); } } const history = [{ day: 0, val: 0, date: formatDate(0) }]; let currentPoints = 0; for (let i = 0; i < outcomes.length; i++) { currentPoints += outcomes[i]; history.push({ day: i + 1, val: currentPoints, date: formatDate(i + 1) }); } // Ensure last point aligns exactly with team points (handles point penalitative modifications or manually set values) if (team.points !== undefined && history[history.length - 1].val !== team.points) { history[history.length - 1].val = team.points; } return history; }; export const ProLeagueView: React.FC = ({ teams = [], currentUser, currentLanguage = 'EN' }) => { const favoriteTeamIds = currentUser?.favoriteTeams || []; // Filter teams with gameType 'pro_league' or 'pro' added in Firestore const proTeams = teams.filter((t) => t.gameType === 'pro_league' || t.gameType === 'pro'); const baseTeams = proTeams; // Clone and sort the teams, placing favorites at the top const activeTeams = [...baseTeams].sort((a, b) => { const isAFavorite = favoriteTeamIds.includes(a.id); const isBFavorite = favoriteTeamIds.includes(b.id); if (isAFavorite && !isBFavorite) return -1; if (!isAFavorite && isBFavorite) return 1; if (b.points !== a.points) return b.points - a.points; return (a.rank || 99) - (b.rank || 99); }); const [isCompareOpen, setIsCompareOpen] = useState(false); const [toastMsg, setToastMsg] = useState(''); const triggerToast = (msg: string) => { setToastMsg(msg); setTimeout(() => setToastMsg(''), 4000); }; const [teamAId, setTeamAId] = useState(''); const [teamBId, setTeamBId] = useState(''); React.useEffect(() => { if (activeTeams.length > 0) { if (!teamAId || !activeTeams.some(t => t.id === teamAId)) { setTeamAId(activeTeams[0].id); } if (activeTeams.length > 1) { if (!teamBId || !activeTeams.some(t => t.id === teamBId)) { setTeamBId(activeTeams[1].id); } } else { setTeamBId(activeTeams[0].id); } } }, [activeTeams, teamAId, teamBId]); const [hoveredTeams, setHoveredTeams] = useState([]); const [vsPosition, setVsPosition] = useState<{ top: number; height: number; center: number } | null>(null); React.useEffect(() => { if (hoveredTeams.length < 2) { setVsPosition(null); return; } const el1 = document.getElementById(`row-${hoveredTeams[0]}`); const el2 = document.getElementById(`row-${hoveredTeams[1]}`); if (el1 && el2) { const top1 = el1.offsetTop; const top2 = el2.offsetTop; const h1 = el1.offsetHeight; const h2 = el2.offsetHeight; const minTop = Math.min(top1, top2); const maxTop = Math.max(top1, top2); const maxH = top1 > top2 ? h1 : h2; const minH = top1 < top2 ? h1 : h2; const start = minTop + minH / 2; const end = maxTop + maxH / 2; setVsPosition({ top: minTop, height: (maxTop + maxH) - minTop, center: minTop + (maxTop + maxH - minTop) / 2 }); } }, [hoveredTeams]); const handleMouseEnterRow = (teamId: string) => { setHoveredTeams((prev) => { if (prev.includes(teamId)) return prev; return [...prev, teamId].slice(-2); }); }; const getTeamStats = (t?: Team) => { if (!t) return { pts: 0, wins: 0, draws: 0, losses: 0, goalsScored: 0, goalsConceded: 0, winRate: 0, defenseRating: 0, played: 0 }; const pts = t.points ?? 0; const wins = t.matchesWon ?? 0; const draws = t.draws ?? 0; const losses = t.losses ?? 0; const played = t.matchesPlayed ?? 0; let goalsScored = 0; let goalsConceded = 0; if (t.goals) { const parts = t.goals.split('-'); if (parts.length === 2) { goalsScored = parseInt(parts[0]) || 0; goalsConceded = parseInt(parts[1]) || 0; } } const winRate = played > 0 ? Math.round((wins / played) * 100) : 0; const avgConceded = played > 0 ? (goalsConceded / played) : 0; const defenseRating = Math.max(0, Math.min(10, Math.round(10 - avgConceded))); return { pts, wins, draws, losses, goalsScored, goalsConceded, winRate, defenseRating, played }; }; const handleToggleFavorite = async (teamId: string) => { if (!currentUser || currentUser.id === 'guest') { triggerToast(currentLanguage === 'UZ' ? "Jamoani tanlanganlarga qo'shish uchun avval tizimga kiring!" : "Please login to add a team to your favorites!"); return; } const currentFavorites = currentUser.favoriteTeams || []; let updatedFavorites: string[]; if (currentFavorites.includes(teamId)) { updatedFavorites = currentFavorites.filter(id => id !== teamId); } else { updatedFavorites = [...currentFavorites, teamId]; } try { const { doc, updateDoc } = await import('firebase/firestore'); const { db } = await import('../firebase'); const userRef = doc(db, 'users', currentUser.id); await updateDoc(userRef, { favoriteTeams: updatedFavorites }); } catch (err) { console.error("Failed to update favorite teams:", err); } }; // Render headers base on language const isUz = currentLanguage === 'UZ'; const labels = { rank: '#', team: isUz ? 'Jamoa' : 'Team / Club', played: "O'", won: "G'", drawn: 'D', lost: 'M', goals: '+/-', points: 'O', trend: isUz ? 'Trend' : 'Form', }; const cmpLabels = { compare: isUz ? "Jamoalarni solishtirish" : currentLanguage === "RU" ? "Сравнение команд" : "Compare Teams", teamA: isUz ? "1-Jamoa" : currentLanguage === "RU" ? "Команда 1" : "Team A", teamB: isUz ? "2-Jamoa" : currentLanguage === "RU" ? "Команда 2" : "Team B", attack: isUz ? "Hujumkorlik" : currentLanguage === "RU" ? "Атака" : "Attack", defense: isUz ? "Himoya" : currentLanguage === "RU" ? "Защита" : "Defense", wins: isUz ? "G'alabalar" : currentLanguage === "RU" ? "Победы" : "Wins", points: isUz ? "Ochkolar" : currentLanguage === "RU" ? "Очки" : "Points", winrate: isUz ? "G'alaba %" : currentLanguage === "RU" ? "% Побед" : "Win Rate %", played: isUz ? "O'yinlar" : currentLanguage === "RU" ? "Матчи" : "Matches", headToHead: isUz ? "Yuzma-yuz solishtirish" : currentLanguage === "RU" ? "Сравнение сил" : "Head-to-Head Comparison", close: isUz ? "Yopish" : currentLanguage === "RU" ? "Закрыть" : "Close", }; const selectedTeamA = activeTeams.find(t => t.id === teamAId) || activeTeams[0]; const selectedTeamB = activeTeams.find(t => t.id === teamBId) || activeTeams[1] || activeTeams[0]; const teamA = selectedTeamA || { id: '', name: 'Team A', logo: '🛡️', points: 0 }; const teamB = selectedTeamB || { id: '', name: 'Team B', logo: '🛡️', points: 0 }; const statsA = getTeamStats(teamA); const statsB = getTeamStats(teamB); const metrics = [ { name: cmpLabels.points, key: 'pts', fullMark: Math.max(...(activeTeams.map(t => t.points ?? 0).concat(10))) }, { name: cmpLabels.played, key: 'played', fullMark: Math.max(...(activeTeams.map(t => t.matchesPlayed ?? 0).concat(5))) }, { name: cmpLabels.wins, key: 'wins', fullMark: Math.max(...(activeTeams.map(t => t.matchesWon ?? 0).concat(5))) }, { name: cmpLabels.attack, key: 'goalsScored', fullMark: Math.max(...(activeTeams.map(t => { const parts = (t.goals || '0-0').split('-'); return parseInt(parts[0]) || 5; }).concat(10))) }, { name: cmpLabels.defense, key: 'defenseRating', fullMark: 10 }, { name: cmpLabels.winrate, key: 'winRate', fullMark: 100 }, ]; const chartData = metrics.map((metric) => { const scoreA = statsA[metric.key as keyof typeof statsA] ?? 0; const scoreB = statsB[metric.key as keyof typeof statsB] ?? 0; const normalizedA = Math.round((scoreA / metric.fullMark) * 100); const normalizedB = Math.round((scoreB / metric.fullMark) * 100); return { metric: metric.name, teamA_raw: scoreA, teamB_raw: scoreB, [teamA.name]: normalizedA, [teamB.name]: normalizedB, }; }); const isRu = currentLanguage === 'RU'; return (
{/* Dynamic Purple/Violet glow animations on corners like the upload image */}
{/* Main Container */}
{/* POLISHED ESPORTS HEADLINE: PRO LIGA */}

PRO ⚡ LIGA

{/* Active Round Badge (2-TUR) as styled in screen */}
2-TUR
{/* STANDINGS ACTIONS AND FILTERS */}
{/* STANDINGS TABLE CARD */}
setHoveredTeams([])} >
{activeTeams.length === 0 ? ( ) : ( activeTeams.map((team, idx) => { const displayRank = idx + 1; const isTopRank = displayRank <= 3; const scoreDifference = team.goals || '0-0'; const isFavorited = favoriteTeamIds.includes(team.id); const isRivalA = hoveredTeams[0] === team.id; const isRivalB = hoveredTeams[1] === team.id; const isAnyRival = isRivalA || isRivalB; const hasTwoRivals = hoveredTeams.length === 2; const rivalryClass = isRivalA ? 'bg-cyan-500/[0.04] border-l-2 border-l-cyan-400 shadow-[inset_4px_0_12px_rgba(34,211,238,0.03)]' : 'bg-purple-500/[0.04] border-l-2 border-l-purple-500 shadow-[inset_4px_0_12px_rgba(168,85,247,0.03)]'; return ( handleMouseEnterRow(team.id)} className={`transition-all duration-150 border-b border-white/5 cursor-pointer ${ hasTwoRivals && isAnyRival ? rivalryClass : isFavorited ? 'bg-amber-500/[0.02] hover:bg-amber-500/[0.04] border-l-2 border-l-amber-500/80 shadow-[inset_4px_0_12px_rgba(245,158,11,0.02)]' : 'hover:bg-white/[0.03]' }`} > {/* Rank Column */} {/* Team Logo/Emoji & Title */} {/* Played Matches */} {/* Games Won */} {/* Games Drawn */} {/* Games Lost */} {/* Goal Difference +/- Ratio */} {/* Points Progression Sparkline */} {/* Seasonal Accumulated points */} ); }) )}
{labels.rank} {labels.team} {labels.played} {labels.won} {labels.drawn} {labels.lost} {labels.goals} {labels.trend} {labels.points}

{isUz ? "Hozircha Pro Liga jamoalari mavjud emas." : "No Pro Liga teams registered yet."}

{isUz ? "Admin tomonidan yangi jamoalar qo'shilishini kuting yoki Admin panel orqali jamoa qo'shing." : "Wait for the admin to register teams or add them via the Admin Panel."}

{displayRank}
{team.logo && (team.logo.startsWith('data:') || team.logo.startsWith('http')) ? ( ) : ( {team.logo || "🎮"} )}
{team.name} {team.tag && ( [{team.tag}] )}
{team.matchesPlayed ?? 0} {team.matchesWon ?? 0} {team.draws ?? 0} {team.losses ?? 0} {scoreDifference}
{ if (active && payload && payload.length) { const data = payload[0].payload; const ptsLabel = isUz ? "Ochkolar" : currentLanguage === "RU" ? "Очки" : "Points"; return (
{data.date}
{ptsLabel}: {data.val}
); } return null; }} />
{team.points ?? 0}
{/* Real-time Rivalry Mode 'VS' Connecting Laser and Badge */} {vsPosition && ( <> {/* Laser beam connecting the two rival rows */} {/* Glowing VS pulse badge */}
VS
)}
{/* Social Channels / Footer section as styled in screenshot */}
{/* Team Comparison Radar Modal */} {isCompareOpen && (
{/* Backdrop */} setIsCompareOpen(false)} className="fixed inset-0 bg-[#020205]/80 backdrop-blur-md" /> {/* Modal Panel */} {/* Purple/cyan abstract glows inside modal */}
{/* Modal Header */}
{cmpLabels.compare}
{/* Modal Body */}
{activeTeams.length === 0 ? (

{isUz ? "Taqqoslash uchun jamoalar mavjud emas!" : "No teams available for comparison!"}

{isUz ? "Iltimos, avval Admin panel orqali jamoalar qo'shing." : "Please add teams through the Admin Panel first."}

) : ( <> {/* Team Selector Row */}
{/* Team A Column */}
{/* VS Indicator */}
VS
{/* Team B Column */}
{/* Main Visuals & Side-by-Side comparative chart */}
{/* Left Column: Metric split list */}

{cmpLabels.headToHead}

{metrics.map((m) => { const rawA = statsA[m.key as keyof typeof statsA] ?? 0; const rawB = statsB[m.key as keyof typeof statsB] ?? 0; const pctA = Math.round((rawA / m.fullMark) * 100); const pctB = Math.round((rawB / m.fullMark) * 100); return (
{m.key === 'winRate' ? `${rawA}%` : rawA} {m.name} {m.key === 'winRate' ? `${rawB}%` : rawB}
{/* Team A bar */}
{/* Split divider */}
{/* Team B bar */}
); })}
{/* Right Column: Radar Chart visualization */}
{ if (active && payload && payload.length) { const data = payload[0].payload; return (

{data.metric}

{teamA.logo} {teamA.name}: {data.teamA_raw}
{teamB.logo} {teamB.name}: {data.teamB_raw}
); } return null; }} />
)}
{/* Modal Footer */}
)} {toastMsg && (
⚠️ {toastMsg}
)}
); };