<?php
declare(strict_types=1);

$partiesFile = dirname(__DIR__) . '/privatedata/parties.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;
    if ($min <= 0) return $sec . ' s';
    return $min . ' min ' . str_pad((string)$sec, 2, '0', STR_PAD_LEFT) . ' s';
}

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

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

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

function coopData(array $party): array {
    return is_array($party['coop'] ?? null) ? $party['coop'] : [];
}

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

function coopLevelWeight(array $party): int {
    $coop = coopData($party);
    $level = (string)($coop['level'] ?? '');
    $rank = (string)($coop['rank_key'] ?? '');

    $weights = [
        'easy' => 1,
        'normal' => 2,
        'medium' => 2,
        'hard' => 3,
        'legend' => 4,
    ];

    $rankWeights = [
        'bronze' => 1,
        'silver' => 2,
        'gold' => 3,
        'legend' => 4,
    ];

    return max(
        $weights[$level] ?? 0,
        $rankWeights[$rank] ?? 0
    );
}

function coopBossLabel(array $party): string {
    $coop = coopData($party);
    $icon = trim((string)($coop['icon'] ?? '👹'));
    $label = trim((string)($coop['label'] ?? 'Boss'));
    return trim($icon . ' ' . $label);
}

function coopRankLabel(array $party): string {
    $coop = coopData($party);
    $icon = trim((string)($coop['rank_icon'] ?? ''));
    $label = trim((string)($coop['rank_label'] ?? ''));
    return trim($icon . ' ' . $label) ?: '—';
}

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

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

function bestRound(array $party): int {
    $best = 0;
    foreach (($party['scores'] ?? []) as $score) {
        foreach (($score['perRound'] ?? []) as $points) {
            $best = max($best, (int)$points);
        }
    }
    return $best;
}

function bestTurnWords(array $party): int {
    $best = 0;
    foreach (($party['teams'] ?? []) as $team) {
        foreach (($team['turnStats'] ?? []) as $turn) {
            if (!is_array($turn)) continue;
            $best = max($best, (int)($turn['foundCount'] ?? count($turn['found'] ?? [])));
        }
    }
    return $best;
}

function playersLabel(array $party): string {
    $names = [];
    foreach (($party['teams'] ?? []) as $team) {
        foreach (($team['players'] ?? []) as $player) {
            if (is_array($player)) {
                $name = trim((string)($player['name'] ?? ''));
            } else {
                $name = trim((string)$player);
            }
            if ($name !== '') {
                $names[$name] = true;
            }
        }
    }

    if (!empty($names)) {
        return implode(', ', array_keys($names));
    }

    return (string)($party['players_count'] ?? 0) . ' joueur(s)';
}

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

$parties = readJson($partiesFile, []);
$filteredParties = [];

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

    $isCoop = isCoopParty($party);

    if ($mode === 'classic' && $isCoop) continue;
    if ($mode === 'coop' && !$isCoop) continue;

    $filteredParties[] = $party;
}

$bestTotalParty = null;
$tightestParty = null;
$bestRoundParty = null;
$longestParty = null;
$latestParty = null;

$strongestBossParty = null;
$fastestCoopWinParty = null;
$closestCoopWinParty = null;
$bestCoopPerformanceParty = null;
$latestCoopParty = null;

foreach ($filteredParties as $party) {
    $isCoop = isCoopParty($party);

    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 && (!$tightestParty || $gap < (scoreGap($tightestParty) ?? PHP_INT_MAX))) {
        $tightestParty = $party;
    }

    if (!$bestRoundParty || bestRound($party) > bestRound($bestRoundParty)) {
        $bestRoundParty = $party;
    }

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

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

        if (coopWon($party)) {
            if (
                !$strongestBossParty ||
                coopLevelWeight($party) > coopLevelWeight($strongestBossParty) ||
                (
                    coopLevelWeight($party) === coopLevelWeight($strongestBossParty) &&
                    (int)(coopData($party)['max_turns'] ?? 0) >= (int)(coopData($strongestBossParty)['max_turns'] ?? 0)
                )
            ) {
                $strongestBossParty = $party;
            }

            if (
                !$fastestCoopWinParty ||
                (int)($party['duration'] ?? PHP_INT_MAX) < (int)($fastestCoopWinParty['duration'] ?? PHP_INT_MAX)
            ) {
                $fastestCoopWinParty = $party;
            }

            $remaining = (int)(coopData($party)['turns_remaining'] ?? PHP_INT_MAX);
            $closestRemaining = (int)(coopData($closestCoopWinParty ?? [])['turns_remaining'] ?? PHP_INT_MAX);
            if (!$closestCoopWinParty || $remaining < $closestRemaining) {
                $closestCoopWinParty = $party;
            }

            $bestRemaining = (int)(coopData($bestCoopPerformanceParty ?? [])['turns_remaining'] ?? -1);
            if (!$bestCoopPerformanceParty || $remaining > $bestRemaining) {
                $bestCoopPerformanceParty = $party;
            }
        }
    }
}

