<?php $pageTitle = 'EL3AB - طاولة'; $hideNav = true; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<link rel="stylesheet" href="/public/css/backgammon.css">

<div class="lobby-page" style="max-width:500px;margin:0 auto;padding:24px;text-align:center;">
  <h2 class="lobby-title" style="margin-bottom:8px;">طاولة</h2>
  <p class="text-muted text-sm" style="margin-bottom:32px;">البحث عن خصم...</p>

  <div class="card" style="padding:32px;">
    <div class="matchmaking-spinner"></div>
    <p id="bg-mm-timer" style="font-size:1.5rem;margin-top:16px;font-weight:700;">0:00</p>
    <p class="text-muted text-sm" style="margin-top:8px;">في الانتظار</p>
  </div>

  <button class="btn btn-outline btn-block" style="margin-top:24px;" onclick="cancelMatchmaking()">
    إلغاء
  </button>
</div>

<script>
(function() {
  var token = localStorage.getItem('el3ab_token');
  var user = JSON.parse(localStorage.getItem('el3ab_user') || 'null');
  if (!token || !user) { window.location.href = '/login'; return; }

  var startTime = Date.now();
  var timerEl = document.getElementById('bg-mm-timer');
  var polling = null;
  var cancelled = false;

  function updateTimer() {
    var elapsed = Math.floor((Date.now() - startTime) / 1000);
    var m = Math.floor(elapsed / 60);
    var s = elapsed % 60;
    timerEl.textContent = m + ':' + (s < 10 ? '0' : '') + s;
  }

  setInterval(updateTimer, 1000);

  function joinQueue() {
    fetch('/api/backgammon.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
      body: JSON.stringify({ action: 'matchmake', sub_action: 'join' })
    }).then(function(r) { return r.json(); }).then(function(data) {
      if (data.match_id) {
        window.location.href = '/backgammon-live?match_id=' + data.match_id;
      } else {
        polling = setInterval(pollQueue, 3000);
      }
    });
  }

  function pollQueue() {
    if (cancelled) return;
    fetch('/api/backgammon.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
      body: JSON.stringify({ action: 'matchmake', sub_action: 'poll' })
    }).then(function(r) { return r.json(); }).then(function(data) {
      if (data.match_id) {
        clearInterval(polling);
        window.location.href = '/backgammon-live?match_id=' + data.match_id;
      }
    });
  }

  window.cancelMatchmaking = function() {
    cancelled = true;
    if (polling) clearInterval(polling);
    fetch('/api/backgammon.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
      body: JSON.stringify({ action: 'matchmake', sub_action: 'leave' })
    }).then(function() {
      window.location.href = '/backgammon';
    });
  };

  joinQueue();
})();
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>
