<?php
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;
}

$user_id = $_SESSION['user_id'];
$current_year = date('Y');
$error = '';

// Lae kasutaja andmed
try {
   $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
   $stmt->execute([$user_id]);
   $user = $stmt->fetch(PDO::FETCH_ASSOC);
   $user['ageGroup'] = getAgeGroup($user['birthDate'], $current_year);
} catch(Exception $e) {
   $error = 'Kasutaja andmete laadimine ebaõnnestus';
   error_log('User data error: ' . $e->getMessage());
}

// Lae üldstatistika
$overall_stats = [];
try {
   $stmt = $pdo->prepare("
       SELECT 
           COUNT(DISTINCT r.competitionId) as competitions_count,
           COUNT(r.id) as results_count,
           AVG(r.points) as avg_points,
           MAX(r.points) as best_points,
           MIN(r.points) as worst_points,
           SUM(r.points) as total_points
       FROM results r
       JOIN competitions c ON r.competitionId = c.id
       WHERE r.userId = ? AND strftime('%Y', c.date) = ?
   ");
   $stmt->execute([$user_id, $current_year]);
   $overall_stats = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
   error_log('Overall stats error: ' . $e->getMessage());
   $overall_stats = ['competitions_count' => 0, 'results_count' => 0, 'avg_points' => 0, 'best_points' => 0];
}

// Lae distsipliinide statistika
$discipline_stats = [];
$disciplines = ['koolisoit', 'takistussoit', 'kestvusratsutamine'];

foreach ($disciplines as $discipline) {
   try {
       $stmt = $pdo->prepare("
           SELECT 
               COUNT(r.id) as count,
               AVG(r.points) as avg_points,
               MAX(r.points) as max_points,
               MIN(r.points) as min_points,
               SUM(r.points) as total_points
           FROM results r
           JOIN competitions c ON r.competitionId = c.id
           WHERE r.userId = ? AND r.discipline = ? AND strftime('%Y', c.date) = ?
       ");
       $stmt->execute([$user_id, $discipline, $current_year]);
       $stats = $stmt->fetch(PDO::FETCH_ASSOC);
       
       // Lae viimased tulemused selles distsipliinis
       $stmt = $pdo->prepare("
           SELECT r.points, r.finished, c.date, c.name as competitionName
           FROM results r
           JOIN competitions c ON r.competitionId = c.id
           WHERE r.userId = ? AND r.discipline = ? AND strftime('%Y', c.date) = ?
           ORDER BY c.date ASC
       ");
       $stmt->execute([$user_id, $discipline, $current_year]);
       $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
       
       // Konverteeri punktid floatiks
       foreach ($results as &$result) {
           $result['points'] = (float)$result['points'];
       }
       
       $stats['results'] = $results;
       
       // UUENDUS: Arvuta hooaja arvestuse punktid
       if (!empty($results)) {
           $season_standings = calculateSeasonStandings($results, $discipline);
           $stats['season_standings'] = $season_standings;
       } else {
           $stats['season_standings'] = [
               'total_points' => 0,
               'counted_results' => [],
               'all_results' => [],
               'starts_count' => 0,
               'max_starts' => $GLOBALS['POINTS_SYSTEM'][$discipline]['max_starts']
           ];
       }
       
       $discipline_stats[$discipline] = $stats;
       
   } catch(PDOException $e) {
       error_log("Discipline stats error for $discipline: " . $e->getMessage());
       $discipline_stats[$discipline] = [
           'count' => 0,
           'avg_points' => 0,
           'max_points' => 0,
           'min_points' => 0,
           'total_points' => 0,
           'results' => [],
           'season_standings' => [
               'total_points' => 0,
               'counted_results' => [],
               'all_results' => [],
               'starts_count' => 0,
               'max_starts' => $GLOBALS['POINTS_SYSTEM'][$discipline]['max_starts']
           ]
       ];
   }
}

// Lae kuustatistika
$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, $current_year]);
   $monthly_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
   error_log('Monthly stats error: ' . $e->getMessage());
}

