<?php
declare(strict_types=1);

$partiesFile = dirname(__DIR__) . '/privatedata/parties.json';
$playersFile = dirname(__DIR__) . '/privatedata/players.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 queryUrl(array $changes = []): string {
    $params = $_GET;
    foreach ($changes as $key => $value) {
        if ($value === null || $value === '') {
            unset($params[$key]);
        } else {
            $params[$key] = $value;
        }
    }
    $query = http_build_query($params);
    return './' . ($query ? '?' . $query : '');
}

function shortDate($date): string {
    $ts = strtotime((string)$date);
    return $ts ? date('d/m/Y · H\hi', $ts) : (string)$date;
}

function formatDuration($seconds): string {
    $seconds = max(0, (int)$seconds);
    $hours = intdiv($seconds, 3600);
    $minutes = intdiv($seconds % 3600, 60);
    $sec = $seconds % 60;

    if ($hours > 0) {
        return $hours . ' h ' . str_pad((string)$minutes, 2, '0', STR_PAD_LEFT);
    }

    if ($minutes > 0) {
        return $minutes . ' min ' . str_pad((string)$sec, 2, '0', STR_PAD_LEFT) . ' s';
    }

    return $sec . ' s';
}

function partyUrl(array $party): string {
    return '/jeux/partie/?id=' . urlencode((string)($party['id'] ?? ''));
}

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

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

function scoreGap(array $party): ?int {
    $scores = [];
    foreach (($party['scores'] ?? []) as $score) {
        $scores[] = (int)($score['total'] ?? 0);
    }
    if (count($scores) < 2) {
        foreach (($party['teams'] ?? []) as $team) {
            $scores[] = (int)($team['total'] ?? 0);
        }
    }
    if (count($scores) < 2) return null;
    rsort($scores);
    return $scores[0] - $scores[1];
}

function totalScore(array $party): int {
    $total = 0;
    foreach (($party['scores'] ?? []) as $score) {
        $total += (int)($score['total'] ?? 0);
    }
    if ($total <= 0) {
        foreach (($party['teams'] ?? []) as $team) {
            $total += (int)($team['total'] ?? 0);
        }
    }
    return $total;
}

function bestTeamInParty(array $party): array {
    $best = ['name' => '—', 'score' => 0];
    foreach (($party['teams'] ?? []) as $team) {
        $score = (int)($team['total'] ?? 0);
        if ($score > $best['score']) {
            $best = ['name' => (string)($team['name'] ?? 'Équipe'), 'score' => $score];
        }
    }
    foreach (($party['scores'] ?? []) as $scoreRow) {
        $score = (int)($scoreRow['total'] ?? 0);
        if ($score > $best['score']) {
            $best = ['name' => (string)($scoreRow['name'] ?? 'Équipe'), 'score' => $score];
        }
    }
    return $best;
}

function countFoundWordsInParty(array $party): int {
    $count = 0;
    foreach (($party['teams'] ?? []) as $team) {
        foreach (($team['turnStats'] ?? []) as $turn) {
            if (isset($turn['foundCount'])) {
                $count += (int)$turn['foundCount'];
            } elseif (isset($turn['found']) && is_array($turn['found'])) {
                $count += count($turn['found']);
            }
        }
    }
    return $count;
}

$playerId = trim((string)($_GET['id'] ?? ''));
$mode = 'all';
$search = '';
$dateFrom = '';
$dateTo = '';

$parties = readJson($partiesFile, []);
$playersSaved = readJson($playersFile, []);

function isCoopParty(array $party): bool {
    return (($party['game_mode'] ?? 'classic') === 'coop') || !empty($party['coop']['enabled']);
}

function coopWon(array $party): bool {
    return isCoopParty($party) && (
        (($party['coop']['won'] ?? false) === true) ||
        (($party['coop']['result'] ?? '') === 'victory') ||
        (($party['winner'] ?? '') === 'Grand Boss vaincu')
    );
}

function coopLabel(array $party): string {
    return trim((string)($party['coop']['label'] ?? 'Boss Coop')) ?: 'Boss Coop';
}

