<?php
require_once '../config/config.php';
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Nõua admin õigusi
requireAdmin();

$current_year = date('Y');
$error = '';

// Lae üldstatistika
try {
    // Kasutajate arv
    $stmt = $pdo->prepare("SELECT COUNT(*) as total, role FROM users WHERE isActive = 1 GROUP BY role");
    $stmt->execute();
    $user_stats = [];
    foreach ($stmt->fetchAll() as $row) {
        $user_stats[$row['role']] = $row['total'];
    }
    
    // Võistluste arv
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM competitions WHERE strftime('%Y', date) = ?");
    $stmt->execute([$current_year]);
    $competitions_count = $stmt->fetch()['count'];
    
    // Tulemuste arv
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM results r 
        JOIN competitions c ON r.competitionId = c.id 
        WHERE strftime('%Y', c.date) = ?
    ");
    $stmt->execute([$current_year]);
    $results_count = $stmt->fetch()['count'];
    
    // Viimased tegevused
    $stmt = $pdo->prepare("
        SELECT al.*, u.firstName, u.lastName 
        FROM activity_log al
        LEFT JOIN users u ON al.user_id = u.id
        ORDER BY al.created_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $recent_activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Viimased tulemused
    $stmt = $pdo->prepare("
        SELECT r.*, u.firstName, u.lastName, c.name as competitionName, c.date as competitionDate
        FROM results r
        JOIN users u ON r.userId = u.id
        JOIN competitions c ON r.competitionId = c.id
        WHERE strftime('%Y', c.date) = ?
        ORDER BY r.createdAt DESC
        LIMIT 8
    ");
    $stmt->execute([$current_year]);
    $recent_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Lähituleviku võistlused
    $stmt = $pdo->prepare("
        SELECT * FROM competitions 
        WHERE date >= date('now') 
        ORDER BY date ASC 
        LIMIT 5
    ");
    $stmt->execute();
    $upcoming_competitions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Kuustatistika
    $stmt = $pdo->prepare("
        SELECT 
            strftime('%m', c.date) as month,
            COUNT(DISTINCT c.id) as competitions,
            COUNT(r.id) as results
        FROM competitions c
        LEFT JOIN results r ON c.id = r.competitionId
        WHERE strftime('%Y', c.date) = ?
        GROUP BY strftime('%m', c.date)
        ORDER BY month
    ");
    $stmt->execute([$current_year]);
    $monthly_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    $error = 'Statistika laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Admin dashboard error: ' . $e->getMessage());
}

// Lae aktiveerimist ootavaid kasutajaid
try {
    $stmt = $pdo->prepare("
        SELECT 
            id, firstName, lastName, email, username, createdAt,
            CASE 
                WHEN email_verified = 0 THEN 'email_not_verified'
                WHEN isActive = 0 THEN 'inactive'
                ELSE 'other'
            END as pending_reason
        FROM users 
        WHERE (email_verified = 0 OR isActive = 0)
        ORDER BY createdAt DESC
        LIMIT 10
    ");
    $stmt->execute();
    $pending_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    error_log('Pending users load error: ' . $e->getMessage());
    $pending_users = [];
}

// Töötle kasutaja aktiveerimist (AJAX)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['activate_user'])) {
    header('Content-Type: application/json');
    
    $user_id = (int)$_POST['user_id'];
    $action = $_POST['action']; // 'activate' või 'verify_email'
    
    try {
        if ($action === 'activate') {
            // Aktiveeri kasutaja
            $stmt = $pdo->prepare("UPDATE users SET isActive = 1, updatedAt = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$user_id]);
            
            logActivity($_SESSION['user_id'], 'user_activated', "User activated (ID: $user_id)");
            echo json_encode(['success' => true, 'message' => 'Kasutaja aktiveeritud']);
            
        } elseif ($action === 'verify_email') {
            // Kinnita email
            $stmt = $pdo->prepare("
                UPDATE users 
                SET email_verified = 1, isActive = 1, verification_token = NULL, verification_expires = NULL, updatedAt = CURRENT_TIMESTAMP 
                WHERE id = ?
            ");
            $stmt->execute([$user_id]);
            
            logActivity($_SESSION['user_id'], 'email_verified_manual', "Email manually verified (ID: $user_id)");
            echo json_encode(['success' => true, 'message' => 'Email kinnitatud ja kasutaja aktiveeritud']);
            
        } else {
            echo json_encode(['success' => false, 'message' => 'Tundmatu tegevus']);
        }
        
    } catch(PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Viga: ' . $e->getMessage()]);
    }
    
    exit;
}

$page_title = 'Admin - Armatuurlaud';
$page_description = 'Estreka Ratsaklubi administraatori armatuurlaud.';

include '../includes/header.php';
?>

<main class="admin-main">
    <div class="container">
        <!-- Header -->
        <div class="admin-header">
            <div class="admin-header-content">
                <h1 class="admin-title">Administraatori paneel</h1>
                <p class="admin-subtitle">
                    Tere tulemast, <?php echo htmlspecialchars($_SESSION['user_name']); ?>!
                </p>
            </div>
            <div class="admin-actions">
                <a href="<?php echo url('admin/competitions.php'); ?>" class="btn btn-primary">
                    <i class="icon-plus"></i>
                    <span>Lisa võistlus</span>
                </a>
                <a href="<?php echo url('admin/results.php'); ?>" class="btn btn-secondary">
                    <i class="icon-trophy"></i>
                    <span>Lisa tulemused</span>
                </a>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistika kaardid -->
        <div class="stats-section">
            <div class="stats-grid">
                <div class="stat-card users-card">
                    <div class="stat-icon">
                        <i class="icon-users"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo ($user_stats['athlete'] ?? 0); ?></div>
                        <div class="stat-label">Sportlast</div>
                    </div>
                    <div class="stat-trend">
                        <a href="<?php echo url('admin/users.php'); ?>">Halda →</a>
                    </div>
                </div>

                <div class="stat-card competitions-card">
                    <div class="stat-icon">
                        <i class="icon-calendar"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $competitions_count; ?></div>
                        <div class="stat-label">Võistlust <?php echo $current_year; ?></div>
                    </div>
                    <div class="stat-trend">
                        <a href="<?php echo url('admin/competitions.php'); ?>">Halda →</a>
                    </div>
                </div>

                <div class="stat-card results-card">
                    <div class="stat-icon">
                        <i class="icon-trophy"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo $results_count; ?></div>
                        <div class="stat-label">Tulemust sisestatud</div>
                    </div>
                    <div class="stat-trend">
                        <a href="<?php echo url('admin/results.php'); ?>">Halda →</a>
                    </div>
                </div>

                <div class="stat-card activity-card">
                    <div class="stat-icon">
                        <i class="icon-activity"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-number"><?php echo count($recent_activities); ?></div>
                        <div class="stat-label">Viimast tegevust</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Aktiveerimist ootavad kasutajad -->
        <?php if (!empty($pending_users)): ?>
        <div class="admin-card pending-users-card">
            <div class="card-header">
                <h2 class="card-title">
                    <i class="icon-user-check"></i>
                    Aktiveerimist ootavad kasutajad
                </h2>
                <span class="pending-badge"><?php echo count($pending_users); ?></span>
            </div>
            <div class="card-content">
                <div class="pending-users-list">
                    <?php foreach ($pending_users as $user): ?>
                        <div class="pending-user-item" id="pending-user-<?php echo $user['id']; ?>">
                            <div class="user-info">
                                <div class="user-name">
                                    <?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?>
                                </div>
                                <div class="user-details">
                                    <span class="user-email"><?php echo htmlspecialchars($user['email']); ?></span>
                                    <span class="user-username">@<?php echo htmlspecialchars($user['username']); ?></span>
                                </div>
                                <div class="user-meta">
                                    <span class="registration-date">
                                        <?php echo formatTimeAgo($user['createdAt']); ?>
                                    </span>
                                    <span class="pending-reason-badge <?php echo $user['pending_reason']; ?>">
                                        <?php 
                                        switch($user['pending_reason']) {
                                            case 'email_not_verified': echo 'Email kinnitamata'; break;
                                            case 'inactive': echo 'Mitteaktiivne'; break;
                                            default: echo 'Ootab aktiveerimist'; break;
                                        }
                                        ?>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="user-actions">
                                <?php if ($user['pending_reason'] === 'email_not_verified'): ?>
                                    <button onclick="activateUser(<?php echo $user['id']; ?>, 'verify_email')" 
                                            class="btn btn-success btn-sm" title="Kinnita email ja aktiveeri">
                                        <i class="icon-mail-check"></i>
                                        <span>Kinnita email</span>
                                    </button>
                                <?php elseif ($user['pending_reason'] === 'inactive'): ?>
                                    <button onclick="activateUser(<?php echo $user['id']; ?>, 'activate')" 
                                            class="btn btn-primary btn-sm" title="Aktiveeri kasutaja">
                                        <i class="icon-user-check"></i>
                                        <span>Aktiveeri</span>
                                    </button>
                                <?php endif; ?>
                                
                                <a href="<?php echo url('admin/users.php?search=' . urlencode($user['email'])); ?>" 
                                   class="btn btn-outline btn-sm" title="Ava kasutajate halduses">
                                    <i class="icon-edit"></i>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <?php if (count($pending_users) >= 10): ?>
                    <div class="pending-users-footer">
                        <a href="<?php echo url('admin/users.php?status=inactive'); ?>" class="btn btn-outline">
                            <i class="icon-users"></i>
                            <span>Vaata kõiki mitteaktiivseid</span>
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Põhisisu grid -->
        <div class="admin-grid">
            <!-- Vasak veerg -->
            <div class="admin-left">
                <!-- Viimased tulemused -->
                <div class="admin-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-trophy"></i>
                            Viimased tulemused
                        </h2>
                        <a href="<?php echo url('admin/results.php'); ?>" class="card-link">Vaata kõiki</a>
                    </div>
                    <div class="card-content">
                        <?php if (empty($recent_results)): ?>
                            <div class="empty-state">
                                <i class="icon-trophy"></i>
                                <p>Tulemusi pole veel lisatud</p>
                            </div>
                        <?php else: ?>
                            <div class="results-list">
                                <?php foreach ($recent_results as $result): ?>
                                    <div class="result-item">
                                        <div class="result-athlete">
                                            <?php echo htmlspecialchars($result['firstName'] . ' ' . $result['lastName']); ?>
                                        </div>
                                        <div class="result-competition">
                                            <?php echo htmlspecialchars($result['competitionName']); ?>
                                        </div>
                                        <div class="result-points">
                                            <?php echo formatPoints($result['points']); ?>p
                                        </div>
                                        <div class="result-discipline">
                                            <span class="discipline-badge <?php echo $result['discipline']; ?>">
                                                <?php echo getDisciplineName($result['discipline']); ?>
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Kuustatistika -->
                <div class="admin-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-bar-chart"></i>
                            Kuustatistika <?php echo $current_year; ?>
                        </h2>
                    </div>
                    <div class="card-content">
                        <?php if (empty($monthly_stats)): ?>
                            <div class="empty-state">
                                <i class="icon-bar-chart"></i>
                                <p>Statistikat pole veel saadaval</p>
                            </div>
                        <?php else: ?>
                            <div class="monthly-chart">
                                <?php 
                                $months = ['01' => 'Jan', '02' => 'Veeb', '03' => 'Märts', '04' => 'Apr', 
                                          '05' => 'Mai', '06' => 'Juuni', '07' => 'Juuli', '08' => 'Aug',
                                          '09' => 'Sept', '10' => 'Okt', '11' => 'Nov', '12' => 'Dets'];
                                $max_results = max(array_column($monthly_stats, 'results'));
                                
                                foreach ($monthly_stats as $month): 
                                ?>
                                    <div class="month-bar">
                                        <div class="month-data">
                                            <div class="month-results" 
                                                 style="height: <?php echo $max_results > 0 ? ($month['results'] / $max_results) * 100 : 0; ?>%">
                                            </div>
                                        </div>
                                        <div class="month-label">
                                            <?php echo $months[$month['month']]; ?>
                                        </div>
                                        <div class="month-count">
                                            <?php echo $month['results']; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Parem veerg -->
            <div class="admin-right">
                <!-- Kiired toimingud -->
                <div class="admin-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-zap"></i>
                            Kiired toimingud
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="quick-actions">
                            <a href="<?php echo url('admin/competitions.php'); ?>" class="action-item primary">
                                <div class="action-icon">
                                    <i class="icon-plus"></i>
                                </div>
                                <div class="action-text">
                                    <div class="action-title">Lisa võistlus</div>
                                    <div class="action-subtitle">Uue võistluse loomine</div>
                                </div>
                            </a>

                            <a href="<?php echo url('admin/results.php'); ?>" class="action-item">
                                <div class="action-icon">
                                    <i class="icon-trophy"></i>
                                </div>
                                <div class="action-text">
                                    <div class="action-title">Lisa tulemused</div>
                                    <div class="action-subtitle">Võistluste tulemuste sisestamine</div>
                                </div>
                            </a>

                            <a href="<?php echo url('admin/users.php'); ?>" class="action-item">
                                <div class="action-icon">
                                    <i class="icon-users"></i>
                                </div>
                                <div class="action-text">
                                    <div class="action-title">Halda kasutajaid</div>
                                    <div class="action-subtitle">Sportlaste ja adminite haldamine</div>
                                </div>
                            </a>

                            <a href="<?php echo url('public/stats.php'); ?>" class="action-item">
                                <div class="action-icon">
                                    <i class="icon-bar-chart"></i>
                                </div>
                                <div class="action-text">
                                    <div class="action-title">Vaata statistikat</div>
                                    <div class="action-subtitle">Üldine hooaja ülevaade</div>
                                </div>
                            </a>

                            <a href="<?php echo url('public/rankings.php'); ?>" class="action-item">
                                <div class="action-icon">
                                    <i class="icon-list"></i>
                                </div>
                                <div class="action-text">
                                    <div class="action-title">Hooaja tabelid</div>
                                    <div class="action-subtitle">Vaata kõiki järjestusi</div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Lähituleviku võistlused -->
                <div class="admin-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-calendar"></i>
                            Lähituleviku võistlused
                        </h2>
                    </div>
                    <div class="card-content">
                        <?php if (empty($upcoming_competitions)): ?>
                            <div class="empty-state">
                                <i class="icon-calendar"></i>
                                <p>Tuleviku võistlusi pole planeeritud</p>
                                <a href="<?php echo url('admin/competitions.php'); ?>" class="btn btn-primary btn-sm">
                                    Lisa võistlus
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="competitions-list">
                                <?php foreach ($upcoming_competitions as $comp): ?>
                                    <div class="competition-item">
                                        <div class="competition-date">
                                            <div class="date-day"><?php echo date('d', strtotime($comp['date'])); ?></div>
                                            <div class="date-month"><?php echo date('M', strtotime($comp['date'])); ?></div>
                                        </div>
                                        <div class="competition-info">
                                            <div class="competition-name">
                                                <?php echo htmlspecialchars($comp['name']); ?>
                                            </div>
                                            <div class="competition-meta">
                                                <?php echo getDisciplineName($comp['discipline']); ?>
                                                <?php if ($comp['location']): ?>
                                                    • <?php echo htmlspecialchars($comp['location']); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Viimased tegevused -->
                <div class="admin-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <i class="icon-activity"></i>
                            Viimased tegevused
                        </h2>
                    </div>
                    <div class="card-content">
                        <?php if (empty($recent_activities)): ?>
                            <div class="empty-state">
                                <i class="icon-activity"></i>
                                <p>Tegevusi pole veel logitud</p>
                            </div>
                        <?php else: ?>
                            <div class="activities-list">
                                <?php foreach ($recent_activities as $activity): ?>
                                    <div class="activity-item">
                                        <div class="activity-icon">
                                            <?php
                                            $action_icons = [
                                                'login' => 'icon-log-in',
                                                'logout' => 'icon-log-out',
                                                'register' => 'icon-user',
                                                'competition_created' => 'icon-plus',
                                                'result_added' => 'icon-trophy',
                                                'user_created' => 'icon-users',
                                                'profile_updated' => 'icon-edit',
                                                'password_changed' => 'icon-lock'
                                            ];
                                            $icon = $action_icons[$activity['action']] ?? 'icon-info';
                                            ?>
                                            <i class="<?php echo $icon; ?>"></i>
                                        </div>
                                        <div class="activity-content">
                                            <div class="activity-text">
                                                <?php if ($activity['firstName']): ?>
                                                    <strong><?php echo htmlspecialchars($activity['firstName'] . ' ' . $activity['lastName']); ?></strong>
                                                <?php else: ?>
                                                    <strong>Tundmatu kasutaja</strong>
                                                <?php endif; ?>
                                                - <?php echo getActionDescription($activity['action']); ?>
                                            </div>
                                            <div class="activity-time">
                                                <?php echo formatTimeAgo($activity['created_at']); ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<style>
/* 🎨 KAASAEGNE ADMIN DASHBOARD - HELE DISAIN
   ================================================== */

/* ===== PÕHI VÄRVIPALETT & MUUTUJAD ===== */
.admin-main {
    --modern-white: #ffffff;
    --modern-gray-50: #f8fafc;
    --modern-gray-100: #f1f5f9;
    --modern-gray-200: #e2e8f0;
    --modern-gray-300: #cbd5e1;
    --modern-gray-400: #94a3b8;
    --modern-gray-500: #64748b;
    --modern-gray-600: #475569;
    --modern-gray-700: #334155;
    --modern-gray-800: #1e293b;
    --modern-gray-900: #0f172a;
    
    /* Pehmemad sinised toonid */
    --modern-primary: #3b82f6;
    --modern-primary-light: #60a5fa;
    --modern-primary-dark: #2563eb;
    --modern-primary-50: #eff6ff;
    --modern-primary-100: #dbeafe;
    
    /* Kaasaegsed aktsendivärvi */
    --modern-success: #10b981;
    --modern-success-50: #ecfdf5;
    --modern-warning: #f59e0b;
    --modern-warning-50: #fffbeb;
    --modern-danger: #ef4444;
    --modern-danger-50: #fef2f2;
    --modern-purple: #8b5cf6;
    --modern-purple-50: #f5f3ff;
    
    /* Kaasaegsed varjud */
    --modern-shadow-xs: 0 1px 2px 0 rgb(0 0 0 / 0.03);
    --modern-shadow-sm: 0 1px 3px 0 rgb(0 0 0 / 0.06), 0 1px 2px -1px rgb(0 0 0 / 0.06);
    --modern-shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.08), 0 2px 4px -2px rgb(0 0 0 / 0.08);
    --modern-shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.08), 0 4px 6px -4px rgb(0 0 0 / 0.08);
    --modern-shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.08), 0 8px 10px -6px rgb(0 0 0 / 0.08);
    
    /* Glassmorphism efektid */
    --glass-bg: rgba(255, 255, 255, 0.8);
    --glass-border: rgba(255, 255, 255, 0.3);
    
    /* Spacing */
    --space-1: 0.25rem;
    --space-2: 0.5rem;
    --space-3: 0.75rem;
    --space-4: 1rem;
    --space-5: 1.25rem;
    --space-6: 1.5rem;
    --space-8: 2rem;
    --space-10: 2.5rem;
    --space-12: 3rem;
    --space-16: 4rem;
    --space-20: 5rem;
    
    /* Border radius */
    --radius-sm: 0.375rem;
    --radius-md: 0.5rem;
    --radius-lg: 0.75rem;
    --radius-xl: 1rem;
    --radius-2xl: 1.5rem;
    --radius-full: 9999px;
    
    /* Transitions */
    --transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
    --transition-normal: 250ms cubic-bezier(0.4, 0, 0.2, 1);
    --transition-slow: 350ms cubic-bezier(0.4, 0, 0.2, 1);
}

/* ===== PÕHI LAYOUT PARANDUSED ===== */
.admin-main {
    padding: var(--space-8) 0 var(--space-16);
    min-height: 100vh;
    background: linear-gradient(135deg, var(--modern-gray-50) 0%, var(--modern-primary-50) 100%);
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}

.container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 var(--space-6);
}

/* ===== KAASAEGNE HEADER SEKTSIOON ===== */
.admin-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: var(--space-12);
    gap: var(--space-6);
    position: relative;
}

