<?php
declare(strict_types=1);

$file = dirname(__DIR__, 2) . '/privatedata/parties.json';

$parties = [];
if (file_exists($file)) {
    $json = file_get_contents($file);
    $parties = json_decode($json, true);
    if (!is_array($parties)) $parties = [];
}

$id = (string)($_GET['id'] ?? '');
$currentParty = null;

foreach ($parties as $party) {

    if (($party['id'] ?? '') === $id) {

        if (($party['status'] ?? 'validated') === 'excluded') {
            $currentParty = null;
            break;
        }

        $currentParty = $party;
        break;
    }
}

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

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 playerName($player): string {
    if (is_array($player)) return trim((string)($player['name'] ?? ''));
    return trim((string)$player);
}

function teamPlayers(array $team): array {
    $out = [];
    foreach (($team['players'] ?? []) as $player) {
        $name = playerName($player);
        if ($name !== '') $out[] = $name;
    }
    return $out;
}

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

function teamColorClass(int $index): string {
    return $index === 1 ? 'blue' : 'purple';
}

$winner = '';
$scores = [];
$teams = [];
$themes = [];
$createdAt = '';
$duration = 0;
$roundsPlayed = 0;
$totalWords = 0;
$totalPasses = 0;
$bestRoundScore = 0;
$bestRoundLabel = '—';
$bestRoundTeam = '—';
$roundTotals = [];
$hardestRound = '—';
$gap = 0;
$mvp = '—';
$winnerTeam = null;
$isCoop = false;
$coop = [];

if ($currentParty) {
    $isCoop = (($currentParty['game_mode'] ?? '') === 'coop');
    $coop = is_array($currentParty['coop'] ?? null) ? $currentParty['coop'] : [];

    $winner = (string)($currentParty['winner'] ?? '');
    $scores = is_array($currentParty['scores'] ?? null) ? $currentParty['scores'] : [];
    $teams = is_array($currentParty['teams'] ?? null) ? $currentParty['teams'] : [];
    $themes = is_array($currentParty['themes'] ?? null) ? $currentParty['themes'] : [];
    $createdAt = (string)($currentParty['created_at'] ?? '');
    $duration = (int)($currentParty['duration'] ?? 0);
    $roundsPlayed = (int)($currentParty['rounds_played'] ?? 0);

    foreach ($teams as $team) {
        if (($team['name'] ?? '') === $winner) {
            $winnerTeam = $team;
            break;
        }
    }

    $winnerPlayers = $winnerTeam ? teamPlayers($winnerTeam) : [];
    $mvp = $winnerPlayers[0] ?? '—';

    foreach ($scores as $score) {
        $totalWords += (int)($score['total'] ?? 0);

        foreach (($score['perRound'] ?? []) as $round => $points) {
            $round = (int)$round;
            $points = (int)$points;
            $roundTotals[$round] = ($roundTotals[$round] ?? 0) + $points;

            if ($points > $bestRoundScore) {
                $bestRoundScore = $points;
                $bestRoundLabel = 'Manche ' . $round;
                $bestRoundTeam = (string)($score['name'] ?? '');
            }
        }
    }

    foreach ($teams as $team) {
        foreach (($team['turnStats'] ?? []) as $turn) {
            if (!empty($turn['passed']) && is_array($turn['passed'])) {
                $totalPasses += count($turn['passed']);
            }
        }
    }

    if (!empty($roundTotals)) {
        asort($roundTotals);
        $hardestRound = 'Manche ' . array_key_first($roundTotals);
    }

    if (count($scores) >= 2) {
        $totals = array_map(fn($s) => (int)($s['total'] ?? 0), $scores);
        rsort($totals);
        $gap = $totals[0] - $totals[1];
    }
}

$publicUrl = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'chrono-party.e-u.fr') . ($_SERVER['REQUEST_URI'] ?? '');

