document.getElementById('mainNav').innerHTML = chromeNav('users');

const flash = document.getElementById('flash');
function showFlash(message, ok) {
  flash.hidden = false;
  flash.className = 'flash ' + (ok ? 'ok' : 'error');
  flash.textContent = message;
}

async function loadUsers() {
  const res = await api('/api/users');
  const data = await res.json().catch(() => ([]));
  if (!res.ok) {
    showFlash(data.error || 'Benutzerliste nicht verfügbar', false);
    document.getElementById('rows').innerHTML = '';
    return;
  }
  const list = Array.isArray(data) ? data : [];
  document.getElementById('rows').innerHTML = list.map(u => {
    const badge = u.isBootstrap
      ? ' <span class="pill muted-pill" title="Über Einstellungen verwaltet">Bootstrap</span>'
      : '';
    const del = u.canDelete
      ? `<button type="button" data-del="${escapeHtml(u.username)}" class="btn-danger">Entfernen</button>`
      : `<span class="muted" title="Letzter Administrator bzw. Bootstrap-Konto">Geschützt</span>`;
    return `<tr>
      <td>${escapeHtml(u.username)}${badge}</td>
      <td>${escapeHtml(u.role)}</td>
      <td class="muted">${u.createdUtc ? new Date(u.createdUtc).toLocaleString() : '—'}</td>
      <td>${del}</td>
    </tr>`;
  }).join('') || '<tr><td colspan="4" class="muted">Keine zusätzlichen Benutzer</td></tr>';

  document.querySelectorAll('[data-del]').forEach(btn => {
    btn.addEventListener('click', async () => {
      const name = btn.getAttribute('data-del');
      const ok = await confirmDialog({
        title: 'Benutzer entfernen',
        message: `Benutzer „${name}“ wirklich entfernen?\nDieser Vorgang kann nicht rückgängig gemacht werden.`,
        confirmLabel: 'Entfernen',
        danger: true
      });
      if (!ok) return;
      const r = await api('/api/users/' + encodeURIComponent(name), { method: 'DELETE' });
      const d = await r.json().catch(() => ({}));
      showFlash(r.ok ? d.message : (d.error || 'Fehler'), r.ok);
      await loadUsers();
    });
  });
}

document.getElementById('userForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const body = {
    username: document.getElementById('username').value.trim(),
    password: document.getElementById('password').value,
    role: document.getElementById('role').value
  };
  const res = await api('/api/users', { method: 'PUT', body: JSON.stringify(body) });
  const data = await res.json().catch(() => ({}));
  showFlash(res.ok ? data.message : (data.error || 'Fehler'), res.ok);
  if (res.ok) {
    document.getElementById('password').value = '';
    await loadUsers();
  }
});

async function init() {
  await initLocale();
  document.getElementById('btnLogout').addEventListener('click', logout);
  const me = await loadMe();
  if (me?.organizationName) document.getElementById('orgName').textContent = me.organizationName;
  if (me?.license) renderLicenseBanner(me.license);
  if (me?.role) applyRoleNav(me.role);
  await loadUsers();
}

init();
