<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Authelia User Manager</title>
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --primary-color: #667eea;
            --primary-dark: #5568d3;
            --secondary-color: #764ba2;
            --success-color: #27ae60;
            --success-dark: #229954;
            --warning-color: #f39c12;
            --warning-dark: #e67e22;
            --danger-color: #e74c3c;
            --danger-dark: #c0392b;
            --info-color: #3498db;
            --info-dark: #2980b9;
            --text-primary: #333;
            --text-secondary: #666;
            --text-light: #999;
            --bg-white: #ffffff;
            --bg-light: #f8f9fa;
            --bg-lighter: #f0f4ff;
            --border-color: #e0e0e0;
            --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 30px rgba(0,0,0,0.15);
            --shadow-xl: 0 20px 60px rgba(0,0,0,0.2);
            --transition-fast: 0.15s ease;
            --transition-normal: 0.3s ease;
            --transition-slow: 0.5s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        @keyframes scaleIn {
            from {
                opacity: 0;
                transform: scale(0.9);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }

        @keyframes spin {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(360deg);
            }
        }

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

        @keyframes ripple {
            to {
                transform: scale(4);
                opacity: 0;
            }
        }

        @keyframes toastSlideIn {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes toastSlideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(400px);
                opacity: 0;
            }
        }

        @keyframes modalIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        @keyframes modalContentIn {
            from {
                opacity: 0;
                transform: scale(0.8) translateY(50px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: var(--primary-gradient);
            min-height: 100vh;
            padding: 20px;
            overflow-x: hidden;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background:
                radial-gradient(circle at 20% 50%, rgba(102, 126, 234, 0.3) 0%, transparent 50%),
                radial-gradient(circle at 80% 80%, rgba(118, 75, 162, 0.3) 0%, transparent 50%);
            pointer-events: none;
            z-index: 0;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            position: relative;
            z-index: 1;
        }

        .header {
            background: var(--bg-white);
            padding: 40px;
            border-radius: 20px;
            box-shadow: var(--shadow-lg);
            margin-bottom: 30px;
            animation: fadeIn 0.6s ease;
            background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(255,255,255,0.9) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.3);
            position: relative;
            overflow: hidden;
        }

        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: var(--primary-gradient);
        }

        h1 {
            color: var(--text-primary);
            margin-bottom: 10px;
            font-size: 2.5em;
            font-weight: 700;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .subtitle {
            color: var(--text-secondary);
            font-size: 1.1em;
        }

        /* Stats Dashboard */
        .stats-dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
            animation: fadeIn 0.8s ease 0.2s backwards;
        }

        .stat-card {
            background: var(--bg-white);
            padding: 25px;
            border-radius: 15px;
            box-shadow: var(--shadow-md);
            display: flex;
            align-items: center;
            gap: 20px;
            transition: all var(--transition-normal);
            position: relative;
            overflow: hidden;
            cursor: pointer;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(102,126,234,0.1) 0%, rgba(118,75,162,0.1) 100%);
            opacity: 0;
            transition: opacity var(--transition-normal);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-lg);
        }

        .stat-card:hover::before {
            opacity: 1;
        }

        .stat-icon {
            font-size: 3em;
            width: 70px;
            height: 70px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 15px;
            background: var(--primary-gradient);
            position: relative;
            z-index: 1;
        }

        .stat-details {
            flex: 1;
            position: relative;
            z-index: 1;
        }

        .stat-label {
            color: var(--text-secondary);
            font-size: 0.9em;
            margin-bottom: 5px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            color: var(--text-primary);
            font-size: 2em;
            font-weight: 700;
        }

        /* Search and Filter Section */
        .search-section {
            background: var(--bg-white);
            padding: 25px;
            border-radius: 15px;
            box-shadow: var(--shadow-md);
            margin-bottom: 30px;
            animation: fadeIn 0.8s ease 0.3s backwards;
        }

        .search-container {
            position: relative;
            max-width: 500px;
        }

        .search-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-light);
            font-size: 1.2em;
        }

        #searchInput {
            width: 100%;
            padding: 15px 15px 15px 45px;
            border: 2px solid var(--border-color);
            border-radius: 10px;
            font-size: 16px;
            transition: all var(--transition-normal);
            background: var(--bg-light);
        }

        #searchInput:focus {
            outline: none;
            border-color: var(--primary-color);
            background: var(--bg-white);
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        .add-user-section {
            background: var(--bg-white);
            padding: 35px;
            border-radius: 20px;
            box-shadow: var(--shadow-lg);
            margin-bottom: 30px;
            animation: slideInRight 0.8s ease 0.4s backwards;
            position: relative;
            overflow: hidden;
        }

        .add-user-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .section-title {
            font-size: 1.8em;
            margin-bottom: 25px;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-icon {
            font-size: 1.2em;
        }

        .form-group {
            margin-bottom: 25px;
            animation: fadeIn 0.5s ease backwards;
        }

        .form-group:nth-child(1) { animation-delay: 0.1s; }
        .form-group:nth-child(2) { animation-delay: 0.2s; }
        .form-group:nth-child(3) { animation-delay: 0.3s; }
        .form-group:nth-child(4) { animation-delay: 0.4s; }

        label {
            display: block;
            margin-bottom: 8px;
            color: var(--text-primary);
            font-weight: 600;
            font-size: 0.95em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        input[type="text"],
        input[type="email"] {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid var(--border-color);
            border-radius: 10px;
            font-size: 15px;
            transition: all var(--transition-normal);
            background: var(--bg-light);
        }

        input[type="text"]:focus,
        input[type="email"]:focus {
            outline: none;
            border-color: var(--primary-color);
            background: var(--bg-white);
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            transform: translateY(-2px);
        }

        .checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 15px;
        }

        .checkbox-item {
            display: flex;
            flex-direction: column;
            padding: 16px;
            background: var(--bg-light);
            border-radius: 12px;
            border: 2px solid var(--border-color);
            transition: all var(--transition-normal);
            position: relative;
            overflow: hidden;
        }

        .checkbox-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 0;
            height: 100%;
            background: linear-gradient(90deg, rgba(102,126,234,0.1) 0%, rgba(118,75,162,0.1) 100%);
            transition: width var(--transition-normal);
        }

        .checkbox-item:hover {
            border-color: var(--primary-color);
            background: var(--bg-lighter);
            transform: translateX(5px);
        }

        .checkbox-item:hover::before {
            width: 100%;
        }

        .checkbox-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }

        .checkbox-header input[type="checkbox"] {
            margin-right: 12px;
            cursor: pointer;
            width: 20px;
            height: 20px;
            accent-color: var(--primary-color);
        }

        .checkbox-header label {
            margin: 0;
            font-weight: 600;
            color: var(--text-primary);
            cursor: pointer;
            font-size: 1em;
        }

        .group-services {
            margin-left: 32px;
            font-size: 11px;
            color: var(--text-secondary);
            line-height: 1.6;
            position: relative;
            z-index: 1;
        }

        .service-tag {
            display: inline-block;
            background: linear-gradient(135deg, #e8eaf6 0%, #c5cae9 100%);
            color: #5568d3;
            padding: 4px 10px;
            border-radius: 6px;
            margin: 3px 3px 3px 0;
            font-size: 10px;
            font-weight: 600;
            transition: all var(--transition-fast);
            box-shadow: var(--shadow-sm);
            cursor: default;
        }

        .service-tag:hover {
            transform: scale(1.05);
            box-shadow: var(--shadow-md);
        }

        .services-section {
            margin-top: 25px;
            padding: 25px;
            background: var(--bg-light);
            border-radius: 15px;
            border: 2px solid var(--border-color);
            transition: all var(--transition-normal);
        }

        .services-section:hover {
            border-color: var(--success-color);
            box-shadow: var(--shadow-md);
        }

        .services-section h3 {
            margin-bottom: 15px;
            color: var(--text-primary);
            font-size: 1.2em;
            display: flex;
            align-items: center;
            gap: 8px;
        }

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

        .service-checkbox-item {
            display: flex;
            align-items: center;
            padding: 12px;
            background: var(--bg-white);
            border-radius: 10px;
            border: 2px solid var(--border-color);
            transition: all var(--transition-normal);
            position: relative;
            overflow: hidden;
        }

        .service-checkbox-item::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(39, 174, 96, 0.1);
            transform: translate(-50%, -50%);
            transition: width var(--transition-normal), height var(--transition-normal);
        }

        .service-checkbox-item:hover::before {
            width: 100%;
            height: 100%;
        }

        .service-checkbox-item:hover {
            border-color: var(--success-color);
            transform: scale(1.02);
        }

        .service-checkbox-item input {
            margin-right: 10px;
            cursor: pointer;
            width: 18px;
            height: 18px;
            accent-color: var(--success-color);
            position: relative;
            z-index: 1;
        }

        .service-checkbox-item label {
            margin: 0;
            font-size: 14px;
            cursor: pointer;
            font-weight: normal;
            position: relative;
            z-index: 1;
        }

        /* Button Styles */
        .btn {
            background: var(--primary-gradient);
            color: white;
            padding: 14px 32px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all var(--transition-normal);
            box-shadow: var(--shadow-md);
            position: relative;
            overflow: hidden;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }

        .btn:hover::before {
            width: 300px;
            height: 300px;
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-lg);
        }

        .btn:active {
            transform: translateY(-1px);
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger-color) 0%, var(--danger-dark) 100%);
        }

        .btn-edit {
            background: linear-gradient(135deg, var(--info-color) 0%, var(--info-dark) 100%);
            padding: 10px 20px;
            font-size: 14px;
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success-color) 0%, var(--success-dark) 100%);
            padding: 10px 20px;
            font-size: 14px;
        }

        .btn-warning {
            background: linear-gradient(135deg, var(--warning-color) 0%, var(--warning-dark) 100%);
            padding: 10px 20px;
            font-size: 14px;
        }

        .btn-copy {
            background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%);
            padding: 10px 20px;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-copy.copied {
            background: linear-gradient(135deg, var(--success-color) 0%, var(--success-dark) 100%);
            animation: pulse 0.3s ease;
        }

        /* Users List */
        .users-list {
            background: var(--bg-white);
            padding: 35px;
            border-radius: 20px;
            box-shadow: var(--shadow-lg);
            animation: slideInLeft 0.8s ease 0.5s backwards;
        }

        .user-card {
            border: 2px solid var(--border-color);
            padding: 25px;
            border-radius: 15px;
            margin-bottom: 20px;
            transition: all var(--transition-normal);
            background: linear-gradient(135deg, var(--bg-white) 0%, var(--bg-light) 100%);
            animation: scaleIn 0.4s ease backwards;
            position: relative;
            overflow: hidden;
        }

        .user-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(102,126,234,0.1), transparent);
            transition: left 0.5s;
        }

        .user-card:hover::before {
            left: 100%;
        }

        .user-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-lg);
            border-color: var(--primary-color);
        }

        .user-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .user-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .user-info h3 {
            color: var(--text-primary);
            margin-bottom: 8px;
            font-size: 1.5em;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-email {
            color: var(--text-secondary);
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .user-groups {
            margin: 15px 0;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .group-badge {
            display: inline-flex;
            align-items: center;
            padding: 8px 16px;
            background: var(--primary-gradient);
            color: white;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 600;
            box-shadow: var(--shadow-sm);
            transition: all var(--transition-normal);
            animation: fadeIn 0.3s ease backwards;
        }

        .group-badge:hover {
            transform: translateY(-2px) scale(1.05);
            box-shadow: var(--shadow-md);
        }

        .services-list {
            margin-top: 15px;
        }

        .service-section {
            margin-bottom: 15px;
            padding: 15px;
            background: var(--bg-light);
            border-radius: 10px;
            border-left: 4px solid var(--primary-color);
            transition: all var(--transition-normal);
        }

        .service-section:hover {
            background: var(--bg-lighter);
            border-left-width: 6px;
        }

        .service-section-title {
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 10px;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .service-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 14px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
            margin: 4px 4px 4px 0;
            transition: all var(--transition-normal);
            cursor: pointer;
            box-shadow: var(--shadow-sm);
        }

        .service-badge:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .service-badge-group {
            background: linear-gradient(135deg, #e8eaf6 0%, #c5cae9 100%);
            color: #5568d3;
            border: 1px solid #c5cae9;
        }

        .service-badge-individual {
            background: linear-gradient(135deg, #e8f8f5 0%, #a9dfbf 100%);
            color: #27ae60;
            border: 1px solid #a9dfbf;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(8px);
            justify-content: center;
            align-items: center;
            z-index: 1000;
            animation: modalIn var(--transition-normal);
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: var(--bg-white);
            padding: 35px;
            border-radius: 20px;
            max-width: 700px;
            width: 90%;
            max-height: 85vh;
            overflow-y: auto;
            box-shadow: var(--shadow-xl);
            animation: modalContentIn var(--transition-slow);
            position: relative;
        }

        .modal-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
            border-radius: 20px 20px 0 0;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        .modal-header h2 {
            color: var(--text-primary);
            font-size: 1.8em;
        }

        .modal-close {
            background: var(--bg-light);
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all var(--transition-normal);
        }

        .modal-close:hover {
            background: var(--danger-color);
            color: white;
            transform: rotate(90deg);
        }

        .password-display {
            background: var(--bg-light);
            padding: 20px;
            border-radius: 12px;
            font-family: 'Courier New', monospace;
            word-break: break-all;
            margin: 15px 0;
            font-size: 18px;
            font-weight: bold;
            border: 2px dashed var(--primary-color);
            position: relative;
            overflow: hidden;
        }

        .password-display::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(102,126,234,0.1), transparent);
            animation: shimmer 3s infinite;
        }

        /* Toast Notifications */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .toast {
            background: var(--bg-white);
            padding: 16px 24px;
            border-radius: 12px;
            box-shadow: var(--shadow-lg);
            display: flex;
            align-items: center;
            gap: 12px;
            min-width: 300px;
            animation: toastSlideIn 0.3s ease;
            border-left: 4px solid var(--primary-color);
        }

        .toast.toast-success {
            border-left-color: var(--success-color);
        }

        .toast.toast-error {
            border-left-color: var(--danger-color);
        }

        .toast.toast-warning {
            border-left-color: var(--warning-color);
        }

        .toast.toast-hide {
            animation: toastSlideOut 0.3s ease forwards;
        }

        .toast-icon {
            font-size: 24px;
        }

        .toast-content {
            flex: 1;
        }

        .toast-title {
            font-weight: 700;
            margin-bottom: 4px;
            color: var(--text-primary);
        }

        .toast-message {
            font-size: 14px;
            color: var(--text-secondary);
        }

        .toast-close {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: var(--text-light);
            transition: color var(--transition-fast);
        }

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

        /* Loading Spinner */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.8s linear infinite;
        }

        .btn.loading {
            pointer-events: none;
            opacity: 0.7;
        }

        .btn.loading::after {
            content: '';
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-left: 10px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.8s linear infinite;
        }

        /* Skeleton Loading */
        .skeleton {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: shimmer 2s infinite;
            border-radius: 8px;
        }

        .skeleton-text {
            height: 16px;
            margin-bottom: 10px;
        }

        .skeleton-title {
            height: 24px;
            width: 60%;
            margin-bottom: 15px;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--text-secondary);
        }

        .empty-state-icon {
            font-size: 5em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-state-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: var(--text-primary);
        }

        .empty-state-message {
            font-size: 1.1em;
        }

        /* Collapsible Sections */
        .collapsible-trigger {
            cursor: pointer;
            user-select: none;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: all var(--transition-fast);
        }

        .collapsible-trigger:hover {
            color: var(--primary-color);
        }

        .collapse-icon {
            transition: transform var(--transition-normal);
        }

        .collapsed .collapse-icon {
            transform: rotate(-90deg);
        }

        .collapsible-content {
            max-height: 1000px;
            overflow: hidden;
            transition: max-height var(--transition-slow), opacity var(--transition-normal);
            opacity: 1;
        }

        .collapsed .collapsible-content {
            max-height: 0;
            opacity: 0;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }

            .header {
                padding: 25px;
            }

            h1 {
                font-size: 1.8em;
            }

            .user-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .user-actions {
                width: 100%;
                justify-content: flex-start;
            }

            .stats-dashboard {
                grid-template-columns: 1fr;
            }

            .modal-content {
                width: 95%;
                padding: 25px;
            }
        }

        /* Scrollbar Styling */
        ::-webkit-scrollbar {
            width: 10px;
            height: 10px;
        }

        ::-webkit-scrollbar-track {
            background: var(--bg-light);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--primary-gradient);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary-dark);
        }

        /* Tooltip */
        [data-tooltip] {
            position: relative;
        }

        [data-tooltip]::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%) translateY(-5px);
            background: rgba(0, 0, 0, 0.9);
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            white-space: nowrap;
            opacity: 0;
            pointer-events: none;
            transition: opacity var(--transition-normal), transform var(--transition-normal);
            z-index: 1000;
        }

        [data-tooltip]:hover::after {
            opacity: 1;
            transform: translateX(-50%) translateY(-10px);
        }
    </style>