// Lae treeningu statistika
$training_stats = [];
try {
   $stmt = $pdo->prepare("
       SELECT 
           COUNT(*) as total_sessions,
           SUM(duration) as total_minutes,
           AVG(mood) as avg_mood,
           trainingType,
           COUNT(*) as type_count
       FROM training_log
       WHERE userId = ?
       GROUP BY trainingType
   ");
   $stmt->execute([$user_id]);
   $training_by_type = $stmt->fetchAll(PDO::FETCH_ASSOC);
   
   $stmt = $pdo->prepare("
       SELECT 
           COUNT(*) as total_sessions,
           SUM(duration) as total_minutes,
           AVG(mood) as avg_mood
       FROM training_log
       WHERE userId = ?
   ");
   $stmt->execute([$user_id]);
   $training_overall = $stmt->fetch(PDO::FETCH_ASSOC);
   
   $training_stats = [
       'overall' => $training_overall,
       'by_type' => $training_by_type
   ];
   
} catch(PDOException $e) {
   error_log('Training stats error: ' . $e->getMessage());
   $training_stats = ['overall' => ['total_sessions' => 0, 'total_minutes' => 0, 'avg_mood' => 0], 'by_type' => []];
}

$page_title = 'Minu statistika';
$page_description = 'Detailne ülevaade oma tulemustest, progressist ja statistikast.';

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

<main class="stats-main">
   <div class="container">
       <!-- Header -->
       <div class="page-header">
           <div class="page-header-content">
               <h1 class="page-title">Minu statistika</h1>
               <p class="page-subtitle">
                   Detailne ülevaade <?php echo $current_year; ?>. aasta tulemustest
               </p>
           </div>
           <div class="user-info">
               <div class="user-badge">
                   <i class="icon-user"></i>
                   <span><?php echo htmlspecialchars($user['firstName'] . ' ' . $user['lastName']); ?></span>
                   <small><?php echo getAgeGroupName($user['ageGroup']); ?></small>
               </div>
           </div>
       </div>

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

       <!-- Üldstatistika -->
       <div class="overview-stats">
           <div class="stats-grid">
               <div class="stat-card">
                   <div class="stat-icon">
                       <i class="icon-calendar"></i>
                   </div>
                   <div class="stat-content">
                       <div class="stat-number"><?php echo $overall_stats['competitions_count'] ?? 0; ?></div>
                       <div class="stat-label">Võistlust</div>
                   </div>
               </div>

               <div class="stat-card">
                   <div class="stat-icon">
                       <i class="icon-trophy"></i>
                   </div>
                   <div class="stat-content">
                       <div class="stat-number"><?php echo $overall_stats['results_count'] ?? 0; ?></div>
                       <div class="stat-label">Tulemust</div>
                   </div>
               </div>

               <div class="stat-card">
                   <div class="stat-icon">
                       <i class="icon-trending-up"></i>
                   </div>
                   <div class="stat-content">
                       <div class="stat-number">
                           <?php echo $overall_stats['avg_points'] ? formatPoints($overall_stats['avg_points']) : '0.0'; ?>
                       </div>
                       <div class="stat-label">Keskmine punktid</div>
                   </div>
               </div>

               <div class="stat-card">
                   <div class="stat-icon">
                       <i class="icon-star"></i>
                   </div>
                   <div class="stat-content">
                       <div class="stat-number">
                           <?php echo $overall_stats['best_points'] ? formatPoints($overall_stats['best_points']) : '0.0'; ?>
                       </div>
                       <div class="stat-label">Parim tulemus</div>
                   </div>
               </div>
           </div>
       </div>

       <!-- Distsipliinide analüüs -->
       <div class="analysis-section">
           <h2 class="section-title">Distsipliinide analüüs</h2>
           
           <div class="disciplines-grid">
               <?php foreach ($disciplines as $discipline): ?>
                   <?php $stats = $discipline_stats[$discipline]; ?>
                   <div class="discipline-card">
                       <div class="discipline-header">
                           <div class="discipline-icon <?php echo $discipline; ?>">
                               <i class="icon-<?php echo $discipline === 'koolisoit' ? 'target' : ($discipline === 'takistussoit' ? 'zap' : 'map'); ?>"></i>
                           </div>
                           <div class="discipline-info">
                               <h3 class="discipline-name"><?php echo getDisciplineName($discipline); ?></h3>
                               <div class="discipline-count"><?php echo $stats['count']; ?> tulemust</div>
                           </div>
                       </div>

                       <div class="discipline-stats">
                           <div class="stat-row">
                               <span class="stat-label">Kokku punkte:</span>
                               <span class="stat-value"><?php echo formatPoints($stats['total_points']); ?></span>
                           </div>
                           
                           <?php if ($stats['count'] > 0 && $stats['season_standings']['max_starts'] > 0): ?>
                               <!-- UUENDUS: Hooaja arvestuse punktid -->
                               <div class="stat-row season-highlight">
                                   <div class="season-info">
                                       <span class="stat-label">Hooaja arvestus:</span>
                                       <span class="stat-hint"><?php echo count($stats['season_standings']['counted_results']); ?>/<?php echo $stats['season_standings']['max_starts']; ?> parimat</span>
                                   </div>
                                   <span class="stat-value primary"><?php echo formatPoints($stats['season_standings']['total_points']); ?></span>
                               </div>
                           <?php endif; ?>
                           
                           <div class="stat-row">
                               <span class="stat-label">Keskmine:</span>
                               <span class="stat-value"><?php echo formatPoints($stats['avg_points']); ?></span>
                           </div>
                           <div class="stat-row">
                               <span class="stat-label">Parim:</span>
                               <span class="stat-value best"><?php echo formatPoints($stats['max_points']); ?></span>
                           </div>
                           <?php if ($stats['count'] > 1): ?>
                               <div class="stat-row">
                                   <span class="stat-label">Halvim:</span>
                                   <span class="stat-value worst"><?php echo formatPoints($stats['min_points']); ?></span>
                               </div>
                           <?php endif; ?>
                       </div>

                       <?php if (!empty($stats['results'])): ?>
                           <div class="progress-chart">
                               <div class="chart-title">Progress</div>
                               <div class="chart-container">
                                   <?php 
                                   $max_points = max(array_column($stats['results'], 'points'));
                                   $max_points = $max_points > 0 ? $max_points : 1;
                                   
                                   // Leia millised tulemused on arvestatud
                                   $counted_points = array_column($stats['season_standings']['counted_results'], 'points');
                                   
                                   foreach ($stats['results'] as $index => $result): 
                                       $is_counted = in_array($result['points'], $counted_points);
                                   ?>
                                       <div class="chart-bar <?php echo $is_counted ? 'counted' : ''; ?>" 
                                            style="height: <?php echo ($result['points'] / $max_points) * 100; ?>%"
                                            title="<?php echo formatPoints($result['points']); ?>p - <?php echo htmlspecialchars($result['competitionName']); ?><?php echo $is_counted ? ' (arvestatud)' : ''; ?>">
                                       </div>
                                   <?php endforeach; ?>
                               </div>
                               <?php if ($stats['count'] > 0 && $stats['season_standings']['max_starts'] > 0): ?>
                                   <div class="chart-legend">
                                       <div class="legend-item">
                                           <div class="legend-box counted"></div>
                                           <span>Hooaja arvestusse</span>
                                       </div>
                                       <div class="legend-item">
                                           <div class="legend-box"></div>
                                           <span>Ülejäänud</span>
                                       </div>
                                   </div>
                               <?php endif; ?>
                           </div>
                       <?php endif; ?>
                   </div>
               <?php endforeach; ?>
           </div>
       </div>

       <!-- Kuustatistika -->
       <?php if (!empty($monthly_stats)): ?>
       <div class="monthly-section">
           <h2 class="section-title">Hooaja aktiivsus</h2>
           
           <div class="monthly-chart-container">
               <div class="monthly-chart">
                   <?php 
                   $months = ['01' => 'Jan', '02' => 'Veeb', '03' => 'Märts', '04' => 'Apr', 
                             '05' => 'Mai', '06' => 'Juuni', '07' => 'Juuli', '08' => 'Aug',
                             '09' => 'Sept', '10' => 'Okt', '11' => 'Nov', '12' => 'Dets'];
                   $max_results = max(array_column($monthly_stats, 'results_count'));
                   $max_points = max(array_column($monthly_stats, 'max_points'));
                   
                   foreach ($monthly_stats as $month): 
                   ?>
                       <div class="month-column">
                           <div class="month-bars">
                               <div class="results-bar" 
                                    style="height: <?php echo $max_results > 0 ? ($month['results_count'] / $max_results) * 100 : 0; ?>%"
                                    title="<?php echo $month['results_count']; ?> tulemust">
                               </div>
                               <div class="points-bar" 
                                    style="height: <?php echo $max_points > 0 ? ($month['max_points'] / $max_points) * 100 : 0; ?>%"
                                    title="Parim: <?php echo formatPoints($month['max_points']); ?>p">
                               </div>
                           </div>
                           <div class="month-label">
                               <?php echo $months[$month['month']]; ?>
                           </div>
                           <div class="month-data">
                               <div class="month-results"><?php echo $month['results_count']; ?></div>
                               <div class="month-avg">Ø <?php echo formatPoints($month['avg_points']); ?>p</div>
                           </div>
                       </div>
                   <?php endforeach; ?>
               </div>
               
               <div class="chart-legend">
                   <div class="legend-item">
                       <div class="legend-color results"></div>
                       <span>Tulemuste arv</span>
                   </div>
                   <div class="legend-item">
                       <div class="legend-color points"></div>
                       <span>Punktide tase</span>
                   </div>
               </div>
           </div>
       </div>
       <?php endif; ?>

       <!-- Treeningu statistika -->
       <?php if ($training_stats['overall']['total_sessions'] > 0): ?>
       <div class="training-section">
           <h2 class="section-title">Treeningu statistika</h2>
           
           <div class="training-overview">
               <div class="training-stat">
                   <div class="training-icon">
                       <i class="icon-calendar"></i>
                   </div>
                   <div class="training-info">
                       <div class="training-value"><?php echo $training_stats['overall']['total_sessions']; ?></div>
                       <div class="training-label">Treeningu korda</div>
                   </div>
               </div>
               
               <div class="training-stat">
                   <div class="training-icon">
                       <i class="icon-clock"></i>
                   </div>
                   <div class="training-info">
                       <div class="training-value">
                           <?php echo $training_stats['overall']['total_minutes'] ? round($training_stats['overall']['total_minutes'] / 60) : 0; ?>h
                       </div>
                       <div class="training-label">Tunde kokku</div>
                   </div>
               </div>
               
               <div class="training-stat">
                   <div class="training-icon">
                       <i class="icon-smile"></i>
                   </div>
                   <div class="training-info">
                       <div class="training-value">
                           <?php echo $training_stats['overall']['avg_mood'] ? number_format($training_stats['overall']['avg_mood'], 1) : '0.0'; ?>/5
                           <?php echo getMoodEmoji(round($training_stats['overall']['avg_mood'])); ?>
                       </div>
                       <div class="training-label">Keskmine meeleolu</div>
                   </div>
               </div>
           </div>

           <?php if (!empty($training_stats['by_type'])): ?>
           <div class="training-types">
               <h3>Treeningu tüübid</h3>
               <div class="training-types-grid">
                   <?php foreach ($training_stats['by_type'] as $type): ?>
                       <div class="training-type-card">
                           <div class="type-name">
                               <?php 
                               $type_names = [
                                   'koolisoit' => 'Koolisõit',
                                   'takistussoit' => 'Takistussõit',
                                   'ratsastus' => 'Ratsastus',
                                   'kestvusratsutamine' => 'Kestvusratsutamine',
                                   'muu' => 'Muu'
                               ];
                               echo $type_names[$type['trainingType']] ?? $type['trainingType'];
                               ?>
                           </div>
                           <div class="type-count"><?php echo $type['type_count']; ?> korda</div>
                       </div>
                   <?php endforeach; ?>
               </div>
           </div>
           <?php endif; ?>
       </div>
       <?php endif; ?>

               <!-- Isiklikud Insights -->
        <?php 
        // Arvuta insights andmed
        $insights_data = calculatePersonalInsights($user_id, $current_year, $pdo);
        if (!empty($insights_data)): 
        ?>
        <div class="insights-section">
            <div class="insights-card">
                <div class="insights-header">
                    <h2 class="insights-title">
                        <i class="icon-trending-up"></i>
                        Sinu isiklikud insights
                    </h2>
                    <p class="insights-subtitle">
                        Huvitavad mustrid ja statistika sinu andmete põhjal
                    </p>
                </div>
                
                <div class="insights-content">
                    <!-- Osaluse analüüs -->
                    <?php if (!empty($insights_data['participation'])): ?>
                    <div class="insight-section">
                        <h3 class="insight-section-title">
                            <i class="icon-map-pin"></i>
                            Sinu võistlusmaailm
                        </h3>
                        <div class="insight-stats-grid">
                            <div class="insight-stat">
                                <div class="insight-stat-number"><?php echo $insights_data['participation']['unique_locations']; ?></div>
                                <div class="insight-stat-label">Erinevat kohta</div>
                            </div>
                            <div class="insight-stat">
                                <div class="insight-stat-number"><?php echo $insights_data['participation']['favorite_location_count']; ?></div>
                                <div class="insight-stat-label">Korda lemmikkohas</div>
                            </div>
                            <div class="insight-stat">
                                <div class="insight-stat-number"><?php echo $insights_data['participation']['new_locations_this_year']; ?></div>
                                <div class="insight-stat-label">Uut kohta sel aastal</div>
                            </div>
                        </div>
                        <div class="insight-highlight">
                            <i class="icon-star"></i>
                            <span>Lemmikkoht: <strong><?php echo htmlspecialchars($insights_data['participation']['favorite_location']); ?></strong></span>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Distsipliinide eelistused -->
                    <?php if (!empty($insights_data['disciplines'])): ?>
                    <div class="insight-section">
                        <h3 class="insight-section-title">
                            <i class="icon-target"></i>
                            Sinu eelistused
                        </h3>
                        <div class="disciplines-insights">
                            <?php foreach ($insights_data['disciplines'] as $discipline => $data): ?>
                                <?php if (!empty($data)): ?>
                                <div class="discipline-insight <?php echo $discipline; ?>">
                                    <div class="discipline-insight-header">
                                        <div class="discipline-insight-icon">
                                            <i class="icon-<?php echo $discipline === 'koolisoit' ? 'target' : ($discipline === 'takistussoit' ? 'zap' : 'map'); ?>"></i>
                                        </div>
                                        <h4><?php echo getDisciplineName($discipline); ?></h4>
                                    </div>
                                    <div class="discipline-insight-content">
                                        <?php if ($discipline === 'takistussoit' && !empty($data['height_stats'])): ?>
                                            <div class="insight-item">
                                                <span class="insight-label">Lemmikkõrgus:</span>
                                                <span class="insight-value"><?php echo $data['height_stats']['favorite']; ?>cm (<?php echo $data['height_stats']['count']; ?> korda)</span>
                                            </div>
                                            <div class="insight-item">
                                                <span class="insight-label">Kõrgeim proovitud:</span>
                                                <span class="insight-value"><?php echo $data['height_stats']['highest']; ?>cm</span>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($discipline === 'koolisoit' && !empty($data['scheme_stats'])): ?>
                                            <div class="insight-item">
                                                <span class="insight-label">Lemmikskeem:</span>
                                                <span class="insight-value"><?php echo $data['scheme_stats']['favorite']; ?> (<?php echo $data['scheme_stats']['count']; ?> korda)</span>
                                            </div>
                                            <?php if (!empty($data['scheme_stats']['best_performing'])): ?>
                                            <div class="insight-item">
                                                <span class="insight-label">Parim skeem:</span>
                                                <span class="insight-value"><?php echo $data['scheme_stats']['best_performing']; ?> (<?php echo number_format($data['scheme_stats']['best_avg'], 1); ?>%)</span>
                                            </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <?php if ($discipline === 'kestvusratsutamine' && !empty($data['distance_stats'])): ?>
                                            <div class="insight-item">
                                                <span class="insight-label">Lemmikdistants:</span>
                                                <span class="insight-value"><?php echo $data['distance_stats']['favorite']; ?>km</span>
                                            </div>
                                            <div class="insight-item">
                                                <span class="insight-label">Kokku "ratsutatud":</span>
                                                <span class="insight-value"><?php echo number_format($data['distance_stats']['total'], 1); ?>km</span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Tulemuste mustrid -->
                    <?php if (!empty($insights_data['performance'])): ?>
                    <div class="insight-section">
                        <h3 class="insight-section-title">
                            <i class="icon-trending-up"></i>
                            Sinu tulemuste mustrid
                        </h3>
                        <div class="performance-insights">
                            <?php if (!empty($insights_data['performance']['best_month'])): ?>
                            <div class="insight-highlight success">
                                <i class="icon-calendar"></i>
                                <span>Parim kuu: <strong><?php echo $insights_data['performance']['best_month']['name']; ?></strong> (keskmine <?php echo number_format($insights_data['performance']['best_month']['avg'], 1); ?>p)</span>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($insights_data['performance']['best_location'])): ?>
                            <div class="insight-highlight primary">
                                <i class="icon-map-pin"></i>
                                <span>Parim koht: <strong><?php echo htmlspecialchars($insights_data['performance']['best_location']['name']); ?></strong> (keskmine <?php echo number_format($insights_data['performance']['best_location']['avg'], 1); ?>p)</span>
                            </div>
                            <?php endif; ?>
                            
                            <div class="insight-stats-row">
                                <div class="insight-mini-stat">
                                    <div class="mini-stat-number"><?php echo $insights_data['performance']['finish_rate']; ?>%</div>
                                    <div class="mini-stat-label">Lõpetamise määr</div>
                                </div>
                                <?php if (!empty($insights_data['performance']['best_placement'])): ?>
                                <div class="insight-mini-stat">
                                    <div class="mini-stat-number"><?php echo $insights_data['performance']['best_placement']; ?>.</div>
                                    <div class="mini-stat-label">Parim koht</div>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($insights_data['performance']['top10_rate'])): ?>
                                <div class="insight-mini-stat">
                                    <div class="mini-stat-number"><?php echo $insights_data['performance']['top10_rate']; ?>%</div>
                                    <div class="mini-stat-label">TOP 10 määr</div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Soovitused -->
                    <?php if (!empty($insights_data['recommendations'])): ?>
                    <div class="insight-section">
                        <h3 class="insight-section-title">
                            <i class="icon-lightbulb"></i>
                            Isiklikud soovitused
                        </h3>
                        <div class="recommendations-list">
                            <?php foreach ($insights_data['recommendations'] as $recommendation): ?>
                            <div class="recommendation-item">
                                <div class="recommendation-icon"><?php echo $recommendation['icon']; ?></div>
                                <div class="recommendation-text"><?php echo htmlspecialchars($recommendation['text']); ?></div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Kiired lingid -->
        <div class="quick-links">
            <div class="links-card">
                <h3>Kiired toimingud</h3>
                <div class="links-grid">
                    <a href="<?php echo url('athlete/results.php'); ?>" class="quick-link">
                        <i class="icon-trophy"></i>
                        <span>Vaata tulemusi</span>
                    </a>
                    <a href="<?php echo url('athlete/training.php'); ?>" class="quick-link">
                        <i class="icon-calendar"></i>
                        <span>Treeningu päevik</span>
                    </a>
                    <a href="<?php echo url('public/rankings.php'); ?>" class="quick-link">
                        <i class="icon-list"></i>
                        <span>Hooaja tabelid</span>
                    </a>
                    <a href="<?php echo url('athlete/dashboard.php'); ?>" class="quick-link">
                        <i class="icon-user"></i>
                        <span>Armatuurlaud</span>
                    </a>
                </div>
            </div>
        </div>
   </div>
