<?php
declare(strict_types=1);

$partiesFile = dirname(__DIR__) . '/privatedata/parties.json';
$profilesFile = dirname(__DIR__) . '/privatedata/players-profiles.json';

function h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function readJson(string $file, $default) {
    if (!file_exists($file)) {
        return $default;
    }

    $json = json_decode((string)file_get_contents($file), true);
    return is_array($json) ? $json : $default;
}

function normalizePlayerKey(string $name): string {
    $name = mb_strtolower(trim($name));
    $name = preg_replace('/\s+/', ' ', $name);
    return $name ?: 'joueur_inconnu';
}

function getPlayerName($player): string {
    if (is_array($player)) {
        return trim((string)($player['name'] ?? ''));
    }
    return trim((string)$player);
}

function getPlayerId($player): string {
    if (is_array($player)) {
        return trim((string)($player['id'] ?? ''));
    }
    return '';
}

function generatedPlayerAvatar(string $playerKey): string {
    $avatars = [
        '🦊','🐼','🦁','🐸','🐵','🐧','🐺','🐯','🐨','🐰',
        '🐢','🦄','🐙','🦉','🐶','🐱','🐭','🐹','🐻','🐻‍❄️',
        '🐮','🐷','🐽','🐔','🐣','🐥','🦆','🦅','🦇','🐺',
        '🐗','🐴','🦓','🦒','🦘','🦬','🐘','🦏','🦛','🐊',
        '🐍','🦎','🐲','🐉','🦖','🦕','🐳','🐬','🦈','🐠',
        '🐡','🦀','🦞','🦐','🦑','🐌','🦋','🐞','🐝','🪲',
        '🤖','👻','👽','🧙','🧛','🧟','🧞','🧚','🦸','🥷'
    ];

    $hash = crc32(mb_strtolower(trim($playerKey)));
    return $avatars[$hash % count($avatars)];
}

function normalizeProfileKey(string $name, string $initials = ''): string {
    $value = mb_strtolower(trim($name . ' ' . $initials));
    $value = preg_replace('/[^a-z0-9]+/u', '-', $value);
    $value = trim((string)$value, '-');
    return $value !== '' ? $value : 'joueur-inconnu';
}

function buildProfileAvatarIndex(array $profiles): array {
    $index = [
        'by_id' => [],
        'by_key' => [],
    ];

    foreach ($profiles as $profileKey => $profile) {
        if (!is_array($profile)) {
            continue;
        }

        $avatar = trim((string)($profile['avatar'] ?? ''));
        if ($avatar === '') {
            continue;
        }

        $id = trim((string)($profile['id'] ?? ''));
        if ($id !== '') {
            $index['by_id'][$id] = $avatar;
        }

        $storedKey = trim((string)($profile['player_key'] ?? $profileKey));
        if ($storedKey !== '') {
            $index['by_key'][mb_strtolower($storedKey)] = $avatar;
        }

        $name = trim((string)($profile['name'] ?? ''));
        $initials = trim((string)($profile['initials'] ?? ''));
        if ($name !== '') {
            $index['by_key'][normalizeProfileKey($name, $initials)] = $avatar;
            $index['by_key'][normalizeProfileKey(trim($name . ' ' . $initials))] = $avatar;
        }
    }

    return $index;
}

function profileAvatar(array $player, array $profileAvatarIndex): string {
    $id = trim((string)($player['id'] ?? ''));
    if ($id !== '' && isset($profileAvatarIndex['by_id'][$id])) {
        return (string)$profileAvatarIndex['by_id'][$id];
    }

    $name = trim((string)($player['name'] ?? ''));
    $key = normalizeProfileKey($name);
    if ($key !== '' && isset($profileAvatarIndex['by_key'][$key])) {
        return (string)$profileAvatarIndex['by_key'][$key];
    }

    return generatedPlayerAvatar($id !== '' ? $id : ($name !== '' ? $name : 'player'));
}

function rankIcon(int $index): string {
    if ($index === 0) return '🥇';
    if ($index === 1) return '🥈';
    if ($index === 2) return '🥉';
    return (string)($index + 1);
}

function playerUrl(array $player): string {
    if (!empty($player['id'])) {
        return '/joueur/?id=' . urlencode((string)$player['id']);
    }

    return '#';
}

function getBadges(array $player): array {
    $games = (int)($player['games'] ?? 0);
    $wins = (int)($player['wins'] ?? 0);
    $found = (int)($player['found'] ?? 0);
    $avgTurn = (float)($player['_avg_turn'] ?? 0);
    $bestTurn = (int)($player['best_turn'] ?? 0);
    $efficiency = (int)($player['_efficiency'] ?? 0);

    $badges = [];

    if ($wins >= 10) {
        $badges[] = ['icon' => '🏆', 'label' => 'Champion'];
    }

    if ($found >= 100) {
        $badges[] = ['icon' => '🧠', 'label' => 'Machine à mots'];
    }

    if ($avgTurn >= 5) {
        $badges[] = ['icon' => '⚡', 'label' => 'Très régulier'];
    }

    if ($bestTurn >= 10) {
        $badges[] = ['icon' => '🚀', 'label' => 'Tour explosif'];
    }

    if ($efficiency >= 80 && $found >= 20) {
        $badges[] = ['icon' => '🎯', 'label' => 'Très efficace'];
    }

    if ($games >= 20) {
        $badges[] = ['icon' => '🔥', 'label' => 'Joueur actif'];
    }

    return $badges;
}

