<div class="admin-card">
  <table class="admin-table">
    <thead><tr><th>Event</th><th>Organizer</th><th>Date</th><th>Type</th><th>Registrations</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
      <% if (events && events.length) { %>
      <% events.forEach(e => { %>
      <tr>
        <td><strong><%= e.title.substring(0,40) %></strong></td>
        <td><%= e.org_name || e.first_name + ' ' + e.last_name %></td>
        <td><%= moment(e.start_date).format('MMM D, YYYY') %></td>
        <td><span class="badge badge-secondary"><%= e.event_type %></span></td>
        <td><%= e.registered_count || 0 %><% if(e.capacity) { %>/<%= e.capacity %><% } %></td>
        <td><span class="badge badge-<%= e.status === 'published' ? 'success' : e.status === 'cancelled' ? 'danger' : 'secondary' %>"><%= e.status %></span></td>
        <td>
          <% if (e.status === 'published') { %><button class="btn btn-xs btn-warning change-status" data-id="<%= e.id %>" data-status="cancelled">Cancel</button>
          <% } else if (e.status === 'draft') { %><button class="btn btn-xs btn-success change-status" data-id="<%= e.id %>" data-status="published">Publish</button><% } %>
        </td>
      </tr>
      <% }) %>
      <% } else { %>
      <tr><td colspan="7" style="text-align:center;padding:32px;color:#9ca3af">No events found.</td></tr>
      <% } %>
    </tbody>
  </table>
</div>

<script>
document.querySelectorAll('.change-status').forEach(btn => {
  btn.addEventListener('click', async () => {
    if (!confirm(`Set event status to "${btn.dataset.status}"?`)) return;
    const res = await fetch(`/admin/events/${btn.dataset.id}/status`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({status:btn.dataset.status})});
    if ((await res.json()).success) location.reload();
  });
});
</script>