</main>

<style>
/* Stats Page Styles */
.stats-main {
   padding: var(--spacing-8) 0;
   min-height: 100vh;
}

.page-header {
   display: flex;
   justify-content: space-between;
   align-items: flex-end;
   margin-bottom: var(--spacing-8);
   gap: var(--spacing-4);
}

.page-title {
   margin-bottom: var(--spacing-2);
}

.page-subtitle {
   color: var(--gray-600);
   font-size: var(--font-size-lg);
   margin: 0;
}

.user-badge {
   display: flex;
   align-items: center;
   gap: var(--spacing-2);
   padding: var(--spacing-3) var(--spacing-4);
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
}

.user-badge i {
   color: var(--primary-color);
}

.user-badge small {
   color: var(--gray-500);
   font-size: var(--font-size-xs);
}

/* Overview Stats */
.overview-stats {
   margin-bottom: var(--spacing-8);
}

.stats-grid {
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
   gap: var(--spacing-6);
}

.stat-card {
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
   padding: var(--spacing-6);
   display: flex;
   align-items: center;
   gap: var(--spacing-4);
   transition: transform var(--transition-fast);
}

.stat-card:hover {
   transform: translateY(-2px);
}

.stat-icon {
   width: 48px;
   height: 48px;
   background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
   color: white;
   border-radius: var(--radius-lg);
   display: flex;
   align-items: center;
   justify-content: center;
   font-size: 20px;
}