$parties = readJson($partiesFile, []);
$profiles = readJson($profilesFile, []);
$profileAvatarIndex = buildProfileAvatarIndex($profiles);

$sort = $_GET['sort'] ?? 'general';
$mode = $_GET['mode'] ?? 'all';
if (!in_array($mode, ['all', 'classic', 'coop'], true)) {
    $mode = 'all';
}

$playersStats = [];

foreach ($parties as $party) {

    if (!is_array($party)) {
        continue;
    }

    $partyStatus = (string)($party['status'] ?? 'validated');

    if ($partyStatus === 'excluded' || $partyStatus === 'suspect') {
        continue;
    }

    // Si l'anti-triche a signalé la partie, elle ne compte pas tant que l'admin ne l'a pas publiée.
    // Quand tu cliques sur "Publier quand même", le statut passe à "validated" : elle est alors comptée.
    if (!empty($party['suspicious']) && $partyStatus !== 'validated') {
        continue;
    }

    $winnerName = trim((string)($party['winner'] ?? ''));
    $isCoopParty = (($party['game_mode'] ?? 'classic') === 'coop');

    if ($mode === 'classic' && $isCoopParty) {
        continue;
    }

    if ($mode === 'coop' && !$isCoopParty) {
        continue;
    }

    $coopData = is_array($party['coop'] ?? null) ? $party['coop'] : [];
    $coopWon = $isCoopParty && (
        (($coopData['won'] ?? false) === true) ||
        (($coopData['result'] ?? '') === 'victory') ||
        (mb_stripos($winnerName, 'vaincu') !== false)
    );

    $createdAt = (string)($party['created_at'] ?? '');

    $playersInParty = [];

    foreach (($party['teams'] ?? []) as $team) {
        if (!is_array($team)) {
            continue;
        }

        $teamName = trim((string)($team['name'] ?? ''));
        $teamScore = (int)($team['total'] ?? 0);
        $isWinnerTeam = ($winnerName !== '' && $teamName === $winnerName);

        foreach (($team['players'] ?? []) as $player) {
            $playerName = getPlayerName($player);
            $playerId = getPlayerId($player);

            if ($playerName === '') {
                continue;
            }

            $key = $playerId !== '' ? $playerId : normalizePlayerKey($playerName);

            // Sécurité : un même profil peut parfois apparaître deux fois dans une partie Coop.
            // On ne compte donc le joueur qu'une seule fois par partie.
            if (isset($playersInParty[$key])) {
                continue;
            }

            $playersInParty[$key] = true;

            if (!isset($playersStats[$key])) {
                $playersStats[$key] = [
                    'id' => $playerId,
                    'name' => $playerName,
                    'games' => 0,
                    'wins' => 0,
                    'losses' => 0,
                    'coop_games' => 0,
                    'coop_wins' => 0,
                    'team_score_total' => 0,
                    'found' => 0,
                    'passed' => 0,
                    'turns' => 0,
                    'best_turn' => 0,
                    'last_played_at' => '',
                ];
            }

            $playersStats[$key]['id'] = $playerId;
            $playersStats[$key]['name'] = $playerName;
            $playersStats[$key]['games']++;

            if ($isCoopParty) {
                $playersStats[$key]['coop_games']++;

                if ($coopWon) {
                    $playersStats[$key]['coop_wins']++;
                }
            }

            $playersStats[$key]['team_score_total'] += $teamScore;
            $playersStats[$key]['last_played_at'] = $createdAt;

          if (!$isCoopParty) {
    if ($isWinnerTeam) {
        $playersStats[$key]['wins']++;
    } else {
        $playersStats[$key]['losses']++;
    }
}
        }
    }

    foreach (($party['teams'] ?? []) as $team) {
        if (!is_array($team)) {
            continue;
        }

        foreach (($team['turnStats'] ?? []) as $turn) {
            if (!is_array($turn)) {
                continue;
            }

            $turnPlayerName = trim((string)($turn['playerName'] ?? ''));

            if ($turnPlayerName === '') {
                continue;
            }

            $foundKey = null;

            foreach ($playersStats as $key => $stats) {
                if (normalizePlayerKey((string)$stats['name']) === normalizePlayerKey($turnPlayerName)) {
                    $foundKey = $key;
                    break;
                }
            }

            if ($foundKey === null) {
                $foundKey = normalizePlayerKey($turnPlayerName);

                if (!isset($playersStats[$foundKey])) {
                    $playersStats[$foundKey] = [
                        'id' => '',
                        'name' => $turnPlayerName,
                        'games' => 0,
                        'wins' => 0,
                        'losses' => 0,
                        'team_score_total' => 0,
                        'found' => 0,
                        'passed' => 0,
                        'turns' => 0,
                        'best_turn' => 0,
                        'last_played_at' => $createdAt,
                    ];
                }
            }

            $foundCount = (int)($turn['foundCount'] ?? count($turn['found'] ?? []));
            $passedCount = is_array($turn['passed'] ?? null) ? count($turn['passed']) : 0;

            $playersStats[$foundKey]['found'] += $foundCount;
            $playersStats[$foundKey]['passed'] += $passedCount;
            $playersStats[$foundKey]['turns']++;
            $playersStats[$foundKey]['best_turn'] = max((int)$playersStats[$foundKey]['best_turn'], $foundCount);
        }
    }
}