if ($currentParty && $isCoop) {
    $bossLabel = trim((string)(($coop['icon'] ?? '👹') . ' ' . ($coop['label'] ?? 'Boss Chrono')));
    $coopResult = !empty($coop['won']) ? 'Boss vaincu' : 'Boss gagnant';

    $pageTitle = $coopResult . ' — ' . $bossLabel . ' en ' . formatDuration($duration);
    $pageDescription = 'Combat Coop Chrono Party : ' . $bossLabel . ', ' . $coopResult . ', ' . (int)($coop['turns_used'] ?? 0) . '/' . (int)($coop['max_turns'] ?? 0) . ' tours et ' . $totalWords . ' mots trouvés.';
} else {
    $pageTitle = $currentParty
        ? $winner . ' remporte une partie Chrono Party en ' . formatDuration($duration)
        : 'Partie introuvable';

    $pageDescription = $currentParty
        ? $winner . ' remporte cette partie Chrono Party avec ' . $totalWords . ' mots trouvés en ' . formatDuration($duration) . '. Découvrez les scores, statistiques et moments forts de cette soirée.'
        : 'Partie Chrono Party introuvable.';
}
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= e($pageTitle) ?></title>
<meta name="description" content="<?= e($pageDescription) ?>">
<meta name="robots" content="index,follow">

<meta property="og:title" content="<?= e($pageTitle) ?>">
<meta property="og:description" content="<?= e($pageDescription) ?>">
<meta property="og:type" content="website">
<meta property="og:url" content="<?= e($publicUrl) ?>">

