<?php
/**
 * MOTIVATSIOONIMOODUL - KAASAEGNE HELE DISAIN + AASTA FILTER
 * 🚨 KRIITILISELT PARANDATUD VERSIOON - TÄIELIK + RESPONSIVE KÕIGELE
 */

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

// Nõua sisselogimist ja sportlase õigusi
requireLogin();
if (!isAthlete()) {
    header('Location: ' . url());
    exit;
}

// 🚨 KRIITILISELT PARANDATUD - Laeme failid õiges järjekorras
require_once 'includes/achievements_data.php';
require_once 'includes/challenges_data.php';
require_once 'includes/motivation_functions.php';

// CSS-faili laadimine + Chart.js + motivation.js
$extra_head_content = '
<link rel="stylesheet" href="' . url('assets/css/motivation.css') . '">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script src="' . url('athlete/assets/js/motivation.js') . '"></script>
';

$user_id = $_SESSION['user_id'];

// 🆕 AASTA FILTER
$selected_year = getGet('year', date('Y'));
$current_year = date('Y');
$error = '';

try {
    // Andmete laadimise plokk
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('Kasutajat ei leitud');
    }
    
    $user['ageGroup'] = getAgeGroup($user['birthDate'], $selected_year);
    
    // 🚨 KRIITILISELT PARANDATUD - Verifitseeri motivation stats
    ensureUserMotivationStats($user_id);
    
    // 🚨 KRIITILISELT PARANDATUD - Kasuta parandatud funktsioone + aasta filter
    $achievements_data = calculateUserAchievements($user_id, $ACHIEVEMENTS, $selected_year);
    
    // Väljakutsed ainult jooksval aastal
    if ($selected_year == $current_year) {
        $challenges_data = generatePersonalChallenges($user_id); // See loob automaatselt väljakutsed!
    } else {
        $challenges_data = []; // Eelmiste aastate väljakutseid ei näita
    }
    
    if (function_exists('getProgressionData')) {
        $progression_data = getProgressionData($user_id, 6, $selected_year);
    } else {
        $progression_data = [];
    }
    
    // Lae kuustatistika graafikute jaoks (valitud aasta)
    $monthly_stats = [];
    try {
        $stmt = $pdo->prepare("
            SELECT 
                strftime('%m', c.date) as month,
                strftime('%Y-%m', c.date) as year_month,
                COUNT(r.id) as results_count,
                AVG(r.points) as avg_points,
                MAX(r.points) as max_points
            FROM results r
            JOIN competitions c ON r.competitionId = c.id
            WHERE r.userId = ? AND strftime('%Y', c.date) = ?
            GROUP BY strftime('%Y-%m', c.date)
            ORDER BY year_month
        ");
        $stmt->execute([$user_id, $selected_year]);
        $monthly_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        error_log('Monthly stats error: ' . $e->getMessage());
    }
    
} catch (Throwable $t) {
    $error = 'Viga motivatsiooni andmete laadimisel: ' . $t->getMessage();
    error_log("Motivation Page Error: " . $t->getMessage() . " in " . $t->getFile() . " on line " . $t->getLine());
}

// 🚨 KRIITILISELT PARANDATUD - MOTIVATSIOONI PUNKTIDE KOGUSUMMA
$total_motivation_points = 0;
$points_breakdown = [];

