<!DOCTYPE html>
<html lang="et">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($page_title) ? $page_title . ' - ' : ''; ?>Estreka Ratsaklubi</title>
    <meta name="description" content="<?php echo isset($page_description) ? $page_description : 'Estreka Ratsaklubi punktiarvestuse süsteem. Jälgi oma tulemusi, vaata hooaja seisu ja arenda end ratsaspordis.'; ?>">
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="<?php echo url('assets/favicon.ico'); ?>">
    
    <!-- CSS -->
    <link rel="stylesheet" href="<?php echo url('assets/css/style.css'); ?>">
    
    <!-- Page-specific CSS -->
    <?php if (isset($page_css)): ?>
        <link rel="stylesheet" href="<?php echo url('assets/css/' . $page_css); ?>">
    <?php endif; ?>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <!-- Icons -->
    <link rel="stylesheet" href="<?php echo url('assets/css/icons.css'); ?>">
    
    <?php if (isset($extra_head_content)) echo $extra_head_content; ?>
</head>
<body class="<?php echo isset($body_class) ? $body_class : ''; ?><?php echo isLoggedIn() ? ' logged-in' : ''; ?>">
    
    <!-- TÄIUSTATUD PERSONAALNE NAVIGATSIOON -->
    <header class="header">
        <nav class="navbar">
            <div class="container">
                <div class="navbar-content">
                    <!-- Logo -->
                    <div class="navbar-brand">
                        <a href="<?php echo url(); ?>" class="brand-link" title="Tagasi avalehele">
                            <i class="icon-trophy brand-icon"></i>
                            <span class="brand-text">Estreka</span>
                        </a>
                    </div>

                    <!-- KASUTAJA MENÜÜ -->
                    <div class="navbar-user">
                        <?php if (isLoggedIn()): ?>
                            <div class="user-menu">
                                <button class="user-menu-toggle" onclick="toggleUserMenu(event)">
                                    <div class="user-avatar">
                                        <i class="icon-user"></i>
                                    </div>
                                    <div class="user-info">
                                        <span class="user-name"><?php echo htmlspecialchars($_SESSION['user_name']); ?></span>
                                        <span class="user-role"><?php echo isAdmin() ? 'Administraator' : 'Sportlane'; ?></span>
                                    </div>
                                    <i class="icon-chevron-down dropdown-arrow"></i>
                                </button>
                                
                                <div class="user-menu-dropdown" id="userMenuDropdown">
                                    <div class="dropdown-header">
                                        <div class="user-avatar large">
                                            <i class="icon-user"></i>
                                        </div>
                                        <div class="user-details">
                                            <div class="user-name"><?php echo htmlspecialchars($_SESSION['user_name']); ?></div>
                                            <div class="user-role"><?php echo isAdmin() ? 'Administraator' : 'Sportlane'; ?></div>
                                        </div>
                                    </div>
                                    
                                    <div class="dropdown-divider"></div>
                                    
                                    <!-- PERSONAALSED KIIRED TOIMINGUD -->
                                    <?php if (isAthlete()): ?>
                                        <a href="<?php echo url('athlete/dashboard.php'); ?>" class="dropdown-item">
                                            <i class="icon-user"></i>
                                            <span>Minu töölaud</span>
                                        </a>
                                        
                                        <!-- 🌟 MOTIVATSIOONI LINK -->
                                        <a href="<?php echo url('athlete/motivation.php'); ?>" class="dropdown-item motivation-link">
                                            <i class="icon-star"></i>
                                            <span>🌟 Minu edusammud</span>
                                            <?php 
                                            // Näita badge'i kui on uusi saavutusi
                                            try {
                                                // Kiire kontroll kas on uusi saavutusi
                                                $stmt = $pdo->prepare("
                                                    SELECT COUNT(*) as new_count 
                                                    FROM user_achievements 
                                                    WHERE userId = ? AND unlocked_at >= datetime('now', '-24 hours')
                                                ");
                                                $stmt->execute([$_SESSION['user_id']]);
                                                $new_achievements = $stmt->fetch()['new_count'];
                                                
                                                if ($new_achievements > 0): ?>
                                                    <span class="notification-badge"><?php echo $new_achievements; ?></span>
                                                <?php endif;
                                            } catch (Exception $e) {
                                                // Ignore errors in header
                                            }
                                            ?>
                                        </a>
                                        
                                        <!-- 📅 KALENDRI LINK -->
                                        <a href="<?php echo url('calendar.php'); ?>" class="dropdown-item calendar-link">
                                            <i class="icon-calendar"></i>
                                            <span>📅 Minu kalender</span>
                                            <?php 
                                            // Näita tänaseid sündmusi kui on
                                            try {
                                                $stmt = $pdo->prepare("
                                                    SELECT COUNT(*) as today_count 
                                                    FROM events 
                                                    WHERE user_id = ? AND DATE(start_datetime) = DATE('now')
                                                ");
                                                $stmt->execute([$_SESSION['user_id']]);
                                                $today_events = $stmt->fetch()['today_count'] ?? 0;
                                                
                                                if ($today_events > 0): ?>
                                                    <span class="notification-badge today-events"><?php echo $today_events; ?></span>
                                                <?php endif;
                                            } catch (Exception $e) {
                                                // Ignore errors in header - tabelit ei pruugi veel olla
                                            }
                                            ?>
                                        </a>
                                        
                                        <a href="<?php echo url('athlete/results.php'); ?>" class="dropdown-item">
                                            <i class="icon-plus"></i>
                                            <span>Lisa tulemus</span>
                                        </a>
                                        <a href="<?php echo url('athlete/results.php'); ?>" class="dropdown-item">
                                            <i class="icon-trophy"></i>
                                            <span>Minu tulemused</span>
                                        </a>
                                        <a href="<?php echo url('athlete/training.php'); ?>" class="dropdown-item">
                                            <i class="icon-calendar"></i>
                                            <span>Treening</span>
                                        </a>
                                        <a href="<?php echo url('athlete/horses.php'); ?>" class="dropdown-item">
                                            <i class="icon-star"></i>
                                            <span>Minu hobused</span>
                                        </a>
                                        <a href="<?php echo url('athlete/stats.php'); ?>" class="dropdown-item">
                                            <i class="icon-bar-chart"></i>
                                            <span>Minu statistika</span>
                                        </a>
                                        
                                    <?php elseif (isAdmin()): ?>
                                        <a href="<?php echo url('admin/dashboard.php'); ?>" class="dropdown-item">
                                            <i class="icon-grid"></i>
                                            <span>Admin ülevaade</span>
                                        </a>
                                        
                                        <!-- 📊 UUENDATUD STATISTIKA SEKTSIOON -->
                                        <div class="dropdown-divider"></div>
                                        <div class="dropdown-section-title">Statistika ja analüüs</div>
                                        
                                        <a href="<?php echo url('admin/advanced-stats.php'); ?>" class="dropdown-item featured-link">
                                            <i class="icon-bar-chart-2"></i>
                                            <span>🔬 Täiustatud statistika</span>
                                            <span class="feature-badge">UUUS</span>
                                        </a>
                                        <a href="<?php echo url('public/stats.php'); ?>" class="dropdown-item">
                                            <i class="icon-bar-chart"></i>
                                            <span>Avalik statistika</span>
                                        </a>
                                        
                                        <!-- PÕHILISED ADMIN FUNKTSIOONID -->
                                        <div class="dropdown-divider"></div>
                                        <div class="dropdown-section-title">Põhihaldus</div>
                                        
                                        <a href="<?php echo url('admin/competitions.php'); ?>" class="dropdown-item">
                                            <i class="icon-calendar"></i>
                                            <span>Võistlused</span>
                                        </a>
                                        <a href="<?php echo url('admin/results.php'); ?>" class="dropdown-item">
                                            <i class="icon-trophy"></i>
                                            <span>Tulemused</span>
                                        </a>
                                        <a href="<?php echo url('admin/users.php'); ?>" class="dropdown-item">
                                            <i class="icon-users"></i>
                                            <span>Kasutajad</span>
                                        </a>
                                        
                                        <!-- 📅 KALENDRI LINK ADMINILE -->
                                        <a href="<?php echo url('calendar.php'); ?>" class="dropdown-item calendar-link admin-feature">
                                            <i class="icon-calendar"></i>
                                            <span>📅 Kalender</span>
                                        </a>
                                        
                                        <!-- 🆕 SÜSTEEMI HALDUS -->
                                        <div class="dropdown-divider"></div>
                                        <div class="dropdown-section-title">Süsteemi haldus</div>
                                        
                                        <a href="<?php echo url('admin/settings.php'); ?>" class="dropdown-item admin-feature">
                                            <i class="icon-settings"></i>
                                            <span>Süsteemi seaded</span>
                                        </a>
                                        <a href="<?php echo url('admin/auto-logout-settings.php'); ?>" class="dropdown-item admin-feature">
                                            <i class="icon-shield"></i>
                                            <span>Auto-logout seaded</span>
                                        </a>
                                        <a href="<?php echo url('admin/backup-system.php'); ?>" class="dropdown-item admin-feature">
                                            <i class="icon-database"></i>
                                            <span>Backup ja turvalisus</span>
                                        </a>
                                        
                                    <?php else: ?>
                                        <!-- KÜLASTAJA LINGID -->
                                        <a href="<?php echo url(); ?>" class="dropdown-item">
                                            <i class="icon-home"></i>
                                            <span>Avaleht</span>
                                        </a>
                                        <a href="<?php echo url('public/results.php'); ?>" class="dropdown-item">
                                            <i class="icon-award"></i>
                                            <span>Tulemused</span>
                                        </a>
                                        <a href="<?php echo url('public/stats.php'); ?>" class="dropdown-item">
                                            <i class="icon-bar-chart"></i>
                                            <span>Statistika</span>
                                        </a>
                                    <?php endif; ?>
                                    
                                    <div class="dropdown-divider"></div>
                                    
                                    <!-- ÜLDISED LINGID KÕIGILE -->
                                    <a href="<?php echo url('public/rankings.php'); ?>" class="dropdown-item">
                                        <i class="icon-list"></i>
                                        <span>Hooaja tabelid</span>
                                    </a>
                                    
                                    <!-- PROFIIL -->
                                    <a href="<?php echo url('profile.php'); ?>" class="dropdown-item">
                                        <i class="icon-edit"></i>
                                        <span>Profiili seaded</span>
                                    </a>
                                    
                                    <?php if (isAdmin()): ?>
                                        <div class="dropdown-divider"></div>
                                        <a href="<?php echo url('index.php'); ?>" class="dropdown-item">
                                            <i class="icon-eye"></i>
                                            <span>Vaata avalikku vaadet</span>
                                        </a>
                                    <?php endif; ?>
                                    
                                    <div class="dropdown-divider"></div>
                                    
                                    <!-- VÄLJALOGIMINE -->
                                    <a href="<?php echo url('logout.php'); ?>" class="dropdown-item logout-item" 
                                       onclick="return confirm('Kas oled kindel, et tahad välja logida?')">
                                        <i class="icon-log-out"></i>
                                        <span>Logi välja</span>
                                    </a>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="auth-buttons">
                                <a href="<?php echo url('login.php'); ?>" class="btn btn-outline">
                                    <i class="icon-log-in"></i>
                                    <span>Sisene</span>
                                </a>
                                <a href="<?php echo url('register.php'); ?>" class="btn btn-primary">
                                    <i class="icon-user-plus"></i>
                                    <span>Registreeru</span>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </nav>
    </header>

    <!-- Teadete konteiner -->
    <div id="notifications" class="notifications-container">
        <?php
        // Kuva flash sõnumeid
        if (isset($_SESSION['flash_message'])) {
            $type = $_SESSION['flash_type'] ?? 'info';
            $icon = $_SESSION['flash_icon'] ?? 'icon-info';
            $timeout = $_SESSION['flash_timeout'] ?? 5000;
            
            echo '<div class="alert alert-' . $type . ' alert-dismissible" data-timeout="' . $timeout . '">';
            echo '<i class="' . $icon . '"></i>';
            echo '<div class="alert-content">';
            echo '<span>' . htmlspecialchars($_SESSION['flash_message']) . '</span>';
            
            // Lisa täiendav info kui saadaval
            if (isset($_SESSION['flash_details'])) {
                $details = $_SESSION['flash_details'];
                if (isset($details['logout_time'])) {
                    echo '<div class="alert-meta">Aeg: ' . $details['logout_time'];
                    if (isset($details['session_duration'])) {
                        echo ' (sessioon kestis ' . $details['session_duration'] . ')';
                    }
                    echo '</div>';
                }
            }
            
            echo '</div>';
            echo '<button class="alert-close" onclick="this.parentElement.remove()">&times;</button>';
            echo '</div>';
            
            unset($_SESSION['flash_message'], $_SESSION['flash_type'], $_SESSION['flash_icon'], $_SESSION['flash_timeout'], $_SESSION['flash_details']);
        }
        ?>
    </div>

    <!-- Põhisisu wrapper -->
    <div class="page-wrapper">

<style>
/* ===== TÄIUSTATUD PERSONAALNE HEADER - TÄIELIK CSS ===== */

.header {
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    position: sticky;
    top: 0;
    z-index: 1000;
    box-shadow: var(--shadow-lg);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.navbar {
    padding: var(--spacing-3) 0;
}

.navbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: var(--spacing-6);
}

/* ===== LOGO ===== */
.navbar-brand {
    flex-shrink: 0;
}

.brand-link {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    text-decoration: none;
    color: white;
    padding: var(--spacing-2) var(--spacing-3);
    border-radius: var(--radius-lg);
    transition: all var(--transition-fast);
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.brand-link:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-1px);
    box-shadow: var(--shadow);
}

.brand-icon {
    font-size: var(--font-size-2xl);
    color: var(--primary-light);
}

.brand-text {
    font-size: var(--font-size-xl);
    font-weight: 700;
    color: white;
}

/* ===== KASUTAJA MENÜÜ ===== */
.navbar-user {
    flex-shrink: 0;
}

.user-menu {
    position: relative;
}

.user-menu-toggle {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    padding: var(--spacing-3) var(--spacing-4);
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: var(--radius-lg);
    color: white;
    cursor: pointer;
    transition: all var(--transition-fast);
    min-width: 180px;
}

.user-menu-toggle:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.3);
    transform: translateY(-1px);
    box-shadow: var(--shadow);
}