.admin-header::before {
    content: '';
    position: absolute;
    top: -50px;
    left: -50px;
    right: -50px;
    bottom: -20px;
    background: linear-gradient(135deg, 
        rgba(59, 130, 246, 0.03) 0%, 
        rgba(139, 92, 246, 0.03) 50%, 
        rgba(16, 185, 129, 0.03) 100%);
    border-radius: var(--radius-2xl);
    z-index: -1;
    backdrop-filter: blur(20px);
}

.admin-header-content {
    z-index: 1;
}

.admin-title {
    font-size: 2.5rem;
    font-weight: 800;
    background: linear-gradient(135deg, var(--modern-gray-900), var(--modern-primary));
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: var(--space-3);
    letter-spacing: -0.025em;
}

.admin-subtitle {
    font-size: 1.125rem;
    color: var(--modern-gray-600);
    font-weight: 500;
    margin: 0;
}

.admin-actions {
    display: flex;
    gap: var(--space-4);
    z-index: 1;
}

.admin-actions .btn {
    padding: var(--space-3) var(--space-6);
    border-radius: var(--radius-lg);
    font-weight: 600;
    font-size: 0.875rem;
    transition: all var(--transition-normal);
    backdrop-filter: blur(10px);
    border: 1px solid transparent;
    position: relative;
    overflow: hidden;
}