if (isset($achievements_data['all_unlocked']) && isset($ACHIEVEMENTS)) {
    // 🚨 PARANDATUD - Loe punktid user_achievements tabelist (kui olemas points_awarded väli)
    try {
        // Kontrolli kas points_awarded väli eksisteerib
        $stmt_check = $pdo->prepare("PRAGMA table_info(user_achievements)");
        $stmt_check->execute();
        $columns = $stmt_check->fetchAll(PDO::FETCH_ASSOC);
        $has_points_awarded = false;
        
        foreach ($columns as $column) {
            if ($column['name'] === 'points_awarded') {
                $has_points_awarded = true;
                break;
            }
        }
        
        if ($has_points_awarded) {
            // Kasuta andmebaasis olevaid punkte - ainult valitud aastani
            $stmt = $pdo->prepare("
                SELECT achievement_key, COALESCE(points_awarded, 0) as points_awarded 
                FROM user_achievements 
                WHERE userId = ? AND strftime('%Y', unlocked_at) <= ?
            ");
            $stmt->execute([$user_id, $selected_year]);
            $user_achievements_with_points = $stmt->fetchAll();
            
            foreach ($user_achievements_with_points as $ach) {
                $achievement_key = $ach['achievement_key'];
                $points = $ach['points_awarded'];
                
                // Kui andmebaasis pole punkte, võta achievements_data.php failist
                if ($points == 0) {
                    $achievement = $ACHIEVEMENTS[$achievement_key] ?? null;
                    if ($achievement) {
                        $points = $achievement['points_reward'] ?? 0;
                    }
                }
                
                $total_motivation_points += $points;
                
                $achievement = $ACHIEVEMENTS[$achievement_key] ?? null;
                if ($achievement && $points > 0) {
                    $points_breakdown[] = [
                        'name' => $achievement['name'],
                        'icon' => $achievement['icon'],
                        'points' => $points,
                        'rarity' => $achievement['rarity']
                    ];
                }
            }
        } else {
            // Fallback: kasuta achievements_data.php faili
            foreach ($achievements_data['all_unlocked'] as $achievement_key) {
                $achievement = $ACHIEVEMENTS[$achievement_key] ?? null;
                if ($achievement) {
                    $points = $achievement['points_reward'] ?? 0;
                    $total_motivation_points += $points;
                    
                    if ($points > 0) {
                        $points_breakdown[] = [
                            'name' => $achievement['name'],
                            'icon' => $achievement['icon'],
                            'points' => $points,
                            'rarity' => $achievement['rarity']
                        ];
                    }
                }
            }
        }
    } catch (Exception $e) {
        error_log('Points calculation error: ' . $e->getMessage());
        // Fallback: kasuta achievements_data.php faili
        foreach ($achievements_data['all_unlocked'] as $achievement_key) {
            $achievement = $ACHIEVEMENTS[$achievement_key] ?? null;
            if ($achievement) {
                $points = $achievement['points_reward'] ?? 0;
                $total_motivation_points += $points;
                
                if ($points > 0) {
                    $points_breakdown[] = [
                        'name' => $achievement['name'],
                        'icon' => $achievement['icon'],
                        'points' => $points,
                        'rarity' => $achievement['rarity']
                    ];
                }
            }
        }
    }
}

// Sorteeri punktide alusel
usort($points_breakdown, function($a, $b) {
    return $b['points'] <=> $a['points'];
});

// 📊 SAAVUTUSTE KATEGOORIATE ANDMED GRAAFIKUTE JAOKS
function getAchievementsCategoryData() {
    global $achievements_data, $ACHIEVEMENTS;
    
    $categories = [];
    
    if (isset($achievements_data['all_unlocked'])) {
        foreach ($achievements_data['all_unlocked'] as $key) {
            $achievement = $ACHIEVEMENTS[$key] ?? null;
            if ($achievement) {
                $category = $achievement['category'];
                $categories[$category] = ($categories[$category] ?? 0) + 1;
            }
        }
    }
    
    return $categories;
}

// 🚨 PARANDATUD - Eestindatud auhindade formateerija
function formatEstonianChallengeReward($challenge) {
    switch ($challenge['reward_type']) {
        case 'achievement_points':
            $points = calculateChallengeReward($challenge['reward_value'], $challenge['difficulty']);
            return "+{$points} saavutuste punkti";
            
        case 'title':
            return "Tiitel: \"" . getEstonianTitle($challenge['reward_value']) . "\"";
            
        case 'badge':
            return "Märk: \"" . getEstonianBadge($challenge['reward_value']) . "\"";
            
        case 'special_achievement':
            return "Eriline saavutus avatud!";
            
        case 'mood_bonus':
            return "+{$challenge['reward_value']} boonust järgmisele tulemusele";
            
        case 'crown':
            return "👑 " . getEstonianTitle($challenge['reward_value']);
            
        default:
            return $challenge['reward_description'] ?? 'Eriline auhind';
    }
}

// 🚨 LISATUD - Eestikeelsed tõlked
function getEstonianTitle($key) {
    $titles = [
        'consistent_champion' => 'Järjekindel šampion',
        'season_explorer' => 'Hooaja avastaja',
        'season_champion' => 'Hooaja šampion',
        'endurance_king' => 'Vastupidavuse kuningas',
        'consistency_king' => 'Järjekindluse kuningas'
    ];
    return $titles[$key] ?? ucfirst(str_replace('_', ' ', $key));
}

function getEstonianBadge($key) {
    $badges = [
        'training_dedication' => 'Treeningu pühenduja',
        'weekend_warrior' => 'Nädalavahetuse sõdalane',
        'discipline_explorer' => 'Avastaja',
        'steady_performer' => 'Stabiilne esineja',
        'versatile_athlete' => 'Mitmekülgne sportlane'
    ];
    return $badges[$key] ?? ucfirst(str_replace('_', ' ', $key));
}

$page_title = 'Minu edusammud - Motivatsioon';
$page_description = 'Jälgi oma saavutusi, väljakutseid ja progressi ratsaspordis.';

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

<!-- 🚨 KRIITILISELT PARANDATUD: JavaScript andmete edastamine -->
<script>
// Edastame PHP andmed JavaScriptile
window.progressionData = <?php echo json_encode($progression_data ?? []); ?>;
window.monthlyStats = <?php echo json_encode($monthly_stats ?? []); ?>;
window.achievementsCategoryData = <?php echo json_encode(getAchievementsCategoryData()); ?>;
</script>

<main class="motivation-main">
    <div class="container">
        
        <!-- 📊 PEALEHT HEADER + AASTA FILTER -->
        <div class="page-header">
            <div class="header-content">
                <h1 class="page-title">
                    <span class="title-icon">📊</span>
                    Minu edusammud
                </h1>
                <p class="page-subtitle">
                    Sinu isiklik arengukeskus ja saavutuste jälgimine
                </p>
            </div>
            
            <!-- 🆕 AASTA FILTER -->
            <div class="year-filter-section">
                <div class="points-badge-header">
                    <div class="points-icon">📈</div>
                    <div class="points-info">
                        <div class="points-number"><?php echo $total_motivation_points; ?></div>
                        <div class="points-label">Saavutuste punkti</div>
                    </div>
                </div>
                
                <div class="year-filter">
                    <form method="GET" class="year-form">
                        <label for="year" class="year-label">Vaata aastat:</label>
                        <select name="year" id="year" class="year-select" onchange="this.form.submit()">
                            <?php 
                            // Leia esimene aasta, mil kasutajal tulemusi on
                            try {
                                $stmt = $pdo->prepare("
                                    SELECT MIN(strftime('%Y', c.date)) as first_year 
                                    FROM results r 
                                    JOIN competitions c ON r.competitionId = c.id 
                                    WHERE r.userId = ?
                                ");
                                $stmt->execute([$user_id]);
                                $first_year = $stmt->fetch()['first_year'] ?? $current_year;
                            } catch (Exception $e) {
                                $first_year = $current_year;
                            }
                            
                            // Näita aastaid alates esimesest tulemusest kuni praeguseni
                            for ($y = $current_year; $y >= max($first_year, $current_year - 10); $y--): 
                            ?>
                                <option value="<?php echo $y; ?>" <?php echo $selected_year == $y ? 'selected' : ''; ?>>
                                    <?php echo $y; ?><?php echo $y == $current_year ? ' (praegune)' : ''; ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                        
                        <?php if ($selected_year != $current_year): ?>
                            <div class="year-badge">
                                📅 Vaatad: <?php echo $selected_year; ?>. aasta andmeid
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>

        <!-- ✨ PEAMINE INFOKAST -->
        <section class="motivation-intro">
            <div class="intro-card">
                <div class="intro-content">
                    <div class="intro-icon">✨</div>
                    <div class="intro-text">
                        <h3 class="intro-title">Sinu isiklik motivatsioonikeskus</h3>
                        <p class="intro-description">
                            See on sinu privaatne arenguruum, kus jälgitakse automaatselt sinu arengut ratsaspordis. 
                            Süsteem tunnustab sinu <strong>järjekindlust, arengut ja saavutusi</strong> – alates esimestest sammudest 
                            kuni kõrgete tulemusteni. Kogud punkte saavutuste eest, täidad kuiseid väljakutseid ja näed 
                            oma progressi graafikutes. 
                            <br><br>
                            <strong>Oluline:</strong> Kõik siin olevad punktid, märgid ja auhinnad on ainult sinu isiklikuks 
                            motivatsiooniks – need ei kajastu avalikes hooaja tabelites ega mõjuta ametlikke võistlustulemusi.
                        </p>
                    </div>
                </div>
            </div>
        </section>

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

        <!-- 🚨 DEBUG INFO (ainult development) -->
        <?php if (defined('DEBUG') && DEBUG): ?>
        <div style="background: #f0f0f0; padding: 10px; margin: 10px 0; border-radius: 5px; font-family: monospace; font-size: 12px;">
            <strong>🔧 DEBUG INFO (<?php echo $selected_year; ?>):</strong><br>
            - Saavutusi kokku: <?php echo count($achievements_data['all_unlocked'] ?? []); ?>/<?php echo count($ACHIEVEMENTS); ?><br>
            - Uusi saavutusi: <?php echo count($achievements_data['newly_unlocked'] ?? []); ?><br>
            - Väljakutseid: <?php echo count($challenges_data ?? []); ?><br>
            - Motivatsioonipunkte: <?php echo $total_motivation_points; ?><br>
            - Points breakdown: <?php echo count($points_breakdown); ?> elementi<br>
            <?php if (function_exists('debugUserCompetitions')): ?>
                <?php $debug_info = debugUserCompetitions($user_id, $selected_year); ?>
                - Tulemusi: <?php echo $debug_info['results_count'] ?? 'N/A'; ?><br>
                - Unikaalseid võistlusi: <?php echo $debug_info['competitions_count'] ?? 'N/A'; ?><br>
                - Edukalt lõpetatud võistlusi: <?php echo $debug_info['successful_competitions_count'] ?? 'N/A'; ?><br>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- 🎯 PUNKTIDE ÜLEVAADE (kui on punkte) -->
        <?php if ($total_motivation_points > 0): ?>
        <section class="points-overview">
            <div class="overview-card">
                <div class="card-header">
                    <h2 class="card-title">
                        <span class="title-icon">🏆</span>
                        Sinu saavutuste punktid <?php echo $selected_year != $current_year ? "($selected_year)" : ""; ?>
                    </h2>
                    <div class="total-badge">
                        <span class="total-number"><?php echo $total_motivation_points; ?></span>
                        <span class="total-text">punkti</span>
                    </div>
                </div>
                
                <div class="card-content">
                    <p class="overview-text">
                        Kogutud <?php echo count($achievements_data['all_unlocked'] ?? []); ?> saavutuse eest
                    </p>
                    
                    <?php if (!empty($points_breakdown)): ?>
                    <div class="top-achievements">
                        <h3>Sinu parimad saavutused:</h3>
                        <div class="achievements-list" id="achievements-list">
                            <?php foreach (array_slice($points_breakdown, 0, 3) as $item): ?>
                                <div class="achievement-item">
                                    <span class="item-icon"><?php echo $item['icon']; ?></span>
                                    <span class="item-name"><?php echo htmlspecialchars($item['name']); ?></span>
                                    <span class="item-points">+<?php echo $item['points']; ?>p</span>
                                </div>
                            <?php endforeach; ?>
                            
                            <?php if (count($points_breakdown) > 3): ?>
                                <?php foreach (array_slice($points_breakdown, 3) as $item): ?>
                                    <div class="achievement-item hidden-achievement" style="display: none;">
                                        <span class="item-icon"><?php echo $item['icon']; ?></span>
                                        <span class="item-name"><?php echo htmlspecialchars($item['name']); ?></span>
                                        <span class="item-points">+<?php echo $item['points']; ?>p</span>
                                    </div>
                                <?php endforeach; ?>
                                
                                <button class="show-more-achievements" onclick="toggleTopAchievements()">
                                    <span class="toggle-icon">▼</span>
                                    <span class="toggle-text">Näita veel <?php echo count($points_breakdown) - 3; ?> saavutust</span>
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- 🆕 UUTE SAAVUTUSTE TEAVITUS (ainult jooksval aastal) -->
        <?php if ($selected_year == $current_year && !empty($achievements_data['newly_unlocked'])): ?>
        <section class="new-achievements-alert">
            <div class="content-card" style="border: 2px solid #10B981; background: #F0FDF4;">
                <div class="card-header" style="background: #DCFCE7;">
                    <h2 class="card-title" style="color: #166534;">
                        <span class="title-icon">🎉</span>
                        Uued saavutused avatud!
                    </h2>
                </div>
                <div class="card-content">
                    <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                        <?php foreach ($achievements_data['newly_unlocked'] as $key): 
                            $achievement = getAchievementData($key);
                            if(!$achievement) continue;
                        ?>
                            <div style="display: inline-flex; align-items: center; gap: 8px; background: white; padding: 8px 12px; border-radius: 8px; border: 1px solid #BBF7D0;">
                                <span style="font-size: 1.2rem;"><?php echo htmlspecialchars($achievement['icon']); ?></span>
                                <span style="font-weight: 600; color: #166534;"><?php echo htmlspecialchars($achievement['name']); ?></span>
                                <span style="background: #10B981; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.8rem; font-weight: 600;">+<?php echo $achievement['points_reward']; ?>p</span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- 📋 PÕHISISU GRID -->
        <div class="content-grid">
            
            <!-- 🚨 PARANDATUD VÄLJAKUTSETE KAARD (RESPONSIVE) - ainult jooksval aastal -->
            <?php if ($selected_year == $current_year): ?>
            <section class="challenges-section">
                <div class="content-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <span class="title-icon">🎯</span>
                            Aktiivsed väljakutsed
                            <?php if (!empty($challenges_data)): ?>
                                <span class="achievement-count">(<?php echo count($challenges_data); ?>)</span>
                            <?php endif; ?>
                        </h2>
                    </div>
                    <div class="card-content">
                        <?php if (empty($challenges_data)): ?>
                            <div class="empty-state">
                                <div class="empty-icon">🎯</div>
                                <p>Väljakutsed genereeritakse automaatselt!</p>
                                <small>Värskenda lehte või tule tagasi hiljem</small>
                            </div>
                        <?php else: ?>
                            <div class="challenges-list" id="challenges-list">
                                <?php foreach ($challenges_data as $index => $challenge): 
                                    $template = getChallengeData($challenge['key']);
                                    if (!$template) continue;
                                    $status_color = getChallengeStatusColor($challenge['percentage']);
                                    $is_hidden_mobile = $index >= 3; // Telefonis peidame alates 4. elemendist
                                ?>
                                    <div class="challenge-item <?php echo ($challenge['completed'] ?? 0) ? 'completed' : ''; ?> <?php echo $is_hidden_mobile ? 'hidden-challenge-mobile' : ''; ?>">
                                        <div class="challenge-header">
                                            <div class="challenge-icon">
                                                <?php echo htmlspecialchars($template['icon']); ?>
                                            </div>
                                            <div class="challenge-info">
                                                <div class="challenge-name"><?php echo htmlspecialchars($template['name']); ?></div>
                                                <div class="challenge-description"><?php echo htmlspecialchars($template['description']); ?></div>
                                            </div>
                                            <div class="challenge-reward">
                                                <?php echo htmlspecialchars(formatEstonianChallengeReward($template)); ?>
                                            </div>
                                        </div>
                                        <div class="challenge-progress">
                                            <div class="progress-info">
                                                <span><?php echo htmlspecialchars($challenge['current_progress']); ?> / <?php echo htmlspecialchars($challenge['target_value']); ?></span>
                                                <span><?php echo round($challenge['percentage']); ?>%</span>
                                            </div>
                                            <div class="progress-bar">
                                                <div class="progress-fill" style="width: <?php echo min(100, $challenge['percentage']); ?>%"></div>
                                            </div>
                                            <?php if ($challenge['completed'] ?? 0): ?>
                                                <div class="challenge-completed">
                                                    ✓ Väljakutse täidetud!
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                
                                <!-- MOBIILI LAIENDAMISE NUPP (ainult telefonis nähtav ja kui on rohkem kui 3 väljakutset) -->
                                <?php if (count($challenges_data) > 3): ?>
                                    <button class="show-more-challenges mobile-only" onclick="toggleChallenges()">
                                        <span class="toggle-icon">▼</span>
                                        <span class="toggle-text">Näita veel <?php echo count($challenges_data) - 3; ?> väljakutset</span>
                                    </button>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </section>
            <?php else: ?>
            <!-- Eelmiste aastate märkus väljakutsete kohta -->
            <section class="challenges-section">
                <div class="content-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <span class="title-icon">🎯</span>
                            Väljakutsed
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="empty-state">
                            <div class="empty-icon">📅</div>
                            <p>Väljakutsed on saadaval ainult jooksval aastal</p>
                            <small>Vali <?php echo $current_year; ?>. aasta, et näha aktiivseid väljakutseid</small>
                        </div>
                    </div>
                </div>
            </section>
            <?php endif; ?>

            <!-- 🚨 PARANDATUD SAAVUTUSTE KAARD (RESPONSIVE) -->
            <section class="achievements-section">
                <div class="content-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            <span class="title-icon">🏆</span>
                            Saavutused <?php echo $selected_year != $current_year ? "($selected_year)" : ""; ?>
                            <span class="achievement-count">
                                (<?php echo isset($achievements_data['all_unlocked']) ? count($achievements_data['all_unlocked']) : 0; ?>/<?php echo count($ACHIEVEMENTS); ?>)
                            </span>
                        </h2>
                    </div>
                    <div class="card-content">
                        <div class="achievements-grid" id="achievements-grid">
                            <?php 
                            $achievement_index = 0;
                            foreach ($ACHIEVEMENTS as $key => $achievement):
                                $progress = $achievements_data['progress'][$key] ?? ['unlocked' => false, 'percentage' => 0];
                                $is_rare = isRareAchievement($key);
                                $is_newly_unlocked = ($selected_year == $current_year) && in_array($key, $achievements_data['newly_unlocked'] ?? []);
                                $is_hidden_mobile = $achievement_index >= 3; // Telefonis peidame alates 4. elemendist
                                $achievement_index++;
                            ?>
                                <div class="achievement-badge <?php echo $progress['unlocked'] ? 'unlocked' : 'locked'; ?> <?php echo $is_rare ? 'rare' : ''; ?> <?php echo $is_newly_unlocked ? 'newly-unlocked' : ''; ?> <?php echo $is_hidden_mobile ? 'hidden-achievement-mobile' : ''; ?>" 
                                     title="<?php echo htmlspecialchars($achievement['description']); ?>"
                                     data-achievement="<?php echo htmlspecialchars($key); ?>">
                                    <div class="achievement-icon"><?php echo htmlspecialchars($achievement['icon']); ?></div>
                                    <div class="achievement-name"><?php echo htmlspecialchars($achievement['name']); ?></div>
                                    <?php if (!$progress['unlocked']): ?>
                                        <div class="achievement-progress"><?php echo round($progress['percentage']); ?>%</div>
                                    <?php else: ?>
                                        <div class="achievement-points">+<?php echo $achievement['points_reward']; ?>p</div>
                                    <?php endif; ?>
                                    <?php if ($is_newly_unlocked): ?>
                                        <div class="new-badge">UUS!</div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- MOBIILI LAIENDAMISE NUPP SAAVUTUSTELE (ainult telefonis nähtav) -->
                        <?php if (count($ACHIEVEMENTS) > 3): ?>
                            <button class="show-more-achievements-grid mobile-only" onclick="toggleAchievementsGrid()">
                                <span class="toggle-icon">▼</span>
                                <span class="toggle-text">Näita veel <?php echo count($ACHIEVEMENTS) - 3; ?> saavutust</span>
                            </button>
                        <?php endif; ?>
                        
                        <?php if (count($achievements_data['all_unlocked'] ?? []) == 0): ?>
                            <div class="empty-state">
                                <div class="empty-icon">🏆</div>
                                <p>Saavutused ootavad sind!</p>
                                <small>Lisa tulemusi ja märgi treeninguid, et avastada oma esimesed saavutused</small>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </section>
        </div>

        <!-- 📊 STATISTIKA SEKTSIOON -->
        <?php if ($total_motivation_points > 0 || count($achievements_data['all_unlocked'] ?? []) > 0): ?>
        <section class="stats-section">
            <div class="content-card">
                <div class="card-header">
                    <h2 class="card-title">
                        <span class="title-icon">📊</span>
                        Sinu progress <?php echo $selected_year != $current_year ? "($selected_year)" : ""; ?>
                    </h2>
                </div>
                <div class="card-content">
                    <div class="stats-grid">
                        <div class="stat-item">
                            <div class="stat-label">Saavutused</div>
                            <div class="stat-value"><?php echo count($achievements_data['all_unlocked'] ?? []); ?> / <?php echo count($ACHIEVEMENTS); ?></div>
                            <div class="stat-bar">
                                <?php $ach_percentage = count($ACHIEVEMENTS) > 0 ? (count($achievements_data['all_unlocked'] ?? []) / count($ACHIEVEMENTS)) * 100 : 0; ?>
                                <div class="stat-fill" style="width: <?php echo $ach_percentage; ?>%"></div>
                            </div>
                        </div>
                        
                        <?php if ($selected_year == $current_year): ?>
                        <div class="stat-item">
                            <div class="stat-label">Aktiivsed väljakutsed</div>
                            <div class="stat-value"><?php echo count($challenges_data ?? []); ?></div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="stat-item">
                            <div class="stat-label">Saavutuste punktid</div>
                            <div class="stat-value highlight"><?php echo $total_motivation_points; ?></div>
                        </div>
                        
                        <?php if ($selected_year == $current_year && !empty($achievements_data['newly_unlocked'])): ?>
                        <div class="stat-item">
                            <div class="stat-label">Uusi saavutusi</div>
                            <div class="stat-value" style="color: #10B981; font-weight: 800;"><?php echo count($achievements_data['newly_unlocked']); ?></div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- 📊 KAASAEGNE GRAAFIKUTE SEKTSIOON -->
        <?php if ($total_motivation_points > 0 || count($achievements_data['all_unlocked'] ?? []) > 0): ?>
        <section class="charts-section">
            <div class="content-card">
                <div class="card-header">
                    <h2 class="card-title">
                        <span class="title-icon">📈</span>
                        Sinu progress graafikutes <?php echo $selected_year != $current_year ? "($selected_year)" : ""; ?>
                    </h2>
                </div>

                <!-- KAASAEGNE NAVIGATSIOON -->
                <div class="chart-navigation">
                    <button class="chart-nav-btn active" data-chart="progression">
                        <span class="chart-nav-icon">📈</span>
                        <span class="chart-nav-text">Punktide areng</span>
                    </button>
                    <button class="chart-nav-btn" data-chart="monthly">
                        <span class="chart-nav-icon">📅</span>
                        <span class="chart-nav-text">Kuude võrdlus</span>
                    </button>
                    <button class="chart-nav-btn" data-chart="achievements">
                        <span class="chart-nav-icon">🏆</span>
                        <span class="chart-nav-text">Saavutused</span>
                    </button>
                </div>

                <!-- GRAAFIKU KONTEINER -->
                <div class="chart-container-wrapper">
                    <!-- PUNKTIDE ARENG -->
                    <div class="chart-panel active" id="progression-panel">
                        <div class="chart-header">
                            <h4 class="chart-title">Punktide areng <?php echo $selected_year; ?>. aastal</h4>
                            <p class="chart-description">Näitab sinu võistluste punktide arengut aja jooksul</p>
                        </div>
                        <div class="single-chart-panel">
                            <div class="chart-container">
                                <canvas id="progressionChart" width="400" height="200"></canvas>
                            </div>
                        </div>
                    </div>

                    <!-- KUUDE VÕRDLUS -->
                    <div class="chart-panel" id="monthly-panel">
                        <div class="chart-header">
                            <h4 class="chart-title">Kuude keskmiste võrdlus (<?php echo $selected_year; ?>)</h4>
                            <p class="chart-description">Võrdleb erinevate kuude keskmisi punktisummasid</p>
                        </div>
                        <div class="single-chart-panel">
                            <div class="chart-container">
                                <canvas id="monthlyChart" width="400" height="200"></canvas>
                            </div>
                        </div>
                    </div>

                    <!-- SAAVUTUSTE JAOTUS -->
                    <div class="chart-panel" id="achievements-panel">
                        <div class="chart-header">
                            <h4 class="chart-title">Saavutuste kategooriate jaotus</h4>
                            <p class="chart-description">Näitab millistes kategooriates oled kõige edukam</p>
                        </div>
                        <div class="single-chart-panel">
                            <div class="chart-container">
                                <canvas id="achievementsChart" width="400" height="200"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- 💡 TEHNILINE MÄRKUS -->
        <section class="technical-notice">
            <div class="notice-content">
                <div class="notice-icon">💡</div>
                <div class="notice-text">
                    <strong>Märkus:</strong> Kui sisestate palju tulemusi korraga, võib kuluda 2-3 lehe värskendamist, 
                    kuni kõik uued saavutused ja märgid ilmuvad. See on normaalne süsteemi töö.
                </div>
            </div>
        </section>

        <!-- ⚡ KIIRED TOIMINGUD -->
        <section class="actions-section">
            <div class="content-card">
                <div class="card-header">
                    <h2 class="card-title">
                        <span class="title-icon">⚡</span>
                        Kiired toimingud
                    </h2>
                </div>
                <div class="card-content">
                    <div class="actions-grid">
                        <a href="<?php echo url('athlete/results.php'); ?>" class="action-item">
                            <div class="action-icon">🏆</div>
                            <div class="action-text">Lisa tulemusi</div>
                            <div class="action-desc">Saavuta uusi märke</div>
                        </a>
                        
                        <a href="<?php echo url('athlete/training.php'); ?>" class="action-item">
                            <div class="action-icon">💪</div>
                            <div class="action-text">Treeningu päevik</div>
                            <div class="action-desc">Märgi treeninguid</div>
                        </a>
                        
                        <a href="<?php echo url('athlete/stats.php'); ?>" class="action-item">
                            <div class="action-icon">📊</div>
                            <div class="action-text">Statistika</div>
                            <div class="action-desc">Vaata detailset analüüsi</div>
                        </a>
                        
                        <a href="<?php echo url('athlete/dashboard.php'); ?>" class="action-item">
                            <div class="action-icon">🏠</div>
                            <div class="action-text">Armatuurlaud</div>
                            <div class="action-desc">Üldine ülevaade</div>
                        </a>
                    </div>
                </div>
            </div>
        </section>
    </div>
</main>

<!-- JavaScript funktsioonid laiendamiseks -->
<script>
// Top achievements laiendamine (punktide ülevaade sektsioonis)
function toggleTopAchievements() {
    const hiddenAchievements = document.querySelectorAll('.hidden-achievement');
    const toggleButton = document.querySelector('.show-more-achievements');
    const toggleIcon = toggleButton.querySelector('.toggle-icon');
    const toggleText = toggleButton.querySelector('.toggle-text');
    const isExpanded = toggleButton.classList.contains('expanded');
    
    if (isExpanded) {
        // Peida saavutused
        hiddenAchievements.forEach(item => {
            item.style.display = 'none';
        });
        toggleButton.classList.remove('expanded');
        toggleText.textContent = `Näita veel ${hiddenAchievements.length} saavutust`;
    } else {
        // Näita saavutused
        hiddenAchievements.forEach(item => {
            item.style.display = 'flex';
        });
        toggleButton.classList.add('expanded');
        toggleText.textContent = 'Näita vähem';
    }
}

// 🚨 UUS - Väljakutsete laiendamine (ainult mobiilis)
function toggleChallenges() {
    const hiddenChallenges = document.querySelectorAll('.hidden-challenge-mobile');
    const toggleButton = document.querySelector('.show-more-challenges');
    const toggleIcon = toggleButton.querySelector('.toggle-icon');
    const toggleText = toggleButton.querySelector('.toggle-text');
    const isExpanded = toggleButton.classList.contains('expanded');
    
    if (isExpanded) {
        // Peida väljakutsed
        hiddenChallenges.forEach(item => {
            item.style.display = 'none';
        });
        toggleButton.classList.remove('expanded');
        toggleText.textContent = `Näita veel ${hiddenChallenges.length} väljakutset`;
    } else {
        // Näita väljakutsed
        hiddenChallenges.forEach(item => {
            item.style.display = 'block';
        });
        toggleButton.classList.add('expanded');
        toggleText.textContent = 'Näita vähem';
    }
}

// 🚨 UUS - Saavutuste grid laiendamine (ainult mobiilis)
function toggleAchievementsGrid() {
    const hiddenAchievements = document.querySelectorAll('.hidden-achievement-mobile');
    const toggleButton = document.querySelector('.show-more-achievements-grid');
    const toggleIcon = toggleButton.querySelector('.toggle-icon');
    const toggleText = toggleButton.querySelector('.toggle-text');
    const isExpanded = toggleButton.classList.contains('expanded');
    
    if (isExpanded) {
        // Peida saavutused
        hiddenAchievements.forEach(item => {
            item.style.display = 'none';
        });
        toggleButton.classList.remove('expanded');
        toggleText.textContent = `Näita veel ${hiddenAchievements.length} saavutust`;
    } else {
        // Näita saavutused
        hiddenAchievements.forEach(item => {
            item.style.display = 'flex';
        });
        toggleButton.classList.add('expanded');
        toggleText.textContent = 'Näita vähem';
    }
}
</script>

<style>
/* 🚨 LISA CSS UUTE ELEMENTIDE JAOKS */
.new-achievements-alert {
    margin-bottom: var(--spacing-6);
}

/* 🆕 AASTA FILTER STIILID */
.year-filter-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-4);
}