.user-avatar {
    width: 32px;
    height: 32px;
    background: transparent;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: var(--font-size-lg);
    flex-shrink: 0;
}

.user-avatar.large {
    width: 40px;
    height: 40px;
    font-size: var(--font-size-xl);
    border: 2px solid var(--gray-300);
    background: transparent;
    color: var(--gray-600);
}

.user-info {
    flex: 1;
    text-align: left;
}

.user-name {
    font-weight: 600;
    font-size: var(--font-size-sm);
    line-height: 1.2;
    display: block;
}

.user-role {
    font-size: var(--font-size-xs);
    opacity: 0.8;
    line-height: 1;
    display: block;
    margin-top: 2px;
}

.dropdown-arrow {
    font-size: var(--font-size-sm);
    transition: transform var(--transition-fast);
}

.user-menu-toggle:hover .dropdown-arrow {
    transform: rotate(180deg);
}

/* ===== DROPDOWN MENÜÜ ===== */
.user-menu-dropdown {
    position: absolute;
    top: calc(100% + var(--spacing-2));
    right: 0;
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-xl);
    min-width: 320px;
    max-width: 380px;
    padding: var(--spacing-4);
    transform: translateY(-10px);
    opacity: 0;
    visibility: hidden;
    transition: all var(--transition-fast);
    z-index: 2000;
    max-height: 80vh;
    overflow-y: auto;
}