.admin-actions .btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left var(--transition-slow);
}

.admin-actions .btn:hover::before {
    left: 100%;
}

.btn-primary {
    background: linear-gradient(135deg, var(--modern-primary), var(--modern-primary-dark));
    color: white;
    box-shadow: var(--modern-shadow-md);
}

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

.btn-secondary {
    background: var(--modern-white);
    color: var(--modern-gray-700);
    border: 1px solid var(--modern-gray-200);
    box-shadow: var(--modern-shadow-sm);
}

.btn-secondary:hover {
    background: var(--modern-gray-50);
    border-color: var(--modern-primary);
    color: var(--modern-primary);
    transform: translateY(-1px);
}

/* ===== STATISTIKA KAARDID (MODERNISEERITUD) ===== */
.stats-section {
    margin-bottom: var(--space-12);
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: var(--space-8);
}

.stat-card {
    background: var(--modern-white);
    border-radius: var(--radius-xl);
    box-shadow: var(--modern-shadow-sm);
    padding: var(--space-8);
    border: 1px solid var(--modern-gray-200);
    transition: all var(--transition-normal);
    position: relative;
    overflow: hidden;
    min-height: 160px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--modern-primary), var(--modern-purple));
    transform: scaleX(0);
    transform-origin: left;
    transition: transform var(--transition-normal);
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--modern-shadow-xl);
    border-color: var(--modern-primary-100);
}

