<?php
require_once 'header.php';

$db = getDB();

/**
 * Champions with progress
 */
$stmt = $db->query("
  SELECT c.*, COALESCE(cp.level, 1) AS level, COALESCE(cp.xp, 0) AS xp
  FROM champions c
  LEFT JOIN champion_progress cp ON c.id = cp.champion_id
  ORDER BY level DESC, xp DESC
");
$champions = $stmt->fetchAll();

/**
 * Load completed bounties as "badges" grouped by champion
 * Requires: bounties.completed_by_champion_id column
 */
$badgeMap = [];
try {
  $stmt = $db->query("
    SELECT
      id,
      name,
      description,
      xp_reward,
      image_path,
      completed_date,
      completed_by_champion_id
    FROM bounties
    WHERE completed = TRUE
      AND completed_by_champion_id IS NOT NULL
    ORDER BY completed_date DESC, id DESC
  ");
  $badges = $stmt->fetchAll();

  foreach ($badges as $b) {
    $cid = (int)$b['completed_by_champion_id'];
    if (!isset($badgeMap[$cid])) $badgeMap[$cid] = [];
    $badgeMap[$cid][] = $b;
  }
} catch (Throwable $e) {
  // If migration not done, badges will just not show
  $badgeMap = [];
}

function fmtDate(?string $ymd): string {
  if (!$ymd) return 'Unknown';
  $ts = strtotime($ymd);
  return $ts ? date('d M Y', $ts) : htmlspecialchars($ymd);
}
?>

<div class="ladder-container mb-20">
  <div class="ladder-header">
    <h2 style="color: var(--gold); font-size: 1.8rem;">🏆 Champion Ladder 🏆</h2>
    <p style="color: #888; margin-top: 5px;">All-Time Legend Rankings</p>
  </div>

  <?php foreach ($champions as $index => $champ): ?>
    <div class="ladder-row">
      <div class="ladder-rank">#<?php echo (int)($index + 1); ?></div>

      <div class="ladder-champion">
        <div class="ladder-avatar">
          <img
            src="<?php echo htmlspecialchars(getChampionImage($champ['name'], 'card')); ?>"
            alt="<?php echo htmlspecialchars($champ['name']); ?>"
            onerror="this.style.display='none'; this.parentElement.querySelector('.avatar-fallback').style.display='flex';"
          />
          <div class="avatar-fallback" style="display:none; height:100%; align-items:center; justify-content:center; font-size:2rem; background:#111;">
            <?php echo htmlspecialchars($champ['emoji']); ?>
          </div>
        </div>

        <div class="ladder-info">
          <h3><?php echo htmlspecialchars($champ['name']); ?></h3>
          <p><?php echo htmlspecialchars($champ['title']); ?></p>
        </div>
      </div>

      <div class="ladder-stat">
        <div class="ladder-stat-value"><?php echo (int)$champ['level']; ?></div>
        <div class="ladder-stat-label">Level</div>
      </div>

      <div class="ladder-stat">
        <div class="ladder-stat-value"><?php echo (int)$champ['xp']; ?></div>
        <div class="ladder-stat-label">XP</div>
      </div>
    </div>
  <?php endforeach; ?>
</div>

<div class="quest-grid">
  <?php foreach ($champions as $champ):
    $maxXP = max(1, ((int)$champ['level']) * 100);
    $xpPercent = min(100, (((int)$champ['xp']) / $maxXP) * 100);
    $cid = (int)$champ['id'];
    $champBadges = $badgeMap[$cid] ?? [];
  ?>
    <div class="champion-card" style="border-color: <?php echo htmlspecialchars($champ['color']); ?>">
      <img
        src="<?php echo htmlspecialchars(getChampionImage($champ['name'], 'flyer')); ?>"
        alt="<?php echo htmlspecialchars($champ['name']); ?>"
        class="champion-card-img"
        onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
      />
      <div style="display:none; height:200px; align-items:center; justify-content:center; font-size:4rem; background:#111; border-radius:5px; margin-bottom:15px; border:2px solid <?php echo htmlspecialchars($champ['color']); ?>;">
        <?php echo htmlspecialchars($champ['emoji']); ?>
      </div>

      <h3 style="color: <?php echo htmlspecialchars($champ['color']); ?>; font-size: 1.5rem; margin-bottom: 5px;">
        <?php echo htmlspecialchars($champ['name']); ?>
      </h3>
      <p style="color:#888; font-size:0.9rem; margin-bottom:10px;">
        <?php echo htmlspecialchars($champ['title']); ?>
      </p>

      <div class="xp-bar-container" style="height:20px; margin:10px 0;">
        <div class="xp-bar-fill" style="width: <?php echo (float)$xpPercent; ?>%; font-size:0.7rem;">
          Lvl <?php echo (int)$champ['level']; ?>
        </div>
      </div>

      <!-- ✅ BADGES -->
      <div class="badge-section">
        <div class="badge-title">Badges</div>

        <?php if (count($champBadges) === 0): ?>
          <div class="badge-empty">No badges yet — go claim some bounties 😈</div>
        <?php else: ?>
          <div class="badge-strip">
            <?php foreach ($champBadges as $b): ?>
              <?php
                $img = $b['image_path'] ? $b['image_path'] : '';
                $achieved = fmtDate($b['completed_date']);
                $xpEarned = (int)($b['xp_reward'] ?? 0);
              ?>
              <div class="badge" tabindex="0">
                <?php if ($img): ?>
                  <img src="<?php echo htmlspecialchars($img); ?>" alt="<?php echo htmlspecialchars($b['name']); ?>"
                       onerror="this.style.display='none'; this.parentElement.querySelector('.badge-fallback').style.display='flex';">
                <?php endif; ?>

                <div class="badge-fallback" style="<?php echo $img ? 'display:none;' : 'display:flex;'; ?>">
                  🏅
                </div>

                <!-- Hover popover -->
                <div class="badge-popover">
                  <div class="badge-popover-title"><?php echo htmlspecialchars($b['name']); ?></div>

                  <?php if ($img): ?>
                    <img class="badge-popover-img" src="<?php echo htmlspecialchars($img); ?>" alt="<?php echo htmlspecialchars($b['name']); ?>">
                  <?php endif; ?>

                  <div class="badge-popover-meta">
                    <div><strong>Achieved:</strong> <?php echo htmlspecialchars($achieved); ?></div>
                    <div><strong>XP:</strong> <?php echo $xpEarned; ?></div>
                  </div>

                  <?php if (!empty($b['description'])): ?>
                    <div class="badge-popover-desc"><?php echo nl2br(htmlspecialchars($b['description'])); ?></div>
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>

      <p style="margin-top: 12px; font-size: 0.9rem; color: #aaa; text-align: center;">
        "<?php echo htmlspecialchars($champ['tagline']); ?>"
      </p>
      <p style="margin-top: 10px; font-size: 0.8rem; color: #666;">
        <?php echo htmlspecialchars($champ['description']); ?>
      </p>
    </div>
  <?php endforeach; ?>
</div>

<?php require_once 'footer.php'; ?>