.year-filter {
    background: white;
    border-radius: var(--radius-lg);
    padding: var(--spacing-4);
    box-shadow: var(--shadow);
    border: 1px solid var(--gray-200);
}

.year-form {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    flex-wrap: wrap;
    justify-content: center;
}

.year-label {
    font-weight: 500;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
}

.year-select {
    padding: var(--spacing-2) var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    background: white;
    font-size: var(--font-size-sm);
    font-weight: 500;
    cursor: pointer;
    transition: all var(--transition-fast);
    min-width: 140px;
}

.year-select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 10%, transparent);
}

.year-badge {
    background: linear-gradient(135deg, #3b82f6, #1e40af);
    color: white;
    padding: var(--spacing-2) var(--spacing-4);
    border-radius: 50px;
    font-size: var(--font-size-sm);
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

/* PARANDATUD SAAVUTUSTE JA VÄLJAKUTSETE NUPUD */
.show-more-achievements, .show-more-challenges, .show-more-achievements-grid {
    width: 100%;
    margin-top: var(--spacing-3);
    padding: var(--spacing-3) var(--spacing-4);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    background: var(--gray-50);
    color: var(--gray-700);
    font-size: var(--font-size-sm);
    font-weight: 500;
    cursor: pointer;
    transition: all var(--transition-fast);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: var(--spacing-2);
}

.show-more-achievements:hover, .show-more-challenges:hover, .show-more-achievements-grid:hover {
    background: var(--gray-100);
    border-color: var(--gray-400);
    color: var(--gray-800);
}

.toggle-icon {
    font-size: 0.8rem;
    transition: transform var(--transition-fast);
}

.show-more-achievements.expanded .toggle-icon,
.show-more-challenges.expanded .toggle-icon,
.show-more-achievements-grid.expanded .toggle-icon {
    transform: rotate(180deg);
}

.hidden-achievement, .hidden-challenge-mobile, .hidden-achievement-mobile {
    animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 🚨 RESPONSIVE VÄLJAKUTSETE SÜSTEEM */
/* Arvutis: näita kõik väljakutsed, ära näita nuppu */
.show-more-challenges.mobile-only, .show-more-achievements-grid.mobile-only {
    display: none;
}

.hidden-challenge-mobile, .hidden-achievement-mobile {
    display: block; /* Arvutis nähtav */
}

/* Telefonis: peida lisaelemendid, näita nuppu */
@media (max-width: 768px) {
    .show-more-challenges.mobile-only, .show-more-achievements-grid.mobile-only {
        display: flex; /* Telefonis nähtav */
    }
    
    .hidden-challenge-mobile, .hidden-achievement-mobile {
        display: none; /* Telefonis peidetud */
    }
    
    /* Kui nupp on avatud, näita kõik */
    .show-more-challenges.expanded ~ .hidden-challenge-mobile,
    .challenges-list .show-more-challenges.expanded + .hidden-challenge-mobile {
        display: block;
    }
    
    .show-more-achievements-grid.expanded ~ .hidden-achievement-mobile,
    .achievements-grid .show-more-achievements-grid.expanded + .hidden-achievement-mobile {
        display: flex;
    }
    
    /* Aasta filter mobile */
    .year-filter-section {
        align-items: stretch;
    }
    
    .year-form {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-3);
    }
    
    .year-select {
        min-width: auto;
        width: 100%;
    }
}

.achievement-badge.newly-unlocked {
    position: relative;
    animation: pulse-glow 3s ease-in-out infinite;
}

@keyframes pulse-glow {
    0%, 100% { 
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transform: scale(1);
    }
    50% { 
        box-shadow: 0 6px 20px rgba(16, 185, 129, 0.3);
        transform: scale(1.02);
    }
}

.new-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: linear-gradient(45deg, #EF4444, #F97316);
    color: white;
    font-size: 10px;
    padding: 3px 6px;
    border-radius: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    box-shadow: 0 2px 4px rgba(239, 68, 68, 0.4);
}

/* ===== MOTIVATSIOONI INFOKASTID ===== */
/* Peamine infokast */
.motivation-intro {
    margin-bottom: var(--spacing-6);
}

.intro-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-xl);
    padding: var(--spacing-5);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    position: relative;
    overflow: hidden;
}