.stat-card:hover::before {
    transform: scaleX(1);
}

.stat-card .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: var(--radius-lg);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
    margin-bottom: var(--space-6);
    position: relative;
    overflow: hidden;
}

.stat-card .stat-icon::after {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
    transform: rotate(45deg);
    transition: transform var(--transition-slow);
}

.stat-card:hover .stat-icon::after {
    transform: rotate(45deg) translateX(100%);
}

.users-card .stat-icon { 
    background: linear-gradient(135deg, var(--modern-primary), var(--modern-primary-dark)); 
}
.competitions-card .stat-icon { 
    background: linear-gradient(135deg, var(--modern-success), #047857); 
}
.results-card .stat-icon { 
    background: linear-gradient(135deg, var(--modern-warning), #d97706); 
}
.activity-card .stat-icon { 
    background: linear-gradient(135deg, var(--modern-purple), #7c3aed); 
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 3rem;
    font-weight: 800;
    color: var(--modern-gray-900);
    margin-bottom: var(--space-2);
    line-height: 1;
    letter-spacing: -0.025em;
}

.stat-label {
    color: var(--modern-gray-600);
    font-size: 0.875rem;
    font-weight: 500;
    margin-bottom: var(--space-4);
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.stat-trend {
    margin-top: auto;
    display: flex;
    align-items: center;
    gap: var(--space-2);
}

.stat-trend a {
    color: var(--modern-primary);
    font-size: 0.875rem;
    font-weight: 600;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: var(--space-2);
    padding: var(--space-2) var(--space-4);
    border-radius: var(--radius-md);
    background: var(--modern-primary-50);
    transition: all var(--transition-fast);
}

.stat-trend a:hover {
    background: var(--modern-primary-100);
    transform: translateX(4px);
}

/* ===== PENDING USERS WIDGET (TÄIUSTATUD) ===== */
.pending-users-card {
    margin-bottom: var(--space-8);
    background: var(--modern-white);
    border-radius: var(--radius-xl);
    box-shadow: var(--modern-shadow-md);
    border-left: 4px solid var(--modern-warning);
    overflow: hidden;
    position: relative;
}

.pending-users-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 4px;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, 
        rgba(245, 158, 11, 0.02) 0%, 
        rgba(239, 68, 68, 0.02) 100%);
    pointer-events: none;
}

.pending-users-card .card-header {
    background: linear-gradient(135deg, var(--modern-warning-50), #fef3c7);
    border-bottom: 1px solid var(--modern-warning-100);
    padding: var(--space-6);
    position: relative;
    z-index: 1;
}

.pending-badge {
    background: linear-gradient(135deg, var(--modern-warning), #d97706);
    color: white;
    padding: var(--space-2) var(--space-4);
    border-radius: var(--radius-full);
    font-size: 0.75rem;
    font-weight: 700;
    min-width: 24px;
    text-align: center;
    box-shadow: var(--modern-shadow-sm);
    animation: pulse-warning 2s infinite;
}

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

.pending-users-list {
    padding: var(--space-6);
    display: flex;
    flex-direction: column;
    gap: var(--space-6);
}

.pending-user-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--space-6);
    background: var(--modern-white);
    border: 1px solid var(--modern-gray-200);
    border-radius: var(--radius-lg);
    transition: all var(--transition-normal);
    position: relative;
    overflow: hidden;
}

.pending-user-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 3px;
    background: linear-gradient(135deg, var(--modern-warning), var(--modern-danger));
    transform: scaleY(0);
    transition: transform var(--transition-normal);
}

.pending-user-item:hover {
    background: var(--modern-gray-50);
    border-color: var(--modern-primary-200);
    box-shadow: var(--modern-shadow-md);
    transform: translateY(-2px);
}

.pending-user-item:hover::before {
    transform: scaleY(1);
}

/* ===== ADMIN GRID (PARANDATUD) ===== */
.admin-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: var(--space-8);
}

@media (min-width: 1024px) {
    .admin-grid {
        grid-template-columns: 2fr 1fr;
        gap: var(--space-12);
    }
}

/* ===== KAASAEGSED KAARDID ===== */
.admin-card {
    background: var(--modern-white);
    border-radius: var(--radius-xl);
    box-shadow: var(--modern-shadow-sm);
    margin-bottom: var(--space-8);
    overflow: hidden;
    border: 1px solid var(--modern-gray-200);
    transition: all var(--transition-normal);
    backdrop-filter: blur(10px);
}

.admin-card:hover {
    box-shadow: var(--modern-shadow-lg);
    border-color: var(--modern-primary-200);
}

.card-header {
    padding: var(--space-6) var(--space-8);
    border-bottom: 1px solid var(--modern-gray-200);
    background: linear-gradient(135deg, var(--modern-gray-50), var(--modern-primary-50));
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
}

.card-header::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, var(--modern-primary), transparent);
    opacity: 0;
    transition: opacity var(--transition-normal);
}

.admin-card:hover .card-header::after {
    opacity: 1;
}

.card-title {
    display: flex;
    align-items: center;
    gap: var(--space-3);
    margin: 0;
}

.card-title h2 {
    margin: 0;
    font-size: 1.125rem;
    font-weight: 700;
    color: var(--modern-gray-900);
    letter-spacing: -0.025em;
}

.card-title i {
    color: var(--modern-primary);
    font-size: 1.25rem;
    filter: drop-shadow(0 2px 4px rgba(59, 130, 246, 0.2));
}

.card-link {
    color: var(--modern-primary);
    font-size: 0.875rem;
    font-weight: 600;
    text-decoration: none;
    padding: var(--space-2) var(--space-4);
    border-radius: var(--radius-md);
    background: var(--modern-primary-50);
    transition: all var(--transition-fast);
    display: inline-flex;
    align-items: center;
    gap: var(--space-2);
}

.card-link::after {
    content: '→';
    transition: transform var(--transition-fast);
}

.card-link:hover {
    background: var(--modern-primary-100);
    transform: translateX(2px);
}

