<%- include('partials/header', { title: 'Devices', heading: 'WhatsApp Devices', active: '/devices' }) %>

<div class="mb-6 flex gap-2">
  <input id="deviceLabel" placeholder="Device label (e.g. Marketing)"
         class="rounded-lg border border-slate-300 px-3 py-2 text-sm w-64" />
  <button onclick="createDevice()" class="bg-emerald-600 hover:bg-emerald-700 text-white text-sm px-4 py-2 rounded-lg">+ Add device</button>
</div>

<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  <% devices.forEach((d) => { %>
    <div class="bg-white rounded-2xl shadow p-5" data-session="<%= d.session_key %>">
      <div class="flex justify-between items-start">
        <div>
          <p class="font-semibold"><%= d.label %></p>
          <p class="text-sm text-slate-500 phone"><%= d.phone_number || 'Not linked' %></p>
        </div>
        <span class="status text-xs px-2 py-1 rounded-full bg-slate-100 text-slate-600"><%= d.status %></span>
      </div>

      <div class="qr-box mt-4 hidden text-center">
        <img class="qr mx-auto w-48 h-48" alt="QR code" />
        <p class="text-xs text-slate-500 mt-2">Open WhatsApp → Linked devices → Link a device</p>
      </div>

      <div class="mt-4 flex gap-2 text-sm">
        <button onclick="connectDevice(<%= d.id %>, '<%= d.session_key %>')" class="px-3 py-1.5 rounded-lg bg-emerald-600 text-white">Connect</button>
        <button onclick="logoutDevice(<%= d.id %>)" class="px-3 py-1.5 rounded-lg bg-amber-500 text-white">Logout</button>
        <button onclick="removeDevice(<%= d.id %>)" class="px-3 py-1.5 rounded-lg bg-rose-500 text-white">Delete</button>
      </div>
    </div>
  <% }); %>
</div>

<script>
  const socket = io();

  function cardFor(sessionKey) {
    return document.querySelector(`[data-session="${sessionKey}"]`);
  }

  async function createDevice() {
    const label = document.getElementById('deviceLabel').value || 'Device';
    await fetch('/devices', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ label }) });
    location.reload();
  }

  async function connectDevice(id, sessionKey) {
    socket.emit('subscribe:session', sessionKey);
    await fetch(`/devices/${id}/connect`, { method: 'POST' });
  }

  async function logoutDevice(id) {
    if (!confirm('Unlink this device?')) return;
    await fetch(`/devices/${id}/logout`, { method: 'POST' });
    location.reload();
  }

  async function removeDevice(id) {
    if (!confirm('Delete this device permanently?')) return;
    await fetch(`/devices/${id}`, { method: 'DELETE' });
    location.reload();
  }

  // Live QR + status updates pushed from the server
  socket.on('qr', ({ qr }) => {
    document.querySelectorAll('[data-session]').forEach((card) => {
      const box = card.querySelector('.qr-box');
      const img = card.querySelector('.qr');
      // The server emits into the per-session room, so any visible box belongs here
      box.classList.remove('hidden');
      img.src = qr;
    });
  });

  socket.on('status', ({ status, phone }) => {
    document.querySelectorAll('[data-session]').forEach((card) => {
      const badge = card.querySelector('.status');
      badge.textContent = status;
      if (status === 'connected') {
        card.querySelector('.qr-box').classList.add('hidden');
        if (phone) card.querySelector('.phone').textContent = phone;
      }
    });
  });
</script>

<%- include('partials/footer') %>
