<!doctype html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
</head>
<body class="bg-slate-900 text-white p-6">
  <h1 class="text-2xl font-bold mb-4">Lobby</h1>
  <div class="grid md:grid-cols-2 gap-6">
    <div>
      <h2 class="font-semibold mb-2">Waiting Players</h2>
      <ul id="waiting" class="space-y-2"></ul>
    </div>
    <div>
      <h2 class="font-semibold mb-2">Create Room</h2>
      <div class="flex gap-2 items-center mb-3">
        <input id="code" class="text-black p-2 rounded" placeholder="Room code (e.g., 4321)">
        <input id="left" class="text-black p-2 rounded" placeholder="Left PID">
        <input id="right" class="text-black p-2 rounded" placeholder="Right PID">
        <button id="create" class="bg-emerald-500 px-3 py-2 rounded">Assign</button>
      </div>
      <h2 class="font-semibold mb-2">Rooms</h2>
      <ul id="rooms" class="space-y-2"></ul>
    </div>
  </div>

<script>
const socket = io("/game");
socket.emit("lobby_subscribe");

const waitingEl = document.getElementById("waiting");
const roomsEl   = document.getElementById("rooms");

socket.on("waiting_list", ({players}) => {
  waitingEl.innerHTML = "";
  players.forEach(pid => {
    const li = document.createElement("li");
    li.className = "bg-slate-800 rounded px-3 py-2 cursor-pointer";
    li.textContent = pid;
    li.onclick = () => {
      const left = document.getElementById("left");
      const right = document.getElementById("right");
      if(!left.value) left.value = pid;
      else if(!right.value) right.value = pid;
      else left.value = pid;
    };
    waitingEl.appendChild(li);
  });
});

socket.on("rooms_list", ({rooms}) => {
  roomsEl.innerHTML = "";
  Object.entries(rooms).forEach(([code, info]) => {
    const li = document.createElement("li");
    li.className = "bg-slate-800 rounded px-3 py-2 flex justify-between";
    li.innerHTML = `<div><b>${code}</b> — L:${info.left ?? "-"} R:${info.right ?? "-"} ${info.running ? "🟢" : "⚪"}</div>
      <a class="underline" href="/host/${code}" target="_blank">Open Host</a>`;
    roomsEl.appendChild(li);
  });
});

document.getElementById("create").onclick = () => {
  const code  = document.getElementById("code").value.trim() || (Math.random()*1e4|0).toString().padStart(4,"0");
  const left  = document.getElementById("left").value.trim();
  const right = document.getElementById("right").value.trim();
  if(!left || !right) return alert("Pick two players.");
  socket.emit("assign_to_room", { code, left, right });
  document.getElementById("code").value = "";
  document.getElementById("left").value = "";
  document.getElementById("right").value = "";
};
</script>
</body>
</html>

