<?php
$pageTitle = 'EL3AB - لودو اونلاين';
$extraCss = ['/public/css/ludo.css'];
$extraJs = ['/public/js/ludo-constants.js', '/public/js/ludo-ui.js', '/public/js/ludo-bot.js', '/public/js/ludo-chat.js', '/public/js/ludo-live.js'];
?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<div class="ludo-layout" id="ludo-page" style="display:none;">
  <div class="ludo-board-column">
    <div class="ludo-players-row" id="ludo-top-players"></div>

    <div class="ludo-board-wrapper">
      <div id="ludo-board"></div>
    </div>

    <div class="ludo-players-row" id="ludo-bottom-players"></div>

    <div class="ludo-mobile-panel">
      <div class="ludo-turn-indicator" id="ludo-turn-mobile"></div>
      <div id="ludo-dice-container-mobile"></div>
    </div>
  </div>

  <div class="ludo-side-panel">
    <div class="ludo-turn-indicator" id="ludo-turn"></div>
    <div id="ludo-dice-container"></div>
    <div class="ludo-log" id="ludo-log"></div>
    <div id="ludo-chat"></div>
  </div>
</div>

<!-- Waiting Room -->
<div id="ludo-waiting" class="space-y-6" style="padding:24px;text-align:center;">
  <h2 style="font-size:22px;font-weight:700;">غرفة لودو</h2>

  <div class="card" id="waiting-card">
    <div class="card-body space-y-4">
      <div id="room-code-display" style="display:none;">
        <p class="text-muted text-sm">كود الغرفة</p>
        <p id="room-code-value" style="font-size:32px;font-weight:700;letter-spacing:6px;color:var(--gold);"></p>
        <button class="btn btn-ghost btn-sm" onclick="copyRoomCode()">نسخ الكود</button>
      </div>

      <div id="waiting-players" class="space-y-2"></div>

      <div id="waiting-status">
        <div class="spinner" style="margin:0 auto;"></div>
        <p class="text-muted text-sm" style="margin-top:8px;">في انتظار اللاعبين...</p>
      </div>

      <button class="btn btn-gold btn-block" id="start-game-btn" style="display:none;" onclick="startGame()">ابدأ اللعبة</button>
      <button class="btn btn-ghost btn-block" onclick="leaveRoom()">مغادرة</button>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var params = new URLSearchParams(window.location.search);
  var action = params.get('action');
  var code = params.get('code');
  var matchId = params.get('id');

  if (!App.isLoggedIn()) {
    window.location.href = '/login';
    return;
  }

  var token = App.token;
  var userId = App.user ? App.user.id : null;

  LudoLive.setAuth(token, userId);

  if (matchId) {
    startLiveGame(matchId);
    return;
  }

  if (action === 'create') {
    LudoLive.createRoom(4, [], function(data) {
      if (data.ok) {
        showWaitingRoom(data.match, data.room_code);
        initLiveConnection(data.match.id);
      } else {
        App.toast(data.error || 'خطأ', 'error');
      }
    });
  } else if (action === 'join' && code) {
    LudoLive.joinRoom(code, function(data) {
      if (data.ok) {
        showWaitingRoom(data.match, data.match.room_code);
        initLiveConnection(data.match.id);
      } else {
        App.toast(data.error === 'room_not_found' ? 'الغرفة غير موجودة' : (data.error || 'خطأ'), 'error');
        setTimeout(function() { window.location.href = '/ludo'; }, 1500);
      }
    });
  }

  function initLiveConnection(id) {
    LudoLive.init({
      matchId: id,
      userId: userId,
      token: token
    });
  }

  function showWaitingRoom(match, roomCode) {
    var codeDisplay = document.getElementById('room-code-display');
    var codeValue = document.getElementById('room-code-value');
    codeDisplay.style.display = 'block';
    codeValue.textContent = roomCode || match.room_code || '';

    updateWaitingPlayers(match);

    if (match.host_id === userId) {
      document.getElementById('start-game-btn').style.display = 'block';
    }

    // Watch for status change
    var checkInterval = setInterval(function() {
      var st = LudoLive.getState();
      if (st.match) {
        var m = st.match;
        var status = m.status;
        updateWaitingPlayers(m);
        if (status === 'in_progress') {
          clearInterval(checkInterval);
          startLiveGame(m.id);
        }
      }
    }, 1000);
  }

  function updateWaitingPlayers(match) {
    var players = typeof match.players === 'string' ? JSON.parse(match.players) : match.players;
    var container = document.getElementById('waiting-players');
    container.innerHTML = '';
    players.forEach(function(p) {
      var el = document.createElement('div');
      el.style.cssText = 'display:flex;align-items:center;gap:8px;padding:8px;border-radius:8px;background:var(--bg-3);';
      el.innerHTML = '<div style="width:12px;height:12px;border-radius:50%;background:var(--ludo-' + p.color.toLowerCase() + ');"></div>' +
        '<span>' + p.name + '</span>' +
        '<span class="text-muted text-sm" style="margin-right:auto;">' + (p.type === 'bot' ? 'بوت' : '') + '</span>';
      container.appendChild(el);
    });
  }

  window.startGame = function() {
    LudoLive.startGame(function(data) {
      if (data.ok) {
        startLiveGame(data.match.id);
      } else {
        App.toast(data.error || 'خطأ', 'error');
      }
    });
  };

  window.startLiveGame = startLiveGame;
  function startLiveGame(id) {
    document.getElementById('ludo-waiting').style.display = 'none';
    document.getElementById('ludo-page').style.display = '';

    if (!LudoLive.getState().matchId) {
      LudoLive.init({
        matchId: id,
        userId: userId,
        token: token
      });
    }
    LudoLive.bindUI();
    LudoLive.fetchState();
  }

  window.leaveRoom = function() {
    LudoLive.leave();
    window.location.href = '/ludo';
  };

  window.copyRoomCode = function() {
    var code = document.getElementById('room-code-value').textContent;
    if (navigator.clipboard) {
      navigator.clipboard.writeText(code);
      App.toast('تم نسخ الكود', 'success');
    }
  };
});
</script>

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