<script setup lang="ts">
/**
 * SettingsView – Galaxy Theme + Admin User Management
 *
 * - Profile (Display-Name ändern)
 * - Passwort ändern
 * - Admin: User-Liste + User anlegen (für owner- und admin-Rollen sichtbar)
 */
import { nextTick, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import {
  Save, Lock, User, Shield, Plus, Mail, Trash2,
  Eye, EyeOff, CheckCircle, X,
} from '@lucide/vue'
import { useAuthStore } from '../stores/auth'
import { apiFetch } from '../services/api'
import { throwApiProblem } from '../api/contracts'
import OpenClawConfigEditor from '../components/openclaw/OpenClawConfigEditor.vue'
import OpenClawSetupCenter from '../components/openclaw/OpenClawSetupCenter.vue'
import AsyncStatePanel from '../components/mission-control/AsyncStatePanel.vue'

const auth = useAuthStore()
const route = useRoute()

/* ── Profile ─────────────────────────────────────── */
const editingName = ref(false)
const displayName = ref(auth.user?.displayName ?? '')
const savingName = ref(false)
const nameError = ref('')
const nameSuccess = ref(false)

async function saveDisplayName() {
  nameError.value = ''
  nameSuccess.value = false
  const trimmed = displayName.value.trim()
  if (!trimmed) {
    nameError.value = 'Anzeigename darf nicht leer sein.'
    return
  }
  savingName.value = true
  try {
    const res = await apiFetch('/api/v1/auth/profile', {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ displayName: trimmed }),
    })
    if (!res.ok) throw new Error('Update fehlgeschlagen')
    const result = await res.json()
    if (auth.user) auth.user.displayName = result.displayName
    nameSuccess.value = true
    editingName.value = false
  } catch (e) {
    nameError.value = e instanceof Error ? e.message : 'Fehler beim Speichern'
  } finally {
    savingName.value = false
  }
}

/* ── Password ────────────────────────────────────── */
const currentPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const changingPassword = ref(false)
const passwordError = ref('')
const passwordSuccess = ref(false)
const showCurrentPw = ref(false)
const showNewPw = ref(false)
const showConfirmPw = ref(false)

async function changePassword() {
  passwordError.value = ''
  passwordSuccess.value = false

  if (!currentPassword.value) {
    passwordError.value = 'Aktuelles Passwort ist erforderlich.'
    return
  }
  if (!newPassword.value || newPassword.value.length < 10) {
    passwordError.value = 'Neues Passwort muss mindestens 10 Zeichen haben.'
    return
  }
  if (newPassword.value !== confirmPassword.value) {
    passwordError.value = 'Passwörter stimmen nicht überein.'
    return
  }

  changingPassword.value = true
  try {
    const res = await apiFetch('/api/v1/auth/change-password', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        currentPassword: currentPassword.value,
        newPassword: newPassword.value,
      }),
    })
    if (!res.ok) {
      const detail = await res.json().catch(() => ({}))
      throw new Error(detail.detail || 'Passwort-Änderung fehlgeschlagen')
    }
    passwordSuccess.value = true
    currentPassword.value = ''
    newPassword.value = ''
    confirmPassword.value = ''
  } catch (e) {
    passwordError.value = e instanceof Error ? e.message : 'Fehler beim Ändern'
  } finally {
    changingPassword.value = false
  }
}

/* ── Admin: User Management ──────────────────────── */
interface AdminUser {
  id: string
  email: string
  displayName: string
  role: string
  createdAt: string
  lastLoginAt: string | null
}

const users = ref<AdminUser[]>([])
const usersLoading = ref(false)
const usersProblem = ref<unknown>(null)
const showCreateUser = ref(false)
const createEmail = ref('')
const createPassword = ref('')
const createDisplayName = ref('')
const createRole = ref('user')
const creatingUser = ref(false)
const createError = ref('')
const createSuccess = ref('')

const canManageUsers = auth.user?.role === 'owner' || auth.user?.role === 'admin'

async function loadUsers() {
  if (!canManageUsers) return
  usersLoading.value = true
  usersProblem.value = null
  try {
    const res = await apiFetch('/api/v1/admin/users')
    if (!res.ok) await throwApiProblem(res, 'Benutzer konnten nicht geladen werden')
    users.value = await res.json()
  } catch (e) {
    usersProblem.value = e
  } finally {
    usersLoading.value = false
  }
}

