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

<div class="space-y-6" style="padding:24px;text-align:center;">
  <h2 style="font-size:22px;font-weight:700;">البحث عن خصم - لودو</h2>

  <div class="card">
    <div class="card-body space-y-4" style="padding:32px;">
      <div id="mm-searching">
        <div style="width:80px;height:80px;margin:0 auto;border-radius:50%;background:linear-gradient(135deg, var(--ludo-p1), var(--ludo-p3));display:flex;align-items:center;justify-content:center;">
          <svg class="icon-lg" style="color:var(--text-1);animation:spin 2s linear infinite;"><use href="/public/icons/sprite.svg#icon-search"></use></svg>
        </div>

        <p style="font-size:18px;font-weight:600;margin-top:16px;">جاري البحث...</p>
        <p class="text-muted text-sm">نبحث عن لاعب بمستواك</p>

        <div id="mm-timer" style="font-size:24px;font-weight:700;color:var(--gold);margin-top:12px;">0:00</div>
      </div>

      <button class="btn btn-ghost btn-block" onclick="cancelSearch()">الغاء</button>
    </div>
  </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
  if (!App.isLoggedIn()) {
    window.location.href = '/login';
    return;
  }

  var token = App.token;
  var timerEl = document.getElementById('mm-timer');
  var startTime = Date.now();
  var pollInterval = null;
  var timerInterval = null;
  var cancelled = false;

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

  function poll() {
    if (cancelled) return;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/ludo', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    xhr.onload = function() {
      try {
        var data = JSON.parse(xhr.responseText);
        if (data.ok && data.status === 'matched' && data.match_id) {
          clearInterval(pollInterval);
          clearInterval(timerInterval);
          window.location.href = '/ludo-live?id=' + data.match_id;
        }
      } catch(e) {}
    };
    xhr.send(JSON.stringify({ action: 'matchmake', sub_action: 'join' }));
  }

  timerInterval = setInterval(updateTimer, 1000);
  poll();
  pollInterval = setInterval(poll, 3000);

  window.cancelSearch = function() {
    cancelled = true;
    clearInterval(pollInterval);
    clearInterval(timerInterval);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/ludo', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    xhr.onload = function() { window.location.href = '/ludo'; };
    xhr.send(JSON.stringify({ action: 'matchmake', sub_action: 'leave' }));
  };
});
</script>

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