<?php $pageTitle = 'EL3AB - العب'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<style>
.tc-categories {
  display: flex;
  gap: 4px;
  margin-bottom: 8px;
}
.tc-cat {
  flex: 1;
  padding: 6px 4px;
  font-size: 11px;
  font-weight: 600;
  border: 1px solid var(--border);
  border-radius: var(--radius-sm);
  background: var(--bg-3);
  color: var(--text-2);
  cursor: pointer;
  text-align: center;
  transition: all 0.15s;
}
.tc-cat.active {
  background: var(--gold);
  color: var(--text-inverse);
  border-color: var(--gold);
}
.tc-cat:hover:not(.active) {
  background: var(--bg-2);
}
.tc-options {
  flex-wrap: wrap;
}
</style>

<div class="lobby-page">

  <a href="/games" class="breadcrumb">
    <svg class="icon" style="width:14px;height:14px;"><use href="/public/icons/sprite.svg#icon-arrow-right"></use></svg>
    العاب
  </a>

  <div class="text-center" style="margin-top:16px;">
    <h2 class="lobby-title">العب شطرنج</h2>
    <p class="text-muted text-sm">اختر نوع المباراة</p>
  </div>

  <div class="lobby-cards">

    <!-- VS Human - MULTIPLAYER -->
    <div class="card lobby-card lobby-card--featured">
      <div class="card-body space-y-4">
        <div class="lobby-card-header">
          <div class="avatar avatar-game" style="background:linear-gradient(135deg, var(--gold), var(--cyan));">
            <svg class="icon-lg" style="color:var(--text-1)"><use href="/public/icons/sprite.svg#icon-sword"></use></svg>
          </div>
          <div>
            <p class="lobby-card-title">ضد لاعب حقيقي</p>
            <p class="text-muted text-sm">ابحث عن خصم بمستواك</p>
          </div>
        </div>

        <!-- Time Control Categories -->
        <div class="tc-categories" id="mp-tc-categories">
          <button class="tc-cat active" data-cat="bullet">⚡ Bullet</button>
          <button class="tc-cat" data-cat="blitz">🔥 Blitz</button>
          <button class="tc-cat" data-cat="rapid">⏱ Rapid</button>
          <button class="tc-cat" data-cat="classical">♟ Classical</button>
        </div>
        <div class="tab-group tc-options" id="mp-time-tabs">
          <button class="tab" data-tc="bullet_1_0" data-time="60000" data-inc="0">1+0</button>
          <button class="tab active" data-tc="bullet_1_1" data-time="60000" data-inc="1000">1+1</button>
          <button class="tab" data-tc="bullet_2_1" data-time="120000" data-inc="1000">2+1</button>
        </div>

        <button class="btn btn-gold btn-block btn-lg" onclick="startMultiplayer()">
          <svg class="icon"><use href="/public/icons/sprite.svg#icon-search"></use></svg>
          ابحث عن خصم
        </button>
      </div>
    </div>

    <!-- VS Bot -->
    <a href="/bots" class="card lobby-card card-hover" style="display:block;text-decoration:none;">
      <div class="card-body lobby-card-row">
        <div class="avatar avatar-game" style="background:var(--bg-3);">
          <svg class="icon-lg" style="color:var(--cyan)"><use href="/public/icons/sprite.svg#icon-bot"></use></svg>
        </div>
        <div style="flex:1;">
          <p class="lobby-card-title-sm">ضد البوت</p>
          <p class="text-muted text-sm">7 مستويات مختلفة</p>
        </div>
        <svg class="icon" style="color:var(--text-3);transform:scaleX(-1)"><use href="/public/icons/sprite.svg#icon-arrow-right"></use></svg>
      </div>
    </a>

    <!-- Quick Match vs Bot -->
    <div class="card lobby-card card-hover" style="cursor:pointer;" onclick="startQuickMatch()">
      <div class="card-body lobby-card-row">
        <div class="avatar avatar-game" style="background:var(--bg-3);">
          <svg class="icon-lg" style="color:var(--gold)"><use href="/public/icons/sprite.svg#icon-bot"></use></svg>
        </div>
        <div style="flex:1;">
          <p class="lobby-card-title-sm">مباراة سريعة ضد بوت</p>
          <p class="text-muted text-sm">5 دقائق ضد بوت عشوائي</p>
        </div>
        <svg class="icon" style="color:var(--text-3);transform:scaleX(-1)"><use href="/public/icons/sprite.svg#icon-arrow-right"></use></svg>
      </div>
    </div>

    <!-- Custom Game -->
    <div class="card lobby-card">
      <div class="card-body space-y-5">
        <p class="lobby-card-title-sm" style="text-align:center;">مباراة مخصصة</p>

        <!-- Time Control -->
        <div>
          <label class="input-label">التوقيت</label>
          <div class="tc-categories" id="custom-tc-categories">
            <button class="tc-cat active" data-cat="bullet">⚡ Bullet</button>
            <button class="tc-cat" data-cat="blitz">🔥 Blitz</button>
            <button class="tc-cat" data-cat="rapid">⏱ Rapid</button>
            <button class="tc-cat" data-cat="classical">♟ Classical</button>
          </div>
          <div class="tab-group tc-options" id="time-tabs">
            <button class="tab" data-time="60" data-inc="0">1+0</button>
            <button class="tab active" data-time="60" data-inc="1">1+1</button>
            <button class="tab" data-time="120" data-inc="1">2+1</button>
          </div>
        </div>

        <!-- Color -->
        <div>
          <label class="input-label">اللون</label>
          <div class="tab-group" id="color-tabs">
            <button class="tab active" data-color="w">ابيض</button>
            <button class="tab" data-color="b">اسود</button>
            <button class="tab" data-color="random">عشوائي</button>
          </div>
        </div>

        <!-- Bot Selection -->
        <div>
          <label class="input-label">الخصم</label>
          <select class="input" id="bot-select" style="direction:ltr;">
            <option value="nour">جاري التحميل...</option>
          </select>
        </div>

        <!-- Note: Bot games are never rated -->
        <p class="text-muted text-sm" style="text-align:center;">مباراة تدريبية (غير مصنفة)</p>

        <button class="btn btn-gold btn-block btn-lg" onclick="startCustomGame()">
          <svg class="icon"><use href="/public/icons/sprite.svg#icon-play"></use></svg>
          ابدأ المباراة
        </button>
      </div>
    </div>

  </div>
