<!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-3">Room <span id="code">{{ code }}</span></h1>
  <div id="info" class="opacity-80 mb-3"></div>
  <button id="start" class="bg-emerald-500 px-4 py-2 rounded mb-4">Start Match</button>

  <div class="relative h-40 rounded bg-slate-800 overflow-hidden">
    <div class="absolute inset-y-0 left-1/2 w-0.5 bg-slate-600"></div>
    <div id="puck" class="absolute top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-white shadow"></div>
    <div class="absolute inset-y-0 left-0 w-1 bg-red-500"></div>
    <div class="absolute inset-y-0 right-0 w-1 bg-blue-500"></div>
  </div>
  <p id="status" class="mt-3 text-lg"></p>

<script>
const code = "{{ code }}";
const socket = io("/game", { transports: ["websocket"] });
socket.emit("host_subscribe", { code });

document.getElementById("start").onclick = () => socket.emit("start_match", { code });

socket.on("room_state", ({exists, left, right, running, puck}) => {
  if(!exists) return;
  document.getElementById("info").textContent = `Left: ${left ?? "-"} | Right: ${right ?? "-"} | ${running ? "LIVE" : "Idle"}`;
  if(typeof puck === "number") updatePuck(puck);
});

socket.on("state", ({code: c, puck}) => {
  if(c !== code) return;
  updatePuck(puck);
});
socket.on("match_end", ({code: c, winner}) => {
  if(c !== code) return;
  document.getElementById("status").textContent = winner.toUpperCase() + " WINS!";
});

function updatePuck(p) {
  const box = document.querySelector(".relative.h-40");
  const puckEl = document.getElementById("puck");
  const w = box.clientWidth;
  const x = (p / 100) * (w/2 - 10);
  puckEl.style.left = `calc(50% + ${x}px)`;
}
</script>
</body>
</html>