async function handleCreateUser() {
  createError.value = ''
  createSuccess.value = ''
  if (!createEmail.value.trim() || !createPassword.value) {
    createError.value = 'E-Mail und Passwort sind erforderlich.'
    return
  }
  if (createPassword.value.length < 10) {
    createError.value = 'Passwort muss mindestens 10 Zeichen haben.'
    return
  }
  creatingUser.value = true
  try {
    const res = await apiFetch('/api/v1/admin/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: createEmail.value.trim(),
        password: createPassword.value,
        displayName: createDisplayName.value.trim() || null,
        role: createRole.value,
      }),
    })
    if (!res.ok) {
      const data = await res.json().catch(() => ({}))
      throw new Error(data.error || 'Benutzer konnte nicht erstellt werden')
    }
    createSuccess.value = `Benutzer ${createEmail.value.trim()} erfolgreich angelegt.`
    createEmail.value = ''
    createPassword.value = ''
    createDisplayName.value = ''
    createRole.value = 'user'
    showCreateUser.value = false
    await loadUsers()
  } catch (e) {
    createError.value = e instanceof Error ? e.message : 'Fehler beim Anlegen'
  } finally {
    creatingUser.value = false
  }
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('de-DE', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit',
  })
}

async function focusRequestedSection() {
  if (route.query.section !== 'openclaw-config') return
  await nextTick()
  const target = document.getElementById('openclaw-config')
  target?.scrollIntoView({ block: 'start', behavior: 'smooth' })
  target?.focus({ preventScroll: true })
}

watch(() => route.query.section, () => void focusRequestedSection(), { immediate: true })

onMounted(() => {
  loadUsers()
  void focusRequestedSection()
})
</script>