.card-link:hover::after {
    transform: translateX(2px);
}

.card-content {
    padding: var(--space-8);
}

/* ===== TULEMUSTE NIMEKIRI (MODERNISEERITUD) ===== */
.results-list {
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
}

.result-item {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: var(--space-6);
    align-items: center;
    padding: var(--space-5);
    border: 1px solid var(--modern-gray-200);
    border-radius: var(--radius-lg);
    transition: all var(--transition-normal);
    background: var(--modern-white);
    position: relative;
    overflow: hidden;
}

.result-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 3px;
    background: linear-gradient(135deg, var(--modern-primary), var(--modern-purple));
    transform: scaleY(0);
    transition: transform var(--transition-normal);
}

.result-item:hover {
    background: var(--modern-gray-50);
    border-color: var(--modern-primary-200);
    box-shadow: var(--modern-shadow-md);
    transform: translateY(-2px);
}

.result-item:hover::before {
    transform: scaleY(1);
}

.result-athlete {
    font-weight: 600;
    color: var(--modern-gray-900);
    font-size: 0.875rem;
    margin-bottom: var(--space-2);
}

.result-competition {
    font-size: 0.875rem;
    color: var(--modern-gray-600);
    margin-bottom: var(--space-2);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.result-points {
    text-align: right;
    flex-shrink: 0;
}

.points-value {
    font-weight: 700;
    color: var(--modern-primary);
    font-size: 1.125rem;
    display: block;
}

.discipline-badge {
    padding: var(--space-2) var(--space-3);
    border-radius: var(--radius-md);
    font-size: 0.75rem;
    font-weight: 600;
    color: white;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
}

.discipline-badge::after {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
    transition: transform var(--transition-slow);
    transform: rotate(45deg) translateX(-100%);
}

.discipline-badge:hover::after {
    transform: rotate(45deg) translateX(100%);
}

.discipline-badge.koolisoit { 
    background: linear-gradient(135deg, var(--modern-primary), var(--modern-primary-dark)); 
}
.discipline-badge.takistussoit { 
    background: linear-gradient(135deg, var(--modern-success), #047857); 
}
.discipline-badge.kestvusratsutamine { 
    background: linear-gradient(135deg, var(--modern-purple), #7c3aed); 
}

/* ===== KUUSTATISTIKA GRAAFIK (KAASAEGNE) ===== */
.monthly-chart {
    display: flex;
    align-items: end;
    gap: var(--space-3);
    height: 140px;
    padding: var(--space-6) 0;
    overflow-x: auto;
    background: linear-gradient(135deg, var(--modern-gray-50), var(--modern-primary-50));
    border-radius: var(--radius-lg);
    margin: var(--space-4) 0;
}

.month-bar {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--space-2);
    height: 100%;
    min-width: 48px;
}

.month-data {
    flex: 1;
    width: 100%;
    display: flex;
    align-items: end;
    position: relative;
}

.month-results {
    width: 100%;
    background: linear-gradient(to top, var(--modern-primary), var(--modern-primary-light));
    border-radius: var(--radius-sm) var(--radius-sm) 0 0;
    min-height: 6px;
    transition: all var(--transition-slow);
    position: relative;
    overflow: hidden;
}

.month-results::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transform: translateX(-100%);
    transition: transform var(--transition-slow);
}

.month-bar:hover .month-results::after {
    transform: translateX(100%);
}

.month-label {
    font-size: 0.75rem;
    color: var(--modern-gray-600);
    font-weight: 600;
    text-align: center;
}

.month-count {
    font-size: 0.75rem;
    color: var(--modern-gray-500);
    text-align: center;
    background: var(--modern-white);
    padding: var(--space-1) var(--space-2);
    border-radius: var(--radius-sm);
    box-shadow: var(--modern-shadow-xs);
}

/* ===== KIIRED TOIMINGUD (KAASAEGNE) ===== */
.quick-actions {
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
}

.action-item {
    display: flex;
    align-items: center;
    gap: var(--space-4);
    padding: var(--space-5);
    border: 1px solid var(--modern-gray-200);
    border-radius: var(--radius-lg);
    color: var(--modern-gray-700);
    text-decoration: none;
    transition: all var(--transition-normal);
    background: var(--modern-white);
    position: relative;
    overflow: hidden;
}

.action-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, 
        rgba(59, 130, 246, 0.02) 0%, 
        rgba(139, 92, 246, 0.02) 100%);
    opacity: 0;
    transition: opacity var(--transition-normal);
}

.action-item:hover {
    border-color: var(--modern-primary-200);
    background: var(--modern-gray-50);
    color: var(--modern-gray-900);
    transform: translateY(-2px);
    box-shadow: var(--modern-shadow-md);
}

.action-item:hover::before {
    opacity: 1;
}

.action-item.primary {
    border-color: var(--modern-primary-200);
    background: linear-gradient(135deg, var(--modern-primary-50), var(--modern-purple-50));
}

.action-item.primary:hover {
    background: linear-gradient(135deg, var(--modern-primary-100), #e0e7ff);
    box-shadow: var(--modern-shadow-lg);
}

.action-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, var(--modern-gray-100), var(--modern-primary-50));
    color: var(--modern-primary);
    border-radius: var(--radius-lg);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
    position: relative;
    overflow: hidden;
    transition: all var(--transition-normal);
}

.action-icon::after {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: transform var(--transition-slow);
    transform: rotate(45deg) translateX(-100%);
}

.action-item:hover .action-icon {
    background: linear-gradient(135deg, var(--modern-primary), var(--modern-primary-dark));
    color: white;
    transform: scale(1.05);
}

.action-item:hover .action-icon::after {
    transform: rotate(45deg) translateX(100%);
}

.action-text {
    flex: 1;
    min-width: 0;
}

.action-title {
    font-weight: 600;
    margin-bottom: var(--space-2);
    font-size: 0.875rem;
    color: var(--modern-gray-900);
}

.action-subtitle {
    font-size: 0.75rem;
    color: var(--modern-gray-500);
    line-height: 1.4;
}

/* ===== VÕISTLUSTE NIMEKIRI (MODERNISEERITUD) ===== */
.competitions-list {
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
}

.competition-item {
    display: flex;
    align-items: center;
    gap: var(--space-4);
    padding: var(--space-5);
    border: 1px solid var(--modern-gray-200);
    border-radius: var(--radius-lg);
    transition: all var(--transition-normal);
    background: var(--modern-white);
    position: relative;
}

.competition-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 3px;
    background: linear-gradient(135deg, var(--modern-success), var(--modern-primary));
    transform: scaleY(0);
    transition: transform var(--transition-normal);
}

.competition-item:hover {
    border-color: var(--modern-primary-200);
    background: var(--modern-gray-50);
    box-shadow: var(--modern-shadow-md);
    transform: translateY(-1px);
}

.competition-item:hover::before {
    transform: scaleY(1);
}

.competition-date {
    text-align: center;
    min-width: 48px;
    flex-shrink: 0;
    padding: var(--space-3);
    background: linear-gradient(135deg, var(--modern-primary-50), var(--modern-purple-50));
    border-radius: var(--radius-md);
}

.date-day {
    font-size: 1.125rem;
    font-weight: 700;
    color: var(--modern-primary);
    line-height: 1;
}

