<?php
require_once __DIR__ . '/functions.php';

$data    = fetchMatches();
$matches = $data['matches'] ?? [];
$isStale = !empty($data['_stale']);
$apiErr  = $data['error'] ?? null;

// LIVE -> UPCOMING -> FINISH ক্রমে সাজানো, একই গ্রুপে priority অনুযায়ী
usort($matches, function ($a, $b) {
    $wa = statusSortWeight($a['status'] ?? '');
    $wb = statusSortWeight($b['status'] ?? '');
    if ($wa !== $wb) return $wa <=> $wb;
    $pa = $a['priority'] ?? 999;
    $pb = $b['priority'] ?? 999;
    return $pa <=> $pb;
});

// ফিল্টার ট্যাবের জন্য ইউনিক স্পোর্ট লিস্ট
$sports = [];
foreach ($matches as $m) {
    $s = $m['sport'] ?? 'Other';
    $sports[$s] = true;
}
$sports = array_keys($sports);
sort($sports);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= h(SITE_NAME) ?> — Live Sports Streaming</title>
<style>
  :root{
    --bg:#0b0d12; --card:#141824; --card-hover:#1b2030; --border:#232838;
    --text:#e9ecf3; --muted:#8b93a7; --primary:#ff3d5a; --primary2:#6d5dfc;
    --live:#ff3d5a; --upcoming:#3d8bff; --finish:#5a6178;
  }
  *{box-sizing:border-box;}
  body{
    margin:0; background:var(--bg); color:var(--text);
    font-family:'Segoe UI',Roboto,Arial,sans-serif;
  }
  header.topbar{
    position:sticky; top:0; z-index:50;
    background:linear-gradient(180deg,#0b0d12 80%,rgba(11,13,18,0));
    backdrop-filter:blur(6px);
    padding:18px 20px 10px;
    display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;
  }
  .brand{display:flex; align-items:center; gap:10px; font-weight:800; font-size:22px;}
  .brand span{color:var(--primary);}
  .refresh-btn{
    background:var(--card); border:1px solid var(--border); color:var(--text);
    padding:8px 14px; border-radius:8px; cursor:pointer; font-size:13px;
  }
  .refresh-btn:hover{background:var(--card-hover);}
  .tabs{
    display:flex; gap:8px; padding:6px 20px 16px; overflow-x:auto;
  }
  .tab{
    flex:0 0 auto; padding:7px 16px; border-radius:20px; font-size:13px;
    background:var(--card); border:1px solid var(--border); color:var(--muted);
    cursor:pointer; white-space:nowrap; user-select:none;
  }
  .tab.active{background:var(--primary); color:#fff; border-color:var(--primary);}
  .stale-banner{
    margin:0 20px 10px; padding:8px 14px; background:#3a2b12; border:1px solid #6b4c1c;
    color:#ffcf8b; border-radius:8px; font-size:13px;
  }
  .grid{
    display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr));
    gap:16px; padding:6px 20px 40px;
  }
  .card{
    background:var(--card); border:1px solid var(--border); border-radius:14px;
    padding:16px; transition:.15s; display:flex; flex-direction:column; gap:12px;
  }
  .card:hover{background:var(--card-hover); transform:translateY(-2px);}
  .card-top{display:flex; justify-content:space-between; align-items:flex-start; gap:8px;}
  .comp{font-size:12px; color:var(--muted); text-transform:uppercase; letter-spacing:.03em;}
  .badge{font-size:11px; padding:3px 9px; border-radius:20px; font-weight:700; white-space:nowrap;}
  .badge-live{background:rgba(255,61,90,.15); color:var(--live); border:1px solid rgba(255,61,90,.4);}
  .badge-live::before{content:"● "; }
  .badge-upcoming{background:rgba(61,139,255,.15); color:var(--upcoming); border:1px solid rgba(61,139,255,.4);}
  .badge-finish{background:rgba(90,97,120,.2); color:var(--finish); border:1px solid rgba(90,97,120,.4);}
  .teams{display:flex; align-items:center; justify-content:space-between; gap:8px;}
  .team{display:flex; flex-direction:column; align-items:center; gap:6px; flex:1; min-width:0;}
  .team img{width:40px; height:40px; object-fit:contain; border-radius:6px; background:#0000;}
  .team span{font-size:13px; text-align:center; color:var(--text); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; max-width:100%;}
  .vs{font-size:11px; color:var(--muted); font-weight:700;}
  .title{font-size:14px; font-weight:600; text-align:center; color:var(--text);}
  .servers{display:flex; flex-wrap:wrap; gap:8px; margin-top:auto;}
  .server-btn{
    flex:1 1 auto; text-align:center; text-decoration:none;
    background:linear-gradient(135deg,var(--primary),var(--primary2));
    color:#fff; font-size:12.5px; font-weight:600; padding:9px 10px; border-radius:8px;
  }
  .server-btn:hover{filter:brightness(1.1);}
  .no-server{
    text-align:center; font-size:12.5px; color:var(--muted); padding:9px 10px;
    border:1px dashed var(--border); border-radius:8px;
  }
  .empty{text-align:center; color:var(--muted); padding:60px 20px;}
  footer.foot{text-align:center; color:var(--muted); font-size:12px; padding:20px; opacity:.6;}
</style>
</head>
<body>

<header class="topbar">
  <div class="brand"><span>e</span>PlayHD</div>
  <button class="refresh-btn" onclick="location.reload()">⟳ রিফ্রেশ</button>
</header>

<div class="tabs" id="tabs">
  <div class="tab active" data-sport="all">সব</div>
  <?php foreach ($sports as $sp): ?>
    <div class="tab" data-sport="<?= h($sp) ?>"><?= h($sp) ?></div>
  <?php endforeach; ?>
</div>

<?php if ($isStale): ?>
  <div class="stale-banner">⚠️ লাইভ সার্ভার থেকে ডাটা আনতে সমস্যা হয়েছে, পুরনো ক্যাশড তথ্য দেখানো হচ্ছে।</div>
<?php elseif ($apiErr): ?>
  <div class="stale-banner">⚠️ ম্যাচ তালিকা লোড করা যায়নি: <?= h($apiErr) ?></div>
<?php endif; ?>

<?php if (empty($matches)): ?>
  <div class="empty">এই মুহূর্তে কোনো ম্যাচ পাওয়া যায়নি।</div>
<?php else: ?>
  <div class="grid" id="grid">
    <?php foreach ($matches as $m):
        $status = $m['status'] ?? 'UPCOMING';
        $isTeamMatch = ($m['homeTeam'] ?? '') !== ($m['awayTeam'] ?? '');
        $servers = $m['servers'] ?? [];
    ?>
    <div class="card" data-sport="<?= h($m['sport'] ?? '') ?>">
      <div class="card-top">
        <div class="comp"><?= h($m['competition'] ?? $m['sport'] ?? '') ?></div>
        <div class="badge <?= statusBadgeClass($status) ?>"><?= h($status) ?></div>
      </div>

      <?php if ($isTeamMatch): ?>
      <div class="teams">
        <div class="team">
          <img src="<?= h($m['homeLogo'] ?? '') ?>" alt="" loading="lazy" onerror="this.style.visibility='hidden'">
          <span><?= h($m['homeTeam'] ?? '') ?></span>
        </div>
        <div class="vs">VS</div>
        <div class="team">
          <img src="<?= h($m['awayLogo'] ?? '') ?>" alt="" loading="lazy" onerror="this.style.visibility='hidden'">
          <span><?= h($m['awayTeam'] ?? '') ?></span>
        </div>
      </div>
      <?php else: ?>
      <div class="title"><?= h($m['title'] ?? '') ?></div>
      <?php endif; ?>

      <div class="servers">
        <?php if (!empty($servers)): ?>
          <?php foreach ($servers as $s): ?>
            <a class="server-btn"
               href="player.php?m=<?= urlencode($m['id']) ?>&s=<?= urlencode($s['id']) ?>"
               target="_blank" rel="noopener">
              ▶ <?= h($s['name'] ?? 'Server') ?>
            </a>
          <?php endforeach; ?>
        <?php else: ?>
          <div class="no-server">কোনো সার্ভার নেই</div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<footer class="foot">&copy; <?= date('Y') ?> <?= h(SITE_NAME) ?></footer>

<script>
  // Sport ফিল্টার ট্যাব (কোনো পেজ রিলোড ছাড়াই)
  document.getElementById('tabs').addEventListener('click', function(e){
    const tab = e.target.closest('.tab');
    if(!tab) return;
    document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
    tab.classList.add('active');
    const sport = tab.dataset.sport;
    document.querySelectorAll('#grid .card').forEach(card=>{
      card.style.display = (sport === 'all' || card.dataset.sport === sport) ? '' : 'none';
    });
  });

  // প্রতি ৬০ সেকেন্ডে হোমপেজ অটো-রিফ্রেশ (LIVE স্ট্যাটাস আপডেট রাখার জন্য)
  setTimeout(()=>location.reload(), 60000);
</script>
</body>
</html>