<style>
:root{
  --yellow:#ffd84d;
  --pink:#ff2eea;
  --purple:#a83cff;
  --purple2:#7c5cff;
  --blue:#00c7ff;
  --green:#23ff86;
  --panel:#111a4f;
  --deep:#070b28;
}
*{box-sizing:border-box}
html,
body{
  margin:0;
  padding:0;
  overflow-x:hidden;
}
body{
  margin:0;
  font-family:Arial,Helvetica,sans-serif;
  color:#fff;
  background:
    radial-gradient(circle at 18% 18%, rgba(124,92,255,.38), transparent 35%),
    radial-gradient(circle at 76% 18%, rgba(0,199,255,.22), transparent 30%),
    linear-gradient(180deg,#060725,#07133a 48%,#050618);
}
.wrap{max-width:740px;margin:0 auto;padding:14px}
.poster{
  position:relative;
  overflow:hidden;
  border:5px solid var(--yellow);
  border-radius:34px;
  background:
    radial-gradient(circle at 18% 0%, rgba(124,92,255,.42), transparent 30%),
    radial-gradient(circle at 84% 46%, rgba(0,199,255,.20), transparent 34%),
    linear-gradient(180deg,#090b32,#08123c 50%,#05091f);
  padding:18px;
  box-shadow:0 30px 90px rgba(0,0,0,.45);
}
.poster:before{
  content:"";
  position:absolute;
  inset:8px;
  border:3px solid var(--purple2);
  border-radius:25px;
  pointer-events:none;
}
.shape1,.shape2{
  position:absolute;
  border-radius:50%;
  background:rgba(124,92,255,.18);
  filter:blur(.2px);
}
.shape1{width:310px;height:250px;left:-130px;top:-50px}
.shape2{width:350px;height:360px;right:-190px;top:260px;background:rgba(0,199,255,.13)}
.content{position:relative;z-index:2}
.head{text-align:center;padding:22px 10px 10px}
.logo{font-weight:900;font-size:42px;letter-spacing:1px;line-height:1}
.date{margin-top:10px;color:var(--yellow);font-weight:900;font-size:16px}
.bigTitle{margin:26px 0 8px;font-size:43px;font-weight:900;letter-spacing:1px}
.thanks{color:#ffe97c;font-size:21px;font-weight:900}
.winner{
  max-width:600px;
  margin:24px auto 22px;
  padding:14px 16px;
  border-radius:18px;
  background:linear-gradient(90deg,#8b15ff,#f227dc);
  text-align:center;
  box-shadow:0 10px 26px rgba(255,46,234,.20);
}
.winner small{display:block;color:var(--yellow);font-weight:900;font-size:15px}
.winner strong{display:block;text-transform:uppercase;font-size:29px;line-height:1.05}
.scoreGrid{
  display:grid;
  grid-template-columns:1fr 76px 1fr;
  gap:14px;
  align-items:center;
  margin:18px 12px 22px;
}
.scoreCard{
  min-height:150px;
  border-radius:25px;
  display:flex;
  align-items:center;
  justify-content:center;
  flex-direction:column;
  background:rgba(255,255,255,.045);
  padding:18px 10px;
}
.scoreCard.purple{border:4px solid var(--pink);box-shadow:0 0 18px rgba(255,46,234,.2) inset}
.scoreCard.blue{border:4px solid var(--blue);box-shadow:0 0 18px rgba(0,199,255,.18) inset}
.scoreName{font-size:20px;font-weight:900;text-align:center}
.scoreCard.purple .scoreName{color:#d665ff}
.scoreCard.blue .scoreName{color:#00c7ff}
.scoreNum{font-size:62px;font-weight:900;margin-top:12px}
.scorePts{color:#c8c9ff;font-size:20px;font-weight:900}
.vs{
  width:76px;
  height:76px;
  margin:auto;
  border-radius:50%;
  background:#111831;
  border:3px solid rgba(255,255,255,.22);
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:30px;
  font-weight:900;
  box-shadow:0 8px 24px rgba(0,0,0,.35);
}
.panel{
  border:4px solid var(--purple2);
  border-radius:24px;
  background:rgba(255,255,255,.035);
  margin:16px 12px;
  padding:18px;
}
.panelTitle{text-align:center;font-size:27px;font-weight:900;margin:0 0 16px}
.summary{display:grid;grid-template-columns:repeat(4,1fr);text-align:center}
.summary>div{padding:8px 6px;border-right:1px solid rgba(255,255,255,.18)}
.summary>div:last-child{border-right:0}
.icon{font-size:31px;margin-bottom:4px}
.label{font-size:15px;font-weight:900;color:#d9dcff}
.val{font-size:24px;font-weight:900;color:var(--green);display:block}
.fun{display:grid;grid-template-columns:repeat(3,1fr)}
.funItem{
  min-height:92px;
  padding:12px;
  border-right:1px solid rgba(255,255,255,.18);
  border-bottom:1px solid rgba(255,255,255,.12);
}
.funItem:nth-child(3n){border-right:0}
.funItem:nth-child(n+7){border-bottom:0}
.funEmoji{font-size:28px;float:left;margin-right:9px}
.funItem small{display:block;text-transform:uppercase;color:#e6dcff;font-size:11px;font-weight:900}
.funItem strong{display:block;margin-top:5px;font-size:18px;line-height:1.15}
.funItem em{display:block;font-style:normal;color:#dcd3ff;font-size:12px;font-weight:900;margin-top:5px}
.twoCols{display:grid;grid-template-columns:1.15fr .85fr;gap:14px;margin:16px 12px}
.twoCols .panel{margin:0;height:100%}
.chartLegend{display:flex;gap:16px;flex-wrap:wrap;margin:4px 0 12px 8px;font-weight:900;color:#dcdcff}
.dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px;background:var(--pink)}
.dot.blue{background:var(--blue)}
.svgChart{width:100%;height:150px;display:block;overflow:visible}
.axis{stroke:rgba(255,255,255,.25);stroke-width:2}
.linePurple{fill:none;stroke:var(--pink);stroke-width:5;stroke-linecap:round;stroke-linejoin:round}
.lineBlue{fill:none;stroke:var(--blue);stroke-width:5;stroke-linecap:round;stroke-linejoin:round}
.pointPurple{fill:var(--pink)}
.pointBlue{fill:var(--blue)}
.chartText{fill:white;font-size:13px;font-weight:900}
.ai{border-color:var(--pink);background:rgba(95,13,102,.36)}
.ai p{margin:0;font-size:18px;line-height:1.38;font-weight:900}
.players{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
.teamBox{background:rgba(255,255,255,.06);border-radius:17px;padding:13px}
.teamBox strong{color:var(--yellow);display:block;margin-bottom:8px}
.pill{display:inline-block;background:rgba(255,255,255,.12);border-radius:999px;padding:7px 10px;margin:4px;font-size:13px;font-weight:900}
.playerLink{
  text-decoration:none;
  color:white;
  display:inline-block;
}

.playerLink:hover{
  transform:translateY(-1px);
  opacity:.9;
}
.themes{text-align:center}
.theme{display:inline-block;margin:5px;padding:8px 13px;border-radius:999px;background:linear-gradient(90deg,#7c5cff,#d62cff);font-weight:900;font-size:13px}
.cta{
  border:4px solid var(--yellow);
  border-radius:24px;
  margin:18px 12px 12px;
  padding:18px;
  display:grid;
  grid-template-columns:1fr 160px;
  gap:20px;
  align-items:center;
}
.cta h2{margin:0 0 14px;font-size:27px;color:var(--yellow)}
.cta p{margin:9px 0;font-size:18px;font-weight:900}
.qr{background:#fff;border:4px solid var(--yellow);border-radius:18px;padding:10px;text-align:center}
.qr img{width:100%;height:auto;display:block;border-radius:8px}
.qr strong{color:#111;display:block;margin-top:8px;font-size:15px}
.actions{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:8px;
  margin:18px 12px 0;
}

.btn{
  border:0;
  border-radius:14px;
  padding:12px 6px;
  text-align:center;
  text-decoration:none;
  font-weight:900;
  font-size:14px;
  line-height:1.15;
  color:white !important;
  background:linear-gradient(90deg,#7c5cff,#f227dc);
  cursor:pointer;
}

.btn.secondary{
  background:rgba(255,255,255,.04);
  border:2px solid rgba(255,255,255,.45);
}
.footer{text-align:center;color:#cfd3ff;font-size:13px;padding:18px 0 6px}
.notFound{min-height:65vh;display:flex;align-items:center;justify-content:center;text-align:center}
@media(max-width:680px){
  .wrap{padding:8px}
  .poster{padding:10px;border-radius:25px}
  .logo{font-size:30px}
  .bigTitle{font-size:33px}
  .thanks{font-size:18px}
  .winner strong{font-size:24px}
  .scoreGrid{grid-template-columns:1fr;gap:8px}
  .vs{width:62px;height:62px;font-size:24px}
  .scoreCard{min-height:118px}
  .scoreNum{font-size:50px}
  .summary{grid-template-columns:repeat(2,1fr)}
  .summary>div{border-right:0;border-bottom:1px solid rgba(255,255,255,.14)}
  .summary>div:nth-child(n+3){border-bottom:0}
  .fun{grid-template-columns:1fr}
  .funItem{border-right:0!important;border-bottom:1px solid rgba(255,255,255,.13)!important}
  .funItem:last-child{border-bottom:0!important}
  .twoCols{grid-template-columns:1fr}
  .players{grid-template-columns:1fr}
  .cta{grid-template-columns:1fr}

}
</style>
</head>

<body>
<div class="wrap">

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

<div class="poster notFound">
  <div class="content">
    <h1>Partie introuvable</h1>
    <p>Vérifie l’ID de la partie.</p>
    <a class="btn" href="https://chrono-party.e-u.fr/">Retour Chrono Party</a>
  </div>
</div>

<?php else: ?>

<?php if ($isCoop): ?>

<div class="poster">
  <div class="shape1"></div>
  <div class="shape2"></div>

  <div class="content">

    <header class="head">
      <div class="logo">👹 CHRONO PARTY COOP</div>
      <div class="date">📅 <?= e(shortDate($createdAt)) ?> · ⏱ <?= e(formatDuration($duration)) ?></div>
      <div class="bigTitle">COMBAT CONTRE LE BOSS</div>
      <div class="thanks">Tous ensemble contre le Boss Chrono !</div>
    </header>

    <section class="winner">
      <small><?= !empty($coop['won']) ? '🏆 BOSS VAINCU' : '💀 BOSS GAGNANT' ?></small>
      <strong><?= e(($coop['icon'] ?? '👹') . ' ' . ($coop['label'] ?? 'Boss Chrono')) ?></strong>
    </section>

    <section class="panel">
      <h2 class="panelTitle">👹 RÉSUMÉ DU COMBAT</h2>
      <div class="summary">
        <div>
          <div class="icon">🎯</div>
          <div class="label">Tours utilisés</div>
          <span class="val"><?= e(($coop['turns_used'] ?? 0) . '/' . ($coop['max_turns'] ?? 0)) ?></span>
        </div>

        <div>
          <div class="icon">✅</div>
          <div class="label">Mots trouvés</div>
          <span class="val"><?= e($totalWords) ?></span>
        </div>

        <div>
          <div class="icon">🏅</div>
          <div class="label">Rang</div>
          <span class="val"><?= e(trim(($coop['rank_icon'] ?? '') . ' ' . ($coop['rank_label'] ?? '—'))) ?></span>
        </div>

        <div>
          <div class="icon">⏱️</div>
          <div class="label"><?= !empty($coop['won']) ? 'Tours restants' : 'Dépassement' ?></div>
          <span class="val">
            <?= !empty($coop['won'])
              ? e(($coop['turns_remaining'] ?? 0) . ' tours')
              : e('+' . ($coop['over_by'] ?? 0) . ' tours')
            ?>
          </span>
        </div>
      </div>
    </section>

    <section class="panel ai">
      <h2 class="panelTitle">🤖 ANALYSE DU COMBAT</h2>
      <p>
        <?php if (!empty($coop['won'])): ?>
          ✅ Bravo ! Le groupe a vaincu le Boss en <?= e($coop['turns_used'] ?? 0) ?> tours sur <?= e($coop['max_turns'] ?? 0) ?>.
        <?php else: ?>
          💀 Le Boss a résisté. Le groupe a dépassé la limite de <?= e($coop['over_by'] ?? 0) ?> tour(s).
        <?php endif; ?>
      </p>
    </section>

    <section class="panel">
      <h2 class="panelTitle">JOUEURS DU COMBAT</h2>
      <div class="players">
        <?php foreach ($teams as $team): ?>
          <div class="teamBox">
            <strong>Groupe Coop</strong>

            <?php foreach (($team['players'] ?? []) as $player): ?>
              <?php
                $playerName = is_array($player) ? trim((string)($player['name'] ?? '')) : trim((string)$player);
                $playerId = is_array($player) ? trim((string)($player['id'] ?? '')) : '';
              ?>

              <?php if ($playerName !== ''): ?>
                <?php if ($playerId !== ''): ?>
                  <a class="pill playerLink" href="/joueur/?id=<?= urlencode($playerId) ?>">
                    <?= e($playerName) ?>
                  </a>
                <?php else: ?>
                  <span class="pill"><?= e($playerName) ?></span>
                <?php endif; ?>
              <?php endif; ?>

            <?php endforeach; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </section>

    <section class="panel themes">
      <h2 class="panelTitle">THÈMES JOUÉS</h2>
      <?php foreach ($themes as $theme): ?>
        <span class="theme"><?= e($theme) ?></span>
      <?php endforeach; ?>
    </section>

    <section class="cta">
      <div>
        <h2>VOUS AVEZ AIMÉ LE MODE COOP ?</h2>
        <p>👹 Affrontez plusieurs Boss</p>
        <p>🏆 Débloquez des badges joueurs</p>
        <p>🎮 Rejouez pour améliorer votre rang</p>
      </div>
      <div class="qr">
        <img src="../assets/img/qr-chrono-party.png" alt="QR code Chrono Party">
        <strong>SCANNEZ POUR JOUER</strong>
      </div>
    </section>

<div class="actions actions3">
  <a class="btn secondary" href="https://chrono-party.e-u.fr/jeux/">
    🏠 Accueil
  </a>

  <<a class="btn secondary" href="https://chrono-party.e-u.fr/demo2026/">
  🎮 Démo
</a>

  <a class="btn" href="https://chrono-party.e-u.fr/jeux/offrir-chrono-party/">
    🎁 Offrir
  </a>
</div>

    <footer class="footer">chrono-party.e-u.fr</footer>

  </div>
</div>

<?php else: ?>

<div class="poster">
  <div class="shape1"></div>
  <div class="shape2"></div>

  <div class="content">

    <header class="head">
      <div class="logo">🏆 CHRONO PARTY</div>
      <div class="date">📅 <?= e(shortDate($createdAt)) ?> · ⏱ <?= e(formatDuration($duration)) ?></div>
      <div class="bigTitle">PARTIE TERMINÉE ! 🎉</div>
      <div class="thanks">Merci à tous pour cette super partie !</div>
    </header>

    <section class="winner">
      <small>👑 ÉQUIPE GAGNANTE</small>
      <strong><?= e($winner) ?></strong>
    </section>

    <section class="scoreGrid">
      <?php foreach ($scores as $i => $score): ?>
        <?php if ($i === 1): ?><div class="vs">VS</div><?php endif; ?>
        <div class="scoreCard <?= e(teamColorClass($i)) ?>">
          <div class="scoreName"><?= e($score['name'] ?? '') ?></div>
          <div class="scoreNum"><?= e($score['total'] ?? 0) ?></div>
          <div class="scorePts">points</div>
        </div>
      <?php endforeach; ?>
    </section>

    <section class="panel">
      <h2 class="panelTitle">⭐ RÉSUMÉ DE LA PARTIE ⭐</h2>
      <div class="summary">
        <div>
          <div class="icon">🎯</div>
          <div class="label">Manches</div>
          <span class="val"><?= e($roundsPlayed) ?>/4</span>
        </div>
        <div>
          <div class="icon">✅</div>
          <div class="label">Mots trouvés</div>
          <span class="val"><?= e($totalWords) ?></span>
        </div>
        <div>
          <div class="icon">⏭️</div>
          <div class="label">Passes</div>
          <span class="val"><?= e($totalPasses) ?></span>
        </div>
        <div>
          <div class="icon">⚡</div>
          <div class="label">Meilleur tour</div>
          <span class="val"><?= e($bestRoundScore) ?></span>
        </div>
      </div>
    </section>

    <section class="panel">
      <h2 class="panelTitle">LES STATS DE LA SOIRÉE 🎉</h2>
      <div class="fun">
        <div class="funItem">
          <span class="funEmoji">👑</span>
          <small>MVP de la partie</small>
          <strong><?= e($mvp) ?></strong>
          <em>équipe gagnante</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">🚀</span>
          <small>Meilleur tour</small>
          <strong><?= e($bestRoundScore) ?> mots</strong>
          <em><?= e($bestRoundTeam) ?> · <?= e($bestRoundLabel) ?></em>
        </div>
        <div class="funItem">
          <span class="funEmoji">😈</span>
          <small>Mot impossible</small>
          <strong><?= e($currentParty['hardest_word'] ?? 'Aucun') ?></strong>
          <em>aucun mot bloquant</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">🔥</span>
          <small>Manche la plus difficile</small>
          <strong><?= e($hardestRound) ?></strong>
          <em>selon les scores</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">⚔️</span>
          <small>Écart final</small>
          <strong><?= e($gap) ?> points</strong>
          <em>d’écart</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">📊</span>
          <small>Équipe la plus régulière</small>
          <strong><?= e($winner) ?></strong>
          <em>sur cette partie</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">😂</span>
          <small>Soirée</small>
          <strong><?= $gap <= 2 ? 'Ultra serrée !' : ($gap >= 15 ? 'Victoire écrasante' : 'Très disputée') ?></strong>
          <em><?= e($gap) ?> points d’écart</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">🧠</span>
          <small>Rythme</small>
          <strong><?= $bestRoundScore >= 10 ? 'Quel rythme incroyable !' : 'Belle régularité' ?></strong>
          <em><?= e($bestRoundScore) ?> mots au meilleur tour</em>
        </div>
        <div class="funItem">
          <span class="funEmoji">🎭</span>
          <small>Moment fort</small>
          <strong><?= e($hardestRound) ?></strong>
          <em>manche la plus difficile</em>
        </div>
      </div>
    </section>

    <div class="twoCols">
      <section class="panel">
        <h2 class="panelTitle">ÉVOLUTION DES SCORES PAR MANCHE</h2>
        <div class="chartLegend">
          <?php foreach ($scores as $i => $score): ?>
            <span><i class="dot <?= $i === 1 ? 'blue' : '' ?>"></i><?= e($score['name'] ?? '') ?></span>
          <?php endforeach; ?>
        </div>

        <?php
          $rounds = [1,2,3,4];
          $maxTotal = 1;
          $cumulatives = [];

          foreach ($scores as $si => $score) {
              $running = 0;
              foreach ($rounds as $r) {
                  $running += (int)($score['perRound'][$r] ?? 0);
                  $cumulatives[$si][$r] = $running;
                  if ($running > $maxTotal) $maxTotal = $running;
              }
          }

          function chartPoints(array $values, array $rounds, int $maxTotal): string {
              $pts = [];
              $count = count($rounds);
              foreach ($rounds as $idx => $r) {
                  $x = 18 + ($idx * (264 / max(1, $count - 1)));
                  $v = (int)($values[$r] ?? 0);
                  $y = 120 - (($v / max(1, $maxTotal)) * 92);
                  $pts[] = round($x,1) . ',' . round($y,1);
              }
              return implode(' ', $pts);
          }
        ?>

        <svg class="svgChart" viewBox="0 0 300 150" preserveAspectRatio="none" aria-label="Évolution des scores par manche">
          <line class="axis" x1="18" y1="120" x2="282" y2="120"></line>
          <line class="axis" x1="18" y1="28" x2="18" y2="120"></line>

          <?php foreach ($cumulatives as $si => $values): ?>
            <?php $points = chartPoints($values, $rounds, $maxTotal); ?>
            <polyline class="<?= $si === 1 ? 'lineBlue' : 'linePurple' ?>" points="<?= e($points) ?>"></polyline>

            <?php
              $coords = explode(' ', $points);
              foreach ($coords as $idx => $coord):
                [$cx,$cy] = explode(',', $coord);
                $round = $rounds[$idx];
                $value = (int)($values[$round] ?? 0);
            ?>
              <circle class="<?= $si === 1 ? 'pointBlue' : 'pointPurple' ?>" cx="<?= e($cx) ?>" cy="<?= e($cy) ?>" r="5"></circle>
              <text class="chartText" x="<?= e($cx) ?>" y="<?= e(max(14, (float)$cy - 8)) ?>" text-anchor="middle"><?= e($value) ?></text>
            <?php endforeach; ?>
          <?php endforeach; ?>

          <?php foreach ($rounds as $idx => $r): ?>
            <?php $x = 18 + ($idx * (264 / max(1, count($rounds) - 1))); ?>
            <text class="chartText" x="<?= e($x) ?>" y="143" text-anchor="middle">M<?= e($r) ?></text>
          <?php endforeach; ?>
        </svg>
      </section>

      <section class="panel ai">
        <h2 class="panelTitle">🤖 ANALYSE IA CHRONO PARTY</h2>
        <p>
          ✅ Belle partie !
          <?php if ($bestRoundScore > 0): ?>
            Gros rythme : le meilleur tour atteint <?= e($bestRoundScore) ?> points.
          <?php endif; ?>
          <?php if ($gap > 0): ?>
            Écart final : <?= e($gap) ?> points.
          <?php endif; ?>
        </p>
      </section>
    </div>

<section class="panel">
  <h2 class="panelTitle">JOUEURS DE LA PARTIE</h2>
  <div class="players">
    <?php foreach ($teams as $team): ?>
      <div class="teamBox">
        <strong><?= e($team['name'] ?? '') ?></strong>

        <?php foreach (($team['players'] ?? []) as $player): ?>
          <?php
            $playerName = is_array($player) ? trim((string)($player['name'] ?? '')) : trim((string)$player);
            $playerId = is_array($player) ? trim((string)($player['id'] ?? '')) : '';
          ?>

          <?php if ($playerName !== ''): ?>
            <?php if ($playerId !== ''): ?>
              <a class="pill playerLink" href="/joueur/?id=<?= urlencode($playerId) ?>">
                <?= e($playerName) ?>
              </a>
            <?php else: ?>
              <span class="pill"><?= e($playerName) ?></span>
            <?php endif; ?>
          <?php endif; ?>

        <?php endforeach; ?>
      </div>
    <?php endforeach; ?>
  </div>
</section>

    <section class="panel themes">
      <h2 class="panelTitle">THÈMES JOUÉS</h2>
      <?php foreach ($themes as $theme): ?>
        <span class="theme"><?= e($theme) ?></span>
      <?php endforeach; ?>
    </section>

    <section class="cta">
      <div>
        <h2>VOUS AVEZ AIMÉ LA PARTIE ?</h2>
        <p>⚡ Installation rapide</p>
        <p>💜 Parfait pour vos soirées</p>
        <p>🎁 Démo gratuite</p>
      </div>
      <div class="qr">
        <img src="../assets/img/qr-chrono-party.png" alt="QR code Chrono Party">
        <strong>SCANNEZ POUR JOUER</strong>
      </div>
    </section>

<div class="actions actions3">
  <a class="btn secondary" href="https://chrono-party.e-u.fr/jeux/">
    🏠 Accueil
  </a>

<a class="btn secondary" href="https://chrono-party.e-u.fr/demo2026/">
  🎮 Démo
</a>

  <a class="btn" href="https://chrono-party.e-u.fr/jeux/offrir-chrono-party/">
    🎁 Offrir
  </a>
</div>

    <footer class="footer">chrono-party.e-u.fr</footer>
  </div>
</div>

<?php endif; ?>

<?php endif; ?>

</div>



<script>


</script>
<script>
if ("scrollRestoration" in history) {
  history.scrollRestoration = "manual";
}

window.addEventListener("pageshow", function () {
  if (window.location.search.includes("replay=1")) {
    window.scrollTo(0, 0);

    setTimeout(function () {
      window.scrollTo(0, 0);
    }, 100);
  }
});
</script>
</body>
</html>