import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Settings, Shield, Activity, Users, Database, Globe, Search, Trash2, Plus, Download, Upload, Loader2, User, CheckCircle, XCircle } from 'lucide-react';
import { httpClient } from '../../../../core/infrastructure/httpClient';
import { deepNormalize } from '../../../../core/utils/normalize';

interface ActivityStatDto {
  date: string;
  messages: number;
  filesSize: number;
}

interface TopUserDto {
  userId: string;
  username: string;
  value: number;
}

interface Stats {
  storageUsedBytes: number;
  storageLimitBytes: number;
  onlineUsers: number;
  offlineUsers: number;
  totalUsers: number;
  activityTimeline: ActivityStatDto[];
  topUsersByMessages: TopUserDto[];
  topUsersByStorage: TopUserDto[];
}

interface SystemConfig {
  serverTimezone: string;
  domainUrl: string;
  adminRoute: string;
  enableRegistration: boolean;
}

interface StoriesConfig {
  enabled: boolean;
  maxStoriesPerPeriod: number;
  storyLifetimeHours: number;
  textStoriesEnabled: boolean;
  textStoryDurationSeconds: number;
  mediaStoryMaxDurationSeconds: number;
  maxMediaSizeBytes: number;
}

interface ChatsConfig {
  supportGroups: boolean;
  maxGroupParticipants: number;
  enableAutoClean: boolean;
  allowChatToGroupConversion: boolean;
  enableFolders: boolean;
}

interface MessagesConfig {
  dailyMessageLimitPerUser: number;
  chatMessageLimit: number;
  allowMedia: boolean;
  maxMediaSizeBytes: number;
  maxFileSize: number;
  allowedMediaTypes: string[];
  allowVoiceMessages: boolean;
  allowForwarding: boolean;
  allowReactions: boolean;
  allowReplies: boolean;
  allowQuoting: boolean;
  allowMessageDeletion: boolean;
  forbidCopying: boolean;
  allowLinks: boolean;
  allowPolls: boolean;
  allowPinning: boolean;
}

interface WebRtcConfig {
  enabled: boolean;
  enableVideoCalls: boolean;
  enableScreenSharing: boolean;
  turnHost: string;
  turnPort: number;
  turnUser: string;
  turnSecret: string;
}

interface TimezoneDto {
  id: string;
  displayName: string;
  standardName: string;
  offsetMinutes: number;
  offsetString: string;
}

interface KlipyConfig {
  enabled: boolean;
  apiKey: string;
  appName: string;
}

interface ImportConfig {
  enableTelegramImport: boolean;
}

interface FederationDomainConfig {
  domain: string;
  isEnabled: boolean;
}

interface FederationConfig {
  enabled: boolean;
  serverDescription: string;
  allowedDomains: FederationDomainConfig[];
}

interface Conf {
  system: SystemConfig;
  stories: StoriesConfig;
  chats: ChatsConfig;
  messages: MessagesConfig;
  webRtc: WebRtcConfig;
  klipy: KlipyConfig;
  import: ImportConfig;
  federation: FederationConfig;
}

interface AppUser {
  id: string;
  username: string;
  displayName: string;
  avatar: string | null;
  bio?: string;
  createdAt: string;
  lastOnlineAt: string;
  isOnline?: boolean;
  isBanned?: boolean;
  messageCount?: number;
  storageSize?: number;
  stats?: {
    messagesCount: number;
    mediaCount: number;
    filesCount: number;
    linksCount: number;
    storageUsedBytes: number;
  };
}

