<?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 formatDuration($seconds): string {
    $seconds = max(0, (int)$seconds);
    $min = floor($seconds / 60);
    $sec = $seconds % 60;
    return $min . ' min ' . str_pad((string)$sec, 2, '0', STR_PAD_LEFT) . ' s';
}

function difficultyName(string $difficulty): string {
    $difficulty = mb_strtolower(trim($difficulty));

    return match ($difficulty) {
        'facile', 'easy' => 'Facile',
        'moyen', 'medium' => 'Moyen',
        'difficile', 'hard' => 'Difficile',
        default => $difficulty !== '' ? ucfirst($difficulty) : '',
    };
}

function difficultiesLabel(array $party): string {
    $difficulties = $party['difficulties'] ?? [];

    if (!is_array($difficulties) || empty($difficulties)) {
        return 'Non enregistrée';
    }

    $labels = [];

    foreach ($difficulties as $difficulty) {
        $label = difficultyName((string)$difficulty);
        if ($label !== '') {
            $labels[] = $label;
        }
    }

    $labels = array_values(array_unique($labels));

    return empty($labels) ? 'Non enregistrée' : implode(' + ', $labels);
}


function difficultiesBadgeKey(array $party): string {
    $difficulties = $party['difficulties'] ?? [];

    if (!is_array($difficulties) || empty($difficulties)) {
        return 'Non enregistrée';
    }

    $order = [
        'facile' => 1,
        'easy' => 1,
        'moyen' => 2,
        'medium' => 2,
        'difficile' => 3,
        'hard' => 3,
    ];

    $labels = [];

    foreach ($difficulties as $difficulty) {
        $key = mb_strtolower(trim((string)$difficulty));

        if (isset($order[$key])) {
            $labels[$order[$key]] = difficultyName($key);
        }
    }

    ksort($labels);

    return empty($labels) ? 'Non enregistrée' : implode(' + ', array_values($labels));
}

function coopBossMeta(string $level): array {
    return match ($level) {
        'easy' => ['icon' => '🥉', 'label' => 'Petit Boss', 'badge' => 'Vainqueur du Petit Boss'],
        'standard' => ['icon' => '🥈', 'label' => 'Boss Chrono', 'badge' => 'Vainqueur du Boss Chrono'],
        'hard' => ['icon' => '🥇', 'label' => 'Grand Boss', 'badge' => 'Vainqueur du Grand Boss'],
        'legend' => ['icon' => '👑', 'label' => 'Boss Légende', 'badge' => 'Vainqueur du Boss Légende'],
        default => ['icon' => '👹', 'label' => 'Boss', 'badge' => 'Vainqueur du Boss'],
    };
}

function isCoopVictory(array $party): bool {
    return (($party['game_mode'] ?? '') === 'coop')
        && is_array($party['coop'] ?? null)
        && !empty($party['coop']['won']);
}

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 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 normalizeName(string $name): string {
    $name = mb_strtolower(trim($name));
    $name = preg_replace('/\s+/', ' ', $name);
    return $name ?? '';
}

$parties = readJson($partiesFile, []);
$profiles = readJson($profilesFile, []);
$profileAvatarIndex = buildProfileAvatarIndex($profiles);
$id = trim((string)($_GET['id'] ?? ''));

$player = null;
$playerParties = [];
$badges = [];
$themesStats = [];
$difficultyStats = [];
$coopBossWinsByDifficulty = [];
$coopBossWins = [
    'easy' => 0,
    'standard' => 0,
    'hard' => 0,
    'legend' => 0,
];

$games = 0;
$classicGames = 0;
$wins = 0;
$total = 0;
$totalFoundWords = 0;
$totalPassedWords = 0;
$totalTurns = 0;
$bestTurn = 0;
$bestPartyScore = 0;
$playerName = '';

