{{ define "admin_users.pages.tmpl" }}
{{ template "head" . }}
<div class="columns">
  <!-- Sidebar -->
  {{ template "sidebar" . }}
  <div class="column is-10">
<h1 class="title">Gestion des utilisateurs</h1>

<!-- Flash message -->
<div id="userFlash"></div>

<!-- Bouton création -->
<div class="mb-4">
  <a class="button is-primary" 
          href="/admin/user/create-form" 
        >
    ➕ Ajouter un utilisateur
</a>
</div>

<!-- Formulaire création -->
<div id="createForm" class="mb-4"></div>

<!-- Tableau -->
<table class="table is-fullwidth is-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Email</th>
      <th>Role</th>
      <th>Actif</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody id="userList">
    {{ range .Users }}
    <tr>
      <td>{{ .ID }}</td>
      <td>{{ .Email }}</td>
      <td>{{ .Role }}</td>
      <td>{{ if .IsActive }}✅{{ else }}❌{{ end }}</td>
      <td>
        <a class="button is-small is-info"
                href="/admin/user/{{ .ID }}/edit"
                >
          ✏️ Modifier
      </a>
        <button class="button is-small is-danger"
                hx-delete="/api/user/delete/{{ .ID }}"
                hx-confirm="Confirmer suppression ?"
                hx-target="#userList"
                hx-swap="outerHTML">
          🗑️ Supprimer
        </button>
      </td>
    </tr>
    {{ end }}
  </tbody>
</table>

<!-- Formulaire modification -->
<hr>
<div id="editForm"></div>
</div>
<!-- Script HTMX flash -->
<script>
  document.body.addEventListener('htmx:afterOnLoad', (e) => {
    if (e.detail && e.detail.xhr) {
      const json = JSON.parse(e.detail.xhr.getResponseHeader("HX-Trigger") || "{}")
      if (json.userCreated) {
        const flash = document.getElementById("userFlash")
        flash.innerHTML = `<div class="notification is-success">${json.userCreated}</div>`
        setTimeout(() => flash.innerHTML = "", 3000)
      }
    }
  })
</script>
{{ end }}
