<section class="section">
  <div class="section-header">
    <p class="eyebrow">Admin</p>
    <h1>Local gateways - <%= event.title %></h1>
  </div>
  <form class="filters" onsubmit="return registerGateway(event)">
    <input name="name" placeholder="Nume gateway" required>
    <button>Genereaza gateway token</button>
  </form>
  <div id="gateway-token" class="notice" hidden></div>
</section>

<section class="section">
  <div class="table-wrap">
    <table>
      <thead><tr><th>Gateway</th><th>Cod</th><th>Status</th><th>Last seen</th><th>Last sync</th><th>Actiuni</th></tr></thead>
      <tbody>
        <% gateways.forEach((gateway) => { %>
          <tr>
            <td><%= gateway.name %></td><td><%= gateway.gateway_code %></td><td><%= gateway.status %></td><td><%= gateway.last_seen_at || '-' %></td><td><%= gateway.last_sync_at || '-' %></td>
            <td>
              <form method="post" action="/admin/events/<%= event.id %>/local-gateways/<%= gateway.id %>/status">
                <%- include('../partials/csrf-field') %>
                <select name="status"><option value="active">active</option><option value="suspended">suspended</option><option value="revoked">revoked</option></select>
                <button>Seteaza</button>
              </form>
            </td>
          </tr>
        <% }) %>
      </tbody>
    </table>
  </div>
</section>

<section class="section">
  <div class="section-header"><h2>Device-uri</h2></div>
  <div class="table-wrap"><table><thead><tr><th>Device</th><th>Rol</th><th>Gateway</th><th>Status</th><th>Last seen</th></tr></thead><tbody>
    <% devices.forEach((device) => { %><tr><td><%= device.device_name %></td><td><%= device.role %></td><td><%= device.gateway_id || '-' %></td><td><%= device.status %></td><td><%= device.last_seen_at || '-' %></td></tr><% }) %>
  </tbody></table></div>
</section>

<section class="section">
  <div class="section-header"><h2>Sync recent si conflicte</h2></div>
  <div class="cards-grid">
    <article class="card"><h3>Sync batches</h3><p><%= batches.length %> in istoric</p></article>
    <article class="card"><h3>Conflicte</h3><p><%= conflicts.length %> necesita review</p></article>
  </div>
</section>

<script>
async function registerGateway(event) {
  event.preventDefault();
  const form = event.target;
  const response = await fetch('/admin/events/<%= event.id %>/local-gateways/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'x-csrf-token': '<%= csrfToken %>' },
    body: JSON.stringify({ event_id: '<%= event.id %>', name: form.name.value })
  });
  const data = await response.json();
  const box = document.getElementById('gateway-token');
  box.hidden = false;
  box.textContent = data.ok ? `Gateway ${data.gateway_code}; token vizibil o singura data: ${data.token}` : data.error;
}
</script>