.stat-number {
   font-size: var(--font-size-2xl);
   font-weight: 700;
   color: var(--gray-900);
}

.stat-label {
   color: var(--gray-600);
   font-size: var(--font-size-sm);
}

/* Section Titles */
.section-title {
   font-size: var(--font-size-2xl);
   font-weight: 600;
   margin-bottom: var(--spacing-6);
   color: var(--gray-900);
}

/* Disciplines */
.analysis-section {
   margin-bottom: var(--spacing-8);
}

.disciplines-grid {
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
   gap: var(--spacing-6);
}

.discipline-card {
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
   padding: var(--spacing-6);
   transition: transform var(--transition-fast);
}

.discipline-card:hover {
   transform: translateY(-2px);
}

.discipline-header {
   display: flex;
   align-items: center;
   gap: var(--spacing-4);
   margin-bottom: var(--spacing-4);
}

.discipline-icon {
   width: 48px;
   height: 48px;
   border-radius: var(--radius-lg);
   display: flex;
   align-items: center;
   justify-content: center;
   color: white;
   font-size: 20px;
}

.discipline-icon.koolisoit { background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); }
.discipline-icon.takistussoit { background: linear-gradient(135deg, var(--success-color), #047857); }
.discipline-icon.kestvusratsutamine { background: linear-gradient(135deg, #8b5cf6, #7c3aed); }

.discipline-name {
   margin: 0 0 var(--spacing-1);
   font-size: var(--font-size-lg);
   font-weight: 600;
}

.discipline-count {
   color: var(--gray-600);
   font-size: var(--font-size-sm);
}

.discipline-stats {
   margin-bottom: var(--spacing-4);
}

.stat-row {
   display: flex;
   justify-content: space-between;
   align-items: center;
   padding: var(--spacing-2) 0;
   border-bottom: 1px solid var(--gray-100);
}

.stat-row:last-child {
   border-bottom: none;
}

/* UUENDUS: Hooaja arvestuse highlight */
.stat-row.season-highlight {
   background: color-mix(in srgb, var(--primary-color) 8%, transparent);
   border: 1px solid color-mix(in srgb, var(--primary-color) 20%, transparent);
   border-radius: var(--radius);
   padding: var(--spacing-3);
   margin: var(--spacing-2) 0;
}

.season-info {
   display: flex;
   flex-direction: column;
   gap: var(--spacing-1);
}

.stat-hint {
   font-size: var(--font-size-xs);
   color: var(--gray-600);
}

.stat-value {
   font-weight: 600;
   color: var(--gray-900);
}

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

.stat-value.best {
   color: var(--success-color);
}

.stat-value.worst {
   color: var(--warning-color);
}

/* Progress Chart */
.progress-chart {
   margin-top: var(--spacing-4);
}

.chart-title {
   font-weight: 500;
   color: var(--gray-700);
   margin-bottom: var(--spacing-3);
   font-size: var(--font-size-sm);
}

.chart-container {
   display: flex;
   align-items: end;
   gap: 2px;
   height: 60px;
   padding: var(--spacing-2) 0;
}

.chart-bar {
   flex: 1;
   background: linear-gradient(to top, var(--gray-400), var(--gray-300));
   border-radius: 2px 2px 0 0;
   min-height: 4px;
   transition: all var(--transition-fast);
   cursor: pointer;
   opacity: 0.6;
}

.chart-bar.counted {
   background: linear-gradient(to top, var(--primary-color), var(--primary-light));
   opacity: 1;
}

.chart-bar:hover {
   opacity: 1;
}

/* Chart Legend */
.chart-legend {
   display: flex;
   justify-content: center;
   gap: var(--spacing-4);
   margin-top: var(--spacing-3);
}

.legend-item {
   display: flex;
   align-items: center;
   gap: var(--spacing-2);
   font-size: var(--font-size-xs);
   color: var(--gray-600);
}

.legend-box {
   width: 16px;
   height: 12px;
   border-radius: 2px;
   background: linear-gradient(to right, var(--gray-400), var(--gray-300));
   opacity: 0.6;
}

.legend-box.counted {
   background: linear-gradient(to right, var(--primary-color), var(--primary-light));
   opacity: 1;
}

/* Monthly Chart */
.monthly-section {
   margin-bottom: var(--spacing-8);
}

.monthly-chart-container {
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
   padding: var(--spacing-6);
}

.monthly-chart {
   display: flex;
   align-items: end;
   gap: var(--spacing-4);
   height: 200px;
   margin-bottom: var(--spacing-4);
}

.month-column {
   flex: 1;
   display: flex;
   flex-direction: column;
   align-items: center;
   gap: var(--spacing-2);
   height: 100%;
}

.month-bars {
   flex: 1;
   display: flex;
   align-items: end;
   gap: 2px;
   width: 100%;
}

.results-bar,
.points-bar {
   flex: 1;
   min-height: 4px;
   border-radius: 2px 2px 0 0;
   transition: all var(--transition-fast);
}

.results-bar {
   background: linear-gradient(to top, var(--primary-color), var(--primary-light));
}

.points-bar {
   background: linear-gradient(to top, var(--success-color), #10b981);
}

.month-label {
   font-size: var(--font-size-xs);
   color: var(--gray-600);
   font-weight: 500;
}

.month-data {
   text-align: center;
}

.month-results {
   font-weight: 600;
   color: var(--gray-900);
   font-size: var(--font-size-sm);
}

.month-avg {
   font-size: var(--font-size-xs);
   color: var(--gray-500);
}

.legend-color {
   width: 16px;
   height: 16px;
   border-radius: var(--radius-sm);
}

.legend-color.results {
   background: var(--primary-color);
}

.legend-color.points {
   background: var(--success-color);
}

/* Training Section */
.training-section {
   margin-bottom: var(--spacing-8);
}

.training-overview {
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
   gap: var(--spacing-4);
   margin-bottom: var(--spacing-6);
}

.training-stat {
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
   padding: var(--spacing-5);
   display: flex;
   align-items: center;
   gap: var(--spacing-3);
}

.training-icon {
   width: 40px;
   height: 40px;
   background: linear-gradient(135deg, var(--success-color), #047857);
   color: white;
   border-radius: var(--radius);
   display: flex;
   align-items: center;
   justify-content: center;
   font-size: 16px;
}

.training-value {
   font-size: var(--font-size-xl);
   font-weight: 700;
   color: var(--gray-900);
}

.training-label {
   color: var(--gray-600);
   font-size: var(--font-size-sm);
}

.training-types {
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
   padding: var(--spacing-6);
}

.training-types h3 {
   margin-bottom: var(--spacing-4);
   color: var(--gray-900);
}

.training-types-grid {
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
   gap: var(--spacing-4);
}

.training-type-card {
   text-align: center;
   padding: var(--spacing-4);
   border: 1px solid var(--gray-200);
   border-radius: var(--radius);
}

.type-name {
   font-weight: 500;
   color: var(--gray-900);
   margin-bottom: var(--spacing-1);
}

.type-count {
   color: var(--gray-600);
   font-size: var(--font-size-sm);
}

/* Insights Section */
.insights-section {
    margin-bottom: var(--spacing-8);
}

.insights-card {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    overflow: hidden;
}

.insights-header {
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    padding: var(--spacing-6);
    text-align: center;
}

.insights-title {
    margin: 0 0 var(--spacing-2);
    font-size: var(--font-size-xl);
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: var(--spacing-2);
}

.insights-subtitle {
    margin: 0;
    opacity: 0.9;
    font-size: var(--font-size-sm);
}

.insights-content {
    padding: var(--spacing-6);
}

.insight-section {
    margin-bottom: var(--spacing-8);
}

.insight-section:last-child {
    margin-bottom: 0;
}

.insight-section-title {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    margin: 0 0 var(--spacing-4);
    font-size: var(--font-size-lg);
    font-weight: 600;
    color: var(--gray-900);
}

.insight-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: var(--spacing-4);
    margin-bottom: var(--spacing-4);
}

.insight-stat {
    text-align: center;
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-radius: var(--radius);
    border: 1px solid var(--gray-200);
}

.insight-stat-number {
    font-size: var(--font-size-xl);
    font-weight: 700;
    color: var(--primary-color);
    margin-bottom: var(--spacing-1);
}

.insight-stat-label {
    font-size: var(--font-size-sm);
    color: var(--gray-600);
    font-weight: 500;
}

.insight-highlight {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    padding: var(--spacing-3) var(--spacing-4);
    background: var(--gray-50);
    border-radius: var(--radius);
    border-left: 4px solid var(--primary-color);
    font-size: var(--font-size-sm);
    color: var(--gray-700);
}

.insight-highlight.success {
    background: color-mix(in srgb, var(--success-color) 5%, transparent);
    border-left-color: var(--success-color);
    color: var(--success-color);
}

.insight-highlight.primary {
    background: color-mix(in srgb, var(--primary-color) 5%, transparent);
    border-left-color: var(--primary-color);
    color: var(--primary-color);
}

.disciplines-insights {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: var(--spacing-4);
}

.discipline-insight {
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-lg);
    overflow: hidden;
    transition: all var(--transition-fast);
}

.discipline-insight:hover {
    border-color: var(--primary-color);
    box-shadow: var(--shadow);
}

.discipline-insight-header {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-bottom: 1px solid var(--gray-200);
}

.discipline-insight-icon {
    width: 40px;
    height: 40px;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
}

.discipline-insight.koolisoit .discipline-insight-icon { 
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); 
}
.discipline-insight.takistussoit .discipline-insight-icon { 
    background: linear-gradient(135deg, var(--success-color), #047857); 
}
.discipline-insight.kestvusratsutamine .discipline-insight-icon { 
    background: linear-gradient(135deg, #8b5cf6, #7c3aed); 
}

.discipline-insight-header h4 {
    margin: 0;
    font-size: var(--font-size-base);
    font-weight: 600;
    color: var(--gray-900);
}

.discipline-insight-content {
    padding: var(--spacing-4);
}

.insight-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-2) 0;
    border-bottom: 1px solid var(--gray-100);
}

.insight-item:last-child {
    border-bottom: none;
}

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

.insight-value {
    font-size: var(--font-size-sm);
    color: var(--gray-900);
    font-weight: 600;
}

.performance-insights {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-4);
}

.insight-stats-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    gap: var(--spacing-3);
}

.insight-mini-stat {
    text-align: center;
    padding: var(--spacing-3);
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius);
}