if ($mode === 'coop') {
    $records = [
        [
            'icon' => '👹',
            'title' => 'Boss le plus puissant vaincu',
            'party' => $strongestBossParty,
            'value' => $strongestBossParty ? coopBossLabel($strongestBossParty) : '—',
            'desc' => 'Le boss le plus difficile battu en mode Coop.'
        ],
        [
            'icon' => '⚡',
            'title' => 'Victoire Coop la plus rapide',
            'party' => $fastestCoopWinParty,
            'value' => $fastestCoopWinParty ? formatDuration($fastestCoopWinParty['duration'] ?? 0) : '—',
            'desc' => 'La victoire la plus rapide contre le boss.'
        ],
        [
            'icon' => '❤️',
            'title' => 'Victoire la plus serrée',
            'party' => $closestCoopWinParty,
            'value' => $closestCoopWinParty ? ((int)(coopData($closestCoopWinParty)['turns_remaining'] ?? 0) . ' tour(s) restant(s)') : '—',
            'desc' => 'Le boss a été vaincu de justesse.'
        ],
        [
            'icon' => '🏆',
            'title' => 'Meilleure performance Coop',
            'party' => $bestCoopPerformanceParty,
            'value' => $bestCoopPerformanceParty ? ((int)(coopData($bestCoopPerformanceParty)['turns_remaining'] ?? 0) . ' tour(s) restant(s)') : '—',
            'desc' => 'La victoire avec la plus grande marge contre le boss.'
        ],
        [
            'icon' => '🆕',
            'title' => 'Dernière partie Coop',
            'party' => $latestCoopParty,
            'value' => $latestCoopParty ? shortDate($latestCoopParty['created_at'] ?? '') : '—',
            'desc' => 'La dernière partie Coop enregistrée.'
        ],
    ];
} else {
    $records = [
        [
            'icon' => '🔥',
            'title' => 'Plus gros score total',
            'party' => $bestTotalParty,
            'value' => $bestTotalParty ? totalScore($bestTotalParty) . ' points' : '—',
            'desc' => 'La partie où les équipes ont marqué le plus de points.'
        ],
        [
            'icon' => '⚔️',
            'title' => 'Partie la plus serrée',
            'party' => $tightestParty,
            'value' => $tightestParty ? scoreGap($tightestParty) . ' point(s) d’écart' : '—',
            'desc' => 'Le duel le plus tendu enregistré.'
        ],
        [
            'icon' => '🚀',
            'title' => 'Meilleur tour',
            'party' => $bestRoundParty,
            'value' => $bestRoundParty ? bestRound($bestRoundParty) . ' points' : '—',
            'desc' => 'Le meilleur score réalisé sur une manche.'
        ],
        [
            'icon' => '⏱️',
            'title' => 'Partie la plus longue',
            'party' => $longestParty,
            'value' => $longestParty ? formatDuration($longestParty['duration'] ?? 0) : '—',
            'desc' => 'La soirée Chrono Party la plus longue.'
        ],
        [
            'icon' => '🆕',
            'title' => 'Dernière partie jouée',
            'party' => $latestParty,
            'value' => $latestParty ? shortDate($latestParty['created_at'] ?? '') : '—',
            'desc' => 'La partie la plus récente enregistrée.'
        ],
    ];
}

$pageSubtitle = 'Les records et moments forts des soirées Chrono Party : gros scores, duels serrés, meilleurs tours et dernières parties.';
if ($mode === 'classic') {
    $pageSubtitle = 'Records des parties classiques uniquement, sans mélanger les parties Coop.';
}
if ($mode === 'coop') {
    $pageSubtitle = 'Records du mode Coop : boss vaincus, victoires rapides et performances collectives.';
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Parties mémorables Chrono Party</title>
<meta name="description" content="Découvrez les parties Chrono Party les plus mémorables : meilleurs scores, parties serrées, meilleur tour, records Coop et records de soirée.">
<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;
  padding-bottom:110px;
}

.container{
  max-width:1100px;
  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:720px;
  color:var(--muted);
  line-height:1.5;
}

.tabs{
  display:flex;
  gap:10px;
  justify-content:center;
  flex-wrap:wrap;
  margin:0 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:1000;
  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);
}

.records{
  display:grid;
  grid-template-columns:repeat(2,1fr);
  gap:16px;
}

.recordCard{
  position:relative;
  overflow:hidden;
  min-height:230px;
  padding:22px;
  border-radius:28px;
  background:var(--card);
  border:1px solid var(--line);
  box-shadow:0 18px 50px rgba(0,0,0,.25);
}