.intro-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--gray-400), var(--gray-600), var(--gray-400));
    opacity: 0.6;
}

.intro-content {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-4);
}

.intro-icon {
    font-size: 2rem;
    background: white;
    width: 56px;
    height: 56px;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;
    border: 2px solid var(--gray-200);
}

.intro-text {
    flex: 1;
    padding-top: var(--spacing-1);
}

.intro-title {
    margin: 0 0 var(--spacing-3);
    font-size: var(--font-size-xl);
    font-weight: 600;
    color: var(--gray-800);
    line-height: 1.3;
}

.intro-description {
    margin: 0;
    color: var(--gray-600);
    line-height: 1.6;
    font-size: var(--font-size-base);
}

.intro-description strong {
    color: var(--gray-800);
    font-weight: 600;
}

/* Tehniline märkus */
.technical-notice {
    margin-bottom: var(--spacing-6);
}

.notice-content {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    background: var(--gray-50);
    border: 1px solid var(--gray-200);
    border-radius: var(--radius);
    padding: var(--spacing-3) var(--spacing-4);
    font-size: var(--font-size-sm);
    color: var(--gray-600);
    line-height: 1.5;
}

.notice-icon {
    font-size: 1.1rem;
    flex-shrink: 0;
    opacity: 0.8;
}

.notice-text {
    flex: 1;
}

.notice-text strong {
    color: var(--gray-700);
    font-weight: 600;
}

/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
    .intro-content {
        flex-direction: column;
        text-align: center;
        gap: var(--spacing-3);
    }
    
    .intro-icon {
        align-self: center;
        width: 48px;
        height: 48px;
        font-size: 1.8rem;
    }
    
    .intro-text {
        padding-top: 0;
    }
    
    .intro-title {
        font-size: var(--font-size-lg);
        margin-bottom: var(--spacing-2);
    }
    
    .intro-description {
        font-size: var(--font-size-sm);
    }
    
    .notice-content {
        flex-direction: column;
        text-align: center;
        gap: var(--spacing-2);
        padding: var(--spacing-4);
    }
}

@media (max-width: 480px) {
    .intro-card {
        padding: var(--spacing-4);
    }
    
    .intro-title {
        font-size: var(--font-size-base);
        font-weight: 700;
    }
    
    .intro-description {
        font-size: 0.9rem;
    }
    
    .notice-content {
        padding: var(--spacing-3);
        font-size: 0.85rem;
    }
}
</style>
    
<?php include '../includes/footer.php'; ?>