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

<div class="matchmaking-page" id="matchmaking-page">

  <!-- Searching state -->
  <div class="mm-searching" id="mm-searching">
    <div class="mm-animation">
      <div class="mm-ring"></div>
      <div class="mm-ring mm-ring-2"></div>
      <svg class="mm-icon"><use href="/public/icons/sprite.svg#icon-sword"></use></svg>
    </div>

    <h2 class="mm-title">جاري البحث عن خصم...</h2>
    <p class="mm-subtitle" id="mm-time-label">بلتز 5 دقائق</p>

    <div class="mm-stats">
      <div class="mm-stat">
        <span class="mm-stat-label">الوقت</span>
        <span class="mm-stat-value" id="mm-wait-time">0:00</span>
      </div>
      <div class="mm-stat">
        <span class="mm-stat-label">التصنيف</span>
        <span class="mm-stat-value" id="mm-rating">1200</span>
      </div>
      <div class="mm-stat">
        <span class="mm-stat-label">النطاق</span>
        <span class="mm-stat-value" id="mm-range">+/- 200</span>
      </div>
    </div>

    <button class="btn btn-ghost btn-block" id="btn-cancel-search" onclick="Matchmaking.cancel()">
      <svg class="icon"><use href="/public/icons/sprite.svg#icon-x"></use></svg>
      الغاء البحث
    </button>
  </div>

  <!-- Found state -->
  <div class="mm-found" id="mm-found" style="display:none;">
    <div class="mm-found-animation">
      <svg class="mm-found-icon"><use href="/public/icons/sprite.svg#icon-check"></use></svg>
    </div>
    <h2 class="mm-title">تم ايجاد خصم!</h2>
    <p class="mm-subtitle">جاري تحضير المباراة...</p>
  </div>

</div>

<style>
.matchmaking-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  text-align: center;
  padding: 24px;
}

.mm-searching {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  width: 100%;
  max-width: 360px;
}

.mm-animation {
  position: relative;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mm-ring {
  position: absolute;
  inset: 0;
  border: 3px solid transparent;
  border-top-color: var(--cyan);
  border-radius: 50%;
  animation: mm-spin 1.5s linear infinite;
}

.mm-ring-2 {
  inset: 10px;
  border-top-color: var(--gold);
  animation-direction: reverse;
  animation-duration: 2s;
}

@keyframes mm-spin {
  to { transform: rotate(360deg); }
}

.mm-icon {
  width: 40px;
  height: 40px;
  color: var(--gold);
}

.mm-title {
  font-size: 20px;
  font-weight: 700;
}

.mm-subtitle {
  font-size: 14px;
  color: var(--text-2);
  margin-top: -12px;
}

.mm-stats {
  display: flex;
  gap: 16px;
  width: 100%;
  justify-content: center;
}

.mm-stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  background: var(--bg-2);
  border: 1px solid var(--border);
  border-radius: var(--radius-md);
  padding: 12px 16px;
  min-width: 80px;
}

.mm-stat-label {
  font-size: 11px;
  color: var(--text-3);
}

.mm-stat-value {
  font-size: 16px;
  font-weight: 700;
  font-family: var(--font-en);
}

/* Found state */
.mm-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.mm-found-animation {
  width: 80px;
  height: 80px;
  background: var(--success);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: mm-pop 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes mm-pop {
  from { transform: scale(0); }
  to { transform: scale(1); }
}

.mm-found-icon {
  width: 40px;
  height: 40px;
  color: var(--text-1);
}
</style>

<script>
const Matchmaking = {
  queueId: null,
  pollInterval: null,
  waitStart: null,
  waitInterval: null,
  timeControl: 'blitz_5_0',
  initialTime: 300000,
  increment: 0,

  init() {
    const params = new URLSearchParams(window.location.search);
    this.timeControl = params.get('tc') || 'blitz_5_0';
    this.initialTime = parseInt(params.get('time') || '300000');
    this.increment = parseInt(params.get('inc') || '0');

    const tcLabels = {
      'bullet_1_0': 'بوليت 1 دقيقة',
      'bullet_1_1': 'بوليت 1|1',
      'bullet_2_1': 'بوليت 2|1',
      'blitz_3_0': 'بلتز 3 دقائق',
      'blitz_3_2': 'بلتز 3|2',
      'blitz_5_0': 'بلتز 5 دقائق',
      'blitz_5_3': 'بلتز 5|3',
      'rapid_10_0': 'سريع 10 دقائق',
      'rapid_10_5': 'سريع 10|5',
      'rapid_15_10': 'سريع 15|10',
      'rapid_30_0': 'كلاسيكي 30 دقيقة',
    };
    document.getElementById('mm-time-label').textContent = tcLabels[this.timeControl] || this.timeControl;

    this.joinQueue();
  },

  async joinQueue() {
    this.waitStart = Date.now();
    this.startWaitTimer();

    const res = await App.fetch('/api/matchmaking', {
      method: 'POST',
      body: JSON.stringify({
        action: 'join',
        time_control: this.timeControl,
        initial_time_ms: this.initialTime,
        increment_ms: this.increment,
        is_rated: true
      })
    });

    if (res && res.queue_id) {
      this.queueId = res.queue_id;

      if (res.rating) {
        document.getElementById('mm-rating').textContent = res.rating;
      }

      if (res.matched) {
        this.onMatched(res.match_id);
      } else {
        this.startPolling();
      }
    } else if (res && res.match_id) {
      this.onMatched(res.match_id);
    } else {
      App.toast('خطأ في الاتصال', 'error');
      setTimeout(() => window.location.href = '/play', 2000);
    }
  },

  startPolling() {
    this.pollInterval = setInterval(async () => {
      const res = await App.fetch('/api/matchmaking', {
        method: 'POST',
        body: JSON.stringify({
          action: 'status',
          queue_id: this.queueId
        })
      });

      if (res && res.status === 'matched' && res.match_id) {
        this.onMatched(res.match_id);
      }
    }, 2000);
  },

  startWaitTimer() {
    const el = document.getElementById('mm-wait-time');
    this.waitInterval = setInterval(() => {
      const elapsed = Math.floor((Date.now() - this.waitStart) / 1000);
      const mins = Math.floor(elapsed / 60);
      const secs = elapsed % 60;
      el.textContent = mins + ':' + secs.toString().padStart(2, '0');

      // Expand range display after time
      const range = 200 + Math.floor(elapsed / 10) * 50;
      document.getElementById('mm-range').textContent = '+/- ' + Math.min(range, 600);
    }, 1000);
  },

  onMatched(matchId) {
    this.stopPolling();
    document.getElementById('mm-searching').style.display = 'none';
    document.getElementById('mm-found').style.display = 'flex';

    setTimeout(() => {
      window.location.href = '/game-live?id=' + matchId;
    }, 1500);
  },

  async cancel() {
    this.stopPolling();

    if (this.queueId) {
      await App.fetch('/api/matchmaking', {
        method: 'POST',
        body: JSON.stringify({
          action: 'leave',
          queue_id: this.queueId
        })
      });
    }

    window.location.href = '/play';
  },

  stopPolling() {
    if (this.pollInterval) clearInterval(this.pollInterval);
    if (this.waitInterval) clearInterval(this.waitInterval);
    this.pollInterval = null;
    this.waitInterval = null;
  }
};

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

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