foreach ($parties as $party) {

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

    // IMPORTANT : les parties exclues dans l'admin ne comptent plus nulle part.
$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.
// Une partie publiée/validée par l’admin doit compter dans le profil joueur, comme dans le classement.
if (!empty($party['suspicious']) && $partyStatus !== 'validated' && $partyStatus !== 'published') {
    continue;
}

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

    $playerWasInParty = false;
    $teamNameFound = '';
    $teamScoreFound = 0;
    $isWinner = false;
    $partyPlayerName = '';

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

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

        foreach (($team['players'] ?? []) as $teamPlayer) {
            $teamPlayerId = getPlayerId($teamPlayer);
            $teamPlayerName = getPlayerName($teamPlayer);

            if ($id !== '' && $teamPlayerId === $id) {
                $playerWasInParty = true;
                $partyPlayerName = $teamPlayerName;
                $teamNameFound = $teamName;
                $teamScoreFound = $teamScore;
                $isWinner = ($winnerName !== '' && $teamName === $winnerName);
                break 2;
            }
        }
    }

    if (!$playerWasInParty) {
        continue;
    }

    if ($playerName === '' && $partyPlayerName !== '') {
        $playerName = $partyPlayerName;
    }

    $games++;

if (($party['game_mode'] ?? 'classic') !== 'coop') {
    $classicGames++;
}
    $total += $teamScoreFound;
    $bestPartyScore = max($bestPartyScore, $teamScoreFound);

if (($party['game_mode'] ?? 'classic') !== 'coop' && $isWinner) {
    $wins++;
}

    if (isCoopVictory($party)) {
        $bossLevel = (string)($party['coop']['level'] ?? '');

        if (array_key_exists($bossLevel, $coopBossWins)) {
            $coopBossWins[$bossLevel]++;

            $difficultyKey = difficultiesBadgeKey($party);

            if (!isset($coopBossWinsByDifficulty[$bossLevel])) {
                $coopBossWinsByDifficulty[$bossLevel] = [];
            }

            $coopBossWinsByDifficulty[$bossLevel][$difficultyKey] =
                ($coopBossWinsByDifficulty[$bossLevel][$difficultyKey] ?? 0) + 1;
        }
    }

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

    $difficultyLabel = difficultiesLabel($party);

    if ($difficultyLabel !== 'Non enregistrée') {
        $difficultyStats[$difficultyLabel] = ($difficultyStats[$difficultyLabel] ?? 0) + 1;
    }

    $partyFound = 0;
    $partyPassed = 0;
    $partyTurns = 0;

    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 ($playerName !== '' && normalizeName($turnPlayerName) === normalizeName($playerName)) {
                $foundCount = (int)($turn['foundCount'] ?? count($turn['found'] ?? []));
                $passedCount = is_array($turn['passed'] ?? null) ? count($turn['passed']) : 0;

                $partyFound += $foundCount;
                $partyPassed += $passedCount;
                $partyTurns++;
                $bestTurn = max($bestTurn, $foundCount);
            }
        }
    }

    $totalFoundWords += $partyFound;
    $totalPassedWords += $partyPassed;
    $totalTurns += $partyTurns;

    $playerParties[] = [
        'party_id' => (string)($party['id'] ?? ''),
        'created_at' => $createdAt,
        'team_name' => $teamNameFound,
        'team_score' => $teamScoreFound,
        'is_winner' => $isWinner,
        'rounds_played' => (int)($party['rounds_played'] ?? 0),
        'difficulty' => $difficultyLabel,
        'players_count' => (int)($party['players_count'] ?? 0),
        'duration' => (int)($party['duration'] ?? 0),
        'found_words' => $partyFound,
        'passed_words' => $partyPassed,
        'turns' => $partyTurns,
        'game_mode' => (string)($party['game_mode'] ?? 'classic'),
        'coop' => is_array($party['coop'] ?? null) ? $party['coop'] : null,
    ];
}

if ($games > 0) {
    $player = [
        'id' => $id,
        'name' => $playerName !== '' ? $playerName : 'Joueur',
    ];

    arsort($themesStats);
    arsort($difficultyStats);

    usort($playerParties, function($a, $b) {
        return strcmp((string)($b['created_at'] ?? ''), (string)($a['created_at'] ?? ''));
    });

    $playerParties = array_slice($playerParties, 0, 20);
}

if (!$player) {
    http_response_code(404);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Fiche joueur - 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);--muted:rgba(255,255,255,.72)}