</head>
<body>
    <!-- Toast Container -->
    <div class="toast-container" id="toastContainer"></div>

    <div class="container">
        <div class="header">
            <h1>🔐 Authelia User Manager</h1>
            <p class="subtitle">Управление пользователями и доступом к сервисам</p>
        </div>

        <!-- Stats Dashboard -->
        <div class="stats-dashboard">
            <div class="stat-card" data-tooltip="Общее количество пользователей">
                <div class="stat-icon">👥</div>
                <div class="stat-details">
                    <div class="stat-label">Пользователей</div>
                    <div class="stat-value" id="totalUsers">0</div>
                </div>
            </div>
            <div class="stat-card" data-tooltip="Доступные группы">
                <div class="stat-icon">🏷️</div>
                <div class="stat-details">
                    <div class="stat-label">Групп</div>
                    <div class="stat-value" id="totalGroups">0</div>
                </div>
            </div>
            <div class="stat-card" data-tooltip="Доступные сервисы">
                <div class="stat-icon">⚙️</div>
                <div class="stat-details">
                    <div class="stat-label">Сервисов</div>
                    <div class="stat-value" id="totalServices">0</div>
                </div>
            </div>
        </div>

        <!-- Search Section -->
        <div class="search-section">
            <div class="search-container">
                <span class="search-icon">🔍</span>
                <input type="text" id="searchInput" placeholder="Поиск по имени, email или группе...">
            </div>
        </div>

        <div class="add-user-section">
            <h2 class="section-title">
                <span class="section-icon">➕</span>
                Добавить пользователя
            </h2>
            <form id="addUserForm">
                <div class="form-group">
                    <label for="username">Имя пользователя:</label>
                    <input type="text" id="username" required placeholder="Введите имя пользователя">
                </div>

                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" id="email" required placeholder="user@example.com">
                </div>

                <div class="form-group">
                    <label for="displayname">Отображаемое имя:</label>
                    <input type="text" id="displayname" required placeholder="Иван Иванов">
                </div>

                <div class="form-group">
                    <label>Группы доступа:</label>
                    <div class="checkbox-group" id="groupsCheckbox"></div>
                </div>

                <div class="services-section">
                    <h3>
                        <span>🛠️</span>
                        Дополнительные индивидуальные сервисы
                    </h3>
                    <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 15px;">
                        Выберите индивидуальные сервисы в дополнение к сервисам из групп
                    </p>
                    <div class="service-checkbox-grid" id="servicesCheckbox"></div>
                </div>

                <button type="submit" class="btn" id="submitBtn">
                    Создать пользователя
                </button>
            </form>
        </div>

        <div class="users-list">
            <h2 class="section-title">
                <span class="section-icon">👤</span>
                Список пользователей
            </h2>
            <div id="usersList"></div>
        </div>
    </div>

    <!-- Password Modal -->
    <div id="passwordModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>✅ Пользователь создан!</h2>
                <button class="modal-close" onclick="closePasswordModal()">&times;</button>
            </div>
            <p style="color: var(--text-secondary); margin-bottom: 15px;">Сохраните пароль в надёжном месте:</p>
            <div class="password-display" id="generatedPassword"></div>
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button class="btn btn-copy" onclick="copyPassword('generatedPassword')">
                    📋 Копировать пароль
                </button>
                <button class="btn" onclick="closePasswordModal()">Закрыть</button>
            </div>
        </div>
    </div>

    <!-- Reset Password Modal -->
    <div id="resetPasswordModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>🔄 Пароль сброшен!</h2>
                <button class="modal-close" onclick="closeResetPasswordModal()">&times;</button>
            </div>
            <p style="margin-bottom: 10px;">Новый пароль для пользователя: <strong id="resetUsername"></strong></p>
            <div class="password-display" id="resetPassword"></div>
            <p style="color: var(--danger-color); margin-top: 15px; font-weight: 600;">
                ⚠️ Сохраните пароль в надёжном месте! Он больше не будет показан.
            </p>
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button class="btn btn-copy" onclick="copyPassword('resetPassword')">
                    📋 Копировать пароль
                </button>
                <button class="btn" onclick="closeResetPasswordModal()">Закрыть</button>
            </div>
        </div>
    </div>

    <!-- Edit Groups Modal -->
    <div id="editGroupsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>✏️ Изменить группы</h2>
                <button class="modal-close" onclick="closeEditGroupsModal()">&times;</button>
            </div>
            <p style="margin-bottom: 20px;">Пользователь: <strong id="editUsername"></strong></p>
            <div class="form-group">
                <label>Группы доступа:</label>
                <div class="checkbox-group" id="editGroupsCheckbox"></div>
            </div>
            <button class="btn" onclick="saveUserGroups()">Сохранить изменения</button>
        </div>
    </div>

    <!-- Edit Services Modal -->
    <div id="editServicesModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>🛠️ Изменить индивидуальные сервисы</h2>
                <button class="modal-close" onclick="closeEditServicesModal()">&times;</button>
            </div>
            <p style="margin-bottom: 20px;">Пользователь: <strong id="editServicesUsername"></strong></p>
            <div class="form-group">
                <label>Индивидуальные сервисы:</label>
                <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 15px;">
                    Сервисы, доступные через группы, отмечены серым цветом
                </p>
                <div class="service-checkbox-grid" id="editServicesCheckbox"></div>
            </div>
            <button class="btn btn-success" onclick="saveUserServices()">Сохранить изменения</button>
        </div>
    </div>

    <script>
        let groups = [];
        let serviceGroups = {};
        let allServices = [];
        let currentEditUser = null;
        let allUsers = [];
        let searchTimeout;

        // Toast Notification System
        function showToast(title, message, type = 'success') {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;

            const icons = {
                success: '✅',
                error: '❌',
                warning: '⚠️',
                info: 'ℹ️'
            };

            toast.innerHTML = `
                <div class="toast-icon">${icons[type] || icons.info}</div>
                <div class="toast-content">
                    <div class="toast-title">${title}</div>
                    <div class="toast-message">${message}</div>
                </div>
                <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
            `;

            container.appendChild(toast);

            setTimeout(() => {
                toast.classList.add('toast-hide');
                setTimeout(() => toast.remove(), 300);
            }, 5000);
        }

        // Copy Password Function
        function copyPassword(elementId) {
            const passwordElement = document.getElementById(elementId);
            const password = passwordElement.textContent;

            navigator.clipboard.writeText(password).then(() => {
                const btn = event.target.closest('button');
                const originalText = btn.innerHTML;
                btn.classList.add('copied');
                btn.innerHTML = '✓ Скопировано!';

                showToast('Успех!', 'Пароль скопирован в буфер обмена', 'success');

                setTimeout(() => {
                    btn.classList.remove('copied');
                    btn.innerHTML = originalText;
                }, 2000);
            }).catch(() => {
                showToast('Ошибка', 'Не удалось скопировать пароль', 'error');
            });
        }

        // Search and Filter
        document.getElementById('searchInput').addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                filterUsers(e.target.value.toLowerCase());
            }, 300);
        });

        function filterUsers(searchTerm) {
            const userCards = document.querySelectorAll('.user-card');
            let visibleCount = 0;

            userCards.forEach((card, index) => {
                const user = allUsers[index];
                if (!user) return;

                const matches =
                    user.username.toLowerCase().includes(searchTerm) ||
                    user.email.toLowerCase().includes(searchTerm) ||
                    user.displayname.toLowerCase().includes(searchTerm) ||
                    user.groups.some(g => g.toLowerCase().includes(searchTerm));

                if (matches) {
                    card.style.display = 'block';
                    card.style.animation = 'scaleIn 0.3s ease';
                    visibleCount++;
                } else {
                    card.style.display = 'none';
                }
            });

            if (visibleCount === 0 && searchTerm) {
                showEmptyState();
            } else {
                removeEmptyState();
            }
        }

        function showEmptyState() {
            const usersList = document.getElementById('usersList');
            if (!document.querySelector('.empty-state')) {
                const emptyState = document.createElement('div');
                emptyState.className = 'empty-state';
                emptyState.innerHTML = `
                    <div class="empty-state-icon">🔍</div>
                    <div class="empty-state-title">Ничего не найдено</div>
                    <div class="empty-state-message">Попробуйте изменить параметры поиска</div>
                `;
                usersList.appendChild(emptyState);
            }
        }

        function removeEmptyState() {
            const emptyState = document.querySelector('.empty-state');
            if (emptyState) emptyState.remove();
        }

        // Update Stats
        function updateStats() {
            document.getElementById('totalUsers').textContent = allUsers.length;
            document.getElementById('totalGroups').textContent = groups.length;
            document.getElementById('totalServices').textContent = allServices.length;
        }

        // Load Groups
        async function loadGroups() {
            try {
                const response = await fetch('/api/groups');
                const data = await response.json();
                groups = data.groups;
                serviceGroups = data.services;

                const container = document.getElementById('groupsCheckbox');
                const editContainer = document.getElementById('editGroupsCheckbox');

                [container, editContainer].forEach((cont, idx) => {
                    cont.innerHTML = '';
                    groups.forEach((group, gIdx) => {
                        const div = document.createElement('div');
                        div.className = 'checkbox-item';
                        div.style.animationDelay = `${gIdx * 0.05}s`;
                        const prefix = cont.id === 'groupsCheckbox' ? 'group_' : 'edit_group_';

                        const services = serviceGroups[group] || [];
                        const servicesHtml = services.length > 0
                            ? services.map(s => `<span class="service-tag">${s}</span>`).join('')
                            : '<span class="service-tag">Нет сервисов</span>';

                        div.innerHTML = `
                            <div class="checkbox-header">
                                <input type="checkbox" id="${prefix}${group}" value="${group}">
                                <label for="${prefix}${group}">${group}</label>
                            </div>
                            <div class="group-services">
                                ${servicesHtml}
                            </div>
                        `;
                        cont.appendChild(div);
                    });
                });

                updateStats();
            } catch (error) {
                showToast('Ошибка', 'Не удалось загрузить группы', 'error');
            }
        }

        // Load Services
        async function loadServices() {
            try {
                const response = await fetch('/api/services');
                const data = await response.json();
                allServices = data.services;

                const container = document.getElementById('servicesCheckbox');
                container.innerHTML = '';

                allServices.forEach((service, idx) => {
                    const div = document.createElement('div');
                    div.className = 'service-checkbox-item';
                    div.style.animationDelay = `${idx * 0.02}s`;
                    div.innerHTML = `
                        <input type="checkbox" id="service_${service}" value="${service}">
                        <label for="service_${service}">${service}</label>
                    `;
                    container.appendChild(div);
                });

                updateStats();
            } catch (error) {
                showToast('Ошибка', 'Не удалось загрузить сервисы', 'error');
            }
        }

        // Load Users
        async function loadUsers() {
            try {
                const response = await fetch('/api/users');
                const users = await response.json();
                allUsers = users;

                const container = document.getElementById('usersList');
                container.innerHTML = '';

                if (users.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <div class="empty-state-icon">👥</div>
                            <div class="empty-state-title">Пользователей пока нет</div>
                            <div class="empty-state-message">Создайте первого пользователя выше</div>
                        </div>
                    `;
                    updateStats();
                    return;
                }

                users.forEach((user, idx) => {
                    const card = document.createElement('div');
                    card.className = 'user-card';
                    card.style.animationDelay = `${idx * 0.05}s`;

                    const groupServicesHtml = user.group_services.length > 0
                        ? user.group_services.map(s =>
                            `<span class="service-badge service-badge-group" data-tooltip="Из группы">${s}</span>`
                        ).join('')
                        : '<span style="color: var(--text-light); font-size: 13px;">Нет сервисов</span>';

                    const individualServicesHtml = user.individual_services.length > 0
                        ? user.individual_services.map(s =>
                            `<span class="service-badge service-badge-individual" data-tooltip="Индивидуальный">${s}</span>`
                        ).join('')
                        : '<span style="color: var(--text-light); font-size: 13px;">Нет индивидуальных сервисов</span>';

                    card.innerHTML = `
                        <div class="user-header">
                            <div class="user-info">
                                <h3>👤 ${user.displayname}</h3>
                                <p class="user-email">📧 ${user.email}</p>
                            </div>
                            <div class="user-actions">
                                <button class="btn btn-edit" onclick="editUserGroups('${user.username}')" data-tooltip="Изменить группы">
                                    ✏️ Группы
                                </button>
                                <button class="btn btn-success" onclick="editUserServices('${user.username}')" data-tooltip="Изменить сервисы">
                                    🛠️ Сервисы
                                </button>
                                <button class="btn btn-warning" onclick="resetUserPassword('${user.username}')" data-tooltip="Сбросить пароль">
                                    🔄 Пароль
                                </button>
                                <button class="btn btn-danger" onclick="deleteUser('${user.username}')" data-tooltip="Удалить пользователя">
                                    🗑️ Удалить
                                </button>
                            </div>
                        </div>
                        <div class="user-groups">
                            ${user.groups.map((g, i) => `<span class="group-badge" style="animation-delay: ${i * 0.05}s">🏷️ ${g}</span>`).join('')}
                        </div>
                        <div class="services-list">
                            <div class="service-section">
                                <div class="service-section-title">
                                    <span>📦</span> Сервисы через группы:
                                </div>
                                ${groupServicesHtml}
                            </div>
                            <div class="service-section">
                                <div class="service-section-title">
                                    <span>⭐</span> Дополнительные сервисы:
                                </div>
                                ${individualServicesHtml}
                            </div>
                        </div>
                    `;
                    container.appendChild(card);
                });

                updateStats();

                // Re-apply search filter if active
                const searchTerm = document.getElementById('searchInput').value;
                if (searchTerm) {
                    filterUsers(searchTerm.toLowerCase());
                }
            } catch (error) {
                showToast('Ошибка', 'Не удалось загрузить пользователей', 'error');
            }
        }

        // Add User Form Submit
        document.getElementById('addUserForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const submitBtn = document.getElementById('submitBtn');
            submitBtn.classList.add('loading');
            submitBtn.disabled = true;

            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;
            const displayname = document.getElementById('displayname').value;

            const selectedGroups = [];
            groups.forEach(group => {
                if (document.getElementById(`group_${group}`).checked) {
                    selectedGroups.push(group);
                }
            });

            const selectedServices = [];
            allServices.forEach(service => {
                if (document.getElementById(`service_${service}`).checked) {
                    selectedServices.push(service);
                }
            });

            try {
                const response = await fetch('/api/users', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        username,
                        email,
                        displayname,
                        groups: selectedGroups,
                        services: selectedServices
                    })
                });

                const result = await response.json();

                if (result.success) {
                    document.getElementById('generatedPassword').textContent = result.password;
                    document.getElementById('passwordModal').classList.add('active');
                    document.getElementById('addUserForm').reset();
                    groups.forEach(group => {
                        document.getElementById(`group_${group}`).checked = false;
                    });
                    allServices.forEach(service => {
                        document.getElementById(`service_${service}`).checked = false;
                    });
                    loadUsers();
                    showToast('Успех!', `Пользователь ${username} успешно создан`, 'success');
                } else {
                    showToast('Ошибка', result.error, 'error');
                }
            } catch (error) {
                showToast('Ошибка', 'Не удалось создать пользователя', 'error');
            } finally {
                submitBtn.classList.remove('loading');
                submitBtn.disabled = false;
            }
        });

        // Edit User Groups
        async function editUserGroups(username) {
            currentEditUser = username;
            const user = allUsers.find(u => u.username === username);

            document.getElementById('editUsername').textContent = username;

            groups.forEach(group => {
                const checkbox = document.getElementById(`edit_group_${group}`);
                checkbox.checked = user.groups.includes(group);
            });

            document.getElementById('editGroupsModal').classList.add('active');
        }

        // Save User Groups
        async function saveUserGroups() {
            const selectedGroups = [];
            groups.forEach(group => {
                if (document.getElementById(`edit_group_${group}`).checked) {
                    selectedGroups.push(group);
                }
            });

            try {
                const response = await fetch(`/api/users/${currentEditUser}/groups`, {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ groups: selectedGroups })
                });

                const result = await response.json();
                if (result.success) {
                    closeEditGroupsModal();
                    loadUsers();
                    showToast('Успех!', 'Группы пользователя обновлены', 'success');
                } else {
                    showToast('Ошибка', result.error, 'error');
                }
            } catch (error) {
                showToast('Ошибка', 'Не удалось обновить группы', 'error');
            }
        }

        // Edit User Services
        async function editUserServices(username) {
            currentEditUser = username;
            const user = allUsers.find(u => u.username === username);

            document.getElementById('editServicesUsername').textContent = username;

            const container = document.getElementById('editServicesCheckbox');
            container.innerHTML = '';

            allServices.forEach((service, idx) => {
                const div = document.createElement('div');
                div.className = 'service-checkbox-item';
                div.style.animationDelay = `${idx * 0.02}s`;

                const isFromGroup = user.group_services.includes(service);
                const isIndividual = user.individual_services.includes(service);

                const style = isFromGroup ? 'opacity: 0.6;' : '';
                const tooltip = isFromGroup ? ' (доступен через группу)' : '';

                div.innerHTML = `
                    <input type="checkbox"
                           id="edit_service_${service}"
                           value="${service}"
                           ${isIndividual ? 'checked' : ''}>
                    <label for="edit_service_${service}" style="${style}">${service}${tooltip}</label>
                `;
                container.appendChild(div);
            });

            document.getElementById('editServicesModal').classList.add('active');
        }

        // Save User Services
        async function saveUserServices() {
            const selectedServices = [];
            allServices.forEach(service => {
                const checkbox = document.getElementById(`edit_service_${service}`);
                if (checkbox && checkbox.checked) {
                    selectedServices.push(service);
                }
            });

            try {
                const response = await fetch(`/api/users/${currentEditUser}/services`, {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ services: selectedServices })
                });

                const result = await response.json();
                if (result.success) {
                    closeEditServicesModal();
                    loadUsers();
                    showToast('Успех!', 'Сервисы пользователя обновлены', 'success');
                } else {
                    showToast('Ошибка', result.error, 'error');
                }
            } catch (error) {
                showToast('Ошибка', 'Не удалось обновить сервисы', 'error');
            }
        }

        // Reset User Password
        async function resetUserPassword(username) {
            if (!confirm(`Вы уверены, что хотите сбросить пароль для пользователя ${username}?`)) return;

            try {
                const response = await fetch(`/api/users/${username}/reset-password`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'}
                });

                const result = await response.json();

                if (result.success) {
                    document.getElementById('resetUsername').textContent = username;
                    document.getElementById('resetPassword').textContent = result.password;
                    document.getElementById('resetPasswordModal').classList.add('active');
                    loadUsers();
                    showToast('Успех!', `Пароль для ${username} сброшен`, 'success');
                } else {
                    showToast('Ошибка', result.error, 'error');
                }
            } catch (error) {
                showToast('Ошибка', 'Не удалось сбросить пароль', 'error');
            }
        }

        // Delete User
        async function deleteUser(username) {
            if (!confirm(`Вы уверены, что хотите удалить пользователя ${username}? Это действие необратимо.`)) return;

            try {
                await fetch(`/api/users/${username}`, {method: 'DELETE'});
                loadUsers();
                showToast('Успех!', `Пользователь ${username} удален`, 'success');
            } catch (error) {
                showToast('Ошибка', 'Не удалось удалить пользователя', 'error');
            }
        }

        // Modal Close Functions
        function closePasswordModal() {
            document.getElementById('passwordModal').classList.remove('active');
        }

        function closeResetPasswordModal() {
            document.getElementById('resetPasswordModal').classList.remove('active');
        }

        function closeEditGroupsModal() {
            document.getElementById('editGroupsModal').classList.remove('active');
            currentEditUser = null;
        }

        function closeEditServicesModal() {
            document.getElementById('editServicesModal').classList.remove('active');
            currentEditUser = null;
        }

        // Close modal on background click
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.classList.remove('active');
                    currentEditUser = null;
                }
            });
        });

        // Initialize
        loadGroups();
        loadServices();
        loadUsers();

        // Auto-refresh users every 30 seconds
        setInterval(loadUsers, 30000);

        // Welcome toast
        setTimeout(() => {
            showToast('Добро пожаловать!', 'Система управления пользователями Authelia готова к работе', 'info');
        }, 1000);
    </script>
</body>
</html>