.mini-stat-number {
    font-size: var(--font-size-lg);
    font-weight: 700;
    color: var(--primary-color);
    margin-bottom: var(--spacing-1);
}

.mini-stat-label {
    font-size: var(--font-size-xs);
    color: var(--gray-600);
    font-weight: 500;
}

.recommendations-list {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
}

.recommendation-item {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-3);
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-radius: var(--radius);
    border-left: 4px solid var(--warning-color);
}

.recommendation-icon {
    width: 24px;
    height: 24px;
    flex-shrink: 0;
    margin-top: 2px;
    color: var(--warning-color);
    display: flex;
    align-items: center;
    justify-content: center;
}

.recommendation-icon i {
    font-size: 18px;
}

.recommendation-text {
    font-size: var(--font-size-sm);
    color: var(--gray-700);
    line-height: 1.5;
}

/* Responsive */
@media (max-width: 768px) {
    .insights-content {
        padding: var(--spacing-4);
    }
    
    .insight-stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .disciplines-insights {
        grid-template-columns: 1fr;
    }
    
    .insight-stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .insight-item {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-1);
    }
}

@media (max-width: 480px) {
    .insights-header {
        padding: var(--spacing-4);
    }
    
    .insights-title {
        font-size: var(--font-size-lg);
        flex-direction: column;
        gap: var(--spacing-1);
    }
    
    .insight-stats-grid {
        grid-template-columns: 1fr;
    }
    
    .insight-stats-row {
        grid-template-columns: 1fr;
    }
}

