const { useState } = React;

function AnalyticsDashboard({ adminStats, formatMoney, onClose, onReset, t, lang }) {
    const [analyticsTab, setAnalyticsTab] = useState('overview');
    const [userSearch, setUserSearch] = useState('');
    const [userList, setUserList] = useState([]);
    const [userLoading, setUserLoading] = useState(false);
    const [deletingUser, setDeletingUser] = useState(null);

    const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname === ''
        ? 'http://localhost:3001'
        : 'https://api.tmn-studio.cloud';

    const ADMIN_KEY = 'lucky-admin-2024';

    const fetchUsers = async (search = '') => {
        setUserLoading(true);
        try {
            const res = await fetch(`${API_URL}/api/admin/users?adminKey=${ADMIN_KEY}&search=${search}`);
            const data = await res.json();
            if (data.success) setUserList(data.users);
        } catch (err) { console.error(err); }
        finally { setUserLoading(false); }
    };

    const deleteUser = async (username) => {
        if (!confirm(lang === 'TR' ? `${username} silinsin mi?` : `Delete ${username}?`)) return;
        setDeletingUser(username);
        try {
            const res = await fetch(`${API_URL}/api/admin/users/${username}`, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ adminKey: ADMIN_KEY })
            });
            const data = await res.json();
            if (data.success) {
                setUserList(prev => prev.filter(u => u.username !== username));
            } else {
                alert(data.error);
            }
        } catch (err) { console.error(err); }
        finally { setDeletingUser(null); }
    };

    React.useEffect(() => {
        if (analyticsTab === 'users') fetchUsers(userSearch);
    }, [analyticsTab]);
    const overview = adminStats.overview || {};
    const daily = adminStats.daily || {};
    const weekly = adminStats.weekly || {};
    const last7 = adminStats.last7Days || [];
    const topWealth = adminStats.topPlayersByWealth || [];
    const topGames = adminStats.topPlayersByGames || [];
    const gm = adminStats.gameplayMetrics || {};
    const Icons = window.Icons;

    const maxGames = Math.max(...last7.map(d => d.games || 0), 1);
    const periodData = analyticsTab === 'daily' ? daily : weekly;
    const periodLabel = analyticsTab === 'daily' ? (t.daily || 'DAILY') : (t.weekly || 'WEEKLY');

    return (
        <div className="fixed inset-0 z-[110] flex items-center justify-center p-4 bg-slate-950/98 backdrop-blur-3xl" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
            <div className="w-full max-w-3xl bg-slate-900 border border-indigo-500/30 rounded-[2.5rem] overflow-hidden shadow-2xl ring-1 ring-indigo-500/20 animate-in fade-in zoom-in duration-300 flex flex-col" style={{maxHeight:'92vh'}}>
                <div className="p-6 border-b border-white/5 flex justify-between items-center bg-gradient-to-r from-indigo-500/10 to-transparent flex-shrink-0">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-indigo-600 rounded-xl"><Icons.Activity size={18} className="text-white" /></div>
                        <div>
                            <h3 className="text-xl font-black text-white tracking-tighter">{t.adminAnalytics || 'ADMIN ANALYTICS'}</h3>
                            <p className="text-[10px] text-indigo-400 font-bold uppercase tracking-widest">{t.liveDashboard || 'LIVE DASHBOARD'}</p>
                        </div>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-white/5 rounded-full transition-colors"><Icons.XCircle size={24} className="text-slate-500 hover:text-white" /></button>
                </div>

                <div className="flex gap-1 p-2 bg-slate-950/40 border-b border-white/5 flex-shrink-0 overflow-x-auto no-scrollbar">
                    {['overview', 'users', 'daily', 'weekly', 'balancing'].map(tab => (
                        <button
                            key={tab}
                            onClick={() => setAnalyticsTab(tab)}
                            className={`flex-1 min-w-[100px] py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${analyticsTab === tab ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-600/20' : 'text-slate-500 hover:text-white hover:bg-white/5'}`}
                        >
                            {tab === 'overview' ? `📊 ${t.overview || 'OVERVIEW'}` : tab === 'users' ? `👥 ${lang === 'TR' ? 'HESAPLAR' : 'ACCOUNTS'}` : tab === 'daily' ? `📅 ${t.daily || 'DAILY'}` : tab === 'weekly' ? `📆 ${t.weekly || 'WEEKLY'}` : `⚖️ ${t.balancing || 'BALANCING'}`}
                        </button>
                    ))}
                </div>

                <div className="overflow-y-auto custom-scrollbar flex-1">
                    <div className="p-6 space-y-5">

                        {analyticsTab === 'users' && (
                            <div className="space-y-4">
                                <div className="relative">
                                    <input 
                                        type="text" 
                                        value={userSearch}
                                        onChange={(e) => {
                                            setUserSearch(e.target.value);
                                            fetchUsers(e.target.value);
                                        }}
                                        placeholder={lang === 'TR' ? "Kullanıcı Ara..." : "Search Users..."}
                                        className="w-full bg-slate-950/50 border border-white/10 rounded-2xl py-3 px-10 text-xs font-bold text-white outline-none focus:border-indigo-500 transition-all"
                                    />
                                    <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500">
                                        <Icons.Search size={14} />
                                    </div>
                                    {userLoading && (
                                        <div className="absolute right-4 top-1/2 -translate-y-1/2">
                                            <div className="w-4 h-4 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />
                                        </div>
                                    )}
                                </div>

                                <div className="space-y-2">
                                    {userList.map(u => (
                                        <div key={u.username} className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl flex items-center justify-between group hover:bg-white/[0.04] transition-all">
                                            <div className="flex items-center gap-3">
                                                <div className="w-10 h-10 bg-indigo-500/10 rounded-xl flex items-center justify-center text-indigo-400">
                                                    <Icons.User size={20} />
                                                </div>
                                                <div>
                                                    <p className="text-sm font-black text-white">{u.username}</p>
                                                    <p className="text-[10px] font-bold text-slate-500 uppercase tracking-tighter">
                                                        💰 {formatMoney(u.totalWealth)} • ✨ {u.xp?.toLocaleString()} XP
                                                    </p>
                                                </div>
                                            </div>
                                            <button 
                                                onClick={() => deleteUser(u.username)}
                                                disabled={deletingUser === u.username}
                                                className="p-2.5 bg-rose-500/10 text-rose-500 rounded-xl opacity-0 group-hover:opacity-100 transition-all hover:bg-rose-500/20 disabled:opacity-50"
                                            >
                                                {deletingUser === u.username ? (
                                                    <div className="w-4 h-4 border-2 border-rose-500 border-t-transparent rounded-full animate-spin" />
                                                ) : (
                                                    <Icons.Trash2 size={16} />
                                                )}
                                            </button>
                                        </div>
                                    ))}
                                    {userList.length === 0 && !userLoading && (
                                        <div className="text-center py-10">
                                            <p className="text-sm text-slate-600 font-bold">{lang === 'TR' ? "Kullanıcı bulunamadı." : "No users found."}</p>
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}

                        {analyticsTab === 'overview' && (
                            <>
                                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                    {[
                                        { label: t.totalUsers || 'Total Users', val: overview.totalUsers || 0, color:'text-white', icon:'👤' },
                                        { label: t.totalGames || 'Total Games', val: overview.totalGamesPlayed || 0, color:'text-indigo-400', icon:'🎲' },
                                        { label: t.newToday || 'New Today', val: overview.newUsersToday || 0, color:'text-emerald-400', icon:'✨' },
                                        { label: t.newThisWeek || 'New This Week', val: overview.newUsersThisWeek || 0, color:'text-cyan-400', icon:'📈' },
                                    ].map(k => (
                                        <div key={k.label} className="p-4 bg-white/[0.03] rounded-2xl border border-white/5 text-center">
                                            <p className="text-lg mb-1">{k.icon}</p>
                                            <p className={`text-2xl font-black ${k.color}`}>{k.val.toLocaleString()}</p>
                                            <p className="text-[10px] font-black text-slate-500 uppercase tracking-wider mt-1">{k.label}</p>
                                        </div>
                                    ))}
                                </div>

                                <div className="p-5 bg-amber-500/5 border border-amber-500/20 rounded-2xl space-y-3">
                                    <p className="text-[10px] font-black text-amber-500 uppercase tracking-widest mb-3">💰 {t.economyPoolManagement || 'ECONOMY POOL'}</p>
                                    {[
                                        { label: t.houseLiquidity || 'House Liquidity', val: formatMoney(overview.houseBank || 0), color: 'text-amber-400' },
                                        { label: t.realHouseBank || 'Real House Bank', val: formatMoney(overview.unlimitedHouseBank || 0), color: 'text-white' },
                                        { label: t.totalPlayerWealth || 'Player Wealth', val: formatMoney(gm.totalWealthInCirculation || 0), color: 'text-emerald-400' },
                                        { label: t.totalPlayerDebt || 'Player Debt', val: formatMoney(overview.totalPlayerDebt || 0), color: 'text-rose-500' },
                                    ].map(r => (
                                        <div key={r.label} className="flex justify-between items-center border-b border-white/5 pb-2 last:border-0 last:pb-0">
                                            <span className="text-xs font-bold text-slate-400">{r.label}</span>
                                            <span className={`text-sm font-black ${r.color} font-mono`}>{r.val}</span>
                                        </div>
                                    ))}
                                </div>

                                <div className="p-5 bg-white/[0.02] border border-white/5 rounded-2xl">
                                    <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-4">🏆 {t.allTimeMetrics || 'ALL TIME METRICS'}</p>
                                    <div className="grid grid-cols-3 gap-3 mb-4">
                                        <div className="text-center">
                                            <p className="text-2xl font-black text-emerald-400">{gm.totalWins || 0}</p>
                                            <p className="text-[10px] text-slate-500 font-bold uppercase">{t.wins || 'Wins'}</p>
                                        </div>
                                        <div className="text-center">
                                            <p className="text-2xl font-black text-rose-400">{gm.totalLosses || 0}</p>
                                            <p className="text-[10px] text-slate-500 font-bold uppercase">{t.losses || 'Losses'}</p>
                                        </div>
                                        <div className="text-center">
                                            <p className="text-2xl font-black text-indigo-400">{gm.completionRate || '0%'}</p>
                                            <p className="text-[10px] text-slate-500 font-bold uppercase">{t.completion || 'Completion'}</p>
                                        </div>
                                    </div>
                                    {(gm.totalWins || gm.totalLosses) ? (
                                        <div className="flex rounded-full overflow-hidden h-2">
                                            <div className="bg-emerald-500 transition-all" style={{width: `${Math.round((gm.totalWins / ((gm.totalWins||0)+(gm.totalLosses||0)))*100)}%`}} />
                                            <div className="bg-rose-500 flex-1" />
                                        </div>
                                    ) : null}
                                    <p className="text-[10px] text-slate-600 mt-2 text-center">{(t.avgRoundsPerGame || 'Avg. {count} rounds/game').replace('{count}', gm.averageRoundsPerGame || 0)}</p>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl">
                                        <p className="text-[10px] font-black text-amber-500 uppercase tracking-widest mb-3">👑 {t.top5ByWealth || 'TOP 5 BY WEALTH'}</p>
                                        <div className="space-y-2">
                                            {topWealth.map((u, i) => (
                                                <div key={u.username} className="flex items-center gap-2">
                                                    <span className={`text-xs font-black w-5 ${i === 0 ? 'text-amber-400' : i === 1 ? 'text-slate-300' : 'text-slate-500'}`}>#{i+1}</span>
                                                    <span className="text-xs text-white font-bold flex-1 truncate">{u.username}</span>
                                                    <span className={`text-xs font-black ${u.totalWealth >= 0 ? 'text-emerald-400' : 'text-rose-400'}`}>{formatMoney(u.totalWealth)}</span>
                                                </div>
                                            ))}
                                            {topWealth.length === 0 && <p className="text-slate-600 text-xs text-center py-2">{t.noHistoryData || 'No data'}</p>}
                                        </div>
                                    </div>
                                    <div className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl">
                                        <p className="text-[10px] font-black text-indigo-400 uppercase tracking-widest mb-3">🎲 {t.top5ByGames || 'TOP 5 BY GAMES'}</p>
                                        <div className="space-y-2">
                                            {topGames.map((u, i) => (
                                                <div key={u.username} className="flex items-center gap-2">
                                                    <span className={`text-xs font-black w-5 ${i === 0 ? 'text-amber-400' : i === 1 ? 'text-slate-300' : 'text-slate-500'}`}>#{i+1}</span>
                                                    <span className="text-xs text-white font-bold flex-1 truncate">{u.username}</span>
                                                    <span className="text-xs font-black text-indigo-400">{u.totalGames} {t.gamesLabel || 'games'}</span>
                                                </div>
                                            ))}
                                            {topGames.length === 0 && <p className="text-slate-600 text-xs text-center py-2">{t.noHistoryData || 'No data'}</p>}
                                        </div>
                                    </div>
                                </div>
                            </>
                        )}

                        {(analyticsTab === 'daily' || analyticsTab === 'weekly') && (
                            <>
                                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                                    {[
                                        { label: t.gameCount || 'Games', val: periodData.games || 0, color:'text-indigo-400', icon:'🎲' },
                                        { label: t.wins || 'Wins', val: periodData.wins || 0, color:'text-emerald-400', icon:'✅' },
                                        { label: t.losses || 'Losses', val: periodData.losses || 0, color:'text-rose-400', icon:'❌' },
                                        { label: t.activePlayers || 'Players', val: periodData.uniquePlayers || 0, color:'text-cyan-400', icon:'👥' },
                                        { label: t.avgScore || 'Avg Score', val: formatMoney(periodData.avgScore || 0), color: (periodData.avgScore||0) >= 0 ? 'text-emerald-400':'text-rose-400', icon:'📊' },
                                        { label: t.completed || 'Finished', val: periodData.completions || 0, color:'text-amber-400', icon:'🏁' },
                                    ].map(k => (
                                        <div key={k.label} className="p-4 bg-white/[0.03] rounded-2xl border border-white/5 text-center">
                                            <p className="text-lg mb-1">{k.icon}</p>
                                            <p className={`text-2xl font-black ${k.color}`}>{typeof k.val === 'number' ? k.val.toLocaleString() : k.val}</p>
                                            <p className="text-[10px] font-black text-slate-500 uppercase tracking-wider mt-1">{k.label}</p>
                                        </div>
                                    ))}
                                </div>

                                {(periodData.wins || periodData.losses) ? (
                                    <div className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl">
                                        <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">{periodLabel} — {t.winLossRate || 'WIN/LOSS RATE'}</p>
                                        <div className="flex rounded-full overflow-hidden h-3 mb-2">
                                            <div className="bg-emerald-500 transition-all" style={{width: `${Math.round(((periodData.wins||0)/Math.max((periodData.wins||0)+(periodData.losses||0),1))*100)}%`}} />
                                            <div className="bg-rose-500 flex-1" />
                                        </div>
                                        <div className="flex justify-between text-[10px] font-bold">
                                            <span className="text-emerald-400">{Math.round(((periodData.wins||0)/Math.max((periodData.wins||0)+(periodData.losses||0),1))*100)}% {lang === 'TR' ? 'Kazandı' : 'Won'}</span>
                                            <span className="text-rose-400">{Math.round(((periodData.losses||0)/Math.max((periodData.wins||0)+(periodData.losses||0),1))*100)}% {lang === 'TR' ? 'Kaybetti' : 'Lost'}</span>
                                        </div>
                                    </div>
                                ) : null}

                                {analyticsTab === 'weekly' && last7.length > 0 && (
                                    <div className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl">
                                        <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-4">{t.last7DaysActivity}</p>
                                        <div className="flex items-end gap-2 h-28">
                                            {last7.map((day, i) => {
                                                const barH = Math.max(4, Math.round((day.games / maxGames) * 100));
                                                const isToday = i === 6;
                                                return (
                                                    <div key={day.date} className="flex-1 flex flex-col items-center gap-1 group relative">
                                                        <div className="absolute bottom-full mb-8 hidden group-hover:flex flex-col items-center bg-slate-800 border border-white/10 rounded-xl p-2 text-[9px] font-bold whitespace-nowrap z-10 shadow-xl">
                                                            <span className="text-white">{day.games} {t.gamesLabel || 'games'}</span>
                                                            <span className="text-emerald-400">{day.wins} {lang === 'TR' ? 'kazandı' : 'won'}</span>
                                                            <span className="text-rose-400">{day.losses} {lang === 'TR' ? 'kaybetti' : 'lost'}</span>
                                                            <span className="text-cyan-400">{day.players} {(t.players || 'Players').toLowerCase()}</span>
                                                        </div>
                                                        <div
                                                            className={`w-full rounded-t-lg transition-all cursor-default ${isToday ? 'bg-indigo-500' : 'bg-slate-700 group-hover:bg-indigo-500/60'}`}
                                                            style={{height: `${barH}%`}}
                                                        />
                                                        <p className={`text-[8px] font-bold truncate w-full text-center ${isToday ? 'text-indigo-400' : 'text-slate-600'}`}>{(day.label || '').split(' ')[0]}</p>
                                                        <p className={`text-[9px] font-black ${isToday ? 'text-white' : 'text-slate-500'}`}>{day.games}</p>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>
                                )}

                                {analyticsTab === 'weekly' && (
                                    <div className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl">
                                        <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">{t.dailyDetail || 'DAILY DETAIL'}</p>
                                        <div className="grid grid-cols-5 items-center mb-2 px-2.5">
                                            <span className="col-span-2 text-[9px] font-black text-slate-600 uppercase">{t.date || 'Date'}</span>
                                            <span className="text-center text-[9px] font-black text-slate-600 uppercase">{t.games || 'Games'}</span>
                                            <span className="text-center text-[9px] font-black text-slate-600 uppercase">{t.players || 'Players'}</span>
                                            <span className="text-right text-[9px] font-black text-slate-600 uppercase">{t.revenue || 'Revenue'}</span>
                                        </div>
                                        <div className="space-y-1.5">
                                            {[...last7].reverse().map(day => (
                                                <div key={day.date} className="grid grid-cols-5 items-center p-2.5 rounded-xl bg-white/[0.02] hover:bg-white/[0.04] transition-colors">
                                                    <span className="col-span-2 text-[10px] font-bold text-slate-400">{day.label}</span>
                                                    <span className="text-center text-[10px] font-black text-indigo-400">{day.games}</span>
                                                    <span className="text-center text-[10px] font-black text-cyan-400">{day.players}</span>
                                                    <span className={`text-right text-[10px] font-black ${day.revenue >= 0 ? 'text-emerald-400':'text-rose-400'}`}>{formatMoney(day.revenue)}</span>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </>
                        )}

                        {analyticsTab === 'balancing' && (
                            <div className="space-y-5">
                                <div className="p-5 bg-indigo-500/5 border border-indigo-500/20 rounded-[2rem] relative overflow-hidden">
                                     <div className="relative z-10">
                                        <p className="text-[10px] font-black text-indigo-400 uppercase tracking-widest mb-4">🏛️ {t.rtpAnalysis || 'RTP ANALYSIS'}</p>
                                        <div className="grid grid-cols-2 gap-4">
                                            <div className="bg-white/[0.03] p-4 rounded-2xl border border-white/5">
                                                <p className="text-[9px] font-black text-slate-500 uppercase mb-1">{t.totalPayouts || 'Total Payouts'}</p>
                                                <p className="text-xl font-black text-emerald-400 font-mono">{formatMoney(gm.totalPayouts || 0)}</p>
                                            </div>
                                            <div className="bg-white/[0.03] p-4 rounded-2xl border border-white/5">
                                                <p className="text-[9px] font-black text-slate-500 uppercase mb-1">{t.dynamicRTP || 'Dynamic RTP'}</p>
                                                <div className="flex items-center gap-2">
                                                    <p className="text-xl font-black text-white">{( (gm.totalPayouts || 0) / Math.max(1, (gm.totalPayouts || 0) + (overview.unlimitedHouseBank || 0) - 1000000000) * 100 ).toFixed(1)}%</p>
                                                    <span className="text-[10px] px-2 py-0.5 bg-emerald-500/20 text-emerald-400 rounded-full font-bold">{t.healthy || 'HEALTHY'}</span>
                                                </div>
                                            </div>
                                        </div>
                                     </div>
                                     <div className="absolute top-0 right-0 p-8 opacity-10"><Icons.Activity size={80} className="text-indigo-500" /></div>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    {adminStats.perGameStats && Object.entries(adminStats.perGameStats).map(([name, s]) => (
                                        <div key={name} className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl">
                                            <div className="flex justify-between items-start mb-3">
                                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{name === 'oneMoreDice' ? '🎲 One More Dice' : '🃏 Card Path'}</p>
                                                <span className="text-[9px] font-bold text-slate-600">{s.count} {t.plays || 'plays'}</span>
                                            </div>
                                            <div className="space-y-2">
                                                <div className="flex justify-between items-center text-[10px]">
                                                    <span className="text-slate-500">{t.winRate || 'Win Rate'}</span>
                                                    <span className="text-white font-black">{s.winRate}</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px]">
                                                    <span className="text-slate-500">{t.avgPayout || 'Avg Payout'}</span>
                                                    <span className="text-emerald-400 font-black">{formatMoney(s.avgPayout)}</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px]">
                                                    <span className="text-slate-500">{t.netImpact || 'Net Impact'}</span>
                                                    <span className={`${s.totalNet >= 0 ? 'text-rose-400' : 'text-emerald-400'} font-black`}>{formatMoney(-s.totalNet)}</span>
                                                </div>
                                                <div className="pt-2">
                                                    <div className="h-1 bg-white/5 rounded-full overflow-hidden">
                                                        <div className="h-full bg-indigo-500 transition-all" style={{width: s.winRate}} />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>

                                <div className="p-4 bg-rose-500/5 border border-rose-500/20 rounded-2xl">
                                    <p className="text-[10px] font-black text-rose-500 uppercase tracking-widest mb-3">⚠️ {t.riskDetection || 'RISK DETECTION'}</p>
                                    <div className="space-y-2">
                                        {topWealth.filter(u => u.winCount / Math.max(1, u.totalGames) > 0.6).map(u => (
                                            <div key={u.username} className="flex items-center justify-between p-2 bg-rose-500/10 rounded-xl border border-rose-500/20">
                                                <div className="flex items-center gap-2">
                                                    <Icons.AlertTriangle size={14} className="text-rose-500" />
                                                    <span className="text-xs font-bold text-white">{u.username}</span>
                                                </div>
                                                <div className="text-right">
                                                    <p className="text-[10px] font-black text-rose-400">{Math.round((u.winCount/u.totalGames)*100)}% {t.winRate || 'Win Rate'}</p>
                                                    <p className="text-[9px] text-rose-500/70">{u.totalGames} {t.gamesLabel || 'games'}</p>
                                                </div>
                                            </div>
                                        ))}
                                        {topWealth.filter(u => u.winCount / Math.max(1, u.totalGames) > 0.6).length === 0 && (
                                            <p className="text-[10px] text-slate-600 text-center py-2 italic">{t.noSuspiciousActivity || 'No suspicious activity'}</p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                <div className="p-4 border-t border-white/5 flex gap-3 flex-shrink-0 bg-slate-950/30">
                    <button onClick={onClose} className="flex-1 py-3 bg-indigo-500/20 hover:bg-indigo-500/30 text-indigo-400 rounded-xl font-black uppercase tracking-widest transition-all border border-indigo-500/30 active:scale-95 text-xs">{t.close || 'CLOSE'}</button>
                    <button onClick={onReset} className="py-3 px-5 bg-rose-500/10 hover:bg-rose-500/20 text-rose-500 rounded-xl font-bold text-[10px] uppercase tracking-[0.15em] transition-all border border-rose-500/20 hover:border-rose-500/40">⚠️ {t.reset || 'RESET'}</button>
                </div>
            </div>
        </div>
    );
}

window.AnalyticsDashboard = AnalyticsDashboard;