.date-month {
    font-size: 0.75rem;
    color: var(--modern-gray-500);
    text-transform: uppercase;
    font-weight: 600;
    letter-spacing: 0.05em;
}

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

.competition-name {
    font-weight: 600;
    color: var(--modern-gray-900);
    margin-bottom: var(--space-1);
    font-size: 0.875rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.competition-meta {
    font-size: 0.75rem;
    color: var(--modern-gray-600);
}

/* ===== TEGEVUSTE NIMEKIRI (KAASAEGNE) ===== */
.activities-list {
    display: flex;
    flex-direction: column;
    gap: var(--space-3);
}

.activity-item {
    display: flex;
    align-items: flex-start;
    gap: var(--space-3);
    padding: var(--space-4);
    border-radius: var(--radius-lg);
    transition: all var(--transition-normal);
    position: relative;
}

.activity-item:hover {
    background: var(--modern-gray-50);
}

.activity-icon {
    width: 36px;
    height: 36px;
    background: linear-gradient(135deg, var(--modern-primary-50), var(--modern-purple-50));
    color: var(--modern-primary);
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    flex-shrink: 0;
    transition: all var(--transition-normal);
}

.activity-item:hover .activity-icon {
    background: linear-gradient(135deg, var(--modern-primary), var(--modern-primary-dark));
    color: white;
    transform: scale(1.1);
}

.activity-content {
    flex: 1;
    min-width: 0;
}

.activity-text {
    font-size: 0.875rem;
    color: var(--modern-gray-700);
    line-height: 1.4;
    margin-bottom: var(--space-1);
}

.activity-time {
    font-size: 0.75rem;
    color: var(--modern-gray-500);
    font-weight: 500;
}

/* ===== TÜHI OLEKU DISAIN ===== */
.empty-state {
    text-align: center;
    padding: var(--space-16) var(--space-6);
    color: var(--modern-gray-500);
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: var(--space-6);
    opacity: 0.5;
    color: var(--modern-gray-400);
}

.empty-state p {
    margin-bottom: var(--space-6);
    font-size: 1rem;
    color: var(--modern-gray-600);
}

.btn-sm {
    padding: var(--space-3) var(--space-5);
    font-size: 0.875rem;
    border-radius: var(--radius-md);
    font-weight: 600;
    transition: all var(--transition-normal);
}

/* ===== TEATISED JA TAGASISIDE ===== */
.notification {
    position: fixed;
    top: var(--space-6);
    right: var(--space-6);
    padding: var(--space-4) var(--space-6);
    border-radius: var(--radius-lg);
    box-shadow: var(--modern-shadow-xl);
    display: flex;
    align-items: center;
    gap: var(--space-3);
    font-size: 0.875rem;
    font-weight: 600;
    z-index: 1000;
    transform: translateX(120%);
    transition: transform var(--transition-normal);
    backdrop-filter: blur(20px);
}

.notification.show {
    transform: translateX(0);
}

.notification-success {
    background: linear-gradient(135deg, var(--modern-success-50), #d1fae5);
    color: var(--modern-gray-800);
    border: 1px solid var(--modern-success);
}

.notification-error {
    background: linear-gradient(135deg, var(--modern-danger-50), #fed7d7);
    color: var(--modern-gray-800);
    border: 1px solid var(--modern-danger);
}

/* ===== MOBILE EXPANSION FUNKTSIOONID ===== */
.expand-toggle {
    display: none;
    width: 100%;
    margin-top: var(--space-4);
    padding: var(--space-3) var(--space-4);
    background: linear-gradient(135deg, var(--modern-gray-50), var(--modern-primary-50));
    border: 1px solid var(--modern-gray-200);
    border-radius: var(--radius-lg);
    color: var(--modern-primary);
    font-weight: 600;
    font-size: 0.875rem;
    cursor: pointer;
    transition: all var(--transition-normal);
    text-align: center;
}

.expand-toggle:hover {
    background: linear-gradient(135deg, var(--modern-primary-50), var(--modern-primary-100));
    border-color: var(--modern-primary);
    transform: translateY(-1px);
    box-shadow: var(--modern-shadow-sm);
}

.expand-toggle i {
    margin-left: var(--space-2);
    transition: transform var(--transition-fast);
}

.expand-toggle.expanded i {
    transform: rotate(180deg);
}

/* Mobile compact states */
.mobile-compact .result-item:nth-child(n+4),
.mobile-compact .activity-item:nth-child(n+4) {
    display: none;
}

.mobile-compact.expanded .result-item,
.mobile-compact.expanded .activity-item {
    display: flex;
}

.mobile-compact .expand-toggle {
    display: block;
}

/* ===== RESPONSIVE PARANDUSED ===== */
@media (max-width: 1023px) {
    .admin-header {
        flex-direction: column;
        align-items: stretch;
        text-align: center;
        gap: var(--space-6);
    }
    
    .admin-title {
        font-size: 2rem;
    }
    
    .stats-grid {
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: var(--space-6);
    }
    
    .stat-card {
        padding: var(--space-6);
        min-height: 140px;
    }
    
    .stat-number {
        font-size: 2.5rem;
    }
}

@media (max-width: 767px) {
    .container {
        padding: 0 var(--space-4);
    }
    
    .admin-main {
        padding: var(--space-6) 0 var(--space-12);
    }
    
    .admin-header::before {
        top: -30px;
        left: -30px;
        right: -30px;
    }
    
    .admin-title {
        font-size: 1.75rem;
    }
    
    .admin-subtitle {
        font-size: 1rem;
    }
    
    .admin-actions {
        flex-direction: column;
        gap: var(--space-3);
    }
    
    .stats-grid {
        grid-template-columns: 1fr;
        gap: var(--space-4);
    }
    
    .stat-card {
        padding: var(--space-5);
        min-height: 120px;
    }
    
    .stat-card .stat-icon {
        width: 48px;
        height: 48px;
        font-size: 20px;
    }
    
    .stat-number {
        font-size: 2rem;
    }
    
    .card-header {
        padding: var(--space-5);
        flex-direction: column;
        align-items: stretch;
        gap: var(--space-3);
        text-align: center;
    }
    
    .card-content {
        padding: var(--space-5);
    }
    
    /* 📱 MOBILE COMPACT MODE - Näita ainult 3 elementi */
    .results-list,
    .activities-list {
        position: relative;
    }
    
    .results-list {
        overflow: hidden;
    }
    
    .activities-list {
        overflow: hidden;
    }
    
    /* Kompaktne režiim - peida üleliigsed elemendid */
    .results-list.mobile-compact .result-item:nth-child(n+4),
    .activities-list.mobile-compact .activity-item:nth-child(n+4) {
        display: none;
    }
    
    /* 🔧 PARANDUS: Kui laienduv on aktiivne, näita kõiki ÕIGE struktuuri säilitades */
    .results-list.mobile-compact.expanded .result-item {
        display: grid !important; /* Force grid layout */
        grid-template-columns: 1fr !important; /* Mobile grid structure */
        gap: var(--space-4) !important;
        text-align: center !important;
    }
    
    .activities-list.mobile-compact.expanded .activity-item {
        display: flex !important; /* Activities use flex */
    }
    
    /* Expand toggle nähtav ainult mobiilis */
    .results-list.mobile-compact .expand-toggle,
    .activities-list.mobile-compact .expand-toggle {
        display: block;
    }
    
    /* 🔧 PARANDUS: Result item mobile stiilid rakenduvad ALATI mobiilis */
    .result-item {
        grid-template-columns: 1fr !important;
        gap: var(--space-4) !important;
        text-align: center !important;
    }
    
    /* 🔧 LISATUD: Ensure result content is stacked vertically on mobile */
    .result-item .result-athlete,
    .result-item .result-competition,
    .result-item .result-points,
    .result-item .discipline-badge {
        width: 100%;
        margin-bottom: var(--space-2);
        display: block;
    }
    
    /* 🔧 LISATUD: Mobile specific result item styling */
    .result-item .points-value {
        font-size: 1.5rem !important;
        display: block;
        margin: var(--space-2) 0;
    }
    
    .result-item .discipline-badge {
        display: inline-block;
        margin: var(--space-2) auto;
    }
    
    .monthly-chart {
        height: 120px;
        gap: var(--space-2);
        padding: var(--space-4) 0;
    }
    
    .month-bar {
        min-width: 36px;
    }
    
    .action-item {
        padding: var(--space-4);
        gap: var(--space-3);
    }
    
    .action-icon {
        width: 40px;
        height: 40px;
        font-size: 18px;
    }
    
    .competition-item {
        flex-direction: column;
        text-align: center;
        gap: var(--space-3);
    }
    
    .competition-date {
        min-width: auto;
    }
    
    .pending-user-item {
        flex-direction: column;
        align-items: stretch;
        gap: var(--space-4);
    }
    
    .user-actions {
        justify-content: center;
    }
    
    .notification {
        top: var(--space-4);
        right: var(--space-4);
        left: var(--space-4);
        padding: var(--space-3) var(--space-4);
    }
}

@media (max-width: 480px) {
    .admin-title {
        font-size: 1.5rem;
    }
    
    .stat-number {
        font-size: 1.75rem;
    }
    
    .monthly-chart {
        height: 100px;
    }
    
    .action-subtitle {
        display: none;
    }
}

/* ===== ACCESSIBILITY PARANDUSED ===== */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
    
    .stat-card:hover,
    .action-item:hover,
    .admin-card:hover {
        transform: none;
    }
}

/* ===== PRINT STIILID ===== */
@media print {
    .admin-actions,
    .card-link,
    .user-actions {
        display: none !important;
    }
    
    .admin-grid {
        grid-template-columns: 1fr !important;
    }
    
    .stats-grid {
        grid-template-columns: repeat(2, 1fr) !important;
    }
    
    .admin-main {
        background: white !important;
    }
    
    .admin-card,
    .stat-card {
        box-shadow: none !important;
        border: 1px solid #ddd !important;
    }
}
</style>

<script>
// 🎯 ADMIN DASHBOARD JAVASCRIPT - TÄIENDATUD MOBILE COMPACT + OLEMASOLEV
// ============================================================================

// ===== MOBILE COMPACT FUNCTIONALITY (UUS) ===== 
function initMobileCompact() {
    // Kontrolli kas on mobile
    function isMobile() {
        return window.innerWidth <= 767;
    }
    
    // Määra mobile compact class
    function setMobileCompact() {
        const resultsLists = document.querySelectorAll('.results-list');
        const activitiesLists = document.querySelectorAll('.activities-list');
        
        if (isMobile()) {
            resultsLists.forEach(list => {
                if (list.children.length > 3) {
                    list.classList.add('mobile-compact');
                    addExpandButton(list, 'tulemust');
                }
            });
            
            activitiesLists.forEach(list => {
                if (list.children.length > 3) {
                    list.classList.add('mobile-compact');
                    addExpandButton(list, 'tegevust');
                }
            });
        } else {
            // Desktop - eemalda mobile compact
            resultsLists.forEach(list => {
                list.classList.remove('mobile-compact', 'expanded');
                removeExpandButton(list);
            });
            
            activitiesLists.forEach(list => {
                list.classList.remove('mobile-compact', 'expanded');
                removeExpandButton(list);
            });
        }
    }
    
    // Lisa expand nupp
    function addExpandButton(list, type) {
        // Kontrolli kas nupp juba olemas
        if (list.querySelector('.expand-toggle')) return;
        
        const totalItems = list.children.length;
        const hiddenCount = totalItems - 3;
        
        const button = document.createElement('button');
        button.className = 'expand-toggle';
        button.innerHTML = `Näita veel ${hiddenCount} ${type} <i class="icon-chevron-down"></i>`;
        
        button.addEventListener('click', function() {
            list.classList.toggle('expanded');
            
            if (list.classList.contains('expanded')) {
                button.innerHTML = `Näita vähem <i class="icon-chevron-up"></i>`;
                button.classList.add('expanded');
                
                // 🔧 PARANDUS: Force mobile layout for result items when expanded
                if (list.classList.contains('results-list')) {
                    const resultItems = list.querySelectorAll('.result-item');
                    resultItems.forEach(item => {
                        // Ensure mobile grid layout is maintained
                        item.style.display = 'grid';
                        item.style.gridTemplateColumns = '1fr';
                        item.style.gap = 'var(--space-4)';
                        item.style.textAlign = 'center';
                    });
                }
                
            } else {
                button.innerHTML = `Näita veel ${hiddenCount} ${type} <i class="icon-chevron-down"></i>`;
                button.classList.remove('expanded');
                
                // 🔧 PARANDUS: Reset any inline styles when collapsed
                if (list.classList.contains('results-list')) {
                    const resultItems = list.querySelectorAll('.result-item');
                    resultItems.forEach(item => {
                        item.style.display = '';
                        item.style.gridTemplateColumns = '';
                        item.style.gap = '';
                        item.style.textAlign = '';
                    });
                }
            }
        });
        
        list.appendChild(button);
    }
    
    // Eemalda expand nupp
    function removeExpandButton(list) {
        const button = list.querySelector('.expand-toggle');
        if (button) {
            button.remove();
        }
    }
    
    // Initialize
    setMobileCompact();
    
    // Listen window resize
    let resizeTimer;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(setMobileCompact, 250);
    });
    
    console.log('📱 Mobile compact functionality initialized');
}

