<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';
require_once __DIR__ . '/includes/stream_lib.php';
@smurf_top50_touch(__DIR__ . '/data/top50.json', __DIR__ . '/data/top50_state.json');
$rows = smurf_top50_sorted(__DIR__ . '/data/top50.json');
if (empty($rows)) {
  $playlistFile = __DIR__ . '/recently_played.txt';
  if (is_readable($playlistFile)) {
    foreach (array_slice(array_reverse(file($playlistFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []), 0, 50) as $track) {
      $rows[] = ['title' => $track, 'count' => null];
    }
  }
}
?>
<main class="content-area">
  <div class="content-wrapper page-shell">
    <section class="content-card center-text">
      <h1>🎵 Top 50 Recently Played</h1>
      <p>Thunder Mountain Radio’s freshest tracks.</p>
      <?php if (empty($rows)): ?>
        <p>No tracks logged yet.</p>
      <?php else: ?>
        <ol class="list-group list-group-numbered" style="text-align:left;max-width:980px;margin:0 auto;">
          <?php foreach ($rows as $row): ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <span><?= htmlspecialchars((string)($row['title'] ?? '')) ?></span>
              <?php if (isset($row['count']) && $row['count'] !== null): ?><span class="badge bg-primary rounded-pill"><?= (int)$row['count'] ?></span><?php endif; ?>
            </li>
          <?php endforeach; ?>
        </ol>
      <?php endif; ?>
    </section>
  </div>
</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