const translations = {
  en: {
    loginTitle: 'Knot Messager Admin',
    username: 'Username',
    password: 'Password',
    loginBtn: 'Sign In',
    dashboard: 'Overview',
    settingsGroup: 'Settings',
    system: 'System',
    stories: 'Stories',
    chats: 'Chats',
    messages: 'Messages',
    webRtc: 'WebRTC',
    klipy: 'Klipy',
    import: 'Import',
    federation: 'Federation',
    userAnalytics: 'Users',
    storageUsed: 'Storage Used',
    storageFree: 'Free Capacity',
    memoryOccupied: 'Disk space consumed by service modules',
    usersOnline: 'Online',
    usersOffline: 'Offline',
    totalRegistered: 'Total Accounts',
    limits: 'System Limits',
    saveChanges: 'Save Changes',
    copied: 'Copied',
    copy: 'Copy',
    copyPassword: 'Copy Password',
    backToList: 'Back to List',
    searchUsers: 'Search users...',
    addUser: 'Add User',
    noUsersFound: 'No users found',
    registeredOn: 'Registered',
    lastSeen: 'Last seen',
    resetPassword: 'Reset Password',
    deleteUser: 'Delete Account',
    banUser: 'Ban User',
    unbanUser: 'Unban User',
    isBanned: 'Banned',
    blockUser: 'Block User',
    unblockUser: 'Unblock User',
    blockedTooltip: 'Blocked',
    authSecurity: 'Security',
    bio: 'Bio',
    messagesSent: 'Messages',
    mediaSent: 'Media',
    filesSent: 'Files',
    linksSent: 'Links',
    userStorageOccupied: 'Attachments',
    sent: 'Messages',
    storage: 'Attachments',
    displayName: 'Display Name',
    cancel: 'Cancel',
    createUser: 'Create User',
    usernamePlaceholder: 'e.g. jdoe',
    displayNamePlaceholder: 'e.g. John Doe',
    passwordPlaceholder: 'Min. 8 characters',
    generate: 'Generate',
    newPassword: 'New Password',
    testConnection: 'Test Connection',
    apiKey: 'API Key',
    appName: 'App Name',
    domainUrl: 'Domain URL',
    adminPublicPath: 'Admin Path',
    enableReg: 'Public Registration',
    timezone: 'Timezone',
    maxStories: 'Max Stories (24h)',
    storyLifetime: 'Lifetime (h)',
    textStories: 'Text Stories',
    textStoryDuration: 'Text Duration (s)',
    mediaStoryDuration: 'Video Duration (s)',
    maxMediaSize: 'Max Media (MB)',
    supportGroups: 'Group Chats',
    maxGroupMembers: 'Max Members',
    autoClean: 'Auto Cleanup',
    chatToGroup: 'Chat to Group',
    enableFolders: 'Folders',
    allowDelete: 'Allow Deletion',
    maxFileSize: 'Max File (MB)',
    dailyLimit: 'Daily Limit',
    chatLimit: 'History Limit',
    allowMedia: 'Media Attachments',
    voiceMessages: 'Voice Messages',
    forwarding: 'Forwarding',
    reactions: 'Reactions',
    replies: 'Replies',
    quoting: 'Quoting',
    noCopy: 'No Copying',
    links: 'Links',
    polls: 'Polls',
    pinning: 'Pinning',
    voiceCalls: 'Voice Calls',
    videoCalls: 'Video Calls',
    screenSharing: 'Screen Sharing',
    turnHost: 'Host',
    turnPort: 'Port',
    turnUser: 'Username',
    turnSecret: 'Secret',
    turnServerConfig: 'TURN Configuration',
    telegramImport: 'Telegram Import',
    serverDesc: 'Server Description',
    successSave: 'Settings saved',
    successClean: 'Cleanup completed',
    errorSave: 'Save failed',
    errorInvalidLogin: 'Invalid credentials',
    errorDelete: 'Delete failed',
    confirmDelete: 'Are you sure? This action is permanent.',
    online: 'Online',
    offline: 'Offline',
    ban: 'Ban',
    unban: 'Unban',
    allowedNodes: 'Trusted Nodes',
    addNode: 'Add',
    noNodes: 'No nodes added',
    importJson: 'Import JSON',
    exportJson: 'Export JSON',
    importTitle: 'Data Import',
    importDescription: 'Tools for migrating data from external services.',
    maintenance: 'Maintenance',
    analyzeJunk: 'Analyze Memory',
    orphanedMessages: 'Orphaned Messages',
    orphanedMedia: 'Orphaned Media',
    runCleanup: 'Run Cleanup',
    selectUser: 'Select a user',
    maxCapacity: 'Max Capacity',
    top5: '(Top 5)',
    hints: {
      domainUrl: 'Primary URL of your instance.',
      adminRoute: 'Custom path for admin panel.',
      enableRegistration: 'Allow new users to sign up.',
      timezone: 'Server time for logs and tasks.',
      maxStories: 'Max stories per user in 24h.',
      storyLifetime: 'Hours a story remains visible.',
      textStoryDuration: 'Display duration for text stories.',
      mediaStoryDuration: 'Max duration for video stories.',
      maxMediaSize: 'Max file size for story media.',
      supportGroups: 'Enable group chat functionality.',
      maxGroupMembers: 'Max participants per group.',
      autoClean: 'Enable/disable auto-cleanup feature for users. Users manage their own chat timers.',
      chatToGroup: 'Allow upgrading 1-on-1 chats to groups.',
      enableFolders: 'Allow users to use chat folders.',
      dailyLimit: 'Max messages per user day (0 = unlimited).',
      chatLimit: 'Max messages per chat (0 = unlimited).',
      maxFileSize: 'Max size for message attachments.',
      noCopy: 'Prevent text copying in clients.',
      links: 'Make URLs clickable.',
      webRtc: 'Enable WebRTC module. This allows voice calls and voice conferences. Video calls and screen sharing are configured separately.',
      turn: 'Required for calls behind NAT.',
      klipy: 'Integration for stickers and GIFs.',
      federation: 'Communication between different Knot instances.',
      import: 'Data migration from other services.',
      voiceCalls: 'Allow audio calls.',
      videoCalls: 'Allow video calls.',
      screenSharing: 'Allow screen sharing.',
      turnHost: 'TURN server domain or IP.',
      turnPort: 'TURN server port.',
      turnUser: 'TURN username.',
      turnSecret: 'TURN shared secret.',
      turnServerConfig: 'WebRTC relay settings.',
      appName: 'Klipy App ID.',
      apiKey: 'Klipy API Key.',
      allowMedia: 'Permit media in messages.',
      voiceMessages: 'Permit voice recordings.',
      forwarding: 'Permit message relaying.',
      reactions: 'Permit emoji reactions.',
      replies: 'Permit message threading.',
      quoting: 'Permit message quoting.',
      allowDelete: 'Allow users to delete messages.',
      polls: 'Enable group polls.',
      pinning: 'Enable message pinning.'
    }
  },
  ru: {
    loginTitle: 'Knot Messager Admin',
    username: 'Логин',
    password: 'Пароль',
    loginBtn: 'Войти',
    dashboard: 'Обзор',
    settingsGroup: 'Настройки',
    system: 'Система',
    stories: 'Истории',
    chats: 'Чаты',
    messages: 'Сообщения',
    webRtc: 'WebRTC',
    klipy: 'Klipy',
    import: 'Импорт',
    federation: 'Федерация',
    userAnalytics: 'Пользователи',
    storageUsed: 'Занято',
    storageFree: 'Свободно',
    memoryOccupied: 'Объем данных всех модулей',
    usersOnline: 'В сети',
    usersOffline: 'Оффлайн',
    totalRegistered: 'Всего аккаунтов',
    limits: 'Лимиты системы',
    saveChanges: 'Сохранить',
    copied: 'Скопировано',
    copy: 'Копировать',
    copyPassword: 'Копировать пароль',
    backToList: 'К списку',
    searchUsers: 'Поиск...',
    addUser: 'Добавить пользователя',
    noUsersFound: 'Никого не нашли',
    registeredOn: 'Регистрация',
    lastSeen: 'Был(а)',
    resetPassword: 'Сброс пароля',
    deleteUser: 'Удалить аккаунт',
    banUser: 'Забанить',
    unbanUser: 'Разбанить',
    isBanned: 'Забанен',
    blockUser: 'Заблокировать',
    unblockUser: 'Разблокировать',
    blockedTooltip: 'Заблокирован',
    authSecurity: 'Безопасность',
    bio: 'О себе',
    messagesSent: 'Сообщения',
    mediaSent: 'Медиа',
    filesSent: 'Файлы',
    linksSent: 'Ссылки',
    userStorageOccupied: 'Вложения',
    sent: 'Сообщения',
    storage: 'Вложения',
    displayName: 'Имя',
    cancel: 'Отмена',
    createUser: 'Создать',
    usernamePlaceholder: 'логин',
    displayNamePlaceholder: 'Имя Фамилия',
    passwordPlaceholder: 'от 8 символов',
    generate: 'Сгенерировать',
    newPassword: 'Новый пароль',
    testConnection: 'Проверить',
    apiKey: 'API ключ',
    appName: 'Имя приложения',
    domainUrl: 'URL домена',
    adminPublicPath: 'Путь админки',
    enableReg: 'Регистрация',
    timezone: 'Пояс',
    maxStories: 'Макс. историй (24ч)',
    storyLifetime: 'Время жизни (ч)',
    textStories: 'Текст в историях',
    textStoryDuration: 'Длительность текста (сек)',
    mediaStoryDuration: 'Длительность видео (сек)',
    maxMediaSize: 'Макс. медиа (МБ)',
    supportGroups: 'Групповые чаты',
    maxGroupMembers: 'Макс. участников',
    autoClean: 'Автоочистка',
    chatToGroup: 'Чат в группу',
    enableFolders: 'Папки',
    allowDelete: 'Удаление',
    maxFileSize: 'Макс. файл (МБ)',
    dailyLimit: 'Дневной лимит',
    chatLimit: 'Лимит истории',
    allowMedia: 'Медиа в сообщениях',
    voiceMessages: 'Голосовые',
    forwarding: 'Пересылка',
    reactions: 'Реакции',
    replies: 'Ответы',
    quoting: 'Цитирование',
    noCopy: 'Запрет копирования',
    links: 'Ссылки',
    polls: 'Опросы',
    pinning: 'Закрепы',
    voiceCalls: 'Аудиозвонки',
    videoCalls: 'Видеозвонки',
    screenSharing: 'Экран',
    turnHost: 'Хост',
    turnPort: 'Порт',
    turnUser: 'Логин',
    turnSecret: 'Секрет',
    turnServerConfig: 'TURN сервер',
    telegramImport: 'Импорт Telegram',
    serverDesc: 'Описание сервера',
    successSave: 'Сохранено',
    successClean: 'Очищено',
    errorSave: 'Ошибка сохранения',
    errorInvalidLogin: 'Неверный логин или пароль',
    errorDelete: 'Ошибка удаления',
    confirmDelete: 'Вы уверены? Это действие нельзя отменить.',
    online: 'В сети',
    offline: 'Оффлайн',
    ban: 'Бан',
    unban: 'Разбан',
    allowedNodes: 'Доверенные узлы',
    addNode: 'Добавить',
    noNodes: 'Узлов нет',
    importJson: 'Импорт JSON',
    exportJson: 'Экспорт JSON',
    importTitle: 'Импорт данных',
    importDescription: 'Миграция данных из внешних сервисов.',
    maintenance: 'Обслуживание',
    analyzeJunk: 'Анализ памяти',
    orphanedMessages: 'Брошенные сообщения',
    orphanedMedia: 'Лишние файлы',
    runCleanup: 'Очистить',
    selectUser: 'Выберите пользователя',
    maxCapacity: 'Лимит диска',
    top5: '(Топ 5)',
    hints: {
      domainUrl: 'Основной адрес сервера.',
      adminRoute: 'Путь для входа в админку.',
      enableRegistration: 'Разрешить регистрацию новых пользователей.',
      timezone: 'Часовой пояс сервера.',
      maxStories: 'Лимит историй от одного пользователя за 24 часа.',
      storyLifetime: 'Сколько часов история будет видна.',
      textStoryDuration: 'Длительность текстовой истории в секундах.',
      mediaStoryDuration: 'Лимит видео в историях по времени.',
      maxMediaSize: 'Лимит одного файла в историях.',
      supportGroups: 'Включить группы.',
      maxGroupMembers: 'Максимум людей в одной группе.',
      autoClean: 'Разрешить пользователям использовать функцию автоочистки. Самим процессом (таймерами) управляют пользователи в своих чатах.',
      chatToGroup: 'Разрешить создавать группы из чатов.',
      enableFolders: 'Разрешить папки чатов.',
      dailyLimit: 'Лимит сообщений в сутки (0 = без лимита).',
      chatLimit: 'Максимум сообщений в чате (0 = без лимита).',
      maxFileSize: 'Лимит файлов в сообщениях.',
      noCopy: 'Мешать копированию текста.',
      links: 'Автоматические ссылки.',
      webRtc: 'Включить модуль WebRTC. Это позволяет совершать аудиозвонки и аудиоконференции. Видеозвонки и трансляция экрана настраиваются отдельно.',
      turn: 'Нужно для звонков за NAT.',
      klipy: 'Стикеры и GIF.',
      federation: 'Связь с другими серверами Knot.',
      import: 'Перенос данных извне.',
      voiceCalls: 'Разрешить аудиозвонки.',
      videoCalls: 'Разрешить видеозвонки.',
      screenSharing: 'Разрешить трансляцию экрана.',
      turnHost: 'Хост TURN сервера.',
      turnPort: 'Порт TURN сервера.',
      turnUser: 'Логин TURN.',
      turnSecret: 'Секрет TURN.',
      turnServerConfig: 'Настройки реле WebRTC.',
      appName: 'ID приложения Klipy.',
      apiKey: 'Ключ Klipy.',
      allowMedia: 'Медиа в чатах.',
      voiceMessages: 'Голосовые сообщения.',
      forwarding: 'Пересылка сообщений.',
      reactions: 'Эмодзи-реакции.',
      replies: 'Ветки ответов.',
      quoting: 'Цитирование сообщений.',
      allowDelete: 'Удаление своих сообщений.',
      polls: 'Опросы в группах.',
      pinning: 'Закрепление сообщений.'
    }
  }
};

const Hint = ({ children }: { children: React.ReactNode }) => (
  <p className="text-[10px] text-gray-500 mt-1 leading-relaxed">{children}</p>
);

