<%- include('partials/header', { title: 'API Keys', heading: 'API Keys', active: '/api-keys' }) %>

<div class="bg-white rounded-2xl shadow p-5 mb-6 max-w-xl">
  <h2 class="font-semibold mb-3">Create API key</h2>
  <div class="flex gap-2">
    <input id="k_label" placeholder="Label (e.g. CRM integration)" class="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm" />
    <button onclick="createKey()" class="bg-emerald-600 text-white rounded-lg px-4 text-sm">Generate</button>
  </div>
  <div id="newKey" class="hidden mt-3 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm">
    <p class="font-medium text-amber-800">Copy this key now — it won't be shown again:</p>
    <code id="newKeyVal" class="block mt-1 break-all"></code>
  </div>
</div>

<div class="bg-white rounded-2xl shadow p-5 max-w-3xl">
  <h2 class="font-semibold mb-3">Existing keys</h2>
  <table class="w-full text-sm">
    <thead class="text-left text-slate-500 border-b"><tr><th class="py-2">Label</th><th>Prefix</th><th>Last used</th><th>Active</th><th></th></tr></thead>
    <tbody>
      <% keys.forEach((k) => { %>
        <tr class="border-b last:border-0">
          <td class="py-2"><%= k.label %></td>
          <td><code><%= k.key_prefix %>…</code></td>
          <td><%= k.last_used_at ? new Date(k.last_used_at).toLocaleString() : '—' %></td>
          <td><%= k.is_active ? 'Yes' : 'Revoked' %></td>
          <td class="text-right"><% if (k.is_active) { %><button onclick="revoke(<%= k.id %>)" class="text-rose-500 hover:underline">Revoke</button><% } %></td>
        </tr>
      <% }); %>
    </tbody>
  </table>
</div>

<script>
  async function createKey() {
    const r = await fetch('/api-keys', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ label: document.getElementById('k_label').value }) });
    const data = await r.json();
    if (data.ok) {
      document.getElementById('newKey').classList.remove('hidden');
      document.getElementById('newKeyVal').textContent = data.apiKey;
    }
  }
  async function revoke(id) {
    if (!confirm('Revoke this key?')) return;
    await fetch(`/api-keys/${id}`, { method: 'DELETE' });
    location.reload();
  }
</script>

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