</div>

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

  document.querySelectorAll('.tab-group').forEach(group => {
    group.querySelectorAll('.tab').forEach(tab => {
      tab.addEventListener('click', () => {
        group.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        tab.classList.add('active');
      });
    });
  });

  // Load bots from API
  try {
    const data = await App.cachedFetch('/api/bots.php', 60000);
    if (data && data.bots) {
      const select = document.getElementById('bot-select');
      select.innerHTML = data.bots.map(bot => {
        const avgElo = Math.round((bot.elo_min + bot.elo_max) / 2);
        const selected = bot.id === 'nour' ? ' selected' : '';
        return '<option value="' + bot.id + '"' + selected + '>' + bot.name + ' (' + avgElo + ')</option>';
      }).join('');
      window._botsData = data.bots;
    }
  } catch (e) {}
});

function getSelectedTime() {
  const active = document.querySelector('#time-tabs .tab.active');
  return { time: active.dataset.time, inc: active.dataset.inc };
}

function getSelectedColor() {
  const active = document.querySelector('#color-tabs .tab.active');
  let color = active.dataset.color;
  if (color === 'random') color = Math.random() < 0.5 ? 'w' : 'b';
  return color;
}

function startMultiplayer() {
  const active = document.querySelector('#mp-time-tabs .tab.active');
  const tc = active.dataset.tc;
  const time = active.dataset.time;
  const inc = active.dataset.inc;
  window.location.href = '/matchmaking?tc=' + tc + '&time=' + time + '&inc=' + inc;
}

function startQuickMatch() {
  const bots = window._botsData
    ? window._botsData.filter(b => b.id !== 'grandmaster').map(b => b.id)
    : ['nour'];
  const bot = bots[Math.floor(Math.random() * bots.length)];
  const color = Math.random() < 0.5 ? 'w' : 'b';
  window.location.href = '/game?bot=' + bot + '&color=' + color + '&time=300&inc=0&rated=false';
}