function coopTurnsUsed(array $party): int {
    return (int)($party['coop']['turns_used'] ?? $party['rounds_played'] ?? 0);
}

function coopTurnsRemaining(array $party): int {
    return (int)($party['coop']['turns_remaining'] ?? 0);
}

function partyMatchesStatsSearch(array $party, string $search): bool {
    if ($search === '') {
        return true;
    }

    $haystack = [];
    $haystack[] = (string)($party['created_at'] ?? '');
    $haystack[] = (string)($party['winner'] ?? '');
    $haystack[] = (string)($party['source'] ?? '');
    $haystack[] = isCoopParty($party) ? 'coop boss cooperatif' : 'classique equipe';
    $haystack[] = (string)($party['coop']['label'] ?? '');
    $haystack[] = (string)($party['coop']['rank_label'] ?? '');

    foreach (($party['themes'] ?? []) as $theme) {
        $haystack[] = (string)$theme;
    }

    foreach (($party['difficulties'] ?? []) as $difficulty) {
        $haystack[] = (string)$difficulty;
    }

    foreach (($party['teams'] ?? []) as $team) {
        $haystack[] = (string)($team['name'] ?? '');
        foreach (($team['players'] ?? []) as $player) {
            $haystack[] = playerName($player);
        }
        foreach (($team['turnStats'] ?? []) as $turn) {
            $haystack[] = (string)($turn['playerName'] ?? '');
        }
    }

    return str_contains(mb_strtolower(implode(' ', $haystack)), mb_strtolower($search));
}


function buildStatsSearchSuggestions(array $parties): array {
    $values = [];

    $add = function($value) use (&$values): void {
        $value = trim((string)$value);
        $value = preg_replace('/\s+/', ' ', $value);
        if ($value !== '' && mb_strlen($value) <= 80) {
            $values[$value] = true;
        }
    };

    foreach ($parties as $party) {
        if (!is_array($party)) {
            continue;
        }

        $status = (string)($party['status'] ?? 'validated');
        if ($status === 'excluded' || $status === 'suspect') {
            continue;
        }
        if (!empty($party['suspicious']) && $status !== 'validated') {
            continue;
        }

        $add(isCoopParty($party) ? 'Coop Boss' : 'Classique');
        $add((string)($party['source'] ?? ''));
        $add((string)($party['winner'] ?? ''));
        $add((string)($party['coop']['label'] ?? ''));
        $add((string)($party['coop']['rank_label'] ?? ''));

        foreach (($party['themes'] ?? []) as $theme) {
            $add($theme);
        }

        foreach (($party['difficulties'] ?? []) as $difficulty) {
            $add($difficulty);
        }

        foreach (($party['teams'] ?? []) as $team) {
            $add((string)($team['name'] ?? ''));

            foreach (($team['players'] ?? []) as $player) {
                $add(playerName($player));
            }

            foreach (($team['turnStats'] ?? []) as $turn) {
                $add((string)($turn['playerName'] ?? ''));
                foreach (($turn['found'] ?? []) as $word) {
                    $add($word);
                }
                foreach (($turn['passed'] ?? []) as $word) {
                    $add($word);
                }
            }
        }
    }

    $values = array_keys($values);
    sort($values, SORT_NATURAL | SORT_FLAG_CASE);
    return array_slice($values, 0, 250);
}


$allValidParties = [];

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;
    }


    $allValidParties[] = $party;
}

$classicParties = array_values(array_filter($allValidParties, fn($party) => !isCoopParty($party)));
$coopParties = array_values(array_filter($allValidParties, fn($party) => isCoopParty($party)));

$validParties = $allValidParties;

$totalParties = count($validParties);
$totalDuration = 0;
$totalFoundWords = 0;
$totalTeamScores = 0;
$totalTeams = 0;
$totalPlayersSlots = 0;
$uniquePlayers = [];
$teamWins = [];
$teamGames = [];
$themes = [];
$difficulties = [];
$latestParty = null;
$bestTeamParty = null;
$biggestWinParty = null;
$tightestParty = null;
$bestTotalParty = null;