.recordCard:first-child{
  grid-column:span 2;
  background:linear-gradient(135deg,rgba(255,216,77,.18),rgba(139,92,246,.18));
}

.recordIcon{
  font-size:42px;
  margin-bottom:12px;
}

.recordTitle{
  font-size:26px;
  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;
}

.recordDesc{
  color:var(--muted);
  line-height:1.5;
  margin-bottom:14px;
}

.partyMeta{
  color:rgba(255,255,255,.82);
  line-height:1.7;
  font-size:14px;
}

.partyMeta strong{
  color:white;
}

.coopPill{
  display:inline-block;
  margin-bottom:8px;
  padding:6px 10px;
  border-radius:999px;
  background:rgba(34,211,238,.12);
  border:1px solid rgba(34,211,238,.25);
  color:#a5f3fc;
  font-weight:1000;
  font-size:12px;
}

.actions{
  margin-top:16px;
}

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

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

.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,var(--purple),var(--cyan));
  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;
  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:760px){
  body{padding:12px;padding-bottom:110px}
  .records{grid-template-columns:1fr}
  .recordCard:first-child{grid-column:auto}
  .tab{
    flex:1;
    text-align:center;
    min-width:110px;
    padding:10px 8px;
    font-size:13px;
  }
  .bottomActions{
    bottom:8px;
    border-radius:22px;
  }
  .bottomActionsGrid{
    grid-template-columns:1fr 1fr;
  }
  .bottomBtn{
    min-height:44px;
    font-size:14px;
  }
}

</style>
</head>

<body>
<div class="container">

<header class="header">
  <div class="logo">🌟</div>
  <h1>Parties mémorables</h1>
  <p class="subtitle">
    <?= h($pageSubtitle) ?>
  </p>
</header>

<nav class="tabs">
  <a class="tab <?= $mode === 'all' ? 'active' : '' ?>" href="?mode=all">🏆 Tous</a>
  <a class="tab <?= $mode === 'classic' ? 'active' : '' ?>" href="?mode=classic">⚔️ Classique</a>
  <a class="tab <?= $mode === 'coop' ? 'active' : '' ?>" href="?mode=coop">🤝 Coop</a>
</nav>


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

  <div class="empty">
    Aucune partie enregistrée pour ce filtre.
  </div>

<?php else: ?>

  <section class="records">
    <?php foreach ($records as $record): ?>
      <?php $party = $record['party']; ?>

      <article class="recordCard">
        <div class="recordIcon"><?= h($record['icon']) ?></div>
        <div class="recordTitle"><?= h($record['title']) ?></div>
        <div class="recordValue"><?= h($record['value']) ?></div>
        <div class="recordDesc"><?= h($record['desc']) ?></div>

        <?php if ($party): ?>
          <?php $isCoopCard = isCoopParty($party); ?>
          <?php $coop = coopData($party); ?>

          <div class="partyMeta">
            <?php if ($isCoopCard): ?>
              <span class="coopPill">🤝 Partie Coop</span><br>
              👹 Boss : <strong><?= h(coopBossLabel($party)) ?></strong><br>
              <?= coopWon($party) ? '✅ Résultat' : '❌ Résultat' ?> :
              <strong><?= coopWon($party) ? 'Boss vaincu' : 'Défaite contre le boss' ?></strong><br>
              🏅 Rang : <?= h(coopRankLabel($party)) ?><br>
              🔁 Tours : <?= (int)($coop['turns_used'] ?? 0) ?> utilisés /
              <?= (int)($coop['max_turns'] ?? 0) ?> max
              <?php if (array_key_exists('turns_remaining', $coop)): ?>
                · <?= (int)$coop['turns_remaining'] ?> restant(s)
              <?php endif; ?><br>
              📅 Date : <?= h(shortDate($party['created_at'] ?? '')) ?><br>
              ⏱ Durée : <?= h(formatDuration($party['duration'] ?? 0)) ?><br>
              👥 Joueurs : <?= h(playersLabel($party)) ?> ·
              🎯 Manches : <?= h($party['rounds_played'] ?? 0) ?>/4
            <?php else: ?>
              👑 Gagnant : <strong><?= h($party['winner'] ?? '—') ?></strong><br>
              📅 Date : <?= h(shortDate($party['created_at'] ?? '')) ?><br>
              ⏱ Durée : <?= h(formatDuration($party['duration'] ?? 0)) ?><br>
              👥 Joueurs : <?= h($party['players_count'] ?? 0) ?> ·
              🎯 Manches : <?= h($party['rounds_played'] ?? 0) ?>/4
            <?php endif; ?>
          </div>

          <div class="actions">
            <a class="btn" href="<?= h(partyUrl($party)) ?>">
              Voir cette partie →
            </a>
          </div>
        <?php endif; ?>
      </article>

    <?php endforeach; ?>
  </section>

<?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/';
}

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>


</body>
</html>