.user-menu-dropdown.show {
    opacity: 1;
    visibility: visible;
    transform: translateY(0);
}

.dropdown-header {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
    margin-bottom: var(--spacing-3);
}

.dropdown-header .user-avatar {
    background: transparent;
    border: 2px solid var(--gray-300);
    color: var(--gray-600);
}

.dropdown-header .user-name {
    font-weight: 600;
    color: var(--gray-900);
    font-size: var(--font-size-base);
}

.dropdown-header .user-role {
    color: var(--gray-600);
    font-size: var(--font-size-sm);
}

/* 🆕 DROPDOWN SECTION TITLE */
.dropdown-section-title {
    font-size: var(--font-size-xs);
    font-weight: 600;
    color: var(--gray-500);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    padding: var(--spacing-2) var(--spacing-3);
    margin: var(--spacing-2) 0 var(--spacing-1);
    border-left: 3px solid var(--primary-color);
    background: color-mix(in srgb, var(--primary-color) 3%, transparent);
}

.dropdown-item {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    padding: var(--spacing-3);
    color: var(--gray-700);
    text-decoration: none;
    border-radius: var(--radius);
    transition: all var(--transition-fast);
    font-size: var(--font-size-sm);
    margin-bottom: var(--spacing-1);
    position: relative;
}