// Statistiques Coop globales séparées
$coopTotal = count($coopParties);
$coopWins = 0;
$coopLosses = 0;
$coopTotalTurnsUsed = 0;
$coopTotalTurnsRemainingOnWins = 0;
$coopLatestParty = null;
$coopFastestWinParty = null;
$coopBestRemainingParty = null;
$coopLongestParty = null;
$coopHighestBossParty = null;
$coopLevels = [];
$coopRanks = [];

foreach ($coopParties as $party) {
    $won = coopWon($party);
    if ($won) {
        $coopWins++;
        $coopTotalTurnsRemainingOnWins += coopTurnsRemaining($party);
    } else {
        $coopLosses++;
    }

    $coopTotalTurnsUsed += coopTurnsUsed($party);

    if (!$coopLatestParty || strtotime((string)($party['created_at'] ?? '')) > strtotime((string)($coopLatestParty['created_at'] ?? ''))) {
        $coopLatestParty = $party;
    }

    if ($won && (!$coopFastestWinParty || coopTurnsUsed($party) < coopTurnsUsed($coopFastestWinParty))) {
        $coopFastestWinParty = $party;
    }

    if ($won && (!$coopBestRemainingParty || coopTurnsRemaining($party) > coopTurnsRemaining($coopBestRemainingParty))) {
        $coopBestRemainingParty = $party;
    }

    if (!$coopLongestParty || (int)($party['duration'] ?? 0) > (int)($coopLongestParty['duration'] ?? 0)) {
        $coopLongestParty = $party;
    }

    if (!$coopHighestBossParty || (int)($party['coop']['max_turns'] ?? 0) > (int)($coopHighestBossParty['coop']['max_turns'] ?? 0)) {
        $coopHighestBossParty = $party;
    }

    $level = trim((string)($party['coop']['label'] ?? $party['coop']['level'] ?? ''));
    if ($level !== '') $coopLevels[$level] = ($coopLevels[$level] ?? 0) + 1;

    $rank = trim((string)($party['coop']['rank_label'] ?? ''));
    if ($rank !== '') $coopRanks[$rank] = ($coopRanks[$rank] ?? 0) + 1;
}

foreach ($validParties as $party) {
    $totalDuration += (int)($party['duration'] ?? 0);
    $totalFoundWords += countFoundWordsInParty($party);
    $totalPlayersSlots += (int)($party['players_count'] ?? 0);

    if (!$latestParty || strtotime((string)($party['created_at'] ?? '')) > strtotime((string)($latestParty['created_at'] ?? ''))) {
        $latestParty = $party;
    }

    if (!$bestTotalParty || totalScore($party) > totalScore($bestTotalParty)) {
        $bestTotalParty = $party;
    }

    $gap = scoreGap($party);
    if ($gap !== null) {
        if (!$tightestParty || $gap < (int)scoreGap($tightestParty)) {
            $tightestParty = $party;
        }
        if (!$biggestWinParty || $gap > (int)scoreGap($biggestWinParty)) {
            $biggestWinParty = $party;
        }
    }

    $bestTeam = bestTeamInParty($party);
    if (!$bestTeamParty || $bestTeam['score'] > bestTeamInParty($bestTeamParty)['score']) {
        $bestTeamParty = $party;
    }

    $winner = trim((string)($party['winner'] ?? ''));
    if ($winner !== '') {
        $teamWins[$winner] = ($teamWins[$winner] ?? 0) + 1;
    }

    foreach (($party['themes'] ?? []) as $theme) {
        $theme = trim((string)$theme);
        if ($theme !== '') $themes[$theme] = ($themes[$theme] ?? 0) + 1;
    }

    foreach (($party['difficulties'] ?? []) as $difficulty) {
        $difficulty = trim((string)$difficulty);
        if ($difficulty !== '') $difficulties[$difficulty] = ($difficulties[$difficulty] ?? 0) + 1;
    }

    foreach (($party['teams'] ?? []) as $team) {
        if (!is_array($team)) continue;
        $teamName = trim((string)($team['name'] ?? 'Équipe'));
        $teamGames[$teamName] = ($teamGames[$teamName] ?? 0) + 1;
        $totalTeamScores += (int)($team['total'] ?? 0);
        $totalTeams++;

        foreach (($team['players'] ?? []) as $player) {
            $name = playerName($player);
            if ($name === '') continue;
            $id = is_array($player) ? trim((string)($player['id'] ?? '')) : '';
            $key = $id !== '' ? $id : normalizeName($name);
            $uniquePlayers[$key] = $name;
        }
    }
}