// ===== USER ACTIVATION FUNCTIONS (OLEMASOLEV) =====
async function activateUser(userId, action) {
    const button = event.target.closest('button');
    const originalContent = button.innerHTML;
    
    // Loading state
    button.disabled = true;
    button.classList.add('loading');
    
    try {
        const formData = new FormData();
        formData.append('activate_user', '1');
        formData.append('user_id', userId);
        formData.append('action', action);
        
        const response = await fetch(window.location.href, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            // Eemalda kasutaja nimekirjast
            const userItem = document.getElementById(`pending-user-${userId}`);
            if (userItem) {
                userItem.style.transition = 'all 0.3s ease';
                userItem.style.opacity = '0';
                userItem.style.transform = 'translateX(100%)';
                
                setTimeout(() => {
                    userItem.remove();
                    
                    // Kui rohkem kasutajaid ei ole, peidame kogu widget'i
                    const remainingUsers = document.querySelectorAll('.pending-user-item');
                    if (remainingUsers.length === 0) {
                        const widget = document.querySelector('.pending-users-card');
                        if (widget) {
                            widget.style.transition = 'all 0.3s ease';
                            widget.style.opacity = '0';
                            setTimeout(() => widget.remove(), 300);
                        }
                    } else {
                        // Uuenda badge'i
                        const badge = document.querySelector('.pending-badge');
                        if (badge) {
                            badge.textContent = remainingUsers.length;
                        }
                    }
                }, 300);
            }
            
            // Näita õnnestumisteadet
            showNotification(result.message, 'success');
            
        } else {
            throw new Error(result.message);
        }
        
    } catch (error) {
        console.error('Activation error:', error);
        showNotification('Viga: ' + error.message, 'error');
        
        // Taasta nupp
        button.disabled = false;
        button.classList.remove('loading');
        button.innerHTML = originalContent;
    }
}