$players = array_values($playersStats);

foreach ($players as &$player) {
    $games = (int)($player['games'] ?? 0);
    $wins = (int)($player['wins'] ?? 0);
    $found = (int)($player['found'] ?? 0);
    $passed = (int)($player['passed'] ?? 0);
    $turns = (int)($player['turns'] ?? 0);

    $classicGames = max(0, $games - (int)($player['coop_games'] ?? 0));

    $player['_winrate'] = $classicGames > 0 ? round(($wins / $classicGames) * 100) : 0;
    $player['_coop_rate'] = (int)($player['coop_games'] ?? 0) > 0
        ? round(((int)($player['coop_wins'] ?? 0) / (int)$player['coop_games']) * 100)
        : 0;
    $player['_avg_turn'] = $turns > 0 ? round($found / $turns, 1) : 0;
    $player['_efficiency'] = ($found + $passed) > 0 ? round(($found / ($found + $passed)) * 100) : 0;
}
unset($player);

function buildUrl(string $mode, string $sort): string {
    return '?mode=' . urlencode($mode) . '&sort=' . urlencode($sort);
}

usort($players, function($a, $b) use ($sort, $mode) {
    if ($sort === 'avg') {
        return
            (($b['_avg_turn'] ?? 0) <=> ($a['_avg_turn'] ?? 0))
            ?: (($b['wins'] ?? 0) <=> ($a['wins'] ?? 0))
            ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0));
    }

    if ($sort === 'best') {
        return
            (($b['best_turn'] ?? 0) <=> ($a['best_turn'] ?? 0))
            ?: (($b['wins'] ?? 0) <=> ($a['wins'] ?? 0))
            ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0));
    }

    if ($sort === 'efficiency') {
        return
            (($b['_efficiency'] ?? 0) <=> ($a['_efficiency'] ?? 0))
            ?: (($b['wins'] ?? 0) <=> ($a['wins'] ?? 0))
            ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0));
    }
if ($sort === 'coop') {
    return
        (($b['coop_wins'] ?? 0) <=> ($a['coop_wins'] ?? 0))
        ?: (($b['coop_games'] ?? 0) <=> ($a['coop_games'] ?? 0))
        ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0));
}

if ($sort === 'wins') {
    return
        (($b['wins'] ?? 0) <=> ($a['wins'] ?? 0))
        ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0))
        ?: (($b['_avg_turn'] ?? 0) <=> ($a['_avg_turn'] ?? 0));
}

if ($sort === 'found') {
    return
        (($b['found'] ?? 0) <=> ($a['found'] ?? 0))
        ?: (($b['wins'] ?? 0) <=> ($a['wins'] ?? 0))
        ?: (($b['_avg_turn'] ?? 0) <=> ($a['_avg_turn'] ?? 0));
}

if ($mode === 'coop') {
    return
        (($b['coop_wins'] ?? 0) <=> ($a['coop_wins'] ?? 0))
        ?: (($b['coop_games'] ?? 0) <=> ($a['coop_games'] ?? 0))
        ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0));
}

return
    (($b['wins'] ?? 0) <=> ($a['wins'] ?? 0))
    ?: (($b['found'] ?? 0) <=> ($a['found'] ?? 0))
    ?: (($b['_avg_turn'] ?? 0) <=> ($a['_avg_turn'] ?? 0))
    ?: (($b['best_turn'] ?? 0) <=> ($a['best_turn'] ?? 0))
    ?: (($b['_efficiency'] ?? 0) <=> ($a['_efficiency'] ?? 0));
});

$topPlayers = array_slice($players, 0, 50);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Classement joueurs Chrono Party</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
:root{
  --bg1:#140f2d;
  --bg2:#08111f;
  --card:rgba(255,255,255,.08);
  --line:rgba(255,255,255,.14);
  --text:#fff;
  --muted:rgba(255,255,255,.72);
  --accent:#8b5cf6;
  --accent2:#22d3ee;
}

*{box-sizing:border-box}

body{
  margin:0;
  min-height:100vh;
  font-family:Arial, Helvetica, sans-serif;
  color:var(--text);
  background:
    radial-gradient(circle at top left, rgba(139,92,246,.35), transparent 35%),
    radial-gradient(circle at top right, rgba(34,211,238,.24), transparent 35%),
    linear-gradient(160deg,var(--bg1),var(--bg2));
  padding:18px;
  padding-bottom:110px;
}