if (!empty($playersSaved)) {
    foreach ($playersSaved as $key => $player) {
        if (is_array($player)) {
            $name = trim((string)($player['name'] ?? $key));
            if ($name !== '') $uniquePlayers[(string)$key] = $name;
        }
    }
}

arsort($teamWins);
arsort($teamGames);
arsort($themes);
arsort($difficulties);
arsort($coopLevels);
arsort($coopRanks);

$avgScoreByTeam = $totalTeams > 0 ? round($totalTeamScores / $totalTeams, 1) : 0;
$avgPlayersByParty = $totalParties > 0 ? round($totalPlayersSlots / $totalParties, 1) : 0;
$topWinnerTeam = $teamWins ? array_key_first($teamWins) : '—';
$mostPlayedTeam = $teamGames ? array_key_first($teamGames) : '—';
$topTheme = $themes ? array_key_first($themes) : '—';
$topDifficulty = $difficulties ? array_key_first($difficulties) : '—';
$bestTeam = $bestTeamParty ? bestTeamInParty($bestTeamParty) : ['name' => '—', 'score' => 0];

$coopSuccessRate = $coopTotal > 0 ? round(($coopWins / $coopTotal) * 100) : 0;
$coopAvgTurnsUsed = $coopTotal > 0 ? round($coopTotalTurnsUsed / $coopTotal, 1) : 0;
$coopAvgTurnsRemaining = $coopWins > 0 ? round($coopTotalTurnsRemainingOnWins / $coopWins, 1) : 0;
$coopTopLevel = $coopLevels ? array_key_first($coopLevels) : '—';
$coopTopRank = $coopRanks ? array_key_first($coopRanks) : '—';

$modeLabel = 'Toutes';

if ($mode === 'coop') {
    $cards = [
        ['icon' => '🤝', 'label' => 'Parties Coop', 'value' => $totalParties],
        ['icon' => '👹', 'label' => 'Boss vaincus', 'value' => $coopWins],
        ['icon' => '💀', 'label' => 'Défaites Coop', 'value' => $coopLosses],
        ['icon' => '🎯', 'label' => 'Réussite Coop', 'value' => $coopSuccessRate . '%'],
    ];

    $records = [
        ['icon' => '⚡', 'title' => 'Victoire Coop la plus rapide', 'value' => $coopFastestWinParty ? coopTurnsUsed($coopFastestWinParty) . ' tour(s)' : '—', 'party' => $coopFastestWinParty],
        ['icon' => '❤️', 'title' => 'Victoire avec le plus de marge', 'value' => $coopBestRemainingParty ? coopTurnsRemaining($coopBestRemainingParty) . ' tour(s) restant(s)' : '—', 'party' => $coopBestRemainingParty],
        ['icon' => '👹', 'title' => 'Boss le plus exigeant joué', 'value' => $coopHighestBossParty ? coopLabel($coopHighestBossParty) . ' · ' . (int)($coopHighestBossParty['coop']['max_turns'] ?? 0) . ' tours max' : '—', 'party' => $coopHighestBossParty],
        ['icon' => '⏱️', 'title' => 'Partie Coop la plus longue', 'value' => $coopLongestParty ? formatDuration($coopLongestParty['duration'] ?? 0) : '—', 'party' => $coopLongestParty],
    ];

    $habits = [
        ['label' => 'Niveau Coop le plus joué', 'value' => $coopTopLevel],
        ['label' => 'Meilleur rang le plus fréquent', 'value' => $coopTopRank],
        ['label' => 'Tours moyens utilisés', 'value' => $coopAvgTurnsUsed],
        ['label' => 'Tours restants moyens en victoire', 'value' => $coopAvgTurnsRemaining],
        ['label' => 'Nombre moyen de joueurs', 'value' => $avgPlayersByParty],
        ['label' => 'Mots trouvés en Coop', 'value' => $totalFoundWords],
    ];
} else {
    $cards = [
        ['icon' => '🎮', 'label' => 'Parties enregistrées', 'value' => $totalParties],
        ['icon' => '👥', 'label' => 'Joueurs uniques', 'value' => count($uniquePlayers)],
        ['icon' => '🧠', 'label' => 'Mots trouvés', 'value' => $totalFoundWords],
        ['icon' => '⏱️', 'label' => 'Temps de jeu total', 'value' => formatDuration($totalDuration)],
    ];

    $records = [
        ['icon' => '🏅', 'title' => 'Meilleur score d’équipe', 'value' => $bestTeam['score'] ? $bestTeam['name'] . ' · ' . $bestTeam['score'] . ' pts' : '—', 'party' => $bestTeamParty],
        ['icon' => '🔥', 'title' => 'Plus gros total de partie', 'value' => $bestTotalParty ? totalScore($bestTotalParty) . ' pts' : '—', 'party' => $bestTotalParty],
        ['icon' => '⚔️', 'title' => 'Partie la plus serrée', 'value' => $tightestParty ? scoreGap($tightestParty) . ' pt(s) d’écart' : '—', 'party' => $tightestParty],
        ['icon' => '🚀', 'title' => 'Plus grosse victoire', 'value' => $biggestWinParty ? scoreGap($biggestWinParty) . ' pt(s) d’écart' : '—', 'party' => $biggestWinParty],
    ];

    $habits = [
        ['label' => 'Score moyen par équipe', 'value' => $avgScoreByTeam . ' pts'],
        ['label' => 'Équipe la plus victorieuse', 'value' => $topWinnerTeam],
        ['label' => 'Équipe la plus jouée', 'value' => $mostPlayedTeam],
        ['label' => 'Nombre moyen de joueurs', 'value' => $avgPlayersByParty],
        ['label' => 'Thème le plus joué', 'value' => $topTheme],
        ['label' => 'Difficulté la plus choisie', 'value' => $topDifficulty],
    ];
}