// ===== NOTIFICATION SYSTEM (OLEMASOLEV + PARANDATUD) =====
function showNotification(message, type = 'info') {
    // Eemalda olemasolevad teatised
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notif => notif.remove());
    
    // Loo notification element
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="icon-${type === 'success' ? 'check-circle' : 'alert-circle'}"></i>
        <span>${message}</span>
        <button onclick="this.parentElement.remove()" style="background: none; border: none; color: inherit; margin-left: auto; cursor: pointer; font-size: 1.2em;">&times;</button>
    `;
    
    // Lisa lehele
    document.body.appendChild(notification);
    
    // Näita animatsiooniga
    setTimeout(() => {
        notification.classList.add('show');
    }, 100);
    
    // Eemalda pärast 4 sekundit
    setTimeout(() => {
        if (notification.parentElement) {
            notification.classList.remove('show');
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 300);
        }
    }, 4000);
    
    console.log(`📢 Notification shown: ${type} - ${message}`);
}

// ===== ENHANCED CARD INTERACTIONS (UUS) =====
function initCardInteractions() {
    // Stat cards hover effect enhancement
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-4px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
    
    // Action items enhanced interaction
    const actionItems = document.querySelectorAll('.action-item');
    actionItems.forEach(item => {
        item.addEventListener('click', function(e) {
            // Ripple effect
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                background: rgba(59, 130, 246, 0.3);
                border-radius: 50%;
                transform: scale(0);
                animation: ripple 0.6s ease-out;
                pointer-events: none;
                z-index: 1;
            `;
            
            this.style.position = 'relative';
            this.appendChild(ripple);
            
            setTimeout(() => ripple.remove(), 600);
        });
    });
    
    console.log('✨ Enhanced card interactions initialized');
}

// ===== SMOOTH SCROLL ENHANCEMENT (UUS) =====
function initSmoothScrolling() {
    // Smooth scroll for internal links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
    
    console.log('🎯 Smooth scrolling initialized');
}

// ===== LOADING STATES ENHANCEMENT (UUS) =====
function initLoadingStates() {
    // Enhanced loading for all buttons
    document.querySelectorAll('button[type="submit"], .btn').forEach(button => {
        if (button.form) {
            button.form.addEventListener('submit', function() {
                if (!button.disabled) {
                    const originalText = button.innerHTML;
                    button.innerHTML = '<i class="icon-loader"></i> Laadimas...';
                    button.disabled = true;
                    
                    // Reset after 10 seconds (failsafe)
                    setTimeout(() => {
                        button.innerHTML = originalText;
                        button.disabled = false;
                    }, 10000);
                }
            });
        }
    });
    
    console.log('⏳ Loading states enhanced');
}

// ===== ACCESSIBILITY ENHANCEMENTS (UUS) =====
function initAccessibility() {
    // Keyboard navigation for cards
    document.querySelectorAll('.stat-card, .action-item, .result-item').forEach(element => {
        if (!element.getAttribute('tabindex')) {
            element.setAttribute('tabindex', '0');
        }
        
        element.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                if (element.tagName === 'A' || element.onclick) {
                    e.preventDefault();
                    element.click();
                }
            }
        });
    });
    
    // Focus management for modals and expanded content
    document.addEventListener('focusin', function(e) {
        const focusedElement = e.target;
        if (focusedElement.closest('.expanded')) {
            // Ensure expanded content is visible
            focusedElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    });
    
    console.log('♿ Accessibility enhancements initialized');
}

// ===== MAIN INITIALIZATION (TÄIENDATUD) =====
document.addEventListener('DOMContentLoaded', function() {
    console.log('🎬 Admin Dashboard JavaScript initializing...');
    
    try {
        // Initialize all features
        initMobileCompact();
        initCardInteractions();
        initSmoothScrolling();
        initLoadingStates();
        initAccessibility();
        
        // Add ripple animation CSS if not exists
        if (!document.getElementById('ripple-animation-styles')) {
            const style = document.createElement('style');
            style.id = 'ripple-animation-styles';
            style.textContent = `
                @keyframes ripple {
                    to {
                        transform: scale(2);
                        opacity: 0;
                    }
                }
                
                .loading {
                    position: relative;
                    color: transparent !important;
                }
                
                .loading::after {
                    content: '';
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    width: 16px;
                    height: 16px;
                    border: 2px solid currentColor;
                    border-radius: 50%;
                    border-top-color: transparent;
                    animation: spin 0.8s linear infinite;
                }
                
                @keyframes spin {
                    to { transform: translate(-50%, -50%) rotate(360deg); }
                }
            `;
            document.head.appendChild(style);
        }
        
        console.log('✅ Admin Dashboard JavaScript fully loaded!');
        
    } catch (error) {
        console.error('❌ Dashboard initialization error:', error);
        showNotification('Süsteemi viga laadimisel', 'error');
    }
});

// ===== GLOBAL ERROR HANDLING (UUS) =====
window.addEventListener('error', function(e) {
    console.error('Global error:', e.error);
    // Don't show notification for every error, just log them
});

// ===== UTILITY FUNCTIONS (UUS) =====
const DashboardUtils = {
    // Format numbers with Estonian locale
    formatNumber: (num, decimals = 0) => {
        return new Intl.NumberFormat('et-EE', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals
        }).format(num);
    },
    
    // Format dates with Estonian locale
    formatDate: (dateString) => {
        return new Intl.DateTimeFormat('et-EE').format(new Date(dateString));
    },
    
    // Debounce function for performance
    debounce: (func, wait) => {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // Check if element is in viewport
    isInViewport: (element) => {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }
};

// Make functions globally available
window.activateUser = activateUser;
window.showNotification = showNotification;
window.DashboardUtils = DashboardUtils;

console.log('🔧 Admin Dashboard JavaScript module loaded');
</script>

<?php 
// Abifunktsioonid
function getActionDescription($action) {
    $actions = [
        'login' => 'logis sisse',
        'logout' => 'logis välja',
        'register' => 'registreerus',
        'competition_created' => 'lõi võistluse',
        'result_added' => 'lisas tulemuse',
        'user_created' => 'lõi kasutaja',
        'profile_updated' => 'uuendas profiili',
        'password_changed' => 'muutis parooli',
        'training_added' => 'lisas treeningu kirje'
    ];
    return $actions[$action] ?? 'tegi midagi';
}

function formatTimeAgo($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 60) return 'just nüüd';
    if ($time < 3600) return floor($time/60) . ' min tagasi';
    if ($time < 86400) return floor($time/3600) . ' tundi tagasi';
    if ($time < 2592000) return floor($time/86400) . ' päeva tagasi';
    return formatDate($datetime);
}

include '../includes/footer.php'; 
?>