*{box-sizing:border-box}
body{margin:0;min-height:100vh;font-family:Arial,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,.24),transparent 35%),linear-gradient(160deg,var(--bg1),var(--bg2));padding:18px;padding-bottom:110px}
.container{max-width:980px;margin:0 auto}
.card{background:var(--card);border:1px solid var(--line);border-radius:28px;padding:24px;box-shadow:0 20px 60px rgba(0,0,0,.3);margin:24px 0}
.avatar{width:82px;height:82px;margin:0 auto 14px;border-radius:26px;display:flex;align-items:center;justify-content:center;font-size:40px;background:linear-gradient(135deg,#8b5cf6,#22d3ee)}
h1{text-align:center;margin:0 0 8px;font-size:34px}
.subtitle{text-align:center;color:var(--muted);margin-bottom:24px}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
.stat{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.12);border-radius:18px;padding:16px;text-align:center}
.stat strong{display:block;font-size:28px}
.stat span{color:var(--muted);font-size:13px}
.sectionTitle{font-size:24px;margin:0 0 14px;font-weight:1000}
.badgesGrid,.themesGrid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
.badgeItem,.themeItem{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px;border-radius:18px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.12)}
.badgeItem span{font-size:28px}
.partyList{display:grid;gap:12px}
.partyCard{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.12);border-radius:20px;padding:14px}
.partyTop{display:flex;justify-content:space-between;gap:12px;align-items:center;margin-bottom:10px}
.partyDate{font-weight:1000}
.badge{display:inline-block;padding:7px 10px;border-radius:999px;font-size:13px;font-weight:1000}
.win{background:rgba(34,197,94,.22);border:1px solid rgba(34,197,94,.45)}
.loss{background:rgba(239,68,68,.18);border:1px solid rgba(239,68,68,.38)}
.partyDetails{color:var(--muted);line-height:1.6;font-size:14px}
.actions{text-align:center;margin:22px 0}
a{color:white;text-decoration:none;font-weight:900}
.buttonLink{display:inline-block;padding:11px 16px;border-radius:999px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.14)}
.partyLink{display:inline-block;margin-top:8px;color:#a5f3fc}
.empty{color:var(--muted);padding:16px;border-radius:18px;background:rgba(255,255,255,.06)}

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


.badgesHelp{
  margin-top:14px;
  padding:14px 16px;
  border-radius:18px;
  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.08);
  color:rgba(255,255,255,.82);
  font-size:13px;
  line-height:1.7;
}
@media(max-width:800px){
  body{padding:12px;padding-bottom:110px}
  .card{margin:14px 0;padding:18px}
  .grid{grid-template-columns:repeat(2,1fr)}
  .badgesGrid,.themesGrid{grid-template-columns:1fr}
  .partyTop{align-items:flex-start;flex-direction:column}
}
</style>
</head>

<body>
<div class="container">

<div class="card">

<?php if (!$player): ?>

  <div class="avatar">❓</div>
  <h1>Joueur introuvable</h1>
  <p class="subtitle">Ce joueur n’existe pas, ou toutes ses parties ont été exclues.</p>

<?php else: ?>

<?php
$losses = max(0, $classicGames - $wins);
$avg = $games > 0 ? round($total / $games, 1) : 0;
$winrate = $classicGames > 0 ? round(($wins / $classicGames) * 100) : 0;
$avgFoundPerTurn = $totalTurns > 0 ? round($totalFoundWords / $totalTurns, 1) : 0;

if ($wins >= 3) $badges[] = ['icon'=>'🏆','label'=>'Gagnant régulier'];
if ($total >= 200) $badges[] = ['icon'=>'🔥','label'=>'Gros scoreur'];
if ($games >= 5) $badges[] = ['icon'=>'⚡','label'=>'Joueur actif'];
if ($winrate >= 60 && $games >= 3) $badges[] = ['icon'=>'🎯','label'=>'Compétiteur redoutable'];
if ($totalFoundWords >= 50) $badges[] = ['icon'=>'🧠','label'=>'Machine à mots'];
if ($bestTurn >= 10) $badges[] = ['icon'=>'🚀','label'=>'Tour explosif'];
if ($totalPassedWords >= 20) $badges[] = ['icon'=>'⏭️','label'=>'Expert du pass'];