.container{max-width:1150px;margin:0 auto}
.header{text-align:center;padding:20px 10px 18px}

.logo{
  width:76px;
  height:76px;
  border-radius:24px;
  margin:0 auto 12px;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:38px;
  background:linear-gradient(135deg,#8b5cf6,#22d3ee);
  box-shadow:0 18px 45px rgba(0,0,0,.35);
}

h1{
  margin:0;
  font-size:clamp(28px,6vw,48px);
  letter-spacing:-1px;
}

.subtitle{
  margin:10px auto 0;
  max-width:720px;
  color:var(--muted);
  line-height:1.5;
  font-size:15px;
}

.tabs{
  display:flex;
  gap:10px;
  justify-content:center;
  flex-wrap:wrap;
  margin:18px 0 22px;
}

.tab{
  color:#fff;
  text-decoration:none;
  padding:10px 14px;
  border-radius:999px;
  border:1px solid var(--line);
  background:rgba(255,255,255,.07);
  font-weight:800;
  font-size:14px;
}

.tab.active{
  background:linear-gradient(135deg,#8b5cf6,#22d3ee);
  border-color:transparent;
  box-shadow:0 10px 25px rgba(0,0,0,.28);
}

.podium{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:14px;
  margin:0 0 18px;
}

.podiumCard{
  position:relative;
  overflow:hidden;
  border:1px solid rgba(255,255,255,.18);
  border-radius:26px;
  padding:18px;
  text-align:center;
  box-shadow:0 18px 45px rgba(0,0,0,.28);
  background:linear-gradient(135deg,rgba(139,92,246,.22),rgba(34,211,238,.12));
}

.podiumCard.first{
  background:linear-gradient(135deg,rgba(255,215,0,.18),rgba(255,255,255,.08));
  transform:translateY(-6px);
}

.podiumRank{
  font-size:34px;
  margin-bottom:8px;
}

.podiumName{
  font-size:18px;
  font-weight:1000;
  margin-bottom:8px;
}

.podiumStats{
  color:var(--muted);
  font-size:13px;
  line-height:1.5;
}

.playerAvatar{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  width:34px;
  height:34px;
  border-radius:12px;
  background:rgba(255,255,255,.10);
  border:1px solid rgba(255,255,255,.14);
  font-size:20px;
  flex-shrink:0;
}

.playerNameLine{
  display:flex;
  align-items:center;
  gap:10px;
}

.podiumName .playerNameLine{
  justify-content:center;
}

.playerLink{
  color:#a5f3fc;
  text-decoration:none;
  font-weight:1000;
  border-bottom:1px dashed rgba(165,243,252,.75);
}

.playerLink::after{
  content:" →";
  font-size:.9em;
  opacity:.85;
}

.playerLink:hover{
  color:#ffffff;
  border-bottom-color:#ffffff;
}

.badges{
  display:flex;
  gap:5px;
  flex-wrap:wrap;
  margin-top:8px;
  justify-content:center;
}

td.name .badges{
  justify-content:flex-start;
  margin-left:44px;
}

.badgeMini{
  position:relative;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:28px;
  height:28px;
  padding:0 7px;
  border-radius:10px;
  background:rgba(255,255,255,.10);
  border:1px solid rgba(255,255,255,.14);
  font-size:15px;
  cursor:default;
}

.badgeMini:hover::after{
  content:attr(data-label);
  position:absolute;
  bottom:34px;
  left:50%;
  transform:translateX(-50%);
  white-space:nowrap;
  background:#111827;
  color:#fff;
  font-size:12px;
  font-weight:900;
  padding:6px 8px;
  border-radius:8px;
  box-shadow:0 10px 25px rgba(0,0,0,.3);
  z-index:20;
}

.desktopTable{
  background:var(--card);
  border:1px solid var(--line);
  border-radius:26px;
  overflow:hidden;
  box-shadow:0 18px 50px rgba(0,0,0,.25);
}

table{width:100%;border-collapse:collapse}

th,td{
  padding:15px 10px;
  text-align:center;
  border-bottom:1px solid rgba(255,255,255,.08);
}

th{
  color:rgba(255,255,255,.8);
  font-size:12px;
  text-transform:uppercase;
  letter-spacing:.04em;
  background:rgba(255,255,255,.06);
}

td.name{
  text-align:left;
  font-weight:1000;
}

.rank{
  font-size:20px;
  font-weight:1000;
}

.mobileList{display:none}

.playerCard{
  background:var(--card);
  border:1px solid var(--line);
  border-radius:22px;
  padding:14px;
  margin-bottom:12px;
  box-shadow:0 12px 32px rgba(0,0,0,.22);
}

.playerTop{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  margin-bottom:12px;
}

.playerLeft{
  display:flex;
  align-items:center;
  gap:12px;
  min-width:0;
}

.mobileRank{
  width:44px;
  height:44px;
  border-radius:16px;
  display:flex;
  align-items:center;
  justify-content:center;
  background:rgba(255,255,255,.12);
  font-weight:1000;
  font-size:20px;
  flex-shrink:0;
}

.playerName{
  font-size:18px;
  font-weight:1000;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}

.lastPlayed{
  color:var(--muted);
  font-size:12px;
  margin-top:3px;
}

.scorePill{
  padding:8px 11px;
  border-radius:999px;
  background:linear-gradient(135deg,rgba(139,92,246,.85),rgba(34,211,238,.85));
  font-weight:1000;
  white-space:nowrap;
}

.mobileBadges{
  margin:8px 0 4px 56px;
  justify-content:flex-start;
}

.statsGrid{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:8px;
}

.statBox{
  border-radius:16px;
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.09);
  padding:10px 8px;
  text-align:center;
}

.statBox strong{
  display:block;
  font-size:18px;
}

.statBox span{
  display:block;
  color:var(--muted);
  font-size:11px;
  margin-top:3px;
}

.empty{
  text-align:center;
  padding:26px;
  color:var(--muted);
  background:var(--card);
  border-radius:22px;
  border:1px solid var(--line);
}

.footerLinks{
  text-align:center;
  margin:22px 0 4px;
  display:flex;
  justify-content:center;
  gap:10px;
  flex-wrap:wrap;
}

.footerLinks a{
  color:#fff;
  text-decoration:none;
  font-weight:900;
  display:inline-block;
  padding:10px 14px;
  border-radius:999px;
  background:rgba(255,255,255,.08);
  border:1px solid var(--line);
}

@media (max-width:760px){
  body{padding:12px;padding-bottom:110px}
  .header{padding-top:12px}
  .logo{
    width:62px;
    height:62px;
    border-radius:20px;
    font-size:32px;
  }
  .podium{grid-template-columns:1fr}
  .podiumCard.first{transform:none}
  .desktopTable{display:none}
  .mobileList{display:block}
  .tabs{gap:8px}
  .tab{
    flex:1;
    text-align:center;
    min-width:120px;
    padding:10px 8px;
    font-size:13px;
  }
}
.bottomActions{
  position:fixed;
  left:50%;
  bottom:calc(12px + env(safe-area-inset-bottom));
  transform:translateX(-50%);
  width:calc(100% - 24px);
  max-width:520px;
  z-index:9999;
  margin:0;
  padding:10px;
  border-radius:26px;
  background:rgba(7,17,31,.82);
  border:1px solid rgba(255,255,255,.12);
  backdrop-filter:blur(14px);
  box-shadow:0 14px 36px rgba(0,0,0,.35);
}

.bottomActionsGrid{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:10px;
}

.bottomBtn{
  appearance:none;
  border:0;
  cursor:pointer;
  display:flex;
  align-items:center;
  justify-content:center;
  min-height:46px;
  padding:11px 12px;
  border-radius:18px;
  color:white;
  text-decoration:none;
  font-weight:1000;
  font-size:14px;
  background:rgba(255,255,255,.09);
  border:1px solid rgba(255,255,255,.14);
}

.bottomBtn.primary{
  background:linear-gradient(135deg,#8b5cf6,#22d3ee);
  border-color:transparent;
}

.bottomBtn.danger{
  background:rgba(255,255,255,.08);
}

.profileModal{
  display:none;
  position:fixed;
  inset:0;
  z-index:100;
  background:rgba(0,0,0,.62);
  padding:18px;
  align-items:center;
  justify-content:center;
}

.profileModal.open{
  display:flex;
}

.profileModalBox{
  width:min(420px,100%);
  background:#15122f;
  border:1px solid rgba(255,255,255,.16);
  border-radius:26px;
  padding:20px;
}

.profileChoice{
  width:100%;
  margin:8px 0;
  padding:13px 14px;
  border-radius:18px;
  border:1px solid rgba(255,255,255,.14);
  background:rgba(255,255,255,.08);
  color:white;
  font-weight:1000;
  cursor:pointer;
}

.profileClose{
  margin-top:12px;
  width:100%;
}


/* Filtres par colonne */
.columnFilterRow th{
  background:rgba(255,255,255,.08) !important;
  padding:8px !important;
}
.columnFilterRow input{
  width:100%;
  box-sizing:border-box;
  border:1px solid rgba(255,255,255,.22);
  border-radius:10px;
  padding:8px 9px;
  background:rgba(255,255,255,.10);
  color:inherit;
  font-weight:800;
  outline:none;
}
.columnFilterRow input::placeholder{color:rgba(255,255,255,.58)}
.filterCounter{
  margin:10px 0 14px;
  font-size:13px;
  font-weight:900;
  color:inherit;
  opacity:.82;
}
.container{
  width:min(96vw, 1680px);
  max-width:1680px;
}

.desktopTable{
  width:100%;
}

.desktopTable table{
  width:100%;
  table-layout:auto;
}

.desktopTable th,
.desktopTable td{
  white-space:normal;
}

@media(max-width:1300px){
  .container{
    width:98vw;
    max-width:98vw;
  }

  .desktopTable{
    overflow-x:auto;
  }

  .desktopTable table{
    min-width:1180px;
  }
}
@media(max-width:760px){

  html,
  body{
    width:100%;
    max-width:100%;
    overflow-x:hidden !important;
  }

  .container{
    width:100% !important;
    max-width:100% !important;
    padding:0 !important;
    overflow-x:hidden !important;
  }

  .podium,
  .mobileList,
  .bottomActions,
  .playerCard,
  .podiumCard{
    width:100% !important;
    max-width:100% !important;
    margin-left:0 !important;
    margin-right:0 !important;
    box-sizing:border-box !important;
    overflow:hidden !important;
  }

  .playerTop{
    width:100% !important;
    max-width:100% !important;
    display:grid !important;
    grid-template-columns:1fr auto !important;
    gap:8px !important;
  }

  .playerLeft{
    min-width:0 !important;
    overflow:hidden !important;
  }

  .playerName,
  .playerLink{
    max-width:135px !important;
    overflow:hidden !important;
    text-overflow:ellipsis !important;
    white-space:nowrap !important;
    display:inline-block !important;
  }

  .scorePill{
    max-width:95px !important;
    white-space:nowrap !important;
    overflow:hidden !important;
    text-overflow:ellipsis !important;
  }

  .statsGrid{
    grid-template-columns:repeat(2, minmax(0, 1fr)) !important;
  }

  .statBox{
    min-width:0 !important;
  }
}
</style>
</head>

<body>
<div class="container">

  <header class="header">
    <div class="logo">🧠</div>
    <h1>Classement joueurs</h1>
    <p class="subtitle">
      Classement individuel avec séparation des parties classiques et des parties Coop contre le Boss.
    </p>
  </header>

  <nav class="tabs">
<a class="tab <?= $mode === 'all' ? 'active' : '' ?>" href="<?= h(buildUrl('all', $sort)) ?>">🌍 Tous</a>
<a class="tab <?= $mode === 'classic' ? 'active' : '' ?>" href="<?= h(buildUrl('classic', $sort)) ?>">⚔️ Classique</a>
<a class="tab <?= $mode === 'coop' ? 'active' : '' ?>" href="<?= h(buildUrl('coop', $sort)) ?>">🤝 Coop</a>
</nav>

<nav class="tabs">
<a class="tab <?= $sort === 'general' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'general')) ?>">🏆 Général</a>
<a class="tab <?= $sort === 'found' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'found')) ?>">🧠 Mots trouvés</a>
<a class="tab <?= $sort === 'avg' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'avg')) ?>">⚡ Moyenne / tour</a>
<a class="tab <?= $sort === 'best' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'best')) ?>">🚀 Meilleur tour</a>
<a class="tab <?= $sort === 'efficiency' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'efficiency')) ?>">🎯 Efficacité</a>
<a class="tab <?= $sort === 'coop' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'coop')) ?>">🤝 Boss vaincus</a>
<a class="tab <?= $sort === 'wins' ? 'active' : '' ?>" href="<?= h(buildUrl($mode, 'wins')) ?>">🏆 Victoires</a>
  </nav>

  <?php if (empty($topPlayers)): ?>

    <div class="empty">
      Aucun joueur enregistré pour le moment.
    </div>

  <?php else: ?>

    <section class="podium">
      <?php foreach(array_slice($topPlayers, 0, 3) as $index => $player): ?>
        <?php $badges = getBadges($player); ?>

        <div class="podiumCard <?= $index === 0 ? 'first' : '' ?>">
          <div class="podiumRank"><?= rankIcon($index) ?></div>

          <div class="podiumName">
            <div class="playerNameLine">
              <span class="playerAvatar">
                <?= h(profileAvatar($player, $profileAvatarIndex)) ?>
              </span>

              <?php if (!empty($player['id'])): ?>
                <a class="playerLink" href="<?= h(playerUrl($player)) ?>">
                  <?= h($player['name'] ?? '-') ?>
                </a>
              <?php else: ?>
                <?= h($player['name'] ?? '-') ?>
              <?php endif; ?>
            </div>
          </div>

          <?php if (!empty($badges)): ?>
            <div class="badges">
              <?php foreach($badges as $badge): ?>
                <span class="badgeMini" data-label="<?= h($badge['label']) ?>">
                  <?= h($badge['icon']) ?>
                </span>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

          <div class="podiumStats">
            <?= (int)($player['found'] ?? 0) ?> mots trouvés<br>
            <?= h($player['_avg_turn'] ?? 0) ?> / tour ·
            meilleur tour <?= (int)($player['best_turn'] ?? 0) ?><br>
            Coop : <?= (int)($player['coop_wins'] ?? 0) ?> boss vaincus / <?= (int)($player['coop_games'] ?? 0) ?> parties<br>
            efficacité <?= (int)($player['_efficiency'] ?? 0) ?>%
          </div>
        </div>
      <?php endforeach; ?>
    </section>

    <div class="desktopTable">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Joueur</th>
            <th>Parties</th>
            <th>Victoires</th>
            <th>Défaites</th>
            <th>Coop</th>
            <th>Boss vaincus</th>
            <th>Réussite Coop</th>
            <th>Mots trouvés perso</th>
            <th>Moy. / tour</th>
            <th>Meilleur tour</th>
            <th>Efficacité</th>
            <th>Taux victoire</th>
            <th>Dernière partie</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($topPlayers as $index => $player): ?>
            <?php $badges = getBadges($player); ?>

            <tr>
              <td class="rank"><?= rankIcon($index) ?></td>

              <td class="name">
                <div class="playerNameLine">
                  <span class="playerAvatar">
                    <?= h(profileAvatar($player, $profileAvatarIndex)) ?>
                  </span>

                  <?php if (!empty($player['id'])): ?>
                    <a class="playerLink" href="<?= h(playerUrl($player)) ?>">
                      <?= h($player['name'] ?? '-') ?>
                    </a>
                  <?php else: ?>
                    <?= h($player['name'] ?? '-') ?>
                  <?php endif; ?>
                </div>

                <?php if (!empty($badges)): ?>
                  <div class="badges">
                    <?php foreach($badges as $badge): ?>
                      <span class="badgeMini" data-label="<?= h($badge['label']) ?>">
                        <?= h($badge['icon']) ?>
                      </span>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </td>

              <td><?= (int)($player['games'] ?? 0) ?></td>
              <td><?= (int)($player['wins'] ?? 0) ?></td>
              <td><?= (int)($player['losses'] ?? 0) ?></td>
              <td><?= (int)($player['coop_games'] ?? 0) ?></td>
              <td><?= (int)($player['coop_wins'] ?? 0) ?></td>
              <td><?= (int)($player['_coop_rate'] ?? 0) ?>%</td>
              <td><strong><?= (int)($player['found'] ?? 0) ?></strong></td>
              <td><?= h($player['_avg_turn'] ?? 0) ?></td>
              <td><?= (int)($player['best_turn'] ?? 0) ?></td>
              <td><?= (int)($player['_efficiency'] ?? 0) ?>%</td>
              <td><?= (int)($player['_winrate'] ?? 0) ?>%</td>
              <td><?= h($player['last_played_at'] ?? '-') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <div class="mobileList">
      <?php foreach($topPlayers as $index => $player): ?>
        <?php $badges = getBadges($player); ?>

        <article class="playerCard">
          <div class="playerTop">
            <div class="playerLeft">
              <div class="mobileRank"><?= rankIcon($index) ?></div>

              <span class="playerAvatar">
                <?= h(profileAvatar($player, $profileAvatarIndex)) ?>
              </span>

              <div>
                <div class="playerName">
                  <?php if (!empty($player['id'])): ?>
                    <a class="playerLink" href="<?= h(playerUrl($player)) ?>">
                      <?= h($player['name'] ?? '-') ?>
                    </a>
                  <?php else: ?>
                    <?= h($player['name'] ?? '-') ?>
                  <?php endif; ?>
                </div>
                <div class="lastPlayed"><?= h($player['last_played_at'] ?? '-') ?></div>
              </div>
            </div>

            <div class="scorePill">
              <?= (int)($player['found'] ?? 0) ?> mots
            </div>
          </div>

          <?php if (!empty($badges)): ?>
            <div class="badges mobileBadges">
              <?php foreach($badges as $badge): ?>
                <span class="badgeMini" data-label="<?= h($badge['label']) ?>">
                  <?= h($badge['icon']) ?>
                </span>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

          <div class="statsGrid">
            <div class="statBox">
              <strong><?= h($player['_avg_turn'] ?? 0) ?></strong>
              <span>Moy. / tour</span>
            </div>

            <div class="statBox">
              <strong><?= (int)($player['best_turn'] ?? 0) ?></strong>
              <span>Meilleur</span>
            </div>

            <div class="statBox">
              <strong><?= (int)($player['_efficiency'] ?? 0) ?>%</strong>
              <span>Efficacité</span>
            </div>

            <div class="statBox">
              <strong><?= (int)($player['_winrate'] ?? 0) ?>%</strong>
              <span>Victoire</span>
            </div>

            <div class="statBox">
              <strong><?= (int)($player['coop_games'] ?? 0) ?></strong>
              <span>Coop</span>
            </div>

            <div class="statBox">
              <strong><?= (int)($player['coop_wins'] ?? 0) ?></strong>
              <span>Boss vaincus</span>
            </div>
          </div>
        </article>
      <?php endforeach; ?>
    </div>

  <?php endif; ?>

<div class="bottomActions">
  <div class="bottomActionsGrid">
    <a class="bottomBtn primary" href="/statistiques/">📊 Statistiques</a>
    <button type="button" class="bottomBtn danger" onclick="closeStatsPage()">✕ Fermer</button>
  </div>
</div>

<div id="profileModal" class="profileModal" aria-hidden="true">
  <div class="profileModalBox">
    <h2>👤 Mon profil joueur</h2>
    <p id="profileModalText">Choisis le profil à consulter.</p>
    <div id="profileChoices"></div>
    <button type="button" class="bottomBtn profileClose" onclick="closeProfileModal()">Fermer</button>
  </div>
</div>

</div>
<script>
const PROFILE_BASE_URL = '/joueur/?id=';

function closeStatsPage(){
  window.location.href = '/jeux/';
}

function openMyPlayerProfile(){
  const savedId = localStorage.getItem('chrono_personal_player_id');

  if(savedId){
    window.location.href = PROFILE_BASE_URL + encodeURIComponent(savedId);
    return;
  }

  const modal = document.getElementById('profileModal');
  const choices = document.getElementById('profileChoices');
  const text = document.getElementById('profileModalText');

  if(!modal || !choices || !text){
    alert('Impossible d’ouvrir le profil.');
    return;
  }

  text.textContent = 'Indique ton prénom et ton initiale pour retrouver ton profil joueur.';

  choices.innerHTML = `
    <input id="profileFirstName" type="text" placeholder="Prénom, ex : Giovanni" style="width:100%;margin:8px 0;padding:13px;border-radius:14px;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.08);color:white;font-weight:900;">
    <input id="profileInitials" type="text" maxlength="2" placeholder="Initiale, ex : C" style="width:100%;margin:8px 0;padding:13px;border-radius:14px;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.08);color:white;font-weight:900;">
    <button type="button" class="bottomBtn primary" style="width:100%;margin-top:10px" onclick="confirmMyPlayerProfile()">Valider mon profil</button>
  `;

  modal.classList.add('open');
  modal.setAttribute('aria-hidden', 'false');
}

async function confirmMyPlayerProfile(){
  const name = document.getElementById('profileFirstName')?.value.trim() || '';
  const initials = document.getElementById('profileInitials')?.value.trim().toUpperCase() || '';

  if(!name || !initials){
    alert('Indique ton prénom et ton initiale.');
    return;
  }

  try{
    const response = await fetch('/api/player-profile.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, initials })
    });

    const data = await response.json();

    if(!response.ok || !data.ok || !data.player || !data.player.id){
      alert(data.error || 'Profil joueur introuvable.');
      return;
    }

    localStorage.setItem('chrono_personal_player_id', data.player.id);
    window.location.href = PROFILE_BASE_URL + encodeURIComponent(data.player.id);

  }catch(e){
    alert('Impossible de récupérer le profil joueur.');
  }
}

function closeProfileModal(){
  const modal = document.getElementById('profileModal');
  if(modal){
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden', 'true');
  }
}

document.addEventListener('click', function(event){
  const modal = document.getElementById('profileModal');
  if(event.target === modal){
    closeProfileModal();
  }
});
</script>

<script>
(function(){
  function getCellValue(row, index){
    const cell = row.children[index];
    return cell ? cell.textContent.trim() : '';
  }

  function parseValue(value){
    const clean = value.replace('%','').replace(',', '.').trim();

    if (/^\d{4}-\d{2}-\d{2}/.test(clean)) {
      return new Date(clean.replace(' ', 'T')).getTime() || 0;
    }

    const number = parseFloat(clean);
    if (!isNaN(number)) return number;

    return clean.toLowerCase();
  }

  document.querySelectorAll('.desktopTable table').forEach(function(table){
    const headers = table.querySelectorAll('thead tr:first-child th');
    const tbody = table.querySelector('tbody');
    if (!tbody) return;

    headers.forEach(function(th, index){
      th.style.cursor = 'pointer';
      th.title = 'Cliquer pour trier';
      th.dataset.sortDirection = 'desc';

      th.addEventListener('click', function(){
        const direction = th.dataset.sortDirection === 'asc' ? 'desc' : 'asc';
        th.dataset.sortDirection = direction;

        headers.forEach(function(otherTh){
          otherTh.textContent = otherTh.textContent.replace(' ↑','').replace(' ↓','');
        });

        th.textContent = th.textContent.replace(' ↑','').replace(' ↓','') + (direction === 'asc' ? ' ↑' : ' ↓');

        const rows = Array.from(tbody.querySelectorAll('tr'));

        rows.sort(function(a, b){
          const aValue = parseValue(getCellValue(a, index));
          const bValue = parseValue(getCellValue(b, index));

          if (typeof aValue === 'number' && typeof bValue === 'number') {
            return direction === 'asc' ? aValue - bValue : bValue - aValue;
          }

          return direction === 'asc'
            ? String(aValue).localeCompare(String(bValue), 'fr', {numeric:true})
            : String(bValue).localeCompare(String(aValue), 'fr', {numeric:true});
        });

        rows.forEach(function(row){
          tbody.appendChild(row);
        });
      });
    });
  });
})();
</script>

</body>
</html>