function startCustomGame() {
  const { time, inc } = getSelectedTime();
  const color = getSelectedColor();
  const bot = document.getElementById('bot-select').value;
  window.location.href = '/game?bot=' + bot + '&color=' + color + '&time=' + time + '&inc=' + inc + '&rated=false';
}

// Time control category switching
const TC_OPTIONS = {
  bullet: [
    { time: '60', inc: '0', label: '1+0', tc: 'bullet_1_0', timeMs: '60000', incMs: '0' },
    { time: '60', inc: '1', label: '1+1', tc: 'bullet_1_1', timeMs: '60000', incMs: '1000' },
    { time: '120', inc: '1', label: '2+1', tc: 'bullet_2_1', timeMs: '120000', incMs: '1000' }
  ],
  blitz: [
    { time: '180', inc: '0', label: '3+0', tc: 'blitz_3_0', timeMs: '180000', incMs: '0' },
    { time: '180', inc: '2', label: '3+2', tc: 'blitz_3_2', timeMs: '180000', incMs: '2000' },
    { time: '300', inc: '0', label: '5+0', tc: 'blitz_5_0', timeMs: '300000', incMs: '0' },
    { time: '300', inc: '3', label: '5+3', tc: 'blitz_5_3', timeMs: '300000', incMs: '3000' }
  ],
  rapid: [
    { time: '600', inc: '0', label: '10+0', tc: 'rapid_10_0', timeMs: '600000', incMs: '0' },
    { time: '600', inc: '5', label: '10+5', tc: 'rapid_10_5', timeMs: '600000', incMs: '5000' },
    { time: '900', inc: '10', label: '15+10', tc: 'rapid_15_10', timeMs: '900000', incMs: '10000' },
    { time: '1200', inc: '0', label: '20+0', tc: 'rapid_20_0', timeMs: '1200000', incMs: '0' }
  ],
  classical: [
    { time: '1800', inc: '0', label: '30+0', tc: 'classical_30_0', timeMs: '1800000', incMs: '0' },
    { time: '1800', inc: '20', label: '30+20', tc: 'classical_30_20', timeMs: '1800000', incMs: '20000' },
    { time: '2700', inc: '0', label: '45+0', tc: 'classical_45_0', timeMs: '2700000', incMs: '0' },
    { time: '3600', inc: '0', label: '60+0', tc: 'classical_60_0', timeMs: '3600000', incMs: '0' }
  ]
};

function setupTcCategories(catContainerId, tabContainerId, isMultiplayer) {
  const catContainer = document.getElementById(catContainerId);
  const tabContainer = document.getElementById(tabContainerId);
  if (!catContainer || !tabContainer) return;

  catContainer.querySelectorAll('.tc-cat').forEach(function(cat) {
    cat.addEventListener('click', function() {
      catContainer.querySelectorAll('.tc-cat').forEach(function(c) { c.classList.remove('active'); });
      cat.classList.add('active');
      var category = cat.dataset.cat;
      var options = TC_OPTIONS[category];
      var html = '';
      options.forEach(function(opt, i) {
        var cls = i === 0 ? ' active' : '';
        if (isMultiplayer) {
          html += '<button class="tab' + cls + '" data-tc="' + opt.tc + '" data-time="' + opt.timeMs + '" data-inc="' + opt.incMs + '">' + opt.label + '</button>';
        } else {
          html += '<button class="tab' + cls + '" data-time="' + opt.time + '" data-inc="' + opt.inc + '">' + opt.label + '</button>';
        }
      });
      tabContainer.innerHTML = html;
      // Rebind tab clicks
      tabContainer.querySelectorAll('.tab').forEach(function(tab) {
        tab.addEventListener('click', function() {
          tabContainer.querySelectorAll('.tab').forEach(function(t) { t.classList.remove('active'); });
          tab.classList.add('active');
        });
      });
    });
  });
}

setupTcCategories('mp-tc-categories', 'mp-time-tabs', true);
setupTcCategories('custom-tc-categories', 'time-tabs', false);
</script>

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