.dropdown-item:hover {
    background: var(--gray-50);
    color: var(--primary-color);
    transform: translateX(4px);
}

.dropdown-item i {
    width: 16px;
    text-align: center;
    color: var(--gray-500);
    flex-shrink: 0;
}

.dropdown-item:hover i {
    color: var(--primary-color);
}

/* 🌟 MOTIVATSIOONI LINGI ERIKUJUNDUS */
.dropdown-item.motivation-link {
    background: linear-gradient(135deg, color-mix(in srgb, var(--primary-color) 10%, transparent), color-mix(in srgb, var(--success-color) 5%, transparent));
    border: 1px solid color-mix(in srgb, var(--primary-color) 20%, transparent);
    margin: var(--spacing-1) 0;
    border-radius: var(--radius);
    position: relative;
}

.dropdown-item.motivation-link:hover {
    background: linear-gradient(135deg, color-mix(in srgb, var(--primary-color) 15%, transparent), color-mix(in srgb, var(--success-color) 10%, transparent));
    border-color: color-mix(in srgb, var(--primary-color) 30%, transparent);
    transform: translateX(6px);
}

.dropdown-item.motivation-link i {
    color: var(--primary-color);
}

/* 📅 KALENDRI LINGI ERIKUJUNDUS */
.dropdown-item.calendar-link {
    background: linear-gradient(135deg, 
        color-mix(in srgb, #3B82F6 8%, transparent), 
        color-mix(in srgb, #06B6D4 5%, transparent));
    border: 1px solid color-mix(in srgb, #3B82F6 20%, transparent);
    margin: var(--spacing-1) 0;
    border-radius: var(--radius);
    position: relative;
}

.dropdown-item.calendar-link:hover {
    background: linear-gradient(135deg, 
        color-mix(in srgb, #3B82F6 12%, transparent), 
        color-mix(in srgb, #06B6D4 8%, transparent));
    border-color: color-mix(in srgb, #3B82F6 30%, transparent);
    transform: translateX(6px);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15);
}

.dropdown-item.calendar-link i {
    color: #3B82F6;
}

/* Tänaste sündmuste badge */
.notification-badge.today-events {
    background: #06B6D4;
    color: white;
    animation: pulse 2s infinite;
}

/* 📊 FEATURED LINK (täiustatud statistika) */
.dropdown-item.featured-link {
    background: linear-gradient(135deg, 
        color-mix(in srgb, var(--primary-color) 8%, transparent), 
        color-mix(in srgb, #8b5cf6 5%, transparent));
    border: 1px solid color-mix(in srgb, var(--primary-color) 25%, transparent);
    margin: var(--spacing-1) 0;
    border-radius: var(--radius);
    position: relative;
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.dropdown-item.featured-link:hover {
    background: linear-gradient(135deg, 
        color-mix(in srgb, var(--primary-color) 12%, transparent), 
        color-mix(in srgb, #8b5cf6 8%, transparent));
    border-color: color-mix(in srgb, var(--primary-color) 35%, transparent);
    transform: translateX(8px) translateY(-1px);
    box-shadow: 0 4px 16px rgba(59, 130, 246, 0.15);
}

.dropdown-item.featured-link i {
    color: var(--primary-color);
    font-size: 16px;
}

/* Feature Badge */
.feature-badge {
    position: absolute;
    top: -6px;
    right: var(--spacing-2);
    background: linear-gradient(135deg, var(--success-color), #10b981);
    color: white;
    font-size: 10px;
    font-weight: 700;
    padding: 2px 6px;
    border-radius: var(--radius-full);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    animation: glow 2s infinite alternate;
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

@keyframes glow {
    0% { 
        box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
        transform: scale(1);
    }
    100% { 
        box-shadow: 0 4px 16px rgba(16, 185, 129, 0.5);
        transform: scale(1.05);
    }
}

.notification-badge {
    position: absolute;
    top: -2px;
    right: var(--spacing-2);
    background: var(--danger-color);
    color: white;
    font-size: var(--font-size-xs);
    font-weight: 600;
    padding: 2px 6px;
    border-radius: var(--radius-full);
    min-width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: pulse 2s infinite;
}

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

/* 🆕 ADMIN FEATURE STIILID */
.dropdown-item.admin-feature {
    background: color-mix(in srgb, var(--primary-color) 5%, transparent);
    border: 1px solid color-mix(in srgb, var(--primary-color) 15%, transparent);
    margin-bottom: var(--spacing-2);
}

.dropdown-item.admin-feature:hover {
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    border-color: color-mix(in srgb, var(--primary-color) 25%, transparent);
    transform: translateX(6px);
}

.dropdown-item.admin-feature i {
    color: var(--primary-color);
}

.logout-item {
    color: var(--danger-color) !important;
    margin-top: var(--spacing-2);
}

.logout-item:hover {
    background: color-mix(in srgb, var(--danger-color) 10%, transparent);
    color: var(--danger-color) !important;
}

.logout-item i {
    color: var(--danger-color) !important;
}

.dropdown-divider {
    height: 1px;
    background: var(--gray-200);
    margin: var(--spacing-3) 0;
}

/* ===== AUTH NUPUD (külastajatele) ===== */
.auth-buttons {
    display: flex;
    gap: var(--spacing-3);
    align-items: center;
}

.btn-outline {
    background: transparent;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
}

.btn-outline:hover {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.5);
}

/* ===== TEADETE SÜSTEEM ===== */
.notifications-container {
    position: fixed;
    top: 70px;
    right: var(--spacing-4);
    z-index: 2000;
    max-width: 400px;
}

.alert-dismissible {
    position: relative;
    padding: var(--spacing-4);
    padding-right: var(--spacing-10);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-lg);
    margin-bottom: var(--spacing-3);
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-3);
    animation: slideInRight 0.3s ease-out;
}

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

.alert-content {
    flex: 1;
}

.alert-meta {
    font-size: var(--font-size-xs);
    opacity: 0.8;
    margin-top: var(--spacing-1);
}

.alert-close {
    position: absolute;
    top: var(--spacing-2);
    right: var(--spacing-2);
    background: none;
    border: none;
    font-size: var(--font-size-lg);
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
    transition: opacity var(--transition-fast);
    width: 24px;
    height: 24px;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
}

.alert-close:hover {
    opacity: 1;
    background: rgba(0, 0, 0, 0.1);
}

/* Alert tüübid */
.alert-success {
    background: color-mix(in srgb, var(--success-color) 10%, white);
    color: var(--success-color);
    border: 1px solid color-mix(in srgb, var(--success-color) 20%, transparent);
}

.alert-warning {
    background: color-mix(in srgb, #f59e0b 10%, white);
    color: #92400e;
    border: 1px solid color-mix(in srgb, #f59e0b 20%, transparent);
}

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

.alert-info {
    background: color-mix(in srgb, var(--primary-color) 10%, white);
    color: var(--primary-color);
    border: 1px solid color-mix(in srgb, var(--primary-color) 20%, transparent);
}

/* ===== RESPONSIVE ===== */
@media (max-width: 1024px) {
    .user-menu-toggle {
        min-width: auto;
        padding: var(--spacing-2) var(--spacing-3);
    }
    
    .user-info {
        display: none;
    }
    
    .user-menu-dropdown {
        min-width: 280px;
        max-width: 320px;
    }
}

@media (max-width: 768px) {
    .brand-text {
        font-size: var(--font-size-lg);
    }
    
    .user-menu-toggle {
        padding: var(--spacing-2);
    }
    
    /* Mobiili dropdown */
    .user-menu-dropdown {
        position: fixed !important;
        top: 70px !important;
        left: var(--spacing-3) !important;
        right: var(--spacing-3) !important;
        width: auto !important;
        min-width: auto !important;
        max-width: none !important;
        border-radius: var(--radius-lg) !important;
        box-shadow: var(--shadow-xl) !important;
        z-index: 2000 !important;
        transform: translateY(0) !important;
        max-height: calc(100vh - 100px);
        overflow-y: auto;
    }
    
    .user-menu-dropdown.show {
        transform: translateY(0) !important;
    }
    
    .user-menu-toggle .user-info {
        display: none;
    }
    
    .user-menu-toggle {
        min-width: auto;
        padding: var(--spacing-2) var(--spacing-3);
    }
    
    .notifications-container {
        left: var(--spacing-3);
        right: var(--spacing-3);
        max-width: none;
    }
    
    /* Dropdown items mobiilis */
    .dropdown-item {
        padding: var(--spacing-4) var(--spacing-3);
        font-size: var(--font-size-base);
    }
    
    .dropdown-section-title {
        padding: var(--spacing-3);
        font-size: var(--font-size-sm);
    }
}

/* ===== SÕLTUVAD STIILID ===== */
.page-wrapper {
    min-height: calc(100vh - 70px);
    padding-top: 0;
}

body.menu-open {
    overflow: hidden;
}

/* ===== HOVER EFFECTS ===== */
.brand-link:hover .brand-icon {
    animation: bounce 0.6s ease-in-out;
}

@keyframes bounce {
    0%, 20%, 60%, 100% {
        transform: translateY(0);
    }
    40% {
        transform: translateY(-4px);
    }
    80% {
        transform: translateY(-2px);
    }
}

/* ===== FOCUS STATES ===== */
.user-menu-toggle:focus {
    outline: 2px solid rgba(255, 255, 255, 0.7);
    outline-offset: 2px;
}

.brand-link:focus {
    outline: 2px solid rgba(255, 255, 255, 0.7);
    outline-offset: 2px;
}

/* ===== SPECIAL LINK ANIMATIONS ===== */
.dropdown-item.featured-link::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
    transform: translateX(-100%);
    transition: transform 0.6s ease;
    pointer-events: none;
}

.dropdown-item.featured-link:hover::before {
    transform: translateX(100%);
}

/* Kalendri lingi samalaadne animatsioon */
.dropdown-item.calendar-link::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, transparent, rgba(59, 130, 246, 0.1), transparent);
    transform: translateX(-100%);
    transition: transform 0.6s ease;
    pointer-events: none;
}

.dropdown-item.calendar-link:hover::before {
    transform: translateX(100%);
}

/* ===== ACCESSIBILITY IMPROVEMENTS ===== */
@media (prefers-reduced-motion: reduce) {
    .dropdown-item,
    .user-menu-toggle,
    .brand-link,
    .feature-badge,
    .notification-badge {
        animation: none !important;
        transition: none !important;
    }
    
    .dropdown-item:hover {
        transform: none !important;
    }
}

/* ===== PRINT STYLES ===== */
@media print {
    .header,
    .notifications-container {
        display: none !important;
    }
    
    .page-wrapper {
        padding-top: 0 !important;
    }
}
</style>

<script>
// ===== TÄIUSTATUD PERSONAALNE NAVIGATSIOON JAVASCRIPT =====

// Kasutaja menüü olekut DEBUG
function debugUserMenu() {
    const dropdown = document.getElementById('userMenuDropdown');
    const toggle = document.querySelector('.user-menu-toggle');
    
    console.log('🔍 DEBUG: User menu elements:', {
        dropdown: !!dropdown,
        toggle: !!toggle,
        dropdownVisible: dropdown?.classList.contains('show'),
        hasResults: <?php echo (isLoggedIn() && isAthlete()) ? 'true' : 'false'; ?>,
        pageType: '<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>',
        isAdmin: <?php echo isAdmin() ? 'true' : 'false'; ?>,
        hasAdvancedStats: !!document.querySelector('a[href*="advanced-stats.php"]'),
        hasCalendar: !!document.querySelector('a[href*="calendar.php"]')
    });
}

// Kasutaja menüü toggle
function toggleUserMenu(event) {
    if (event) {
        event.stopPropagation();
        event.preventDefault();
    }
    
    console.log('👤 User menu toggle clicked');
    
    const dropdown = document.getElementById('userMenuDropdown');
    const arrow = document.querySelector('.dropdown-arrow');
    
    if (!dropdown) {
        console.error('❌ User menu dropdown not found!');
        return;
    }
    
    const isCurrentlyVisible = dropdown.classList.contains('show');
    console.log('Current state:', isCurrentlyVisible ? 'visible' : 'hidden');
    
    // Sulge KÕIK dropdown menüüd esmalt
    document.querySelectorAll('.user-menu-dropdown').forEach(menu => {
        menu.classList.remove('show');
    });
    
    // Reset kõik arrow'ed
    document.querySelectorAll('.dropdown-arrow').forEach(arr => {
        arr.style.transform = 'rotate(0deg)';
    });
    
    // Kui menüü EI OLNUD avatud, ava see
    if (!isCurrentlyVisible) {
        dropdown.classList.add('show');
        if (arrow) arrow.style.transform = 'rotate(180deg)';
        console.log('✅ User menu OPENED');
        
        // Lisa outside click listener
        setTimeout(() => {
            function handleOutsideClick(e) {
                const userMenu = e.target.closest('.user-menu');
                if (!userMenu && dropdown.classList.contains('show')) {
                    dropdown.classList.remove('show');
                    if (arrow) arrow.style.transform = 'rotate(0deg)';
                    document.removeEventListener('click', handleOutsideClick);
                    console.log('🔒 Menu closed by outside click');
                }
            }
            document.addEventListener('click', handleOutsideClick);
        }, 50);
    } else {
        console.log('✅ User menu CLOSED (was already open)');
    }
}

// ESC vajutus
function handleEscapeKey(event) {
    if (event.key === 'Escape') {
        const dropdown = document.getElementById('userMenuDropdown');
        const arrow = document.querySelector('.dropdown-arrow');
        if (dropdown && dropdown.classList.contains('show')) {
            dropdown.classList.remove('show');
            if (arrow) arrow.style.transform = 'rotate(0deg)';
            console.log('🔒 Menu closed by ESC');
        }
    }
}

// Aktiivse lingi märkimine
function setActiveNavLink() {
    const currentPath = window.location.pathname;
    const navLinks = document.querySelectorAll('.dropdown-item');
    
    navLinks.forEach(link => {
        const href = link.getAttribute('href');
        if (href && currentPath.includes(href.replace(/^.*\//, ''))) {
            link.style.background = 'color-mix(in srgb, var(--primary-color) 15%, transparent)';
            link.style.borderLeft = '3px solid var(--primary-color)';
            console.log('🎯 Active link found:', href);
        }
    });
}

// Logo click handling
function handleLogoClick() {
    const brandLinks = document.querySelectorAll('.brand-link');
    brandLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            console.log('🏠 Navigating home via logo');
        });
    });
}

// Notification auto-hide
function autoHideNotifications() {
    const notifications = document.querySelectorAll('.alert-dismissible');
    notifications.forEach(notification => {
        const timeout = parseInt(notification.dataset.timeout) || 5000;
        
        setTimeout(() => {
            if (notification.parentElement) {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }
        }, timeout);
    });
}

// Keyboard navigation
function handleKeyboardNavigation() {
    document.addEventListener('keydown', function(e) {
        if (e.altKey && e.key === 'u') {
            e.preventDefault();
            toggleUserMenu(e);
        }
        
        if (e.key === 'Escape') {
            handleEscapeKey(e);
        }
        
        // 📅 Kalendri kiirklahv
        if (e.altKey && e.key === 'c') {
            e.preventDefault();
            const calendarLink = document.querySelector('a[href*="calendar.php"]');
            if (calendarLink) {
                console.log('📅 Navigeerin kalendrisse kiirklahviga');
                window.location.href = calendarLink.href;
            }
        }
    });
}

// ===== AUTOMAATNE VÄLJALOGIMINE INTEGRATSIOON =====
function initializeAutoLogout() {
    <?php if (isLoggedIn()): ?>
        console.log('🔒 Automaatse väljalogimise süsteem laadimas...');
        
        // Lae automaatse väljalogimise script
        const autoLogoutScript = document.createElement('script');
        autoLogoutScript.src = '<?php echo url("assets/js/auto-logout.js"); ?>';
        autoLogoutScript.async = true;
        
        autoLogoutScript.onload = function() {
            console.log('✅ Auto-logout script laetud');
            
            // Kasutaja on sisse logitud - käivita automaatne väljalogimine
            console.log('👤 Kasutaja sisse logitud - käivitan auto-logout');
            
            // Lae süsteemi seaded andmebaasist
            const autoLogoutSettings = {
                timeoutMinutes: parseInt('<?php echo getSystemSetting('auto_logout_timeout', '30'); ?>'),
                warningMinutes: parseInt('<?php echo getSystemSetting('auto_logout_warning', '5'); ?>'),
                checkInterval: parseInt('<?php echo getSystemSetting('session_check_interval', '5'); ?>') * 60000,
                enabled: '<?php echo getSystemSetting('auto_logout_enabled', '1'); ?>' === '1'
            };
            
            console.log('🔧 Auto-logout seaded:', autoLogoutSettings);
            
            // Käivita auto-logout ainult kui lubatud
            if (autoLogoutSettings.enabled) {
                setTimeout(() => {
                    if (typeof window.initAutoLogout === 'function') {
                        window.initAutoLogout(autoLogoutSettings);
                        console.log('🔒 Auto-logout aktiveeritud');
                    } else {
                        console.error('❌ Auto-logout funktsioon pole saadaval');
                    }
                }, 1000);
            } else {
                console.log('🚫 Auto-logout keelatud süsteemi seadetes');
            }
        };
        
        autoLogoutScript.onerror = function() {
            console.error('❌ Auto-logout script laadimine ebaõnnestus');
        };
        
        document.head.appendChild(autoLogoutScript);
        
        // Debug info
        console.log('🔍 Kasutaja info:', {
            userId: '<?php echo $_SESSION['user_id'] ?? 'unknown'; ?>',
            userName: '<?php echo $_SESSION['user_name'] ?? 'unknown'; ?>',
            userRole: '<?php echo $_SESSION['user_role'] ?? 'unknown'; ?>',
            isAdmin: <?php echo isAdmin() ? 'true' : 'false'; ?>
        });
        
        // Admin debugging
        <?php if (isAdmin()): ?>
            window.autoLogoutAdmin = {
                getSettings: function() {
                    return {
                        current: window.autoLogout ? window.autoLogout.getStatus() : null,
                        available: typeof window.initAutoLogout === 'function'
                    };
                },
                updateTimeout: function(minutes) {
                    if (window.autoLogout) {
                        window.autoLogout.destroy();
                    }
                    window.initAutoLogout({
                        timeoutMinutes: minutes,
                        warningMinutes: Math.min(5, Math.floor(minutes / 6))
                    });
                    console.log(`⚙️ Admin: Timeout muudetud ${minutes} minutile`);
                },
                disable: function() {
                    if (window.autoLogout) {
                        window.autoLogout.destroy();
                        console.log('⚙️ Admin: Auto-logout keelatud');
                    }
                }
            };
            
            console.log('👑 Admin auto-logout kontrolli käsud: window.autoLogoutAdmin');
        <?php endif; ?>
        
    <?php else: ?>
        console.log('🚫 Auto-logout keelatud - kasutaja pole sisse logitud');
    <?php endif; ?>
}

// Sessiooni monitooring
function initializeSessionMonitoring() {
    <?php if (isLoggedIn()): ?>
        let sessionCheckInterval;
        
        function startSessionMonitoring() {
            sessionCheckInterval = setInterval(() => {
                fetch('<?php echo url("api/check-session.php"); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'same-origin'
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.valid) {
                        console.warn('⚠️ Sessioon aegunud serveris - suunan login lehele');
                        
                        if (window.autoLogout) {
                            window.autoLogout.destroy();
                        }
                        
                        window.location.href = '<?php echo url("login.php"); ?>?session_expired=1';
                    }
                })
                .catch(error => {
                    console.error('❌ Sessiooni kontroll ebaõnnestus:', error);
                });
            }, 5 * 60 * 1000);
        }
        
        setTimeout(startSessionMonitoring, 10000);
        
        window.addEventListener('beforeunload', () => {
            if (sessionCheckInterval) {
                clearInterval(sessionCheckInterval);
            }
        });
    <?php endif; ?>
}

// Development features
function initializeDevelopmentFeatures() {
    <?php if (isLoggedIn() && defined('APP_ENVIRONMENT') && APP_ENVIRONMENT === 'development'): ?>
        window.showSessionInfo = function() {
            if (window.autoLogout) {
                const status = window.autoLogout.getStatus();
                console.table({
                    'Viimane aktiivsus': status.lastActivity.toLocaleString('et-EE'),
                    'Aega jäänud (sek)': status.timeUntilLogout,
                    'Hoiatus nähtav': status.warningShown ? 'Jah' : 'Ei',
                    'Timeout (min)': status.timeoutMinutes
                });
            } else {
                console.log('Auto-logout pole aktiivne');
            }
        };
        
        console.log('🔧 Development: Sessiooni info käsk: window.showSessionInfo()');
    <?php endif; ?>
}

// ===== PEAMINE INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
    console.log('🎬 Header navigation initializing with calendar support...');
    
    const userMenuToggle = document.querySelector('.user-menu-toggle');
    const userMenuDropdown = document.getElementById('userMenuDropdown');
    
    console.log('🔍 Elements check:', {
        userMenuToggle: !!userMenuToggle,
        userMenuDropdown: !!userMenuDropdown,
        isLoggedIn: <?php echo isLoggedIn() ? 'true' : 'false'; ?>,
        userRole: '<?php echo isLoggedIn() ? $_SESSION['user_role'] : 'none'; ?>',
        isAdmin: <?php echo isAdmin() ? 'true' : 'false'; ?>,
        hasAdvancedStats: !!document.querySelector('a[href*="advanced-stats.php"]'),
        hasCalendar: !!document.querySelector('a[href*="calendar.php"]'),
        hasAdminFeatures: document.querySelectorAll('.admin-feature').length,
        hasFeaturedLinks: document.querySelectorAll('.featured-link').length
    });
    
    // Initialize all functions
    handleLogoClick();
    setActiveNavLink();
    autoHideNotifications();
    handleKeyboardNavigation();
    
    // Initialize security features
    initializeAutoLogout();
    initializeSessionMonitoring();
    initializeDevelopmentFeatures();
    
    // JavaScript event listener for menu toggle
    if (userMenuToggle) {
        userMenuToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleUserMenu(e);
        });
    }
    
    // Page visibility change handling
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            const dropdown = document.getElementById('userMenuDropdown');
            const arrow = document.querySelector('.dropdown-arrow');
            if (dropdown && dropdown.classList.contains('show')) {
                dropdown.classList.remove('show');
                if (arrow) arrow.style.transform = 'rotate(0deg)';
            }
        }
    });
    
    // 🆕 ADVANCED STATS LINK ENHANCEMENT
    const advancedStatsLink = document.querySelector('a[href*="advanced-stats.php"]');
    if (advancedStatsLink) {
        console.log('📊 Advanced statistics link found');
        
        // Add click tracking
        advancedStatsLink.addEventListener('click', function() {
            console.log('📊 Navigating to advanced statistics');
            
            // Optional: Add loading state
            this.style.opacity = '0.7';
            this.innerHTML = this.innerHTML.replace('🔬', '⏳');
        });
        
        // Add special hover effect
        advancedStatsLink.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(10px) translateY(-2px)';
            this.style.boxShadow = '0 6px 20px rgba(59, 130, 246, 0.2)';
        });
        
        advancedStatsLink.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(6px)';
            this.style.boxShadow = '0 4px 16px rgba(59, 130, 246, 0.15)';
        });
    }
    
    // 📅 KALENDRI LINK ENHANCEMENT
    const calendarLinks = document.querySelectorAll('a[href*="calendar.php"]');
    calendarLinks.forEach(calendarLink => {
        console.log('📅 Calendar link found');
        
        // Add click tracking
        calendarLink.addEventListener('click', function() {
            console.log('📅 Navigating to calendar');
            
            // Optional: Add loading state
            this.style.opacity = '0.7';
            const originalText = this.innerHTML;
            this.innerHTML = originalText.replace('📅', '⏳');
            
            // Restore after short delay
            setTimeout(() => {
                this.innerHTML = originalText;
                this.style.opacity = '1';
            }, 1000);
        });
        
        // Add special hover effect
        calendarLink.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(8px) translateY(-1px)';
            this.style.boxShadow = '0 4px 16px rgba(59, 130, 246, 0.2)';
        });
        
        calendarLink.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(6px)';
            this.style.boxShadow = '0 2px 8px rgba(59, 130, 246, 0.15)';
        });
    });
    
    // Admin features enhancement
    if (<?php echo isAdmin() ? 'true' : 'false'; ?>) {
        console.log('👑 Admin features loaded with calendar access');
        
        const adminFeatures = document.querySelectorAll('.admin-feature');
        adminFeatures.forEach(feature => {
            feature.addEventListener('mouseenter', function() {
                this.style.boxShadow = '0 4px 12px rgba(37, 99, 235, 0.15)';
            });
            
            feature.addEventListener('mouseleave', function() {
                this.style.boxShadow = 'none';
            });
        });
        
        // Log available admin features
        console.log('🔧 Admin features available:', {
            settings: !!document.querySelector('a[href*="settings.php"]'),
            autoLogout: !!document.querySelector('a[href*="auto-logout-settings.php"]'),
            backup: !!document.querySelector('a[href*="backup-system.php"]'),
            advancedStats: !!document.querySelector('a[href*="advanced-stats.php"]'),
            basicStats: !!document.querySelector('a[href*="stats.php"]'),
            calendar: !!document.querySelector('a[href*="calendar.php"]')
        });
    }
    
    console.log('✅ Header navigation initialized with calendar support and all features!');
    
    // Debug check after load
    setTimeout(() => {
        debugUserMenu();
        console.log('🎯 Page loaded successfully with user type:', '<?php echo isLoggedIn() ? (isAdmin() ? 'Admin' : 'Athlete') : 'Guest'; ?>');
        
        // Auto-logout status check
        <?php if (isLoggedIn()): ?>
            setTimeout(() => {
                if (window.autoLogout) {
                    const status = window.autoLogout.getStatus();
                    console.log('🔒 Auto-logout status:', status);
                } else {
                    console.log('⚠️ Auto-logout not active yet');
                }
            }, 2000);
        <?php endif; ?>
        
        // Calendar link status
        if (document.querySelector('a[href*="calendar.php"]')) {
            console.log('📅 Calendar link active and enhanced');
        }
    }, 1000);
});

// Export functions for external use
window.headerNav = {
    toggleUserMenu,
    setActiveNavLink,
    debugUserMenu
};

// Admin debugging tools
<?php if (isAdmin()): ?>
    window.adminDebug = {
        autoLogout: () => window.autoLogoutAdmin || 'Not available',
        sessionInfo: () => window.showSessionInfo ? window.showSessionInfo() : 'Not available',
        forceLogout: () => window.autoLogout ? window.autoLogout.performLogout() : 'Auto-logout not active',
        statsLinks: () => {
            return {
                advanced: !!document.querySelector('a[href*="advanced-stats.php"]'),
                basic: !!document.querySelector('a[href*="stats.php"]'),
                rankings: !!document.querySelector('a[href*="rankings.php"]'),
                calendar: !!document.querySelector('a[href*="calendar.php"]')
            };
        }
    };
<?php endif; ?>

console.log('🚀 Header navigation fully loaded with calendar support, statistics, auto-logout, security features and admin debugging!');
</script>