<?php require_once 'api_helper.php'; ?>
<?php include 'partials/header.php'; ?>

<?php
$categoryFilter = isset($_GET['category']) ? $_GET['category'] : 'ALL';
$sizeFilter = isset($_GET['size']) ? $_GET['size'] : 'ALL';

$filteredMatches = array_filter($matches, function($m) use ($categoryFilter, $sizeFilter, $user) {
    if ($categoryFilter === 'MY') {
        if (!isset($m['userJoinedName'])) return false;
    } elseif ($categoryFilter !== 'ALL' && ($m['category'] ?? '') !== $categoryFilter) {
        return false;
    }
    if ($sizeFilter === 'SMALL' && (int)($m['entryFee'] ?? 0) >= 500) return false;
    if ($sizeFilter === 'BIG' && (int)($m['entryFee'] ?? 0) < 500) return false;
    return true;
});

$statusColors = [
    'ACTIVE' => 'bg-green-500/10 text-green-400',
    'FULL' => 'bg-amber-500/10 text-amber-400',
    'CLOSED' => 'bg-rose-500/10 text-rose-400',
    'COMPLETED' => 'bg-sky-500/10 text-sky-400',
];
?>

<div class="space-y-5 pb-28">
  <!-- Header with back icon -->
  <div class="flex items-center gap-3 border-b border-slate-800 pb-3">
    <button onclick="history.back()" class="p-1 px-2.5 rounded-lg bg-slate-800/100 hover:bg-slate-700 text-slate-100" id="matches-back-btn">
      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline mr-1"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>
      Back
    </button>
    <div>
      <h2 class="text-[#f8fafc] text-lg font-black tracking-tight leading-none">Ludo Matches</h2>
      <span class="text-xs text-slate-400 font-bold uppercase font-mono"><?= htmlspecialchars($categoryFilter) ?> Tournaments</span>
    </div>
  </div>

  <!-- Categories Horizontal Tabs -->
  <div class="grid grid-cols-4 gap-1.5 bg-slate-900/100 p-1 rounded-xl border border-slate-800">
    <?php foreach (['ALL', 'MY', 'SPECIAL', 'REGULAR'] as $cat): ?>
      <a href="?category=<?= $cat ?>&size=<?= urlencode($sizeFilter) ?>"
         class="py-2 text-[10px] font-black tracking-widest text-center uppercase rounded-lg transition-all <?= $categoryFilter === $cat ? 'bg-gradient-to-r from-amber-500 to-yellow-400 text-slate-950 font-extrabold shadow-md' : 'text-slate-400 hover:text-slate-100' ?>">
        <?= $cat ?>
      </a>
    <?php endforeach; ?>
  </div>

  <!-- Sub-filters: ALL, SMALL, BIG -->
  <div class="flex items-center justify-between">
    <span class="text-[10px] text-slate-400 font-black tracking-widest uppercase font-mono">BET RANGE FILTER:</span>
    <div class="flex gap-2">
      <?php foreach (['ALL', 'SMALL', 'BIG'] as $sz): ?>
        <a href="?category=<?= urlencode($categoryFilter) ?>&size=<?= $sz ?>"
           class="px-3 py-1 text-[9px] font-black tracking-wider uppercase rounded-full border transition-all <?= $sizeFilter === $sz ? 'bg-slate-100/100 text-slate-950 border-white' : 'text-slate-400 hover:text-slate-100 border-slate-800 bg-slate-950/40' ?>">
          <?= $sz ?>
        </a>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Matches Cards -->
  <div class="space-y-4">
    <?php if (empty($filteredMatches)): ?>
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-10 flex flex-col items-center justify-center text-center">
      <div class="w-16 h-16 rounded-full bg-slate-800 flex items-center justify-center mb-4">
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-pulse"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
      </div>
      <h4 class="text-white font-bold text-base">No matches matches available!</h4>
      <p class="text-[#94a3b8] text-xs max-w-xs mt-1">
        <?= $categoryFilter === 'MY' ? 'আপনি এখনও কোনো ম্যাচে অংশ নেননি। হোম স্ক্রিন থেকে যেকোনো ম্যাচে যুক্ত হন!' : 'দয়া করে চেক ব্যাক করুন, কিছুক্ষণের মধ্যেই নতুন ম্যাচ প্রকাশিত হবে!' ?>
      </p>
    </div>
    <?php else: ?>
      <?php foreach ($filteredMatches as $match):
        $hasJoined = isset($match['userJoinedName']);
        $progressPercent = min(100, ((int)($match['playersJoined'] ?? 0) / max(1, (int)($match['totalPlayersNeeded'] ?? 1))) * 100);
        $status = $match['status'] ?? 'ACTIVE';
      ?>
      <div class="relative overflow-hidden bg-slate-900 border rounded-2xl p-5 shadow-lg space-y-4 transition-all hover:border-slate-700 <?= $hasJoined ? 'border-indigo-500/40' : 'border-slate-800' ?>" id="match-card-<?= htmlspecialchars($match['id'] ?? '') ?>">
        <!-- Upper row: Titles & type -->
        <div class="flex items-start justify-between">
          <div class="space-y-1">
            <h4 class="text-white font-extrabold text-base tracking-tight leading-tight"><?= htmlspecialchars($match['title'] ?? '') ?></h4>
            <div class="flex items-center gap-1.5 text-xs text-slate-400 font-bold">
              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#facc15" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
              <span><?= htmlspecialchars($match['time'] ?? '') ?></span>
            </div>
          </div>
          <div class="flex flex-col items-end gap-1.5 shrink-0">
            <span class="text-[9px] bg-slate-800 border border-slate-700 text-yellow-400 font-black tracking-wider uppercase px-2.5 py-0.5 rounded-full font-mono">Game: <?= htmlspecialchars($match['gameName'] ?? '') ?></span>
            <span class="text-[9px] bg-blue-500/10 text-cyan-400 font-black tracking-wider uppercase px-2.5 py-0.5 rounded-full font-mono">Type: CLASSIC</span>
          </div>
        </div>

        <!-- Notice -->
        <div class="bg-[#b91c1c]/10 border border-red-700/20 text-red-400 rounded-lg p-2 text-[10px] font-bold text-center">সিট ফুল হলে রুম আইডি দেওয়া হবে</div>

        <!-- Winning Prize vs Entry Fee -->
        <div class="grid grid-cols-2 gap-3 bg-slate-950/60 rounded-xl p-3 text-center border border-slate-800/60">
          <div>
            <span class="text-[10px] text-slate-400 font-bold block uppercase tracking-widest font-mono">WINNING PRIZE</span>
            <span class="text-[#facc15] font-black text-2xl tracking-tight"><?= htmlspecialchars($match['winningPrize'] ?? '') ?></span>
          </div>
          <div class="border-l border-slate-800/80">
            <span class="text-[10px] text-slate-400 font-bold block uppercase tracking-widest font-mono">ENTRY FEE</span>
            <span class="text-white font-black text-2xl tracking-tight"><?= htmlspecialchars($match['entryFee'] ?? '') ?></span>
          </div>
        </div>

        <!-- Players joined -->
        <div class="space-y-1.5">
          <div class="flex items-center justify-between text-[11px] font-bold text-slate-400 uppercase">
            <span><?= ((int)($match['totalPlayersNeeded'] ?? 0) - (int)($match['playersJoined'] ?? 0)) ?> Players Need</span>
            <span class="text-white"><?= (int)($match['playersJoined'] ?? 0) ?>/<?= (int)($match['totalPlayersNeeded'] ?? 0) ?></span>
          </div>
          <div class="w-full h-2 bg-slate-950 rounded-full overflow-hidden">
            <div class="bg-gradient-to-r from-red-500 to-rose-600 h-full rounded-full transition-all duration-500" style="width: <?= $progressPercent ?>%"></div>
          </div>
        </div>

        <!-- Room Code when joined and FULL -->
        <?php if ($hasJoined && $status === 'FULL'): ?>
        <div class="bg-emerald-500/10 border border-emerald-500/20 rounded-xl p-3.5 flex items-center justify-between">
          <div>
            <span class="text-[10px] text-slate-400 font-bold uppercase block leading-none mb-1 font-mono">Ludo Room Code:</span>
            <span class="text-white font-mono font-black text-base tracking-wider select-all"><?= htmlspecialchars($match['roomCode'] ?? 'ROOM_412554') ?></span>
          </div>
          <button onclick="navigator.clipboard.writeText('<?= htmlspecialchars($match['roomCode'] ?? 'ROOM_412554', ENT_QUOTES) ?>');alert('রুম কোড কপি করা হয়েছে! Ludo King-এ গিয়ে জয়েন করুন。');" class="bg-emerald-500 py-1 px-3 rounded-lg text-slate-950 font-bold text-xs">কপি করুন</button>
        </div>
        <?php endif; ?>

        <!-- Action button -->
        <div class="pt-1">
          <?php if ($status === 'CLOSED' || $status === 'COMPLETED'): ?>
            <button class="w-full bg-[#1e293b] text-slate-500 border border-slate-800 font-black tracking-widest uppercase text-xs py-3 rounded-xl cursor-not-allowed"><?= $status === 'COMPLETED' ? 'COMPLETED' : 'CLOSED' ?></button>
          <?php elseif ($hasJoined): ?>
            <?php if ($status === 'FULL'): ?>
              <a href="evidence.php?id=<?= urlencode($match['id'] ?? '') ?>" class="w-full bg-gradient-to-r from-emerald-500 to-green-600 hover:from-emerald-600 hover:to-green-700 text-slate-950 font-black tracking-widest uppercase text-xs py-3 rounded-xl flex items-center justify-center gap-2 shadow-lg">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#0f172a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                UPLOAD EVIDENCE / SUBMIT WIN
              </a>
            <?php else: ?>
              <button class="w-full bg-indigo-600 text-white font-black tracking-widest uppercase text-xs py-3 rounded-xl border border-indigo-500 shadow-md">✓ JOINED (WAITING FOR COMPANIONS)</button>
            <?php endif; ?>
          <?php else: ?>
            <a href="match-detail.php?id=<?= urlencode($match['id'] ?? '') ?>" class="w-full bg-gradient-to-r from-[#22c55e] to-[#16a34a] hover:from-[#18a248] hover:to-[#128a3c] text-white font-black tracking-widest uppercase text-xs py-3 rounded-xl cursor-pointer shadow-lg active:scale-[0.98] transition-transform text-center block">JOIN MATCH</a>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<?php include 'partials/footer.php'; ?>