$coopCards = [
    ['icon' => '🤝', 'label' => 'Parties Coop', 'value' => $coopTotal],
    ['icon' => '👹', 'label' => 'Boss vaincus', 'value' => $coopWins],
    ['icon' => '💀', 'label' => 'Boss perdus', 'value' => $coopLosses],
    ['icon' => '🎯', 'label' => 'Réussite Coop', 'value' => $coopSuccessRate . '%'],
];
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Statistiques Chrono Party</title>
<meta name="description" content="Découvrez les statistiques globales Chrono Party : parties enregistrées, joueurs, mots trouvés, records, thèmes et performances.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root{
  --bg1:#130f2f;
  --bg2:#07111f;
  --card:rgba(255,255,255,.08);
  --line:rgba(255,255,255,.14);
  --muted:rgba(255,255,255,.72);
  --yellow:#ffd84d;
  --cyan:#22d3ee;
  --purple:#8b5cf6;
}
*{box-sizing:border-box}
body{
  margin:0;
  min-height:100vh;
  font-family:Arial, Helvetica, sans-serif;
  color:white;
  background:
    radial-gradient(circle at top left, rgba(139,92,246,.35), transparent 35%),
    radial-gradient(circle at top right, rgba(34,211,238,.22), transparent 35%),
    linear-gradient(160deg,var(--bg1),var(--bg2));
  padding:18px;
}
.container{max-width:1120px;margin:0 auto}
.header{text-align:center;padding:26px 10px 20px}
.logo{
  width:76px;height:76px;border-radius:24px;margin:0 auto 14px;
  display:flex;align-items:center;justify-content:center;font-size:38px;
  background:linear-gradient(135deg,var(--purple),var(--cyan));
  box-shadow:0 18px 45px rgba(0,0,0,.35)
}
h1{margin:0;font-size:clamp(30px,6vw,52px);letter-spacing:-1px}
.subtitle{margin:12px auto 0;max-width:760px;color:var(--muted);line-height:1.5}
.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:900;font-size:14px
}
.tab.active{
  background:linear-gradient(135deg,var(--purple),var(--cyan));
  border-color:transparent;box-shadow:0 10px 25px rgba(0,0,0,.28)
}
.grid4{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin:0 0 18px}
.statCard{
  background:var(--card);border:1px solid var(--line);border-radius:24px;
  padding:18px;box-shadow:0 18px 50px rgba(0,0,0,.22)
}
.statIcon{font-size:30px;margin-bottom:10px}
.statValue{font-size:30px;font-weight:1000;color:var(--yellow);line-height:1}
.statLabel{color:var(--muted);font-weight:800;margin-top:8px;font-size:14px}
.sectionTitle{font-size:26px;font-weight:1000;margin:28px 0 14px}
.records{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}
.record{
  background:var(--card);border:1px solid var(--line);border-radius:26px;
  padding:20px;box-shadow:0 18px 50px rgba(0,0,0,.22)
}
.record:first-child{background:linear-gradient(135deg,rgba(255,216,77,.18),rgba(139,92,246,.18))}
.recordIcon{font-size:34px;margin-bottom:10px}
.recordTitle{font-size:20px;font-weight:1000;margin-bottom:8px}
.recordValue{
  display:inline-block;padding:8px 12px;border-radius:999px;
  background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.14);
  color:var(--yellow);font-weight:1000;margin-bottom:12px
}
.recordMeta{color:rgba(255,255,255,.78);line-height:1.6;font-size:14px}
.recordMeta a{color:#a5f3fc;text-decoration:none;font-weight:1000;border-bottom:1px dashed rgba(165,243,252,.75)}
.habits{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
.habit{background:rgba(255,255,255,.07);border:1px solid var(--line);border-radius:20px;padding:15px}
.habitLabel{color:var(--muted);font-size:13px;font-weight:900}
.habitValue{margin-top:6px;font-size:18px;font-weight:1000}
.latest{
  background:var(--card);border:1px solid var(--line);border-radius:26px;
  padding:20px;box-shadow:0 18px 50px rgba(0,0,0,.22)
}
.latestTop{display:flex;justify-content:space-between;gap:14px;align-items:center}
.btn{
  display:inline-block;color:white;text-decoration:none;padding:11px 15px;
  border-radius:999px;font-weight:1000;
  background:linear-gradient(135deg,var(--purple),var(--cyan));
  white-space:nowrap;border:0;cursor:pointer;font-size:15px
}
.empty{
  text-align:center;padding:30px;color:var(--muted);
  background:var(--card);border:1px solid var(--line);border-radius:24px
}

.profileBox{
  margin:22px 0 14px;
  text-align:center;
  background:linear-gradient(135deg,rgba(139,92,246,.20),rgba(34,211,238,.13));
  border:1px solid var(--line);
  border-radius:26px;
  padding:20px;
}

.profileBox p{
  margin:0 0 14px;
  color:var(--muted);
  line-height:1.5;
}

.bottomActions{
  position:sticky;
  bottom:10px;
  z-index:20;
  margin:24px 0 8px;
  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,var(--purple),var(--cyan));
  border-color:transparent;
}

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

.quickLinks{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
  justify-content:center;
  margin:16px 0 4px;
}

.quickLinks a{
  color:white;
  text-decoration:none;
  font-weight:900;
  font-size:13px;
  padding:10px 12px;
  border-radius:999px;
  background:rgba(255,255,255,.08);
  border:1px solid var(--line);
}

.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;
  box-shadow:0 24px 70px rgba(0,0,0,.45);
}