/* Quick Links */
.quick-links {
    margin-top: var(--spacing-8);
}

.links-card {
   background: white;
   border-radius: var(--radius-lg);
   box-shadow: var(--shadow);
   padding: var(--spacing-6);
}

.links-card h3 {
   margin-bottom: var(--spacing-4);
   color: var(--gray-900);
}

.links-grid {
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
   gap: var(--spacing-4);
}

.quick-link {
   display: flex;
   align-items: center;
   gap: var(--spacing-3);
   padding: var(--spacing-4);
   border: 1px solid var(--gray-200);
   border-radius: var(--radius);
   color: var(--gray-700);
   text-decoration: none;
   transition: all var(--transition-fast);
}

.quick-link:hover {
   border-color: var(--primary-color);
   background: var(--gray-50);
   color: var(--primary-color);
}

.quick-link i {
   color: var(--primary-color);
}

/* Responsive */
@media (max-width: 768px) {
   .page-header {
       flex-direction: column;
       align-items: stretch;
       gap: var(--spacing-4);
   }
   
   .disciplines-grid {
       grid-template-columns: 1fr;
   }
   
   .training-overview {
       grid-template-columns: 1fr;
   }
   
   .monthly-chart {
       gap: var(--spacing-2);
   }
   
   .chart-legend {
       flex-direction: column;
       align-items: center;
       gap: var(--spacing-2);
   }
   
   /* Hooaja arvestuse responsive */
   .stat-row.season-highlight {
       flex-direction: column;
       align-items: flex-start;
       gap: var(--spacing-2);
   }
   
   .stat-row.season-highlight .stat-value.primary {
       align-self: flex-end;
   }
}

@media (max-width: 480px) {
   .stats-grid {
       grid-template-columns: 1fr;
   }
   
   .monthly-chart {
       gap: var(--spacing-1);
   }
   
   .month-label {
       font-size: 10px;
   }
   
   .links-grid {
       grid-template-columns: 1fr;
   }
}
</style>

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