<template>
  <div class="settings-wrap nexus-page nexus-page--reading">
    <div class="settings-heading">
      <h1><span class="grad-text">Einstellungen</span></h1>
      <p class="settings-subtitle">Profil, Sicherheit &amp; Benutzerverwaltung</p>
    </div>

    <div class="settings-grid">
      <OpenClawSetupCenter v-if="auth.user?.role === 'owner'" class="gateway-card" />
      <OpenClawConfigEditor
        v-if="auth.user?.role === 'owner'"
        id="openclaw-config"
        tabindex="-1"
        class="openclaw-config-card"
      />
      <!-- ── Profile Card ────────────────────────── -->
      <section class="glass-card">
        <div class="card-head">
          <User :size="18" />
          <h2>Profil</h2>
        </div>

        <div class="field-row">
          <div class="field">
            <label>E-Mail</label>
            <div class="value-tag">{{ auth.user?.email }}</div>
          </div>

          <div class="field">
            <label>Rolle</label>
            <div class="role-badge">{{ auth.user?.role }}</div>
          </div>
        </div>

        <div class="field">
          <label for="profile-display-name">Anzeigename</label>
          <div v-if="editingName" class="name-edit">
            <div class="input-group">
              <input id="profile-display-name" v-model="displayName" maxlength="100" class="galaxy-input" />
              <button type="button" class="btn-primary btn-sm" @click="saveDisplayName" :disabled="savingName">
                <Save :size="13" /> {{ savingName ? 'Speichert…' : 'Speichern' }}
              </button>
              <button type="button" class="btn-ghost btn-sm" @click="editingName = false">Abbrechen</button>
            </div>
            <p v-if="nameError" class="msg error">{{ nameError }}</p>
            <p v-else-if="nameSuccess" class="msg success">Anzeigename aktualisiert.</p>
          </div>
          <div v-else class="value-row">
            <span class="value-tag">{{ auth.user?.displayName }}</span>
            <button type="button" class="btn-ghost btn-sm" @click="editingName = true">Bearbeiten</button>
          </div>
        </div>
      </section>

      <!-- ── Password Card ────────────────────────── -->
      <section class="glass-card">
        <div class="card-head">
          <Lock :size="18" />
          <h2>Passwort ändern</h2>
        </div>

        <form class="password-form" @submit.prevent="changePassword">
          <div class="field">
            <label for="current-password">Aktuelles Passwort</label>
            <div class="pw-wrap">
              <input id="current-password" v-model="currentPassword" :type="showCurrentPw ? 'text' : 'password'" class="galaxy-input" autocomplete="current-password" />
              <button
                type="button"
                class="pw-toggle"
                :aria-label="showCurrentPw ? 'Aktuelles Passwort ausblenden' : 'Aktuelles Passwort anzeigen'"
                @click="showCurrentPw = !showCurrentPw"
              >
                <Eye v-if="!showCurrentPw" :size="16" />
                <EyeOff v-else :size="16" />
              </button>
            </div>
          </div>
          <div class="field">
            <label for="new-password">Neues Passwort</label>
            <div class="pw-wrap">
              <input id="new-password" v-model="newPassword" :type="showNewPw ? 'text' : 'password'" class="galaxy-input" autocomplete="new-password" minlength="10" />
              <button
                type="button"
                class="pw-toggle"
                :aria-label="showNewPw ? 'Neues Passwort ausblenden' : 'Neues Passwort anzeigen'"
                @click="showNewPw = !showNewPw"
              >
                <Eye v-if="!showNewPw" :size="16" />
                <EyeOff v-else :size="16" />
              </button>
            </div>
          </div>
          <div class="field">
            <label for="confirm-password">Passwort bestätigen</label>
            <div class="pw-wrap">
              <input id="confirm-password" v-model="confirmPassword" :type="showConfirmPw ? 'text' : 'password'" class="galaxy-input" autocomplete="new-password" />
              <button
                type="button"
                class="pw-toggle"
                :aria-label="showConfirmPw ? 'Passwortbestätigung ausblenden' : 'Passwortbestätigung anzeigen'"
                @click="showConfirmPw = !showConfirmPw"
              >
                <Eye v-if="!showConfirmPw" :size="16" />
                <EyeOff v-else :size="16" />
              </button>
            </div>
          </div>

          <p v-if="passwordError" class="msg error">{{ passwordError }}</p>
          <p v-else-if="passwordSuccess" class="msg success">
            <CheckCircle :size="14" /> Passwort erfolgreich geändert.
          </p>

          <button type="submit" class="btn-primary" :disabled="changingPassword">
            <Lock :size="14" /> {{ changingPassword ? 'Ändert…' : 'Passwort ändern' }}
          </button>
        </form>
      </section>

      <!-- ── Admin: User Management (owner & admin) ── -->
      <section v-if="canManageUsers" class="glass-card admin-card">
        <div class="card-head">
          <Shield :size="18" />
          <h2>Benutzerverwaltung</h2>
          <button type="button" class="btn-primary btn-sm create-user-btn" @click="showCreateUser = true">
            <Plus :size="13" /> Benutzer anlegen
          </button>
        </div>

        <AsyncStatePanel
          v-if="usersLoading && !users.length"
          state="loading"
          title="Benutzer werden geladen"
          compact
        />

        <AsyncStatePanel
          v-else-if="usersProblem && !users.length"
          state="error"
          title="Benutzer nicht verfügbar"
          :problem="usersProblem"
          compact
          @action="loadUsers"
        />

        <template v-else-if="users.length">
          <AsyncStatePanel
            v-if="usersProblem"
            state="stale"
            title="Benutzerliste möglicherweise veraltet"
            :problem="usersProblem"
            action-label="Aktualisieren"
            compact
            @action="loadUsers"
          />
          <div class="user-list">
            <div v-for="user in users" :key="user.id" class="user-row">
              <div class="user-avatar">
                {{ user.displayName.charAt(0).toUpperCase() }}
              </div>
              <div class="user-info">
                <div class="user-name">{{ user.displayName }}</div>
                <div class="user-email">
                  <Mail :size="11" /> {{ user.email }}
                </div>
              </div>
              <div class="user-meta">
                <span class="role-tag" :class="user.role">{{ user.role }}</span>
                <span class="user-date">
                  Seit {{ formatDate(user.createdAt) }}
                </span>
              </div>
            </div>
          </div>
        </template>

        <AsyncStatePanel
          v-else
          state="empty"
          title="Noch keine Benutzer"
          message="Lege den ersten zusätzlichen Nexus-Benutzer an."
          compact
        />

        <!-- Create User Modal -->
        <Teleport to="body">
          <div v-if="showCreateUser" class="modal-overlay" @click.self="showCreateUser = false">
            <div class="modal-card">
              <div class="modal-header">
                <h2>Benutzer anlegen</h2>
                <button type="button" class="modal-close" aria-label="Dialog schließen" @click="showCreateUser = false"><X :size="16" /></button>
              </div>
              <form @submit.prevent="handleCreateUser" class="modal-form">
                <div class="field">
                  <label for="create-user-email">E-Mail <span class="req">*</span></label>
                  <input id="create-user-email" v-model="createEmail" type="email" class="galaxy-input" placeholder="user@noveria.net" required />
                </div>
                <div class="field">
                  <label for="create-user-password">Passwort <span class="req">*</span> (min. 10 Zeichen)</label>
                  <input id="create-user-password" v-model="createPassword" type="password" class="galaxy-input" minlength="10" required />
                </div>
                <div class="field">
                  <label for="create-user-display-name">Anzeigename (optional)</label>
                  <input id="create-user-display-name" v-model="createDisplayName" class="galaxy-input" placeholder="Max Mustermann" />
                </div>
                <div class="field">
                  <label for="create-user-role">Rolle</label>
                  <select id="create-user-role" v-model="createRole" class="galaxy-input galaxy-select">
                    <option value="user">User</option>
                    <option value="admin">Admin</option>
                    <option value="viewer">Viewer</option>
                    <!-- owner ist nicht über UI wählbar – bleibt Sonderrolle -->
                  </select>
                </div>
                <p v-if="createError" class="msg error">{{ createError }}</p>
                <p v-if="createSuccess" class="msg success">{{ createSuccess }}</p>
                <div class="modal-actions">
                  <button type="button" class="btn-ghost" @click="showCreateUser = false">Abbrechen</button>
                  <button type="submit" class="btn-primary" :disabled="creatingUser">
                    <Plus :size="14" /> {{ creatingUser ? 'Erstelle…' : 'Benutzer anlegen' }}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </Teleport>
      </section>
    </div>
  </div>