.profileModalBox h2{
  margin:0 0 8px;
  font-size:24px;
}

.profileModalBox p{
  margin:0 0 14px;
  color:var(--muted);
}

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

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

@media(max-width:900px){
  .grid4{grid-template-columns:repeat(2,1fr)}
  .habits{grid-template-columns:repeat(2,1fr)}
}

@media(max-width:640px){
  body{padding:12px}
  .grid4,.records,.habits{grid-template-columns:1fr}
  .latestTop{display:block}
  .latestTop .btn{margin-top:14px}

  .bottomActions{
    bottom:8px;
    border-radius:22px;
  }

  .bottomActionsGrid{
    grid-template-columns:1fr 1fr;
  }

  .bottomBtn{
    min-height:44px;
    font-size:14px;
  }
}


/* Filtre rapide */
.quickFilterBox{
  margin:18px 0 22px;
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.14);
  border-radius:18px;
  padding:14px;
}
.quickFilterBox input{
  width:100%;
  box-sizing:border-box;
  border:1px solid rgba(255,255,255,.22);
  border-radius:14px;
  padding:13px 14px;
  background:rgba(255,255,255,.10);
  color:white;
  font-weight:900;
  outline:none;
}
.quickFilterBox input::placeholder{color:rgba(255,255,255,.60)}
.quickFilterCounter{
  margin-top:8px;
  font-size:13px;
  color:rgba(255,255,255,.72);
  font-weight:800;
}