export default function AdminPage() {
  const [activeTab, setActiveTab] = useState('dashboard');
  const [activeSettingsTab, setActiveSettingsTab] = useState('system');
  const [lang, setLang] = useState<'en' | 'ru'>('ru');
  const t = translations[lang];

  const formatDateTime = (dateStr: string) => {
    const d = new Date(dateStr);
    const options: Intl.DateTimeFormatOptions = {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit'
    };
    return d.toLocaleDateString(lang === 'ru' ? 'ru-RU' : 'en-US', options).replace(',', '');
  };

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const dm = 2;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  };

  const bytesToMb = (bytes: number) => Math.floor(bytes / (1024 * 1024));
  const mbToBytes = (mb: number) => mb * 1024 * 1024;

  interface CleanStats {
    orphanedMessagesCount: number;
    orphanedMediaBytes: number;
  }

  const [stats, setStats] = useState<Stats | null>(null);
  const [config, setConfig] = useState<Conf | null>(null);
  const [cleanStats, setCleanStats] = useState<CleanStats | null>(null);
  const [authHeader, setAuthHeader] = useState(localStorage.getItem('knot_admin_auth') || '');
  const [creds, setCreds] = useState({ user: '', pass: '' });
  const [authenticated, setAuthenticated] = useState(false);

  const [users, setUsers] = useState<AppUser[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearching, setIsSearching] = useState(false);
  const [selectedUser, setSelectedUser] = useState<AppUser | null>(null);

  const [isTestingTurn, setIsTestingTurn] = useState<boolean>(false);
  const [isTestingKlipy, setIsTestingKlipy] = useState<boolean>(false);

  const [domainInput, setDomainInput] = useState('');

  // Add User State
  const [showAddUserModal, setShowAddUserModal] = useState(false);
  const [newUser, setNewUser] = useState({ username: '', displayName: '', password: '' });
  const [generatedPass, setGeneratedPass] = useState('');

  // Delete User Modal State
  const [deleteUserModal, setDeleteUserModal] = useState<{ userId: string; username: string } | null>(null);

  const [timezones, setTimezones] = useState<TimezoneDto[]>([]);
  const [tzSearch, setTzSearch] = useState('');
  const [showTzDropdown, setShowTzDropdown] = useState(false);

  const [toast, setToast] = useState<{ message: string, type: 'success' | 'error' } | null>(null);

  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  const generatePassword = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()';
    let pass = '';
    for (let i = 0; i < 12; i++) pass += chars[Math.floor(Math.random() * chars.length)];
    return pass;
  };

  const handleAddUser = async () => {
    try {
      await httpClient.request('/admin/users', {
        method: 'POST',
        body: JSON.stringify({ ...newUser, email: null, bio: null })
      });
      showToast(t.successSave, 'success');
      setShowAddUserModal(false);
      setNewUser({ username: '', displayName: '', password: '' });
      searchUsers(searchQuery);
    } catch {
      showToast(t.errorSave, 'error');
    }
  };

  const handleResetPassword = async (userId: string) => {
    const newPass = generatePassword();
    try {
      await httpClient.request(`/admin/users/${userId}/reset-password`, {
        method: 'POST',
        body: JSON.stringify({ newPassword: newPass })
      });
      setGeneratedPass(newPass);
    } catch {
      showToast(t.errorSave, 'error');
    }
  };

  const handleBanUser = async (userId: string) => {
    try {
      await httpClient.request(`/admin/users/${userId}/ban`, { method: 'POST' });
      showToast(t.successSave, 'success');
      if (selectedUser && selectedUser.id === userId) {
        setSelectedUser(prev => prev ? { ...prev, isBanned: true } : null);
      }
      setUsers(users.map(u => u.id === userId ? { ...u, isBanned: true } : u));
    } catch {
      showToast(t.errorSave, 'error');
    }
  };

  const handleUnbanUser = async (userId: string) => {
    try {
      await httpClient.request(`/admin/users/${userId}/unban`, { method: 'POST' });
      showToast(t.successSave, 'success');
      if (selectedUser && selectedUser.id === userId) {
        setSelectedUser(prev => prev ? { ...prev, isBanned: false } : null);
      }
      setUsers(users.map(u => u.id === userId ? { ...u, isBanned: false } : u));
    } catch {
      showToast(t.errorSave, 'error');
    }
  };

  const handleDeleteUser = async (userId: string) => {
    setDeleteUserModal(null);
    try {
      await httpClient.request(`/admin/users/${userId}`, { method: 'DELETE' });
      showToast(t.successSave, 'success');
      setSelectedUser(null);
      searchUsers(searchQuery);
    } catch {
      showToast(t.errorDelete, 'error');
    }
  };

  const fetchDashboard = async () => {
    try {
      const res = await httpClient.request<Stats>('/admin/dashboard');
      setStats(res);
    } catch { }
  };

  const fetchSettings = async () => {
    try {
      const res = await httpClient.request<Conf>('/admin/settings');
      setConfig(res);
    } catch { }
  };

  const fetchTimezones = async () => {
    try {
      const res = await httpClient.request<TimezoneDto[]>('/admin/timezones');
      setTimezones(res);
    } catch { }
  };

  const saveSettings = async () => {
    if (!config) return;
    try {
      await httpClient.request('/admin/settings', {
        method: 'PUT',
        body: JSON.stringify(config)
      });
      showToast(t.successSave, 'success');
    } catch { showToast(t.errorSave, 'error'); }
  };

  const handleTestTurn = async () => {
    if (!config || !config.webRtc.turnHost) return;
    setIsTestingTurn(true);
    let resolved = false;

    try {
      const turnUrl = `turn:${config.webRtc.turnHost}:${config.webRtc.turnPort}`;
      const stunUrl = `stun:${config.webRtc.turnHost}:${config.webRtc.turnPort}`;

      const servers: RTCIceServer[] = [
        { urls: stunUrl }
      ];

      if (config.webRtc.turnUser) {
        servers.push({
          urls: [turnUrl, turnUrl + "?transport=tcp"],
          username: config.webRtc.turnUser,
          credential: config.webRtc.turnSecret || config.webRtc.turnUser
        });
      }

      const pc = new RTCPeerConnection({ iceServers: servers });
      pc.createDataChannel('test');
      const offer = await pc.createOffer();
      await pc.setLocalDescription(offer);

      await new Promise<void>((resolve, reject) => {
        const timeout = setTimeout(() => {
          if (!resolved) { resolved = true; reject(new Error("Timeout")); }
        }, 10000);

        pc.onicecandidate = (e) => {
          if (e.candidate && (e.candidate.type === 'relay' || e.candidate.type === 'srflx')) {
            if (!resolved) { resolved = true; clearTimeout(timeout); resolve(); }
          }
          if (e.candidate === null) {
            if (!resolved) { resolved = true; clearTimeout(timeout); reject(new Error("Failed to gather candidates")); }
          }
        };
      });

      showToast("Success", 'success');
      pc.close();
    } catch (err: any) {
      showToast("Error: " + err.message, 'error');
    } finally {
      setIsTestingTurn(false);
    }
  };

  const handleTestKlipy = async () => {
    if (!config || !config.klipy.apiKey) {
      showToast("API Key is required", 'error');
      return;
    }

    setIsTestingKlipy(true);
    try {
      await httpClient.request('/admin/settings/test-klipy', {
        method: 'POST',
        body: JSON.stringify({
          apiKey: config.klipy.apiKey,
          appName: config.klipy.appName
        })
      });
      showToast("Success", 'success');
    } catch {
      showToast("Failed", 'error');
    } finally {
      setIsTestingKlipy(false);
    }
  };

  const handleCalcCleanup = async () => {
    try {
      const res = await httpClient.request<CleanStats>('/admin/clean/dry-run');
      setCleanStats(res);
    } catch { showToast(t.errorSave, 'error'); }
  };

  const handleRunCleanup = async () => {
    try {
      await httpClient.request('/admin/clean/run', { method: 'POST' });
      showToast(t.successClean, 'success');
      setCleanStats(null);
      fetchDashboard();
    } catch { showToast(t.errorSave, 'error'); }
  };

  const addDomain = () => {
    if (!config || !domainInput) return;
    const domain = domainInput.trim().toLowerCase();
    const domains = [...config.federation.allowedDomains];
    if (domains.find(d => d.domain === domain)) return;
    domains.push({ domain, isEnabled: true });
    setConfig({ ...config, federation: { ...config.federation, allowedDomains: domains } });
    setDomainInput('');
  };

  const removeDomain = (domain: string) => {
    if (!config) return;
    const domains = config.federation.allowedDomains.filter(d => d.domain !== domain);
    setConfig({ ...config, federation: { ...config.federation, allowedDomains: domains } });
  };

  const exportDomains = () => {
    if (!config) return;
    const blob = new Blob([JSON.stringify(config.federation.allowedDomains, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'federation-whitelist.json';
    a.click();
    URL.revokeObjectURL(url);
  };

  const importDomains = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !config) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const data = JSON.parse(ev.target?.result as string);
        if (Array.isArray(data)) {
          setConfig({ ...config, federation: { ...config.federation, allowedDomains: data } });
        }
      } catch { showToast("Invalid JSON", 'error'); }
    };
    reader.readAsText(file);
  };

  const searchUsers = async (q: string) => {
    setIsSearching(true);
    try {
      const res = await httpClient.request<AppUser[]>(`/admin/users?query=${encodeURIComponent(q)}`);
      setUsers(res);
    } catch { } finally {
      setIsSearching(false);
    }
  };

  const fetchUserStats = async (id: string) => {
    try {
      const res = await httpClient.request<AppUser>(`/admin/users/${id}`);
      setSelectedUser(res);
    } catch { }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    const header = `Basic ${btoa(`${creds.user}:${creds.pass}`)}`;
    httpClient.setToken(header);

    try {
      await httpClient.request('/admin/dashboard');
      setAuthHeader(header);
      localStorage.setItem('knot_admin_auth', header);
      setAuthenticated(true);
      fetchDashboard();
      fetchSettings();
      fetchTimezones();
      searchUsers('');
    } catch (err: any) {
      showToast(t.errorInvalidLogin, 'error');
      if (err.status === 401 || err.status === 403) {
        httpClient.setToken(null);
        localStorage.removeItem('knot_admin_auth');
      }
    }
  };

  useEffect(() => {
    const initAuth = async () => {
      const savedHeader = localStorage.getItem('knot_admin_auth');
      if (savedHeader) {
        httpClient.setToken(savedHeader);
        try {
          await httpClient.request('/admin/dashboard');
          setAuthenticated(true);
          fetchDashboard();
          fetchSettings();
          fetchTimezones();
          searchUsers('');
        } catch (err: any) {
          console.error('Session verify failed', err);
          if (err.status === 401 || err.status === 403 || (err.message && err.message.includes('auth'))) {
             localStorage.removeItem('knot_admin_auth');
             httpClient.setToken(null);
             setAuthenticated(false);
             setAuthHeader('');
          }
        }
      }
    };
    initAuth();
  }, []);

  useEffect(() => {
    if (!authenticated || !authHeader) return;
    const interval = setInterval(() => {
      if (activeTab === 'dashboard') {
        fetchDashboard();
      }
    }, 10000);
    return () => clearInterval(interval);
  }, [authenticated, authHeader, activeTab]);

  if (!authenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-surface-container-lowest text-on-surface font-sans">
        <form onSubmit={handleLogin} className="knot-card p-12 w-full max-w-sm flex flex-col items-center gap-8 border border-outline-variant/10">
          <div className="w-16 h-16 rounded-3xl bg-primary/10 border border-primary/20 flex items-center justify-center text-primary">
            <span className="material-symbols-outlined text-4xl">hub</span>
          </div>

          <div className="text-center">
            <h1 className="text-3xl font-black font-headline tracking-tighter uppercase mb-2">{t.loginTitle}</h1>
            <p className="text-[10px] font-black text-on-surface-variant/40 uppercase tracking-[0.3em]">Administrator</p>
          </div>

          <div className="w-full flex flex-col gap-5">
            <div className="knot-input-group">
              <label className="block text-[11px] font-black uppercase tracking-[0.2em] text-on-surface-variant/40 mb-3 ml-1">
                {lang === 'ru' ? 'ИМЯ ПОЛЬЗОВАТЕЛЯ' : 'USERNAME'}
              </label>
              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-on-surface-variant/40 text-[20px]">person</span>
                <input
                  type="text"
                  placeholder="username"
                  className="w-full pl-12 pr-4 py-4 rounded-2xl bg-surface-container-highest/60 text-on-surface placeholder-on-surface-variant/20 border-none focus:ring-2 focus:ring-primary/20 transition-all outline-none text-[15px]"
                  value={creds.user}
                  onChange={(e) => setCreds({ ...creds, user: e.target.value })}
                  autoComplete="off"
                />
              </div>
            </div>

            <div className="knot-input-group">
              <label className="block text-[11px] font-black uppercase tracking-[0.2em] text-on-surface-variant/40 mb-3 ml-1">
                {lang === 'ru' ? 'ПАРОЛЬ' : 'PASSWORD'}
              </label>
              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-on-surface-variant/40 text-[20px]">lock</span>
                <input
                  type="password"
                  placeholder="••••••••"
                  className="w-full pl-12 pr-4 py-4 rounded-2xl bg-surface-container-highest/60 text-on-surface placeholder-on-surface-variant/20 border-none focus:ring-2 focus:ring-primary/20 transition-all outline-none text-[15px]"
                  value={creds.pass}
                  onChange={(e) => setCreds({ ...creds, pass: e.target.value })}
                  autoComplete="current-password"
                />
              </div>
            </div>
          </div>

          <button className="knot-button-primary w-full py-4.5 flex items-center justify-center gap-3 slide-on-ice mt-4">
            <span className="font-black uppercase tracking-widest text-[14px]">{t.loginBtn}</span>
            <span className="material-symbols-outlined text-[20px]">arrow_forward</span>
          </button>

          <div className="flex gap-4 p-1.5 bg-surface-container-highest/20 rounded-2xl w-full">
            <button type="button" onClick={() => setLang('ru')} className={`flex-1 py-3 text-[11px] font-black rounded-xl transition-all ${lang === 'ru' ? 'bg-primary text-on-primary' : 'text-on-surface-variant/40 hover:text-on-surface'}`}>RU</button>
            <button type="button" onClick={() => setLang('en')} className={`flex-1 py-3 text-[11px] font-black rounded-xl transition-all ${lang === 'en' ? 'bg-primary text-on-primary' : 'text-on-surface-variant/40 hover:text-on-surface'}`}>EN</button>
          </div>
        </form>
      </div>
    );
  }

  return (
    <div className="h-full flex overflow-hidden bg-surface-container-lowest text-on-surface font-sans selection:bg-primary/30">
      {/* Sidebar */}
      <aside className="w-[280px] flex-shrink-0 bg-surface-container-low border-r border-outline-variant/10 flex flex-col slide-on-ice z-20">
        <div className="p-8 pb-4 flex items-center gap-4">
          <div className="w-10 h-10 rounded-2xl bg-primary/10 border border-primary/20 flex items-center justify-center">
            <span className="material-symbols-outlined text-primary text-[24px]">hub</span>
          </div>
          <h2 className="text-xl font-black font-headline tracking-tighter">Knot</h2>
        </div>

        <nav className="flex-1 overflow-y-auto px-4 py-6 space-y-1 custom-scrollbar">
          <div className="px-4 mb-4 text-[10px] font-black uppercase tracking-[0.2em] text-on-surface-variant/30">
            {t.dashboard}
          </div>
          <NavButton icon="dashboard" label={t.dashboard} active={activeTab === 'dashboard'} onClick={() => setActiveTab('dashboard')} />
          <NavButton icon="group" label={t.userAnalytics} active={activeTab === 'users'} onClick={() => { setActiveTab('users'); setSelectedUser(null); }} />

          <div className="px-4 mt-8 mb-4 text-[10px] font-black uppercase tracking-[0.2em] text-on-surface-variant/30">
            {t.settingsGroup}
          </div>
          <NavButton icon="settings" label={t.system} active={activeTab === 'settings' && activeSettingsTab === 'system'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('system'); }} />
          <NavButton icon="auto_stories" label={t.stories} active={activeTab === 'settings' && activeSettingsTab === 'stories'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('stories'); }} />
          <NavButton icon="chat_bubble" label={t.chats} active={activeTab === 'settings' && activeSettingsTab === 'chats'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('chats'); }} />
          <NavButton icon="message" label={t.messages} active={activeTab === 'settings' && activeSettingsTab === 'messages'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('messages'); }} />
          <NavButton icon="call" label={t.webRtc} active={activeTab === 'settings' && activeSettingsTab === 'webRtc'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('webRtc'); }} />
          <NavButton icon="gif_box" label={t.klipy} active={activeTab === 'settings' && activeSettingsTab === 'klipy'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('klipy'); }} />
          <NavButton icon="download" label={t.importTitle} active={activeTab === 'settings' && activeSettingsTab === 'import'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('import'); }} />
          <NavButton icon="language" label={t.federation} active={activeTab === 'settings' && activeSettingsTab === 'federation'} onClick={() => { setActiveTab('settings'); setActiveSettingsTab('federation'); }} />
        </nav>

        <div className="p-4 border-t border-outline-variant/10">
          <button
            onClick={() => setLang(lang === 'ru' ? 'en' : 'ru')}
            className="w-full flex items-center justify-between p-3 rounded-2xl bg-surface-container-highest/10 hover:bg-surface-container-highest/20 transition-all border border-outline-variant/5 group slide-on-ice"
          >
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-xl bg-primary/10 flex items-center justify-center text-[10px] font-black text-primary">
                {lang.toUpperCase()}
              </div>
              <span className="text-[13px] font-bold text-on-surface-variant group-hover:text-on-surface transition-colors">
                {lang === 'ru' ? 'Русский' : 'English'}
              </span>
            </div>
            <span className="material-symbols-outlined text-on-surface-variant/20 group-hover:text-primary transition-colors text-[18px]">language</span>
          </button>
        </div>
      </aside>

      {/* Content */}
      <main className="flex-1 p-8 overflow-y-auto relative">
        <AnimatePresence mode="wait">
          {activeTab === 'dashboard' && stats && (
            <motion.div key="dashboard" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} className="flex flex-col gap-6 max-w-5xl">
              <h1 className="text-3xl font-bold">{t.dashboard}</h1>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                <div className="knot-card p-10 lg:col-span-2 relative overflow-hidden group border border-outline-variant/10">
                  <div className="flex justify-between items-end mb-8">
                    <div>
                      <h3 className="text-on-surface-variant/40 text-[10px] mb-2 flex items-center gap-3 uppercase tracking-[0.3em] font-black">
                        <span className="material-symbols-outlined text-primary text-sm">database</span> {t.storageUsed}
                      </h3>
                      <div className="text-5xl font-black font-headline tracking-tighter flex items-baseline gap-3">
                        {formatBytes(stats.storageUsedBytes)}
                        <span className="text-sm font-medium text-on-surface-variant/20 tracking-normal">/ {formatBytes(stats.storageLimitBytes)}</span>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-2xl font-black text-accent leading-none">
                        {((stats.storageUsedBytes / (stats.storageLimitBytes || 1)) * 100).toFixed(1)}%
                      </div>
                      <div className="text-[10px] text-gray-500 uppercase font-bold mt-1 tracking-tighter">{t.maxCapacity}</div>
                    </div>
                  </div>
                  <div className="w-full bg-white/5 h-3 rounded-full overflow-hidden p-[2px] border border-white/5">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${Math.min((stats.storageUsedBytes / (stats.storageLimitBytes || 1)) * 100, 100)}%` }}
                      transition={{ duration: 1, ease: "easeOut" }}
                      className="bg-accent h-full rounded-full shadow-[0_0_20px_rgba(var(--accent-rgb),0.3)]"
                    />
                  </div>
                </div>

                <div className="bg-surface border border-white/10 p-8 rounded-3xl lg:col-span-1">
                  <h3 className="text-gray-400 text-[10px] mb-4 flex items-center gap-2 uppercase tracking-[0.2em] font-black">
                    <Users className="w-4 h-4 text-accent" /> {t.totalRegistered}
                  </h3>
                  <div className="text-5xl font-black mb-2 tracking-tighter">{stats.totalUsers}</div>
                  <div className="flex items-center gap-2">
                    <span className="flex h-2 w-2 relative">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                      <span className="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
                    </span>
                    <span className="text-xs text-green-400 font-bold uppercase tracking-wider">{stats.onlineUsers} {t.usersOnline}</span>
                  </div>
                </div>

                <div className="bg-surface border border-white/10 p-6 rounded-2xl lg:col-span-3">
                  <h3 className="text-gray-400 text-sm mb-4">{t.maintenance}</h3>
                  {!cleanStats ? (
                    <button onClick={handleCalcCleanup} className="bg-accent/10 hover:bg-accent/20 text-accent px-4 py-2 rounded-xl transition-colors">{t.analyzeJunk}</button>
                  ) : (
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <div className="bg-black/20 p-4 rounded-xl flex flex-col justify-between min-h-[100px]">
                        <div className="text-xs text-gray-500">{t.orphanedMessages}</div>
                        <div className="text-xl font-bold">{cleanStats.orphanedMessagesCount}</div>
                      </div>
                      <div className="bg-black/20 p-4 rounded-xl flex flex-col justify-between min-h-[100px]">
                        <div className="text-xs text-gray-500">{t.orphanedMedia}</div>
                        <div className="text-xl font-bold">{formatBytes(cleanStats.orphanedMediaBytes)}</div>
                      </div>
                      <div className="col-span-2 flex items-end justify-end">
                        <button onClick={handleRunCleanup} className="bg-red-500/20 hover:bg-red-500/30 text-red-400 px-6 py-2 rounded-xl transition-colors font-bold">{t.runCleanup}</button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </motion.div>
          )}

          {activeTab === 'settings' && config && (
            <motion.div key="settings" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} className="flex flex-col gap-6 max-w-4xl pb-20">
              <div className="flex items-center gap-4 mb-2">
                <h1 className="text-3xl font-bold uppercase tracking-tight text-white/90">
                  {String(t[activeSettingsTab as keyof typeof t] || activeSettingsTab)}
                </h1>
                <div className="ml-auto flex gap-2">
                  <button onClick={fetchSettings} className="p-3 hover:bg-surface-container-highest/10 rounded-2xl text-on-surface-variant/60 hover:text-on-surface transition-all active:scale-95 slide-on-ice">
                    <span className="material-symbols-outlined text-[20px] font-black">sync</span>
                  </button>
                  <button onClick={saveSettings} className="knot-button-primary px-10 py-3 rounded-2xl flex items-center gap-3 slide-on-ice">
                    <span className="text-[11px] font-black uppercase tracking-widest">{t.saveChanges}</span>
                    <span className="material-symbols-outlined text-[18px]">save</span>
                  </button>
                </div>
              </div>

              {/* System Settings */}
              {activeSettingsTab === 'system' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10">
                  <h3 className="text-xl font-semibold opacity-30 uppercase tracking-widest text-sm">{t.system}</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-8">
                    <label className="flex flex-col gap-1.5 group">
                      <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1 group-focus-within:text-accent transition-colors">{t.domainUrl}</span>
                      <input className="knot-input-group" value={config.system.domainUrl} onChange={e => setConfig({ ...config, system: { ...config.system, domainUrl: e.target.value } })} />
                      <Hint>{t.hints.domainUrl}</Hint>
                    </label>
                    <label className="flex flex-col gap-1.5 group">
                      <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1 group-focus-within:text-accent transition-colors">{t.adminPublicPath}</span>
                      <input className="knot-input-group" value={config.system.adminRoute} onChange={e => setConfig({ ...config, system: { ...config.system, adminRoute: e.target.value } })} placeholder="/admin" />
                      <Hint>{t.hints.adminRoute}</Hint>
                    </label>
                    <div className="bg-surface-container-highest/20 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-gray-200 font-semibold">{t.enableReg}</span>
                        <Toggle checked={config.system.enableRegistration} onChange={v => setConfig({ ...config, system: { ...config.system, enableRegistration: v } })} />
                      </div>
                      <Hint>{t.hints.enableRegistration}</Hint>
                    </div>
                    <div className="flex flex-col gap-1.5 group relative">
                      <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1 group-focus-within:text-primary transition-colors">{t.timezone}</span>
                      <div className="relative">
                        <input
                          className="w-full knot-input-group transition-all font-mono text-xs pr-10"
                          value={config.system.serverTimezone}
                          onFocus={() => setShowTzDropdown(true)}
                          onChange={e => {
                            setConfig({ ...config, system: { ...config.system, serverTimezone: e.target.value } });
                            setTzSearch(e.target.value);
                          }}
                          placeholder="UTC"
                        />
                        <span className="material-symbols-outlined absolute right-4 top-1/2 -translate-y-1/2 text-on-surface-variant/30">public</span>

                        <AnimatePresence>
                          {showTzDropdown && (
                            <motion.div
                              initial={{ opacity: 0, y: -10 }}
                              animate={{ opacity: 1, y: 0 }}
                              exit={{ opacity: 0, y: -10 }}
                              className="absolute left-0 right-0 top-full mt-2 bg-surface-container-high border border-outline-variant/10 rounded-3xl shadow-[0_16px_48px_rgba(0,0,0,0.6)] z-[100] max-h-64 overflow-y-auto custom-scrollbar p-2"
                            >
                              {timezones
                                .filter(tz => tz.displayName.toLowerCase().includes(tzSearch.toLowerCase()) || tz.id.toLowerCase().includes(tzSearch.toLowerCase()))
                                .map(tz => (
                                  <button
                                    key={tz.id}
                                    onClick={() => {
                                      setConfig({ ...config, system: { ...config.system, serverTimezone: tz.id } });
                                      setTzSearch('');
                                      setShowTzDropdown(false);
                                    }}
                                    className="w-full text-left p-4 hover:bg-primary/10 rounded-2xl transition-all flex flex-col gap-1 group"
                                  >
                                    <div className="flex justify-between items-center w-full">
                                      <span className="text-[13px] font-bold text-on-surface group-hover:text-primary transition-colors">{tz.displayName}</span>
                                      <span className="text-[10px] font-mono text-gray-500 group-hover/tz:text-accent/50 ml-2 shrink-0">{tz.offsetString}</span>
                                    </div>
                                    <span className="text-[10px] text-gray-600 truncate">{tz.id}</span>
                                  </button>
                                ))
                              }
                            </motion.div>
                          )}
                        </AnimatePresence>
                      </div>
                      {showTzDropdown && <div className="fixed inset-0 z-[90]" onClick={() => setShowTzDropdown(false)} />}
                      <Hint>{t.hints.timezone}</Hint>
                    </div>
                  </div>
                </div>
              )}

              {/* Stories Settings */}
              {activeSettingsTab === 'stories' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xl font-semibold opacity-30 uppercase tracking-widest text-sm">{t.stories}</h3>
                    <Toggle checked={config.stories.enabled} onChange={v => setConfig({ ...config, stories: { ...config.stories, enabled: v } })} />
                  </div>
                  {config.stories.enabled && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-10 pt-4 border-t border-white/10">
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.maxStories}</span>
                        <input type="number" className="knot-input-group" value={config.stories.maxStoriesPerPeriod} onChange={e => setConfig({ ...config, stories: { ...config.stories, maxStoriesPerPeriod: parseInt(e.target.value) || 0 } })} />
                        <Hint>{t.hints.maxStories}</Hint>
                      </label>
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.storyLifetime}</span>
                        <input type="number" className="knot-input-group" value={config.stories.storyLifetimeHours} onChange={e => setConfig({ ...config, stories: { ...config.stories, storyLifetimeHours: parseInt(e.target.value) || 0 } })} />
                        <Hint>{t.hints.storyLifetime}</Hint>
                      </label>
                      <div className="bg-surface-container-highest/20 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-200 font-semibold">{t.textStories}</span>
                          <Toggle checked={config.stories.textStoriesEnabled} onChange={v => setConfig({ ...config, stories: { ...config.stories, textStoriesEnabled: v } })} />
                        </div>
                        <Hint>{t.hints.textStoryDuration}</Hint>
                      </div>
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.mediaStoryDuration}</span>
                        <input type="number" className="knot-input-group" value={config.stories.mediaStoryMaxDurationSeconds} onChange={e => setConfig({ ...config, stories: { ...config.stories, mediaStoryMaxDurationSeconds: parseInt(e.target.value) || 0 } })} />
                        <Hint>{t.hints.mediaStoryDuration}</Hint>
                      </label>
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.maxMediaSize}</span>
                        <input type="number" className="knot-input-group" value={bytesToMb(config.stories.maxMediaSizeBytes)} onChange={e => setConfig({ ...config, stories: { ...config.stories, maxMediaSizeBytes: mbToBytes(parseInt(e.target.value) || 0) } })} />
                        <Hint>{t.hints.maxMediaSize}</Hint>
                      </label>
                    </div>
                  )}
                </div>
              )}

              {/* Chats Settings */}
              {activeSettingsTab === 'chats' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10">
                  <h3 className="text-xl font-semibold opacity-30 uppercase tracking-widest text-sm">{t.chats}</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-12">
                    <div className="flex flex-col gap-8">
                      <div className="bg-surface-container-highest/20 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-200 font-semibold">{t.supportGroups}</span>
                          <Toggle checked={config.chats.supportGroups} onChange={v => setConfig({ ...config, chats: { ...config.chats, supportGroups: v } })} />
                        </div>
                        <Hint>{t.hints.supportGroups}</Hint>
                      </div>
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.maxGroupMembers}</span>
                        <input type="number" className="knot-input-group" value={config.chats.maxGroupParticipants} onChange={e => setConfig({ ...config, chats: { ...config.chats, maxGroupParticipants: parseInt(e.target.value) || 0 } })} />
                        <Hint>{t.hints.maxGroupMembers}</Hint>
                      </label>
                    </div>
                    <div className="flex flex-col gap-6">
                      <div className="bg-surface-container-highest/20 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-200 font-semibold">{t.autoClean}</span>
                          <Toggle checked={config.chats.enableAutoClean} onChange={v => setConfig({ ...config, chats: { ...config.chats, enableAutoClean: v } })} />
                        </div>
                        <Hint>{t.hints.autoClean}</Hint>
                      </div>
                      <div className="bg-surface-container-highest/20 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-200 font-semibold">{t.chatToGroup}</span>
                          <Toggle checked={config.chats.allowChatToGroupConversion} onChange={v => setConfig({ ...config, chats: { ...config.chats, allowChatToGroupConversion: v } })} />
                        </div>
                        <Hint>{t.hints.chatToGroup}</Hint>
                      </div>
                      <div className="bg-surface-container-highest/20 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-200 font-semibold">{t.enableFolders}</span>
                          <Toggle checked={config.chats.enableFolders} onChange={v => setConfig({ ...config, chats: { ...config.chats, enableFolders: v } })} />
                        </div>
                        <Hint>{t.hints.enableFolders}</Hint>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Messages Settings */}
              {activeSettingsTab === 'messages' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10">
                  <h3 className="text-xl font-semibold opacity-30 uppercase tracking-widest text-sm">{t.messages}</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-x-16 gap-y-10">
                    <div className="flex flex-col gap-8">
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.dailyLimit}</span>
                        <input type="number" className="knot-input-group font-mono" value={config.messages.dailyMessageLimitPerUser} onChange={e => setConfig({ ...config, messages: { ...config.messages, dailyMessageLimitPerUser: parseInt(e.target.value) || 0 } })} />
                        <Hint>{t.hints.dailyLimit}</Hint>
                      </label>
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.chatLimit}</span>
                        <input type="number" className="knot-input-group font-mono" value={config.messages.chatMessageLimit} onChange={e => setConfig({ ...config, messages: { ...config.messages, chatMessageLimit: parseInt(e.target.value) || 0 } })} />
                        <Hint>{t.hints.chatLimit}</Hint>
                      </label>
                      <label className="flex flex-col gap-1.5 group">
                        <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.maxFileSize}</span>
                        <input type="number" className="knot-input-group font-mono" value={bytesToMb(config.messages.maxFileSize)} onChange={e => setConfig({ ...config, messages: { ...config.messages, maxFileSize: mbToBytes(parseInt(e.target.value) || 0) } })} />
                        <Hint>{t.hints.maxFileSize}</Hint>
                      </label>
                    </div>

                    <div className="space-y-4">
                      {[
                        { k: 'allowMedia', l: t.allowMedia, h: t.hints.allowMedia },
                        { k: 'allowVoiceMessages', l: t.voiceMessages, h: t.hints.voiceMessages },
                        { k: 'allowForwarding', l: t.forwarding, h: t.hints.forwarding },
                        { k: 'allowReactions', l: t.reactions, h: t.hints.reactions },
                        { k: 'allowReplies', l: t.replies, h: t.hints.replies },
                        { k: 'allowQuoting', l: t.quoting, h: t.hints.quoting },
                        { k: 'allowMessageDeletion', l: t.allowDelete, h: t.hints.allowDelete },
                        { k: 'forbidCopying', l: t.noCopy, h: t.hints.noCopy },
                        { k: 'allowLinks', l: t.links, h: t.hints.links },
                        { k: 'allowPolls', l: t.polls, h: t.hints.polls },
                        { k: 'allowPinning', l: t.pinning, h: t.hints.pinning }
                      ].map(item => (
                        <div key={item.k} className="flex flex-col gap-1 bg-white/[0.01] p-2 px-3 rounded-xl border border-white/[0.03]">
                          <div className="flex items-center justify-between">
                            <span className="text-sm text-gray-300 font-medium">{item.l}</span>
                            <Toggle checked={(config.messages as any)[item.k]} onChange={v => setConfig({ ...config, messages: { ...config.messages, [item.k]: v } })} />
                          </div>
                          {item.h && <Hint>{item.h}</Hint>}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* WebRTC Settings */}
              {activeSettingsTab === 'webRtc' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10 shadow-xl shadow-accent/5">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xl font-bold text-accent uppercase tracking-tighter flex items-center gap-2">
                      <Globe className="w-5 h-5" /> {t.webRtc}
                    </h3>
                    <Toggle checked={config.webRtc.enabled} onChange={v => setConfig({ ...config, webRtc: { ...config.webRtc, enabled: v } })} />
                  </div>
                  <Hint>{t.hints.webRtc}</Hint>

                  {config.webRtc.enabled && (<>
                    <div className="flex flex-col gap-10 pt-4 border-t border-white/10">
                      <div className="bg-white/[0.03] p-4 rounded-2xl border border-white/5 flex flex-col gap-3">
                        <div className="flex items-center justify-between">
                          <span className="text-xs font-bold text-gray-400 uppercase">{t.videoCalls}</span>
                          <Toggle checked={config.webRtc.enableVideoCalls} onChange={v => setConfig({ ...config, webRtc: { ...config.webRtc, enableVideoCalls: v } })} />
                        </div>
                        <Hint>{t.hints.videoCalls}</Hint>
                      </div>
                      <div className="bg-white/[0.03] p-4 rounded-2xl border border-white/5 flex flex-col gap-3">
                        <div className="flex items-center justify-between">
                          <span className="text-xs font-bold text-gray-400 uppercase">{t.screenSharing}</span>
                          <Toggle checked={config.webRtc.enableScreenSharing} onChange={v => setConfig({ ...config, webRtc: { ...config.webRtc, enableScreenSharing: v } })} />
                        </div>
                        <Hint>{t.hints.screenSharing}</Hint>
                      </div>
                    </div>

                    <div className="space-y-6">
                      <div className="flex items-center gap-3">
                        <Shield className="w-4 h-4 text-accent" />
                        <span className="text-xs font-black uppercase text-accent tracking-widest">{t.turnServerConfig}</span>
                        <div className="h-px flex-1 bg-accent/20" />
                      </div>
                      <Hint>{t.hints.turn}</Hint>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <label className="flex flex-col gap-1.5 group">
                          <span className="text-[10px] font-black uppercase text-gray-500 ml-1 group-focus-within:text-accent transition-colors">{t.turnHost}</span>
                          <input className="knot-input-group" value={config.webRtc.turnHost} onChange={e => setConfig({ ...config, webRtc: { ...config.webRtc, turnHost: e.target.value } })} placeholder="turn.example.com" />
                          <Hint>{t.hints.turnHost}</Hint>
                        </label>
                        <label className="flex flex-col gap-1.5 group">
                          <span className="text-[10px] font-black uppercase text-gray-500 ml-1 group-focus-within:text-accent transition-colors">{t.turnPort}</span>
                          <input type="number" className="knot-input-group" value={config.webRtc.turnPort} onChange={e => setConfig({ ...config, webRtc: { ...config.webRtc, turnPort: parseInt(e.target.value) || 0 } })} />
                          <Hint>{t.hints.turnPort}</Hint>
                        </label>
                        <label className="flex flex-col gap-1.5 group">
                          <span className="text-[10px] font-black uppercase text-gray-500 ml-1 group-focus-within:text-accent transition-colors">{t.turnUser}</span>
                          <input className="knot-input-group" value={config.webRtc.turnUser} onChange={e => setConfig({ ...config, webRtc: { ...config.webRtc, turnUser: e.target.value } })} />
                          <Hint>{t.hints.turnUser}</Hint>
                        </label>
                        <label className="flex flex-col gap-1.5 group">
                          <span className="text-[10px] font-black uppercase text-gray-500 ml-1 group-focus-within:text-accent transition-colors">{t.turnSecret}</span>
                          <input type="password" name="turnSecret" className="knot-input-group" value={config.webRtc.turnSecret} onChange={e => setConfig({ ...config, webRtc: { ...config.webRtc, turnSecret: e.target.value } })} />
                          <Hint>{t.hints.turnSecret}</Hint>
                        </label>
                      </div>
                      <button onClick={handleTestTurn} disabled={isTestingTurn} className="bg-accent/10 hover:bg-accent/20 text-accent font-bold px-8 py-3.5 rounded-xl flex items-center justify-center gap-3 transition-all w-full md:w-max mt-4">
                        {isTestingTurn ? <Loader2 className="w-5 h-5 animate-spin" /> : <Activity className="w-5 h-5" />}
                        {t.testConnection}
                      </button>
                    </div>
                  </>)}
                </div>
              )}

              {/* Klipy Settings */}
              {activeSettingsTab === 'klipy' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10 shadow-xl shadow-purple-500/5">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xl font-bold flex items-center gap-3">
                      <div className="w-6 h-6 bg-purple-500 rounded-md" /> {t.klipy}
                    </h3>
                    <Toggle checked={config.klipy.enabled} onChange={v => setConfig({ ...config, klipy: { ...config.klipy, enabled: v } })} />
                  </div>
                  <Hint>{t.hints.klipy}</Hint>
                  {config.klipy.enabled && (
                    <div className="flex flex-col gap-8 pt-4 border-t border-white/10">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <label className="flex flex-col gap-1.5 group">
                          <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1 group-focus-within:text-purple-400 transition-colors">{t.appName}</span>
                          <input className="knot-input-group" value={config.klipy.appName} onChange={e => setConfig({ ...config, klipy: { ...config.klipy, appName: e.target.value } })} />
                          <Hint>{t.hints.appName}</Hint>
                        </label>
                        <label className="flex flex-col gap-1.5 group">
                          <span className="text-[11px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1 group-focus-within:text-purple-400 transition-colors">{t.apiKey}</span>
                          <input className="knot-input-group" value={config.klipy.apiKey} onChange={e => setConfig({ ...config, klipy: { ...config.klipy, apiKey: e.target.value } })} type="password" />
                          <Hint>{t.hints.apiKey}</Hint>
                        </label>
                      </div>
                      <button onClick={handleTestKlipy} disabled={isTestingKlipy} className="bg-primary/10 hover:bg-primary/20 text-primary font-black px-8 py-3.5 rounded-2xl flex items-center justify-center gap-3 transition-all w-full md:w-max uppercase text-[10px] tracking-widest">
                        {isTestingKlipy ? <span className="material-symbols-outlined animate-spin">refresh</span> : <span className="material-symbols-outlined">network_check</span>}
                        {t.testConnection}
                      </button>
                    </div>
                  )}
                </div>
              )}

              {/* Import Settings */}
              {activeSettingsTab === 'import' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10 shadow-xl shadow-blue-500/5">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xl font-bold flex items-center gap-3">
                      <span className="material-symbols-outlined text-primary text-2xl">download</span> {t.importTitle}
                    </h3>
                  </div>
                  <Hint>{t.hints.import}</Hint>
                  <div className="flex flex-col gap-6 pt-4 border-t border-white/10">
                    <div className="bg-surface-container-highest/10 p-6 rounded-3xl border border-outline-variant/10 flex flex-col gap-4">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-black uppercase tracking-widest text-on-surface-variant/70">{t.telegramImport}</span>
                        <Toggle checked={config.import.enableTelegramImport} onChange={v => setConfig({ ...config, import: { ...config.import, enableTelegramImport: v } })} />
                      </div>
                      <Hint>{t.hints.import}</Hint>
                      <p className="text-[11px] text-on-surface-variant/30 leading-relaxed italic mt-2">
                        {t.importDescription}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              {/* Federation Settings */}
              {activeSettingsTab === 'federation' && (
                <div className="knot-card p-10 flex flex-col gap-8 border border-outline-variant/10">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xl font-semibold opacity-30 uppercase tracking-widest text-sm">{t.federation}</h3>
                    <Toggle checked={config.federation.enabled} onChange={v => setConfig({ ...config, federation: { ...config.federation, enabled: v } })} />
                  </div>

                  {config.federation.enabled && (
                    <div className="flex flex-col gap-6 pt-4 border-t border-white/10">
                      <div className="flex justify-between items-center mb-2">
                        <span className="text-[10px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.allowedNodes}</span>
                        <div className="flex gap-2">
                          <input type="file" id="jsonIn" className="hidden" accept=".json" onChange={importDomains} />
                          <label htmlFor="jsonIn" className="flex items-center gap-2 px-4 py-2 rounded-xl bg-surface-container-highest/10 hover:bg-surface-container-highest/20 transition-all text-[10px] uppercase font-black tracking-widest cursor-pointer border border-outline-variant/10">
                            <span className="material-symbols-outlined text-sm">upload</span> {t.importJson}
                          </label>
                          <button onClick={exportDomains} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-surface-container-highest/10 hover:bg-surface-container-highest/20 transition-all text-[10px] uppercase font-black tracking-widest border border-outline-variant/10">
                            <span className="material-symbols-outlined text-sm">download</span> {t.exportJson}
                          </button>
                        </div>
                      </div>

                      <div className="flex gap-2">
                        <div className="knot-input-group flex-1">
                          <input value={domainInput} onChange={e => setDomainInput(e.target.value)} placeholder="domain.tld" />
                        </div>
                        <button onClick={addDomain} className="bg-primary/10 hover:bg-primary/20 text-primary px-8 rounded-2xl font-black text-[11px] uppercase tracking-widest transition-all">{t.addNode}</button>
                      </div>

                      <div className="flex flex-col gap-2 max-h-60 overflow-y-auto pr-1">
                        {config.federation.allowedDomains.map(d => (
                          <div key={d.domain} className="flex items-center justify-between p-5 rounded-2xl bg-surface-container-highest/5 border border-outline-variant/5 group hover:border-outline-variant/20 transition-all">
                            <span className="text-sm font-mono text-on-surface-variant/70">{d.domain}</span>
                            <button onClick={() => removeDomain(d.domain)} className="text-on-surface-variant/20 hover:text-error opacity-0 group-hover:opacity-100 transition-all p-2"><span className="material-symbols-outlined text-[18px]">delete</span></button>
                          </div>
                        ))}
                        {config.federation.allowedDomains.length === 0 && (
                          <div className="text-center py-10 text-gray-600 border border-dashed border-white/10 rounded-2xl text-sm italic">
                            {t.noNodes}
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </motion.div>
          )}

          {activeTab === 'users' && (
            <motion.div key="users" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} className="flex gap-6 h-full items-start">
              <div className="flex-1 min-w-0 bg-surface border border-white/10 rounded-2xl flex flex-col h-full overflow-hidden">
                <div className="p-4 border-b border-white/10 flex gap-4 items-center bg-white/[0.02]">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input className="w-full bg-black/40 border border-white/10 rounded-xl pl-10 pr-4 py-2 outline-none text-white focus:border-accent text-sm" value={searchQuery} onChange={e => { setSearchQuery(e.target.value); searchUsers(e.target.value); }} placeholder={t.searchUsers} />
                  </div>
                  <button onClick={() => setShowAddUserModal(true)} className="bg-accent/10 hover:bg-accent/20 text-accent px-4 py-2 rounded-xl transition-colors font-semibold text-sm flex items-center gap-2 shrink-0">
                    <Plus className="w-4 h-4" /> {t.addUser}
                  </button>
                </div>
                <div className="flex-1 overflow-y-auto p-2 flex flex-col gap-1">
                  {users.length === 0 && !isSearching && <div className="text-center py-10 text-gray-500">{t.noUsersFound}</div>}
                  {users.map(u => (
                    <button
                      key={u.id}
                      onClick={() => fetchUserStats(u.id)}
                      className={`flex items-center gap-3 p-4 rounded-2xl transition-all text-left group border shadow-sm ${selectedUser?.id === u.id
                        ? 'bg-primary/10 border-primary/30 scale-[1.01] shadow-primary/5'
                        : 'hover:bg-surface-container-highest/10 border-transparent'
                        }`}
                    >
                      <div className="relative">
                        <div className="w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center text-primary font-black shrink-0 slide-on-ice border border-primary/10">
                          {u.avatar ? <img src={u.avatar} className="w-full h-full rounded-full" /> : u.username.charAt(0).toUpperCase()}
                        </div>
                        {u.isBanned && (
                          <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-surface-container-lowest rounded-full flex items-center justify-center" title={t.blockedTooltip}>
                            <span className="material-symbols-outlined text-error text-[14px]">block</span>
                          </div>
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-semibold truncate text-white">{u.displayName}</div>
                        <div className="text-xs text-gray-500 truncate">@{u.username}</div>
                      </div>
                      <div className="flex items-center gap-2">
                        {u.isOnline ? (
                          <span className="text-[10px] bg-green-500/20 text-green-400 px-2 py-0.5 rounded-full font-bold">{t.online.toUpperCase()}</span>
                        ) : (
                          <span className="text-xs text-gray-400">{t.offline}</span>
                        )}
                      </div>

                      <div className="ml-4 flex items-center gap-4 shrink-0 text-[10px]">
                        <div className="flex flex-col items-end">
                          <span className="text-gray-500 uppercase font-black tracking-tighter opacity-50">{t.sent}</span>
                          <span className="text-accent font-bold">{u.messageCount || 0}</span>
                        </div>
                        <div className="flex flex-col items-end border-l border-white/5 pl-4">
                          <span className="text-gray-500 uppercase font-black tracking-tighter opacity-50">{t.storage}</span>
                          <span className="text-white font-bold">{formatBytes(u.storageSize || 0)}</span>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {selectedUser ? (
                <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} className="w-80 bg-surface border border-white/10 rounded-2xl p-6 flex flex-col gap-6 shrink-0 sticky top-0 overflow-y-auto max-h-full">
                  <div className="flex flex-col items-center gap-4 text-center pb-6 border-b border-white/10">
                    <div className="relative">
                      <div className="w-24 h-24 rounded-full bg-primary/20 flex items-center justify-center text-3xl font-black text-primary slide-on-ice border border-primary/10">
                        {selectedUser.avatar ? <img src={selectedUser.avatar} className="w-full h-full rounded-full" /> : selectedUser.username.charAt(0).toUpperCase()}
                      </div>
                      {selectedUser.isBanned && (
                        <div className="absolute -bottom-1 -right-1 w-8 h-8 bg-surface-container-lowest rounded-full flex items-center justify-center border border-outline-variant/10" title={t.blockedTooltip}>
                          <span className="material-symbols-outlined text-error text-[20px]">block</span>
                        </div>
                      )}
                    </div>
                    <div>
                      <h2 className="text-xl font-bold text-white leading-tight">{selectedUser.displayName}</h2>
                      <div className="text-gray-500 text-sm">@{selectedUser.username}</div>
                    </div>
                  </div>

                  <div className="flex flex-col gap-4">
                    <div className="bg-black/20 p-3 rounded-xl">
                      <div className="text-[10px] text-gray-500 uppercase mb-1">{t.registeredOn}</div>
                      <div className="text-sm">{formatDateTime(selectedUser.createdAt)}</div>
                    </div>
                    <div className="bg-black/20 p-3 rounded-xl">
                      <div className="text-[10px] text-gray-500 uppercase mb-1">{t.lastSeen}</div>
                      <div className="text-sm">{selectedUser.isOnline ? t.online : (selectedUser.lastOnlineAt ? formatDateTime(selectedUser.lastOnlineAt) : '-')}</div>
                    </div>
                  </div>

                  <div className="mt-auto flex flex-col gap-4">
                    <button onClick={() => handleResetPassword(selectedUser.id)} className="w-full py-4 rounded-2xl bg-surface-container-highest/10 hover:bg-surface-container-highest/20 text-on-surface-variant font-black uppercase text-[10px] tracking-widest transition-all slide-on-ice">
                      {t.resetPassword}
                    </button>
                    {generatedPass && (
                      <div className="p-4 bg-primary/10 border border-primary/20 rounded-2xl flex items-center justify-between">
                        <span className="font-mono text-primary text-sm font-black">{generatedPass}</span>
                        <button onClick={() => { navigator.clipboard.writeText(generatedPass); showToast(t.copied); }} className="text-primary underline text-[10px] font-black uppercase tracking-widest">{t.copy}</button>
                      </div>
                    )}
                    {selectedUser.isBanned ? (
                      <button onClick={() => handleUnbanUser(selectedUser.id)} className="w-full py-4 rounded-2xl bg-primary/10 hover:bg-primary/20 text-primary font-black uppercase text-[10px] tracking-widest transition-all slide-on-ice">
                        {t.unblockUser}
                      </button>
                    ) : (
                      <button onClick={() => handleBanUser(selectedUser.id)} className="w-full py-4 rounded-2xl bg-error/10 hover:bg-error/20 text-error font-black uppercase text-[10px] tracking-widest transition-all slide-on-ice">
                        {t.blockUser}
                      </button>
                    )}
                    <button onClick={() => setDeleteUserModal({ userId: selectedUser.id, username: selectedUser.username })} className="w-full py-4 rounded-2xl bg-error/5 hover:bg-error/10 text-error/60 hover:text-error font-black uppercase text-[10px] tracking-widest transition-all slide-on-ice">
                      {t.deleteUser}
                    </button>
                  </div>
                </motion.div>
              ) : (
                <div className="w-80 flex items-center justify-center bg-surface/30 border border-white/5 border-dashed rounded-2xl text-gray-600 font-medium">
                  {t.selectUser}
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>
      </main>

      {/* MODALS */}
      {showAddUserModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-surface-container-lowest/90 backdrop-blur-xl" onClick={() => setShowAddUserModal(false)}>
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} onClick={e => e.stopPropagation()} className="w-full max-w-sm knot-card p-10 border border-outline-variant/20 relative shadow-2xl">
            <button onClick={() => setShowAddUserModal(false)} className="absolute top-6 right-6 text-on-surface-variant/40 hover:text-on-surface"><span className="material-symbols-outlined">close</span></button>
            <h2 className="text-2xl font-black font-headline tracking-tighter mb-8">{t.addUser}</h2>
            <div className="flex flex-col gap-6">
              <label className="flex flex-col gap-2">
                <span className="text-[10px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.username}</span>
                <div className="knot-input-group">
                  <input value={newUser.username} onChange={e => setNewUser({ ...newUser, username: e.target.value.toLowerCase() })} placeholder={t.usernamePlaceholder} />
                </div>
              </label>
              <label className="flex flex-col gap-2">
                <span className="text-[10px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.displayName}</span>
                <div className="knot-input-group">
                  <input value={newUser.displayName} onChange={e => setNewUser({ ...newUser, displayName: e.target.value })} placeholder={t.displayNamePlaceholder} />
                </div>
              </label>
              <label className="flex flex-col gap-2">
                <span className="text-[10px] font-black uppercase tracking-widest text-on-surface-variant/40 ml-1">{t.password}</span>
                <div className="flex gap-2">
                  <div className="knot-input-group flex-1">
                    <input className="font-mono text-sm" value={newUser.password} onChange={e => setNewUser({ ...newUser, password: e.target.value })} placeholder={t.passwordPlaceholder} />
                  </div>
                  <button onClick={() => setNewUser({ ...newUser, password: generatePassword() })} className="bg-primary/10 hover:bg-primary/20 text-primary px-4 rounded-2xl font-black text-[10px] uppercase tracking-widest transition-all">{t.generate}</button>
                </div>
              </label>
              <button onClick={handleAddUser} disabled={!newUser.username || !newUser.password} className="knot-button-primary w-full py-4 mt-4 disabled:opacity-30">
                {t.createUser}
              </button>
            </div>
          </motion.div>
        </div>
      )}

      {/* Global Toast */}
      {toast && (
        <motion.div
          initial={{ opacity: 0, y: 20, x: '-50%' }}
          animate={{ opacity: 1, y: 0, x: '-50%' }}
          exit={{ opacity: 0, y: 20, x: '-50%' }}
          className="fixed bottom-10 left-1/2 z-[9999] px-6 py-4 rounded-3xl bg-surface-container-high border border-outline-variant/20 text-on-surface shadow-[0_24px_64px_rgba(0,0,0,0.8)] flex items-center gap-4 min-w-[280px] backdrop-blur-3xl"
        >
          <div className={`w-10 h-10 rounded-full flex items-center justify-center ${toast.type === 'success' ? 'bg-primary/10' : 'bg-error/10'}`}>
            <span className={`material-symbols-outlined text-[22px] ${toast.type === 'success' ? 'text-primary' : 'text-error'}`}>
              {toast.type === 'success' ? 'check_circle' : 'error'}
            </span>
          </div>
          <div className="flex flex-col">
            <span className="text-[10px] font-black uppercase tracking-widest opacity-40">{toast.type === 'success' ? (lang === 'ru' ? 'Успешно' : 'Success') : (lang === 'ru' ? 'Ошибка' : 'Error')}</span>
            <span className="text-[13px] font-bold">{toast.message}</span>
          </div>
        </motion.div>
      )}

      {/* Delete User Confirmation Modal */}
      <AnimatePresence>
        {deleteUserModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
            onClick={() => setDeleteUserModal(null)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="bg-surface-container-high border border-outline-variant/20 rounded-3xl p-8 max-w-md w-full shadow-2xl"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center gap-4 mb-6">
                <div className="w-12 h-12 rounded-2xl bg-error/10 flex items-center justify-center">
                  <span className="material-symbols-outlined text-error text-2xl">warning</span>
                </div>
                <div>
                  <h3 className="text-xl font-black">{lang === 'ru' ? 'Удаление пользователя' : 'Delete User'}</h3>
                  <p className="text-sm text-on-surface-variant/60">{lang === 'ru' ? 'Это действие необратимо' : 'This action is irreversible'}</p>
                </div>
              </div>

              <div className="bg-surface-container-lowest/50 rounded-2xl p-4 mb-6">
                <p className="text-sm text-on-surface-variant/60 mb-2">{lang === 'ru' ? 'Вы собираетесь удалить:' : 'You are about to delete:'}</p>
                <p className="text-lg font-black text-on-surface">@{deleteUserModal.username}</p>
              </div>

              <p className="text-sm text-on-surface-variant/40 mb-8">
                {t.confirmDelete}
              </p>

              <div className="flex gap-3">
                <button
                  onClick={() => setDeleteUserModal(null)}
                  className="flex-1 py-4 rounded-2xl bg-surface-container-highest hover:bg-surface-container-high transition-all font-black uppercase text-[12px] tracking-widest"
                >
                  {t.cancel}
                </button>
                <button
                  onClick={() => handleDeleteUser(deleteUserModal.userId)}
                  className="flex-1 py-4 rounded-2xl bg-error hover:bg-error/90 text-white font-black uppercase text-[12px] tracking-widest transition-all"
                >
                  {lang === 'ru' ? 'Удалить' : 'Delete'}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function NavButton({ icon, label, active, onClick }: { icon: string, label: string, active: boolean, onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className={`w-full flex items-center gap-4 px-4 py-3 rounded-2xl transition-all duration-400 ease-ice group relative ${active
        ? 'bg-primary/10 text-primary'
        : 'text-on-surface-variant/40 hover:text-on-surface hover:bg-surface-container-highest/10'
        }`}
    >
      {active && (
        <motion.div
          layoutId="nav-active"
          className="absolute left-0 w-1 h-6 bg-primary rounded-full"
          transition={{ type: 'spring', stiffness: 300, damping: 30 }}
        />
      )}
      <span className="material-symbols-outlined text-[22px] transition-transform group-hover:scale-110">
        {icon}
      </span>
      <span className="text-[13px] font-black uppercase tracking-widest">{label}</span>
    </button>
  );
}

function Toggle({ checked, onChange }: { checked: boolean, onChange: (v: boolean) => void }) {
  return (
    <button
      onClick={() => onChange(!checked)}
      className={`w-11 h-6 rounded-full relative transition-all duration-300 ${checked ? 'bg-primary' : 'bg-surface-container-highest'
        }`}
    >
      <motion.div
        animate={{ x: checked ? 22 : 3 }}
        transition={{ type: 'spring', stiffness: 500, damping: 30 }}
        className={`absolute top-1 w-4 h-4 rounded-full ${checked ? 'bg-surface-container-lowest' : 'bg-on-surface-variant/40'
          }`}
      />
    </button>
  );
}