</template>

<style scoped>
.settings-wrap {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  animation: fadeIn 0.35s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to   { opacity: 1; transform: translateY(0); }
}

.settings-heading {
  margin-bottom: 24px;
}

.settings-heading h1 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  font-family: 'Space Grotesk', sans-serif;
  letter-spacing: -0.02em;
}

.grad-text {
  background: linear-gradient(135deg, var(--a-blue), var(--a-purple));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.settings-subtitle {
  margin: 4px 0 0;
  font-size: 11px;
  color: var(--tx-3);
  font-family: 'Manrope', sans-serif;
}

.settings-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.gateway-card {
  grid-column: 1 / -1;
  border-color: var(--line-2);
  background: linear-gradient(145deg, var(--glass), var(--grad-soft));
}

.openclaw-config-card {
  grid-column: 1 / -1;
}

.connection-state {
  margin-left: auto;
  flex: 0 0 auto;
}

.gateway-contract {
  margin: 0;
  color: var(--tx-2);
  line-height: 1.6;
}

.gateway-diagnostics {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 8px;
}

.gateway-diagnostics > div {
  display: grid;
  gap: 5px;
  padding: 11px;
  border: 1px solid var(--line);
  border-radius: var(--r-sm);
  background: var(--accent-wash);
}

.gateway-diagnostics span {
  color: var(--tx-3);
  font-family: var(--font-mono-v2);
  font-size: 11px;
  text-transform: uppercase;
}

.gateway-diagnostics strong,
.gateway-diagnostics code {
  overflow: hidden;
  color: var(--tx-2);
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.gateway-diagnostics code {
  font-family: var(--font-mono-v2);
  font-size: 11px;
}

.gateway-scopes {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.gateway-scopes code {
  padding: 5px 8px;
  border: 1px solid var(--line-2);
  border-radius: 999px;
  background: var(--glass);
  color: var(--tx-2);
  font-family: var(--font-mono-v2);
  font-size: 11px;
}

.gateway-recovery {
  display: grid;
  grid-template-columns: auto minmax(0, 1fr);
  gap: 10px;
  align-items: start;
  padding: 12px;
  border: 1px solid var(--status-queue-line);
  border-radius: var(--r-sm);
  background: var(--status-queue-bg);
  color: var(--st-queue);
}

.gateway-recovery strong {
  color: var(--tx);
}

.gateway-recovery p {
  margin: 3px 0 0;
  color: var(--tx-2);
  line-height: 1.5;
}

.pairing-request code {
  display: block;
  width: fit-content;
  max-width: 100%;
  margin-top: 8px;
  padding: 6px 8px;
  overflow: hidden;
  border: 1px solid var(--status-queue-line);
  border-radius: 7px;
  background: color-mix(in srgb, var(--space-0) 45%, transparent);
  color: var(--tx);
  font-family: var(--font-mono-v2);
  font-size: 10.5px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* ── Glass Card ─────────────────────────────── */
.glass-card {
  background: linear-gradient(160deg, color-mix(in srgb, var(--space-3) 75%, transparent), color-mix(in srgb, var(--space-1) 75%, transparent));
  border: 1px solid color-mix(in srgb, var(--a-mid) 10%, transparent);
  border-radius: 18px;
  padding: 24px;
  backdrop-filter: blur(12px);
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.card-head {
  display: flex;
  align-items: center;
  gap: 10px;
  color: var(--tx);
  padding-bottom: 14px;
  border-bottom: 1px solid color-mix(in srgb, var(--a-mid) 8%, transparent);
}

.card-head h2 {
  margin: 0;
  font-size: 15px;
  font-weight: 700;
  font-family: 'Space Grotesk', sans-serif;
}

.create-user-btn {
  margin-left: auto;
}

/* ── Fields ──────────────────────────────────── */
.field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.field label {
  font-size: 10px;
  font-weight: 600;
  color: var(--tx-2);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.field-row {
  display: flex;
  gap: 24px;
}

.field-row > .field {
  flex: 1;
}

.galaxy-input {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid color-mix(in srgb, var(--a-mid) 12%, transparent);
  border-radius: 11px;
  background: color-mix(in srgb, var(--space-1) 55%, transparent);
  color: var(--tx);
  font-size: 13.5px;
  font-family: 'Manrope', sans-serif;
  outline: none;
  transition: border-color 0.2s, box-shadow 0.2s;
  box-sizing: border-box;
}

.galaxy-input:focus {
  border-color: color-mix(in srgb, var(--a-mid) 50%, transparent);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--a-mid) 12%, transparent);
}

.galaxy-select {
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236f6aa0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  padding-right: 36px;
}

.galaxy-select option {
  background: var(--space-3);
  color: var(--tx);
}

.value-tag {
  font-size: 14px;
  color: var(--tx);
  font-weight: 500;
}

.value-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.role-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  background: linear-gradient(135deg, color-mix(in srgb, var(--a-blue) 15%, transparent), color-mix(in srgb, var(--a-purple) 15%, transparent));
  color: var(--tx-2);
  border: 1px solid color-mix(in srgb, var(--a-mid) 15%, transparent);
  width: fit-content;
}

/* ── Name Edit ──────────────────────────────────── */
.name-edit {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.input-group .galaxy-input {
  flex: 1;
}

/* ── Password ────────────────────────────────── */
.password-form {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.pw-wrap {
  position: relative;
  display: flex;
  align-items: center;
}

.pw-wrap .galaxy-input {
  padding-right: 44px;
}

.pw-toggle {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  display: grid;
  place-items: center;
  border: none;
  border-radius: 8px;
  background: transparent;
  color: var(--tx-3);
  cursor: pointer;
  transition: background 0.15s, color 0.15s;
}

.pw-toggle:hover {
  background: color-mix(in srgb, var(--a-mid) 8%, transparent);
  color: var(--tx-2);
}

/* ── Messages ──────────────────────────────────── */
.msg {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0;
  font-size: 12px;
  padding: 8px 12px;
  border-radius: 8px;
}

.msg.error {
  background: color-mix(in srgb, var(--st-block) 10%, transparent);
  border: 1px solid color-mix(in srgb, var(--st-block) 20%, transparent);
  color: var(--st-block);
}

.msg.success {
  background: color-mix(in srgb, var(--st-work) 10%, transparent);
  border: 1px solid color-mix(in srgb, var(--st-work) 20%, transparent);
  color: var(--st-work);
}

/* ── Buttons ──────────────────────────────────── */
.btn-primary {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 9px 16px;
  border: none;
  border-radius: 10px;
  background: linear-gradient(135deg, var(--a-blue), var(--a-mid), var(--a-purple));
  color: var(--tx);
  font-size: 12.5px;
  font-weight: 600;
  font-family: 'Manrope', sans-serif;
  cursor: pointer;
  transition: opacity 0.2s, transform 0.15s;
  width: fit-content;
}

.btn-primary:hover:not(:disabled) {
  opacity: 0.9;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 11px;
  border-radius: 8px;
}

.btn-ghost {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  font-size: 11px;
  font-family: 'Manrope', sans-serif;
  background: transparent;
  border: 1px solid color-mix(in srgb, var(--a-mid) 12%, transparent);
  color: var(--tx-2);
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.15s, color 0.15s;
}

.btn-ghost:hover {
  background: color-mix(in srgb, var(--a-mid) 8%, transparent);
  color: var(--tx);
}

/* ── Admin User Management ───────────────────── */
.admin-card {
  border-color: color-mix(in srgb, var(--a-mid) 15%, transparent);
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.user-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 14px;
  border-radius: 12px;
  background: color-mix(in srgb, var(--space-1) 35%, transparent);
  border: 1px solid color-mix(in srgb, var(--a-mid) 6%, transparent);
  transition: background 0.15s, border-color 0.15s;
}

.user-row:hover {
  background: color-mix(in srgb, var(--a-mid) 5%, transparent);
  border-color: color-mix(in srgb, var(--a-mid) 12%, transparent);
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: grid;
  place-items: center;
  background: linear-gradient(135deg, color-mix(in srgb, var(--a-blue) 20%, transparent), color-mix(in srgb, var(--a-purple) 20%, transparent));
  border: 1px solid color-mix(in srgb, var(--a-mid) 15%, transparent);
  color: var(--tx-2);
  font-weight: 700;
  font-size: 14px;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 13px;
  font-weight: 600;
  color: var(--tx);
}

.user-email {
  font-size: 11px;
  color: var(--tx-3);
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 2px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  flex-shrink: 0;
}

.role-tag {
  display: inline-block;
  padding: 1px 8px;
  border-radius: 5px;
  font-size: 10px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  background: color-mix(in srgb, var(--a-mid) 10%, transparent);
  color: var(--tx-2);
  border: 1px solid color-mix(in srgb, var(--a-mid) 10%, transparent);
}

.role-tag.owner {
  background: linear-gradient(135deg, color-mix(in srgb, var(--st-block) 15%, transparent), color-mix(in srgb, var(--st-queue) 15%, transparent));
  color: var(--st-queue);
  border-color: color-mix(in srgb, var(--st-queue) 20%, transparent);
}

.role-tag.admin {
  background: color-mix(in srgb, var(--a-blue) 12%, transparent);
  color: var(--tx-2);
  border-color: color-mix(in srgb, var(--a-blue) 20%, transparent);
}

.role-tag.viewer {
  background: color-mix(in srgb, var(--tx-3) 15%, transparent);
  color: var(--tx-2);
  border-color: color-mix(in srgb, var(--tx-3) 20%, transparent);
}

.user-date {
  font-size: 10px;
  color: var(--tx-3);
}

.loading-pulse {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.pulse-bar {
  height: 52px;
  border-radius: 12px;
  background: linear-gradient(90deg, color-mix(in srgb, var(--a-mid) 4%, transparent), color-mix(in srgb, var(--a-mid) 10%, transparent), color-mix(in srgb, var(--a-mid) 4%, transparent));
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0%   { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 32px;
  color: var(--tx-3);
}

.empty-state p {
  margin: 0;
  font-size: 12px;
}

/* ── Modal ────────────────────────────────── */
.modal-overlay {
  position: fixed;
  inset: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  background: color-mix(in srgb, var(--space-0) 75%, transparent);
  backdrop-filter: blur(16px);
}

.modal-card {
  width: 100%;
  max-width: 460px;
  background: linear-gradient(160deg, color-mix(in srgb, var(--space-3) 92%, transparent), color-mix(in srgb, var(--space-1) 92%, transparent));
  border: 1px solid color-mix(in srgb, var(--a-mid) 18%, transparent);
  border-radius: 18px;
  padding: 24px;
  box-shadow: 0 0 0 1px color-mix(in srgb, var(--a-mid) 12%, transparent), 0 20px 60px -12px color-mix(in srgb, var(--space-0) 50%, transparent);
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
  padding-bottom: 14px;
  border-bottom: 1px solid color-mix(in srgb, var(--a-mid) 8%, transparent);
}

.modal-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 700;
  color: var(--tx);
  font-family: 'Space Grotesk', sans-serif;
}

.modal-close {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
  color: var(--tx-3);
  cursor: pointer;
  border-radius: 6px;
  font-size: 20px;
  transition: background 0.15s, color 0.15s;
}

.modal-close:hover {
  background: color-mix(in srgb, var(--a-mid) 8%, transparent);
  color: var(--tx);
}

.req {
  color: var(--st-block);
}

.modal-form {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 4px;
}

@media (max-width: 720px) {
  .gateway-diagnostics {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .gateway-card .card-head {
    flex-wrap: wrap;
  }

  .connection-state {
    margin-left: 0;
  }
}

@media (max-width: 460px) {
  .gateway-diagnostics {
    grid-template-columns: 1fr;
  }
}
</style>