</style>
</head>
<body>
<div class="container">
<header class="header">
  <div class="logo">📊</div>
  <h1>Statistiques Chrono Party</h1>
  <p class="subtitle">Vue <?= h($modeLabel) ?> des parties enregistrées : joueurs, mots trouvés, records, équipes, thèmes et performances globales.</p>
</header>

<nav class="tabs" aria-label="Navigation statistiques Chrono Party">
  <a class="tab active" href="/statistiques/">📊 Statistiques</a>
  <a class="tab" href="/classement-joueurs/">🏆 Classement joueurs</a>
  <a class="tab" href="/top-equipes/">👥 Top équipes</a>
  <a class="tab" href="/parties-memorables/">⭐ Parties mémorables</a>
</nav>

<?php if ($totalParties <= 0): ?>
  <div class="empty">Aucune partie enregistrée pour le moment.</div>
<?php else: ?>

<section class="grid4">
  <?php foreach ($cards as $card): ?>
    <article class="statCard">
      <div class="statIcon"><?= h($card['icon']) ?></div>
      <div class="statValue"><?= h($card['value']) ?></div>
      <div class="statLabel"><?= h($card['label']) ?></div>
    </article>
  <?php endforeach; ?>
</section>

<?php if ($mode === 'all' && $coopTotal > 0): ?>
<div class="sectionTitle">🤝 Statistiques Coop</div>
<section class="grid4">
  <?php foreach ($coopCards as $card): ?>
    <article class="statCard">
      <div class="statIcon"><?= h($card['icon']) ?></div>
      <div class="statValue"><?= h($card['value']) ?></div>
      <div class="statLabel"><?= h($card['label']) ?></div>
    </article>
  <?php endforeach; ?>
</section>
<?php endif; ?>

<div class="sectionTitle"><?= $mode === 'coop' ? '🤝 Records Coop' : '🏆 Records globaux' ?></div>
<section class="records">
  <?php foreach ($records as $record): ?>
    <article class="record">
      <div class="recordIcon"><?= h($record['icon']) ?></div>
      <div class="recordTitle"><?= h($record['title']) ?></div>
      <div class="recordValue"><?= h($record['value']) ?></div>
      <?php if (!empty($record['party'])): ?>
        <div class="recordMeta">
          Partie du <strong><?= h(shortDate($record['party']['created_at'] ?? '')) ?></strong><br>
          Gagnant : <strong><?= h($record['party']['winner'] ?? '—') ?></strong><br>
          <a href="<?= h(partyUrl($record['party'])) ?>">Voir le détail</a>
        </div>
      <?php endif; ?>
    </article>
  <?php endforeach; ?>
</section>

<div class="sectionTitle">🎭 Habitudes de jeu</div>
<section class="habits">
  <?php foreach ($habits as $habit): ?>
    <article class="habit">
      <div class="habitLabel"><?= h($habit['label']) ?></div>
      <div class="habitValue"><?= h($habit['value']) ?></div>
    </article>
  <?php endforeach; ?>
</section>

<?php if ($latestParty): ?>
<div class="sectionTitle">🆕 Dernière partie enregistrée</div>
<section class="latest">
  <div class="latestTop">
    <div>
      <strong><?= h(shortDate($latestParty['created_at'] ?? '')) ?></strong><br>
      <?= h((string)($latestParty['players_count'] ?? '—')) ?> joueurs · <?= isCoopParty($latestParty) ? 'mode Coop' : h((string)($latestParty['teams_count'] ?? '—')) . ' équipes' ?> · gagnant : <strong><?= h($latestParty['winner'] ?? '—') ?></strong>
    </div>
    <a class="btn" href="<?= h(partyUrl($latestParty)) ?>">Voir la partie</a>
  </div>
