<?php $pageTitle = 'EL3AB - البحث عن خصم'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<div class="lobby-page" style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;text-align:center;">
  <div class="matchmaking-spinner">
    <svg class="icon-lg" style="color:var(--gold);width:48px;height:48px;animation:spin 2s linear infinite;">
      <use href="/public/icons/sprite.svg#icon-search"></use>
    </svg>
  </div>
  <h2 style="margin-top:20px;color:var(--text-1);">جاري البحث عن خصم...</h2>
  <p class="text-muted" id="matchmaking-status">يتم البحث عن لاعبين مناسبين</p>
  <p class="text-muted text-sm" id="matchmaking-timer" style="margin-top:8px;"></p>
  <button class="btn btn-ghost" style="margin-top:24px;" onclick="cancelMatchmaking()">إلغاء</button>
</div>

<style>
@keyframes spin { to { transform: rotate(360deg); } }
</style>

<script>
(function() {
  var params = new URLSearchParams(window.location.search);
  var mode = params.get('mode') || '2p';
  var pollInterval = null;
  var startTime = Date.now();

  function updateTimer() {
    var elapsed = Math.floor((Date.now() - startTime) / 1000);
    var mins = Math.floor(elapsed / 60);
    var secs = elapsed % 60;
    document.getElementById('matchmaking-timer').textContent = (mins > 0 ? mins + ':' : '') + (secs < 10 ? '0' : '') + secs;
  }

  function pollMatchmaking() {
    App.fetch('/api/domino.php', {
      method: 'POST',
      body: JSON.stringify({ action: 'matchmake', sub_action: 'join', mode: mode })
    }).then(function(res) {
      if (res.status === 'matched' && res.match_id) {
        clearInterval(pollInterval);
        document.getElementById('matchmaking-status').textContent = 'تم العثور على خصم!';
        setTimeout(function() {
          window.location.href = '/domino-live?match_id=' + res.match_id;
        }, 1000);
      }
    }).catch(function() {});
  }

  pollInterval = setInterval(function() {
    updateTimer();
    pollMatchmaking();
  }, 3000);

  updateTimer();
  pollMatchmaking();

  window.cancelMatchmaking = function() {
    clearInterval(pollInterval);
    App.fetch('/api/domino.php', {
      method: 'POST',
      body: JSON.stringify({ action: 'matchmake', sub_action: 'leave', mode: mode })
    }).then(function() {
      window.location.href = '/domino';
    });
  };
})();
</script>

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