foreach ($coopBossWinsByDifficulty as $bossLevel => $difficultyWins) {
    $boss = coopBossMeta((string)$bossLevel);

    foreach ($difficultyWins as $difficultyLabel => $count) {
        $badges[] = [
            'icon' => $boss['icon'],
            'label' => $boss['badge'] . ' — niveau ' . $difficultyLabel,
        ];
    }
}

?>

<div class="avatar"><?= h(profileAvatar($player ?? [], $profileAvatarIndex)) ?></div>
  <h1><?= h($player['name'] ?? 'Joueur') ?></h1>
  <p class="subtitle">Fiche joueur Chrono Party</p>

  <div class="grid">
    <div class="stat"><strong><?= h($games) ?></strong><span>Parties jouées</span></div>
    <div class="stat"><strong><?= h($wins) ?></strong><span>Victoires</span></div>
    <div class="stat"><strong><?= h($losses) ?></strong><span>Défaites</span></div>
    <div class="stat"><strong><?= h($winrate) ?>%</strong><span>Taux de victoire</span></div>
    <div class="stat"><strong><?= h($total) ?></strong><span>Score total</span></div>
    <div class="stat"><strong><?= h($avg) ?></strong><span>Moyenne score</span></div>
    <div class="stat"><strong><?= h($totalFoundWords) ?></strong><span>Mots trouvés</span></div>
    <div class="stat"><strong><?= h($bestTurn) ?></strong><span>Meilleur tour</span></div>
  </div>

<?php endif; ?>

</div>

<?php if ($player): ?>

<div class="card">
  <h2 class="sectionTitle">👹 Boss vaincus</h2>
  <div class="themesGrid">
    <?php foreach($coopBossWins as $bossLevel => $bossWinCount): ?>
      <?php $boss = coopBossMeta((string)$bossLevel); ?>
      <div class="themeItem">
        <strong><?= h($boss['icon'] . ' ' . $boss['label']) ?></strong>
        <span><?= h($bossWinCount) ?> victoire(s)</span>
      </div>
    <?php endforeach; ?>
  </div>

  <?php if (!empty($coopBossWinsByDifficulty)): ?>
    <div class="badgesHelp">
      <strong>Détail par niveau de mots :</strong><br>
      <?php foreach($coopBossWinsByDifficulty as $bossLevel => $difficultyWins): ?>
        <?php $boss = coopBossMeta((string)$bossLevel); ?>
        <?php foreach($difficultyWins as $difficultyLabel => $count): ?>
          <?= h($boss['icon'] . ' ' . $boss['label']) ?> — niveau <?= h($difficultyLabel) ?> : <strong><?= h($count) ?></strong> victoire(s)<br>
        <?php endforeach; ?>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<?php if (!empty($badges)): ?>
<div class="card">
  <h2 class="sectionTitle">🎖 Badges débloqués</h2>
  <div class="badgesGrid">
    <?php foreach($badges as $badge): ?>
      <div class="badgeItem">
        <span><?= h($badge['icon']) ?></span>
        <strong><?= h($badge['label']) ?></strong>
      </div>
    <?php endforeach; ?>
  </div>
  <div class="badgesHelp">
    <strong>Signification des badges :</strong><br>
    🏆 Gagnant régulier : au moins 3 victoires<br>
    🔥 Gros scoreur : 200 points cumulés ou plus<br>
    ⚡ Joueur actif : 5 parties jouées ou plus<br>
    🎯 Compétiteur redoutable : 60% de victoire avec au moins 3 parties<br>
    🧠 Machine à mots : 50 mots trouvés personnels ou plus<br>
    🚀 Tour explosif : 10 mots ou plus sur un seul tour<br>
    ⏭️ Expert du pass : 20 mots passés ou plus<br>
    🥉 🥈 🥇 👑 Boss vaincus : badge séparé selon le Boss et le niveau des mots joué<br>
    Exemple : Grand Boss — niveau Facile + Moyen est différent de Grand Boss — niveau Difficile
  </div>
</div>
<?php endif; ?>

