<template>
  <div class="permissions-view">
    <div class="header">
      <h1>{{ pageTitle }}</h1>
      <p class="subtitle">{{ pageSubtitle }}</p>
    </div>

    <div v-if="loading" class="loading">{{ t('permissions.loadingMembers') }}</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else class="permissions-content">
      <div v-if="showRoleLegend" class="role-legend">
        <h3>{{ t('permissions.availableRoles') }}</h3>
        <div class="roles-grid">
          <div v-for="role in availableRoles" :key="role.value" class="role-card">
            <div class="role-name">{{ role.label }}</div>
            <div class="role-description">{{ role.description }}</div>
          </div>
        </div>
      </div>

      <div v-if="isRolesMode" class="roles-admin-layout">
        <div class="role-catalog card">
          <div class="catalog-header">
            <h3>Rollen im Verein</h3>
            <button v-if="!isReadOnly" class="btn-primary" @click="startCreateRole">Neue Rolle</button>
          </div>
          <div class="role-catalog-list">
            <button
              v-for="role in clubRoles"
              :key="role.id"
              type="button"
              class="role-catalog-item"
              :class="{ active: selectedRole && selectedRole.id === role.id }"
              @click="selectRole(role)"
            >
              <span class="role-catalog-name">{{ role.name }}</span>
            </button>
          </div>
        </div>

        <div class="role-editor card">
          <div class="catalog-header">
            <h3>{{ roleEditorTitle }}</h3>
            <button
              v-if="selectedRole && !selectedRole.isSystemRole && !isReadOnly"
              class="btn-danger"
              @click="deleteSelectedRole"
            >
              Rolle löschen
            </button>
          </div>

          <div v-if="selectedRole" class="role-editor-form">
            <label class="field-block">
              <span>Name</span>
              <input v-model="selectedRole.name" class="role-input" :disabled="isReadOnly" />
            </label>
            <label class="field-block">
              <span>Beschreibung</span>
              <textarea v-model="selectedRole.description" class="role-textarea" rows="3" :disabled="isReadOnly"></textarea>
            </label>

            <div class="permissions-grid">
              <div v-for="(resource, key) in permissionStructure" :key="`role-${key}`" class="permission-group">
                <div class="permission-group-header">
                  <h4>{{ resource.label }}</h4>
                  <button class="btn-reset" @click="resetRoleResource(key)" :disabled="isReadOnly">Zurücksetzen</button>
                </div>
                <div class="permission-actions">
                  <div v-for="action in resource.actions" :key="action" class="permission-row">
                    <span class="permission-action-label">{{ getActionLabel(action) }}</span>
                    <button
                      class="perm-state"
                      :class="selectedRole.permissions?.[key]?.[action] ? 'state-allow' : 'state-deny'"
                      @click="toggleRolePermission(key, action)"
                      :disabled="isReadOnly"
                    >
                      {{ selectedRole.permissions?.[key]?.[action] ? 'Erlaubt' : 'Verboten' }}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="!isReadOnly" class="dialog-footer role-editor-actions">
              <button @click="resetRolePermissions" class="btn-secondary">Alles zurücksetzen</button>
              <button @click="saveRole" class="btn-primary">Rolle speichern</button>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="members-table">
        <h3>{{ t('permissions.clubMembers') }}</h3>
        <table>
          <thead>
            <tr>
              <th>{{ t('permissions.email') }}</th>
              <th>Rollen</th>
              <th>{{ t('permissions.status') }}</th>
              <th v-if="!isReadOnly">{{ t('permissions.actions') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="member in members" :key="member.userId">
              <td>{{ member.user?.email || 'N/A' }}</td>
              <td>
                <div v-if="!member.isOwner && !isReadOnly" class="member-role-list">
                  <label v-for="role in clubRoles" :key="`${member.userId}-${role.id}`" class="member-role-option">
                    <input
                      type="checkbox"
                      :checked="memberHasRole(member, role.id)"
                      @change="toggleMemberRole(member, role.id, $event.target.checked)"
                    />
                    <span>{{ role.name }}</span>
                  </label>
                </div>
                <div v-else class="member-role-badges">
                  <span
                    v-for="role in member.roles"
                    :key="`${member.userId}-${role.id || role.roleKey}`"
                    class="role-badge"
                  >
                    {{ role.name }}
                  </span>
                  <span v-if="member.isOwner" class="owner-badge">👑 {{ t('permissions.creator') }}</span>
                </div>
              </td>
              <td>
                <span 
                  v-if="member.approved !== false"
                  class="status-badge status-active"
                  :class="{ 'clickable': !member.isOwner && !isReadOnly }"
                  @click="!member.isOwner && !isReadOnly ? toggleMemberStatus(member) : null"
                  :title="!member.isOwner && !isReadOnly ? t('permissions.clickToDeactivate') : ''"
                >
                  ✓ {{ t('permissions.active') }}
                </span>
                <span 
                  v-else
                  class="status-badge status-inactive"
                  :class="{ 'clickable': !isReadOnly }"
                  @click="!isReadOnly ? toggleMemberStatus(member) : null"
                  :title="!isReadOnly ? t('permissions.clickToActivate') : ''"
                >
                  ✗ {{ t('permissions.inactive') }}
                </span>
              </td>
              <td v-if="!isReadOnly">
                <button 
                  v-if="!member.isOwner" 
                  @click="openPermissionsDialog(member)"
                  class="btn-small"
                >
                  {{ customizeButtonLabel }}
                </button>
                <span v-else class="muted">—</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Custom Permissions Dialog -->
    <div v-if="selectedMember" class="dialog-overlay" @click.self="closePermissionsDialog">
      <div class="dialog-content">
        <div class="dialog-header">
          <h2>{{ t('permissions.permissionsFor') }} {{ selectedMember.user?.email }}</h2>
          <button @click="closePermissionsDialog" class="close-btn">&times;</button>
        </div>
        
        <div class="dialog-body">
          <p class="info-text">
            Zugewiesene Rollen:
            <strong>{{ selectedMemberRoleNames }}</strong><br>
            {{ t('permissions.customizeInfo') }}
          </p>

          <div class="permissions-grid">
            <div v-for="(resource, key) in permissionStructure" :key="key" class="permission-group">
              <div class="permission-group-header">
                <h4>{{ resource.label }}</h4>
                <button class="btn-reset" @click="resetResource(key)" :disabled="isReadOnly">{{ t('permissions.reset') }}</button>
              </div>
              <div class="permission-actions">
                <div v-for="action in resource.actions" :key="action" class="permission-row">
                  <span class="permission-action-label">{{ getActionLabel(action) }}</span>
                  <button 
                    class="perm-state"
                    :class="stateClass(customPermissions[key][action], key, action)"
                    @click="togglePermission(key, action)"
                    :disabled="isReadOnly"
                    >{{ stateLabel(customPermissions[key][action], key, action) }}</button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="dialog-footer">
          <button @click="resetAll" class="btn-secondary" :disabled="isReadOnly">{{ t('permissions.resetAll') }}</button>
          <button @click="closePermissionsDialog" class="btn-secondary">{{ t('permissions.cancel') }}</button>
          <button @click="saveCustomPermissions" class="btn-primary">{{ t('permissions.save') }}</button>
        </div>
      </div>
    </div>

    <InfoDialog
      v-model="infoDialog.isOpen"
      :title="infoDialog.title"
      :message="infoDialog.message"
      :details="infoDialog.details"
      :type="infoDialog.type"
    />

    <ConfirmDialog
      v-model="confirmDialog.isOpen"
      :title="confirmDialog.title"
      :message="confirmDialog.message"
      :details="confirmDialog.details"
      :type="confirmDialog.type"
      :confirm-text="confirmDialog.confirmText"
      :cancel-text="confirmDialog.cancelText"
      :show-cancel="confirmDialog.showCancel"
      @confirm="handleConfirmResult(true)"
      @cancel="handleConfirmResult(false)"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import i18n from '../i18n';
import apiClient from '../apiClient.js';
import { usePermissions } from '../composables/usePermissions.js';
import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';

export default {
  name: 'PermissionsView',
  props: {
    viewMode: {
      type: String,
      default: 'permissions',
    },
  },
  components: {
    InfoDialog,
    ConfirmDialog
  },
  setup(props) {
    const store = useStore();
    const t = (key, params) => i18n.global.t(key, params);
    const { isOwner, isAdmin, can } = usePermissions();
    
    const infoDialog = ref({
      isOpen: false,
      title: '',
      message: '',
      details: '',
      type: 'info'
    });
    const confirmDialog = ref({
      isOpen: false,
      title: '',
      message: '',
      details: '',
      type: 'info',
      confirmText: 'OK',
      cancelText: t('permissions.cancel'),
      showCancel: true,
      resolveCallback: null
    });

    const showInfo = async (title, message, details = '', type = 'info') => {
      infoDialog.value = {
        isOpen: true,
        title,
        message,
        details,
        type
      };
    };

    const showConfirm = async (title, message, details = '', type = 'info', options = {}) => {
      return new Promise((resolve) => {
        confirmDialog.value = {
          isOpen: true,
          title,
          message,
          details,
          type,
          confirmText: options.confirmText || 'OK',
          cancelText: options.cancelText || t('permissions.cancel'),
          showCancel: options.showCancel !== false,
          resolveCallback: resolve
        };
      });
    };

    const handleConfirmResult = (confirmed) => {
      if (confirmDialog.value.resolveCallback) {
        confirmDialog.value.resolveCallback(confirmed);
        confirmDialog.value.resolveCallback = null;
      }
      confirmDialog.value.isOpen = false;
    };

    const currentClub = computed(() => store.getters.currentClub);
    const members = ref([]);
    const availableRoles = ref([]);
    const clubRoles = ref([]);
    const permissionStructure = ref({});
    const loading = ref(true);
    const error = ref(null);
    const selectedMember = ref(null);
    const customPermissions = ref({});

    const isReadOnly = computed(() => {
      return !can('permissions', 'write');
    });

    const pageTitle = computed(() => {
      if (props.viewMode === 'users') {
        return 'Benutzer';
      }
      if (props.viewMode === 'roles') {
        return 'Rollen und Rechte';
      }
      return t('permissions.title');
    });

    const pageSubtitle = computed(() => {
      if (props.viewMode === 'users') {
        return 'Benutzerzugänge, Status und individuelle Rechte für diesen Verein.';
      }
      if (props.viewMode === 'roles') {
        return 'Rollen vergeben und effektive Berechtigungen für Vereinsbenutzer steuern.';
      }
      return t('permissions.subtitle');
    });

    const showRoleLegend = computed(() => props.viewMode !== 'users');
    const customizeButtonLabel = computed(() => (
      props.viewMode === 'users' ? 'Rechte' : t('permissions.customize')
    ));
    const isRolesMode = computed(() => props.viewMode === 'roles');
    const selectedRole = ref(null);
    const roleEditorTitle = computed(() => selectedRole.value?.id ? 'Rolle bearbeiten' : 'Neue Rolle');
    const selectedMemberRoleNames = computed(() => {
      if (!selectedMember.value?.roles?.length) {
        return 'Keine Rolle';
      }
      return selectedMember.value.roles.map((role) => role.name).join(', ');
    });

    const normalizeRolePermissions = (permissions) => {
      if (!permissions) {
        return {};
      }
      if (typeof permissions === 'string') {
        try {
          return JSON.parse(permissions);
        } catch (_error) {
          return {};
        }
      }
      return JSON.parse(JSON.stringify(permissions));
    };

    const normalizeBooleanFlag = (value) => {
      if (typeof value === 'boolean') {
        return value;
      }
      if (typeof value === 'number') {
        return value === 1;
      }
      if (typeof value === 'string') {
        const normalized = value.trim().toLowerCase();
        return normalized === '1' || normalized === 'true';
      }
      return false;
    };

    const loadData = async (force = false) => {
      loading.value = true;
      error.value = null;

      try {
        const rolesResponse = await apiClient.get(`/permissions/${currentClub.value}/roles`);
        clubRoles.value = (rolesResponse.data || []).map((role) => ({
          ...role,
          isSystemRole: normalizeBooleanFlag(role.isSystemRole),
          permissions: normalizeRolePermissions(role.permissions),
        }));
        availableRoles.value = clubRoles.value.map((role) => ({
          value: role.roleKey,
          label: role.name,
          description: role.description,
        }));

        // Load permission structure
        const structureResponse = await apiClient.get('/permissions/structure/all');
        permissionStructure.value = structureResponse.data;

        // Load members with permissions
        const bust = force ? `?t=${Date.now()}` : '';
        const membersResponse = await apiClient.get(`/permissions/${currentClub.value}/members${bust}`);
        members.value = membersResponse.data;
        if (!selectedRole.value && clubRoles.value.length > 0) {
          selectRole(clubRoles.value[0]);
        }
      } catch (err) {
        console.error('Error loading permissions data:', err);
        
        if (err.response?.status === 403) {
          error.value = 'Keine Berechtigung: Nur Administratoren können Berechtigungen verwalten.';
          // Redirect nach kurzer Verzögerung
          setTimeout(() => {
            window.location.href = '/';
          }, 2000);
        } else {
          error.value = err.response?.data?.error || t('permissions.errorLoadingData');
        }
      } finally {
        loading.value = false;
      }
    };

    const memberHasRole = (member, roleId) => {
      return Array.isArray(member.roles) && member.roles.some((role) => Number(role.id) === Number(roleId));
    };

    const toggleMemberRole = async (member, roleId, checked) => {
      try {
        const nextRoleIds = new Set(Array.isArray(member.roles) ? member.roles.map((role) => Number(role.id)) : []);
        if (checked) {
          nextRoleIds.add(Number(roleId));
        } else {
          nextRoleIds.delete(Number(roleId));
        }

        await apiClient.put(
          `/permissions/${currentClub.value}/user/${member.userId}/roles`,
          { roleIds: [...nextRoleIds] }
        );

        await loadData();
      } catch (err) {
        console.error('Error updating roles:', err);
        await showInfo(t('messages.error'), err.response?.data?.error || 'Fehler beim Aktualisieren der Rollen', '', 'error');
        await loadData();
      }
    };

    const toggleMemberStatus = async (member) => {
      const newStatus = member.approved === false ? true : false;
      const action = newStatus ? 'aktivieren' : 'deaktivieren';
      
      const confirmed = await showConfirm(
        'Status ändern',
        `Möchten Sie ${member.user?.email} wirklich ${action}?`,
        '',
        'warning'
      );
      if (!confirmed) {
        return;
      }

      try {
        await apiClient.put(
          `/permissions/${currentClub.value}/user/${member.userId}/status`,
          { approved: newStatus }
        );
        
        // Update local state - visual feedback happens automatically
        member.approved = newStatus;
      } catch (err) {
        console.error('Error updating status:', err);
        // Reload to revert changes on error
        await loadData();
      }
    };

    const openPermissionsDialog = async (member) => {
      selectedMember.value = member;
      
      // Load fresh data for this specific member to ensure we have the latest permissions
      try {
        const membersResponse = await apiClient.get(`/permissions/${currentClub.value}/members?t=${Date.now()}`);
        const freshMember = membersResponse.data.find(m => m.userId === member.userId);
        if (freshMember) {
          selectedMember.value = freshMember;
        }
      } catch (err) {
        console.error('Error loading fresh member data:', err);
        // Continue with existing data if fresh load fails
      }
      
      // Initialize custom permissions from the stored custom permissions, not effective permissions
      customPermissions.value = {};
      for (const resource in permissionStructure.value) {
        customPermissions.value[resource] = {};
        const customPerms = selectedMember.value.permissions || {};
        for (const action of permissionStructure.value[resource].actions) {
          // Use custom permissions if they exist, otherwise undefined (inherit from role)
          customPermissions.value[resource][action] = customPerms[resource]?.[action];
        }
      }
      
    };

    const selectRole = (role) => {
      selectedRole.value = {
        id: role.id,
        roleKey: role.roleKey,
        name: role.name,
        description: role.description || '',
        isSystemRole: normalizeBooleanFlag(role.isSystemRole),
        permissions: normalizeRolePermissions(role.permissions),
      };
    };

    const startCreateRole = () => {
      selectedRole.value = {
        id: null,
        roleKey: '',
        name: '',
        description: '',
        isSystemRole: false,
        permissions: {},
      };
    };

    const toggleRolePermission = (resourceKey, action) => {
      if (!selectedRole.value.permissions[resourceKey]) {
        selectedRole.value.permissions[resourceKey] = {};
      }
      selectedRole.value.permissions[resourceKey][action] = !Boolean(selectedRole.value.permissions[resourceKey][action]);
    };

    const resetRoleResource = (resourceKey) => {
      selectedRole.value.permissions[resourceKey] = {};
    };

    const resetRolePermissions = () => {
      selectedRole.value.permissions = {};
    };

    const saveRole = async () => {
      if (!selectedRole.value?.name?.trim()) {
        await showInfo('Fehler', 'Bitte einen Rollennamen angeben.', '', 'error');
        return;
      }

      try {
        if (selectedRole.value.id) {
          await apiClient.put(`/permissions/${currentClub.value}/roles/${selectedRole.value.id}`, {
            name: selectedRole.value.name,
            description: selectedRole.value.description,
            permissions: selectedRole.value.permissions,
          });
        } else {
          await apiClient.post(`/permissions/${currentClub.value}/roles`, {
            name: selectedRole.value.name,
            description: selectedRole.value.description,
            permissions: selectedRole.value.permissions,
          });
        }
        await loadData(true);
      } catch (err) {
        console.error('Error saving role:', err);
        await showInfo('Fehler', err.response?.data?.error || 'Rolle konnte nicht gespeichert werden.', '', 'error');
      }
    };

    const deleteSelectedRole = async () => {
      if (!selectedRole.value?.id) return;
      const confirmed = await showConfirm('Rolle löschen', `Möchten Sie die Rolle "${selectedRole.value.name}" wirklich löschen?`, '', 'warning');
      if (!confirmed) return;

      try {
        await apiClient.delete(`/permissions/${currentClub.value}/roles/${selectedRole.value.id}`);
        selectedRole.value = null;
        await loadData(true);
      } catch (err) {
        console.error('Error deleting role:', err);
        await showInfo('Fehler', err.response?.data?.error || 'Rolle konnte nicht gelöscht werden.', '', 'error');
      }
    };

    const closePermissionsDialog = () => {
      selectedMember.value = null;
      customPermissions.value = {};
    };

    const saveCustomPermissions = async () => {
      try {
        // Only send permissions that are explicitly set (not undefined)
        const permissionsToSave = {};
        for (const resourceKey in customPermissions.value) {
          permissionsToSave[resourceKey] = {};
          for (const action in customPermissions.value[resourceKey]) {
            const value = customPermissions.value[resourceKey][action];
            if (value !== undefined) {
              permissionsToSave[resourceKey][action] = value;
            }
          }
          // Only include resource if it has at least one permission set
          if (Object.keys(permissionsToSave[resourceKey]).length === 0) {
            delete permissionsToSave[resourceKey];
          }
        }
        
        const response = await apiClient.put(
          `/permissions/${currentClub.value}/user/${selectedMember.value.userId}/permissions`,
          { permissions: permissionsToSave }
        );
        
        // Update local member data immediately
        const memberIndex = members.value.findIndex(m => m.userId === selectedMember.value.userId);
        if (memberIndex !== -1) {
          members.value[memberIndex].permissions = permissionsToSave;
          members.value[memberIndex].effectivePermissions = response.data?.effectivePermissions || members.value[memberIndex].effectivePermissions;
        }
        
        closePermissionsDialog();
        // Hard reload from server to reflect saved values (cache-busting)
        await loadData(true);
      } catch (err) {
        console.error('Error saving permissions:', err);
        await showInfo(t('messages.error'), err.response?.data?.error || t('permissions.errorSavingPermissions'), '', 'error');
      }
    };

    const togglePermission = (resourceKey, action) => {
      const current = customPermissions.value[resourceKey][action];
      const roleValue = selectedMember.value?.effectivePermissions?.[resourceKey]?.[action] === true;
      
      // Toggle between: role value -> opposite of role value -> role value
      if (current === undefined) {
        // Currently using role value, set to opposite
        customPermissions.value[resourceKey][action] = !roleValue;
      } else {
        // Currently overridden, reset to role value
        customPermissions.value[resourceKey][action] = undefined;
      }
    };

    const resetResource = (resourceKey) => {
      for (const action of permissionStructure.value[resourceKey].actions) {
        customPermissions.value[resourceKey][action] = undefined;
      }
    };

    const resetAll = () => {
      for (const resourceKey in permissionStructure.value) {
        resetResource(resourceKey);
      }
    };

    const stateLabel = (val, resourceKey, action) => {
      if (val === true) return 'Erlaubt';
      if (val === false) return 'Verboten';
      
      // Show role-based permission
      const roleValue = selectedMember.value?.effectivePermissions?.[resourceKey]?.[action] === true;
      return roleValue ? 'Erlaubt' : 'Verboten';
    };

    const stateClass = (val, resourceKey, action) => {
      // If undefined, it's using role value (inherit)
      if (val === undefined) {
        return 'state-inherit';
      }
      
      // If explicitly set, show as override
      return val === true ? 'state-allow' : 'state-deny';
    };

    const getRoleLabel = (roleValue) => {
      const role = availableRoles.value.find(r => r.value === roleValue);
      return role ? role.label : roleValue;
    };

    const getActionLabel = (action) => {
      const labels = {
        read: 'Lesen',
        write: 'Schreiben',
        delete: 'Löschen'
      };
      return labels[action] || action;
    };

    onMounted(() => {
      if (!currentClub.value) {
        error.value = 'Bitte wählen Sie einen Club aus';
        loading.value = false;
        return;
      }

      loadData();
    });

    return {
      t,
      pageTitle,
      pageSubtitle,
      showRoleLegend,
      isRolesMode,
      customizeButtonLabel,
      loading,
      error,
      members,
      availableRoles,
      clubRoles,
      permissionStructure,
      selectedMember,
      selectedRole,
      roleEditorTitle,
      selectedMemberRoleNames,
      customPermissions,
      isReadOnly,
      isOwner,
      isAdmin,
      currentClub,
      infoDialog,
      confirmDialog,
      showInfo,
      showConfirm,
      handleConfirmResult,
      memberHasRole,
      toggleMemberRole,
      toggleMemberStatus,
      openPermissionsDialog,
      closePermissionsDialog,
      selectRole,
      startCreateRole,
      toggleRolePermission,
      resetRoleResource,
      resetRolePermissions,
      saveRole,
      deleteSelectedRole,
      saveCustomPermissions,
      togglePermission,
      resetResource,
      resetAll,
      stateLabel,
      stateClass,
      getRoleLabel,
      getActionLabel
    };
  }
};
</script>

<style scoped>
.permissions-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  margin: 0 0 10px 0;
  color: var(--text-color);
}

.subtitle {
  color: var(--text-muted);
  margin: 0;
}

.loading, .error {
  padding: 20px;
  text-align: center;
  border-radius: 8px;
}

.error {
  background-color: rgba(180, 66, 66, 0.12);
  color: var(--danger-color);
}

.role-legend {
  background: var(--background-soft);
  border: 1px solid var(--border-color);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.role-legend h3 {
  margin-top: 0;
  color: var(--text-color);
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.role-card {
  background: white;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid var(--border-color);
}

.role-name {
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 5px;
}

.role-description {
  font-size: 0.9em;
  color: var(--text-muted);
}

.members-table {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid var(--border-color);
  box-shadow: var(--shadow-soft);
}

.members-table h3 {
  margin-top: 0;
  color: var(--text-color);
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

th {
  background-color: var(--background-soft);
  font-weight: 600;
  color: var(--text-color);
}

.role-select {
  padding: 6px 10px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 0.95em;
}

.role-badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 0.9em;
  font-weight: 500;
}

.role-admin {
  background-color: var(--primary-soft);
  color: var(--primary-dark);
}

.role-trainer {
  background-color: rgba(106, 27, 154, 0.12);
  color: #6a1b9a;
}

.role-team_manager {
  background-color: rgba(212, 132, 30, 0.14);
  color: #9c5700;
}

.role-member {
  background-color: var(--background-soft);
  color: var(--text-muted);
}

.owner-badge {
  font-size: 0.9em;
}

.status-badge {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 0.85em;
  font-weight: 500;
}

.status-active {
  background-color: rgba(46, 125, 50, 0.12);
  color: var(--success-color);
}

.status-inactive {
  background-color: rgba(180, 66, 66, 0.12);
  color: var(--danger-color);
}

.status-badge.clickable {
  cursor: pointer;
  transition: opacity 0.2s;
}

.status-badge.clickable:hover {
  opacity: 0.7;
}

.btn-small {
  padding: 6px 12px;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.btn-small:hover {
  opacity: 0.95;
}

.muted {
  color: #999;
}

/* Dialog Styles */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.dialog-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-strong);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--border-color);
}

.dialog-header h2 {
  margin: 0;
  color: var(--text-color);
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: var(--text-muted);
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: var(--text-color);
}

.dialog-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.info-text {
  background-color: var(--background-soft);
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.permissions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.permission-group {
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 15px;
}

.permission-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-group h4 {
  margin: 0 0 12px 0;
  color: var(--text-color);
  font-size: 1em;
}

.permission-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.permission-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.permission-action-label {
  color: var(--text-color);
}

.permission-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 0.95em;
}

.permission-checkbox input[type="checkbox"] {
  cursor: pointer;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-primary, .btn-secondary {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1em;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
}

.btn-primary:hover {
  opacity: 0.95;
}

.btn-secondary {
  background-color: var(--background-soft);
  color: var(--text-color);
}

.btn-secondary:hover {
  background-color: var(--surface-hover);
}

.btn-reset {
  background: var(--background-soft);
  border: 1px solid var(--border-color);
  color: var(--text-color);
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-reset:disabled {
  opacity: 0.6;
  cursor: default;
}

.perm-state {
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.state-inherit {
  background: var(--background-soft);
  color: var(--text-color);
}

.state-allow {
  background: rgba(46, 125, 50, 0.12);
  color: var(--success-color);
}

.state-deny {
  background: rgba(180, 66, 66, 0.12);
  color: var(--danger-color);
}
</style>