</section>
<?php endif; ?>

<?php endif; ?>


<div class="bottomActions">
  <div class="bottomActionsGrid">
    <button type="button" class="bottomBtn primary" onclick="openMyPlayerProfile()">👤 Mon profil</button>
    <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/';
}

async 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');

  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');

  setTimeout(function(){
    const input = document.getElementById('profileFirstName');
    if(input) input.focus();
  }, 100);
}

async function confirmMyPlayerProfile(){

  const nameInput = document.getElementById('profileFirstName');
  const initialsInput = document.getElementById('profileInitials');

  const name = nameInput ? nameInput.value.trim() : '';
  const initials = initialsInput ? initialsInput.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;
    }

    const displayName = ((data.player.name || name) + ' ' + (data.player.initials || initials)).trim();

    localStorage.setItem('chrono_personal_player_id', data.player.id);
    localStorage.setItem('chrono_personal_player_name', displayName);

    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');
  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 normalizeText(value){
    return (value || '').toString().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
  }

  function setupQuickFilter(){
    const input = document.getElementById('quickPageFilter');
    if(!input) return;
    const counter = document.getElementById('quickPageFilterCounter');
    const selector = input.dataset.filterSelector || '.recordCard,.record,.habit,.statCard,.latest';
    const items = Array.from(document.querySelectorAll(selector));

    const datalist = document.createElement('datalist');
    const listId = 'quick-page-filter-suggestions';
    const values = new Set();

    items.forEach(function(item){
      const title = item.querySelector('h1,h2,h3,h4,strong,.title,.recordTitle,.statTitle');
      const text = (item.textContent || '').replace(/\s+/g, ' ').trim();
      if(title && title.textContent.trim()) values.add(title.textContent.replace(/\s+/g, ' ').trim());

      text.split(/\s*[|•·—–-]\s*/).forEach(function(part){
        part = part.replace(/\s+/g, ' ').trim();
        if(part.length >= 3 && part.length <= 70) values.add(part);
      });
    });

    Array.from(values)
      .filter(function(value){ return value.length <= 90; })
      .sort(function(a,b){ return a.localeCompare(b, 'fr', {numeric:true, sensitivity:'base'}); })
      .slice(0, 120)
      .forEach(function(value){
        const option = document.createElement('option');
        option.value = value;
        datalist.appendChild(option);
      });

    datalist.id = listId;
    input.setAttribute('list', listId);
    input.parentNode.insertBefore(datalist, input.nextSibling);

    let resetBtn = document.getElementById('quickPageFilterReset');
    if(!resetBtn){
      resetBtn = document.createElement('button');
      resetBtn.id = 'quickPageFilterReset';
      resetBtn.type = 'button';
      resetBtn.textContent = 'Reset';
      resetBtn.style.marginLeft = '8px';
      resetBtn.style.padding = '11px 14px';
      resetBtn.style.border = '0';
      resetBtn.style.borderRadius = '12px';
      resetBtn.style.background = '#7c5cff';
      resetBtn.style.color = 'white';
      resetBtn.style.fontWeight = '900';
      resetBtn.style.cursor = 'pointer';
      input.parentNode.insertBefore(resetBtn, datalist.nextSibling);
    }

    function apply(){
      const q = normalizeText(input.value);
      let visible = 0;
      items.forEach(function(item){
        const ok = !q || normalizeText(item.textContent).includes(q);
        item.style.display = ok ? '' : 'none';
        if(ok) visible++;
      });
      if(counter) counter.textContent = visible + ' élément(s) affiché(s)';
    }

    input.addEventListener('input', apply);
    input.addEventListener('change', apply);
    resetBtn.addEventListener('click', function(){
      input.value = '';
      apply();
      input.focus();
    });
    apply();
  }

  if(document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded', setupQuickFilter);
  }else{
    setupQuickFilter();
  }
})();
</script>

</body>
</html>