<div class="card">
  <h2 class="sectionTitle">⭐ Thèmes favoris</h2>
  <?php if (empty($themesStats)): ?>
    <div class="empty">Aucun thème trouvé pour ce joueur.</div>
  <?php else: ?>
    <div class="themesGrid">
      <?php foreach(array_slice($themesStats, 0, 6, true) as $theme => $count): ?>
        <div class="themeItem">
          <strong><?= h($theme) ?></strong>
          <span><?= h($count) ?> partie(s)</span>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<div class="card">
  <h2 class="sectionTitle">🎚️ Difficultés jouées</h2>
  <?php if (empty($difficultyStats)): ?>
    <div class="empty">Aucune difficulté enregistrée pour ce joueur.</div>
  <?php else: ?>
    <div class="themesGrid">
      <?php foreach(array_slice($difficultyStats, 0, 6, true) as $difficulty => $count): ?>
        <div class="themeItem">
          <strong><?= h($difficulty) ?></strong>
          <span><?= h($count) ?> partie(s)</span>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<div class="card">
  <h2 class="sectionTitle">🕘 Dernières parties</h2>

  <?php if (empty($playerParties)): ?>
    <div class="empty">Aucune partie détaillée trouvée pour ce joueur.</div>
  <?php else: ?>
    <div class="partyList">
      <?php foreach($playerParties as $party): ?>
        <div class="partyCard">
          <div class="partyTop">
            <div class="partyDate"><?= h($party['created_at']) ?></div>
            <div class="badge <?= $party['is_winner'] ? 'win' : 'loss' ?>">
              <?= $party['is_winner'] ? 'Victoire' : 'Défaite' ?>
            </div>
          </div>

          <div class="partyDetails">
            <?php if (($party['game_mode'] ?? 'classic') === 'coop' && is_array($party['coop'] ?? null)): ?>
              <?php
                $coop = $party['coop'];
                $boss = coopBossMeta((string)($coop['level'] ?? ''));
                $bossWon = !empty($coop['won']);
              ?>
              Mode : <strong>Coop Boss Chrono</strong><br>
              Boss : <strong><?= h($boss['icon'] . ' ' . ($coop['label'] ?? $boss['label'])) ?></strong><br>
              Niveau des mots : <strong><?= h($party['difficulty']) ?></strong><br>
              Résultat : <strong><?= $bossWon ? 'Boss vaincu' : 'Défi perdu' ?></strong><br>
              Tours joueur : <strong><?= h((int)($coop['turns_used'] ?? 0)) ?> / <?= h((int)($coop['max_turns'] ?? 0)) ?></strong><br>
              <?php if ($bossWon): ?>
                Tours restants : <strong><?= h((int)($coop['turns_remaining'] ?? 0)) ?></strong><br>
                Rang : <strong><?= h(($coop['rank_icon'] ?? '') . ' ' . ($coop['rank_label'] ?? '')) ?></strong><br>
              <?php else: ?>
                Dépassement : <strong>+<?= h((int)($coop['over_by'] ?? 0)) ?> tour(s)</strong><br>
              <?php endif; ?>
            <?php else: ?>
              Équipe : <strong><?= h($party['team_name']) ?></strong><br>
              Difficulté : <strong><?= h($party['difficulty']) ?></strong><br>
              Score équipe : <strong><?= h($party['team_score']) ?> pts</strong><br>
            <?php endif; ?>
            Mots trouvés par ce joueur : <strong><?= h($party['found_words']) ?></strong><br>
            Mots passés : <strong><?= h($party['passed_words']) ?></strong><br>
            Manches jouées : <?= h($party['rounds_played']) ?> ·
            Joueurs : <?= h($party['players_count']) ?> ·
            Durée : <?= h(formatDuration($party['duration'])) ?>
          </div>

          <?php if ($party['party_id'] !== ''): ?>
            <a class="partyLink" href="/jeux/partie/?id=<?= urlencode($party['party_id']) ?>" target="_blank">
              Voir la partie →
            </a>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<?php endif; ?>

<div class="bottomActions">
  <div class="bottomActionsGrid">
    <a class="bottomBtn primary" href="/statistiques/">📊 Statistiques</a>
    <a class="bottomBtn danger" href="/jeux/">✕ Fermer</a>
  </div>
</div>

</div>
</body>
</html>