<?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'];
$error = '';
$success = '';

// KASUTA SAMA LOGIKAT MIS ADMINIL - TULEMUSE SALVESTAMINE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_result'])) {
    try {
        $result_id = getPost('result_id');
        $competitionId = getPost('competitionId');
        $discipline = getPost('discipline');
        $finished = isset($_POST['finished']) ? 1 : 0;
        $placement = getPost('placement');
        $notes = getPost('notes');
        
        // Distsipliini spetsiifilised väljad
        $percentage = getPost('percentage');
        $scheme = getPost('scheme');
        $faultPoints = getPost('faultPoints');
        $distance = getPost('distance');
        $height = getPost('height');
        $time_input = getPost('time_input');
        $pulse = getPost('pulse');
        
        if (empty($competitionId) || empty($discipline)) {
            throw new Exception('Võistlus ja distsipliin on kohustuslikud');
        }
        
        // PIIRANG: Sportlane saab muuta ainult oma tulemusi
        if ($result_id) {
            $stmt = $pdo->prepare("SELECT userId FROM results WHERE id = ?");
            $stmt->execute([$result_id]);
            $existing_result = $stmt->fetch();
            if (!$existing_result || $existing_result['userId'] != $user_id) {
                throw new Exception('Sa saad muuta ainult oma tulemusi');
            }
        }
        
        // Kontrolli distsipliini lubatavust võistlusel - SAMA LOOGIKA MIS ADMINIL
        $stmt = $pdo->prepare("SELECT disciplines, discipline FROM competitions WHERE id = ?");
        $stmt->execute([$competitionId]);
        $competition = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$competition) {
            throw new Exception('Võistlust ei leitud');
        }
        
        $allowed_disciplines = [];
        if ($competition['disciplines']) {
            $allowed_disciplines = json_decode($competition['disciplines'], true) ?: [];
        } else {
            $allowed_disciplines = [$competition['discipline']];
        }
        
        if (!in_array($discipline, $allowed_disciplines)) {
            throw new Exception("Distsipliin '$discipline' ei ole sellel võistlusel lubatud");
        }
        
        // KASUTA SAMA PUNKTIDE ARVUTAMISE LOGIKAT MIS ADMINIL
        $points_data = [
            'finished' => $finished,
            'placement' => $placement ? (int)$placement : null
        ];
        
        if ($discipline === 'koolisoit') {
            if (empty($percentage) || empty($scheme)) {
                throw new Exception('Koolisõidu puhul on protsent ja skeem kohustuslikud');
            }
            $points_data['percentage'] = (float)$percentage;
            $points_data['scheme'] = $scheme;
            
        } elseif ($discipline === 'takistussoit') {
            if ($faultPoints === '') {
                throw new Exception('Takistussõidu puhul on karistuspunktid kohustuslikud');
            }
            $points_data['fault_points'] = (int)$faultPoints;
            
            // LISATUD: Valideeri takistussõidu aja sisend
            if (!empty($time_input) && !validateJumpingTimeInput($time_input)) {
                throw new Exception('Takistussõidu aeg peab olema formaadis sekundid.sajandikud (nt. 65.42)');
            }
            
        } elseif ($discipline === 'kestvusratsutamine') {
            if (empty($distance)) {
                throw new Exception('Kestvusratsutamise puhul on distants kohustuslik');
            }
            
            // LISATUD: Valideeri numbriline distants
            if (!validateEnduranceDistance($distance)) {
                throw new Exception('Distants peab olema 5-200 km vahemikus');
            }
            
            $points_data['distance'] = (float)$distance;
        }
        
        $calculated_points = calculatePoints($discipline, $points_data);
        $total_points = $calculated_points['points'];
        
        // PARANDATUD: Konverteerib aeg sekunditeks distsipliini järgi
        $time_seconds = parseTimeToSeconds($time_input, $discipline);
        
        if ($result_id) {
            // Uuenda olemasolevat tulemust (ainult oma)
            $sql = "UPDATE results SET 
                    competitionId = ?, discipline = ?, points = ?, 
                    finished = ?, placement = ?, notes = ?, 
                    percentage = ?, scheme = ?, faultPoints = ?, 
                    distance = ?, height = ?, time_seconds = ?, pulse = ?,
                    updatedAt = CURRENT_TIMESTAMP 
                    WHERE id = ? AND userId = ?";
            $params = [
                $competitionId, $discipline, $total_points,
                $finished, $placement, $notes,
                $percentage, $scheme, $faultPoints,
                $distance, $height, $time_seconds, $pulse,
                $result_id, $user_id
            ];
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $success = 'Tulemus edukalt uuendatud!';
            
        } else {
            // Lisa uus tulemus (automaatselt oma userid)
            $sql = "INSERT INTO results 
                    (userId, competitionId, discipline, points, finished, placement, notes, 
                     percentage, scheme, faultPoints, distance, height, time_seconds, pulse) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $params = [
                $user_id, $competitionId, $discipline, $total_points,
                $finished, $placement, $notes,
                $percentage, $scheme, $faultPoints,
                $distance, $height, $time_seconds, $pulse
            ];
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $success = 'Uus tulemus edukalt lisatud!';
            logActivity($user_id, 'result_added', "Result added by athlete");
        }
        
    } catch(Exception $e) {
        $error = 'Tulemuse salvestamine ebaõnnestus: ' . $e->getMessage();
    }
}

// KASUTA SAMA LOGIKAT MIS ADMINIL - TULEMUSE KUSTUTAMINE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_result'])) {
    $result_id = getPost('result_id');
    
    try {
        $stmt = $pdo->prepare("DELETE FROM results WHERE id = ? AND userId = ?");
        $stmt->execute([$result_id, $user_id]);
        
        if ($stmt->rowCount() > 0) {
            $success = 'Tulemus edukalt kustutatud!';
            logActivity($user_id, 'result_deleted', "Result deleted by athlete");
        } else {
            $error = 'Sa saad kustutada ainult oma tulemusi';
        }
        
    } catch(PDOException $e) {
        $error = 'Tulemuse kustutamine ebaõnnestus: ' . $e->getMessage();
    }
}

// KASUTA SAMA LOGIKAT MIS ADMINIL - VÕISTLUSE LISAMINE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_competition'])) {
    $name = getPost('name');
    $location = getPost('location');
    $selected_disciplines = $_POST['disciplines'] ?? [];
    $description = getPost('description');
    
    // PARANDATUD: Multi-day toe lisamine sportlasele
    $is_multi_day = isset($_POST['is_multi_day']) ? 1 : 0;
    $start_date = null;
    $end_date = null;
    $legacy_date = null;
    
    if ($is_multi_day) {
        $start_date = getPost('start_date');
        $end_date = getPost('end_date');
        
        if (empty($start_date) || empty($end_date)) {
            $error = 'Mitme päeva pikkuse võistluse puhul on algus- ja lõppkuupäev kohustuslikud';
        } elseif ($start_date > $end_date) {
            $error = 'Alguskuupäev ei saa olla hilisem kui lõppkuupäev';
        } else {
            $legacy_date = $start_date;
        }
    } else {
        $legacy_date = getPost('date');
        $start_date = $legacy_date;
        $end_date = $legacy_date;
    }
    
    if (empty($name) || empty($legacy_date) || empty($selected_disciplines)) {
        $error = 'Nimi, kuupäev ja vähemalt üks distsipliin on kohustuslikud';
    } else {
        $valid_disciplines = ['koolisoit', 'takistussoit', 'kestvusratsutamine'];
        foreach ($selected_disciplines as $disc) {
            if (!in_array($disc, $valid_disciplines)) {
                $error = 'Kehtetu distsipliin: ' . $disc;
                break;
            }
        }
        
        if (!$error) {
            try {
                $disciplines_json = json_encode($selected_disciplines);
                $primary_discipline = $selected_disciplines[0];
                
                $stmt = $pdo->prepare("
                    INSERT INTO competitions (name, date, start_date, end_date, is_multi_day, location, discipline, disciplines, description)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $name, $legacy_date, $start_date, $end_date, $is_multi_day,
                    $location, $primary_discipline, $disciplines_json, $description
                ]);
                
                $success = 'Võistlus edukalt loodud! Nüüd saad lisada oma tulemuse.';
                logActivity($user_id, 'competition_created', "Competition '$name' created by athlete");
                
            } catch(PDOException $e) {
                $error = 'Võistluse loomine ebaõnnestus: ' . $e->getMessage();
            }
        }
    }
}

// LEIA ANDMED - sama loogika mis adminil
$current_year = date('Y');

// Lae ainult oma tulemused
$results = [];
try {
    $stmt = $pdo->prepare("
        SELECT 
            r.*,
            c.name as competitionName, c.date as competitionDate, c.location
        FROM results r
        JOIN competitions c ON r.competitionId = c.id
        WHERE r.userId = ? AND strftime('%Y', c.date) = ?
        ORDER BY c.date DESC, r.points DESC
    ");
    $stmt->execute([$user_id, $current_year]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    $error = 'Tulemuste laadimine ebaõnnestus: ' . $e->getMessage();
}

// Lae võistlused - sama loogika mis adminil
$competitions = [];
try {
    $stmt = $pdo->prepare("
        SELECT id, name, date, start_date, end_date, is_multi_day, discipline, disciplines, location, description
        FROM competitions 
        WHERE strftime('%Y', COALESCE(start_date, date)) = ?
        ORDER BY COALESCE(start_date, date) DESC
    ");
    $stmt->execute([$current_year]);
    $competitions_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($competitions_raw as $comp) {
        $processed_comp = $comp;
        
        if ($comp['disciplines']) {
            $disciplines_array = json_decode($comp['disciplines'], true);
            $processed_comp['disciplines_array'] = is_array($disciplines_array) ? $disciplines_array : [$comp['discipline']];
        } else {
            $processed_comp['disciplines_array'] = [$comp['discipline']];
        }
        
        $competitions[] = $processed_comp;
    }
    
} catch(PDOException $e) {
    $competitions = [];
}

$page_title = 'Minu tulemused';
$page_description = 'Halda oma võistluste tulemusi ja lisa uusi võistlusi.';

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

<main class="athlete-results-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Minu tulemused</h1>
                <p class="page-subtitle">
                    Halda oma võistluste tulemusi hooajast <?php echo $current_year; ?>
                </p>
            </div>
            <div class="page-actions">
                <button onclick="openModal('resultModal')" class="btn btn-primary">
                    <i class="icon-plus"></i>
                    <span>Lisa tulemus</span>
                </button>
            </div>
        </div>

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

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

        <!-- Tulemuste loend -->
        <div class="results-container">
            <div class="results-header">
                <h2 class="results-title">
                    Sinu tulemused (<?php echo count($results); ?>)
                </h2>
            </div>

            <?php if (empty($results)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="icon-trophy"></i>
                    </div>
                    <h3>Tulemusi pole veel</h3>
                    <p>Lisa oma esimene võistluse tulemus!</p>
                    <button onclick="openModal('resultModal')" class="btn btn-primary">
                        <i class="icon-plus"></i>
                        <span>Lisa tulemus</span>
                    </button>
                </div>
            <?php else: ?>
                <div class="results-grid">
                    <?php foreach ($results as $result): ?>
                        <div class="result-card">
                            <div class="result-header">
                                <div class="result-competition">
                                    <h4 class="competition-name">
                                        <?php echo htmlspecialchars($result['competitionName']); ?>
                                    </h4>
                                    <div class="competition-date">
                                        <?php echo formatDate($result['competitionDate']); ?>
                                        <?php if ($result['location']): ?>
                                            • <?php echo htmlspecialchars($result['location']); ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="result-discipline">
                                    <span class="discipline-badge <?php echo $result['discipline']; ?>">
                                        <?php echo getDisciplineName($result['discipline']); ?>
                                    </span>
                                </div>
                            </div>

                            <div class="result-body">
                                <div class="result-details">
                                    <?php if ($result['discipline'] === 'koolisoit'): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Protsent:</span>
                                            <span class="detail-value"><?php echo formatPercentage($result['percentage']); ?></span>
                                        </div>
                                        <div class="detail-item">
                                            <span class="detail-label">Skeem:</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($result['scheme']); ?></span>
                                        </div>
                                    <?php elseif ($result['discipline'] === 'takistussoit'): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Karistuspunktid:</span>
                                            <span class="detail-value"><?php echo $result['faultPoints']; ?></span>
                                        </div>
                                        <?php if ($result['height']): ?>
                                            <div class="detail-item">
                                                <span class="detail-label">Kõrgus:</span>
                                                <span class="detail-value"><?php echo $result['height']; ?>cm</span>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($result['time_seconds']): ?>
                                            <!-- PARANDATUD: Takistussõidu aja kuvamine -->
                                            <div class="detail-item">
                                                <span class="detail-label">Aeg:</span>
                                                <span class="detail-value"><?php echo formatTime($result['time_seconds'], 'takistussoit'); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($result['discipline'] === 'kestvusratsutamine'): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Distants:</span>
                                            <span class="detail-value"><?php echo $result['distance']; ?>km</span>
                                        </div>
                                        <?php if ($result['time_seconds']): ?>
                                            <div class="detail-item">
                                                <span class="detail-label">Aeg:</span>
                                                <span class="detail-value"><?php echo formatTime($result['time_seconds']); ?></span>
                                            </div>
                                            
                                            <!-- PARANDATUD: Tagasihoidlik kiiruse kuvamine -->
                                            <?php 
                                            $average_speed = calculateAverageSpeed($result['distance'], $result['time_seconds']);
                                            if ($average_speed): 
                                            ?>
                                                <div class="detail-item">
                                                    <span class="detail-label">Kiirus:</span>
                                                    <span class="detail-value speed-subtle"><?php echo formatSpeed($average_speed); ?></span>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <?php if ($result['pulse']): ?>
                                            <div class="detail-item">
                                                <span class="detail-label">Pulss:</span>
                                                <span class="detail-value"><?php echo $result['pulse']; ?> l/min</span>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <?php if ($result['placement']): ?>
                                        <div class="detail-item placement">
                                            <span class="detail-label">Koht:</span>
                                            <span class="detail-value placement-value"><?php echo $result['placement']; ?>.</span>
                                            <?php if ($result['placement'] <= 3): ?>
                                                <span class="medal-icon">
                                                    <?php echo $result['placement'] === 1 ? '🥇' : ($result['placement'] === 2 ? '🥈' : '🥉'); ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div class="result-points">
                                    <div class="points-value">
                                        <?php echo formatPoints($result['points']); ?>
                                    </div>
                                    <div class="points-label">punkti</div>
                                </div>
                            </div>

                            <?php if ($result['notes']): ?>
                                <div class="result-notes">
                                    <div class="notes-label">Märkused:</div>
                                    <div class="notes-content"><?php echo htmlspecialchars($result['notes']); ?></div>
                                </div>
                            <?php endif; ?>

                            <div class="result-actions">
                                <button onclick="editResult(<?php echo htmlspecialchars(json_encode($result)); ?>)" 
                                        class="btn btn-outline btn-sm">
                                    <i class="icon-edit"></i>
                                    <span>Muuda</span>
                                </button>
                                
                                <form method="POST" style="display: inline;" 
                                      onsubmit="return confirm('Kas oled kindel, et tahad selle tulemuse kustutada?')">
                                    <input type="hidden" name="result_id" value="<?php echo $result['id']; ?>">
                                    <button type="submit" name="delete_result" class="btn btn-danger btn-sm">
                                        <i class="icon-trash"></i>
                                        <span>Kustuta</span>
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- PARANDATUD: TAKISTUSSÕIDU AJA MODAL -->
    <div id="resultModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modalTitle">Lisa tulemus</h3>
                    <button class="modal-close" onclick="closeModal('resultModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form" id="resultForm">
                    <input type="hidden" name="result_id" id="result_id">

                    <!-- PARANDATUD: Võistluse otsing + dropdown -->
                    <div class="form-group">
                        <label for="competition_search" class="form-label">Võistlus * <span class="label-help">(otsi või vali dropdown'ist)</span></label>
                        
                        <div class="competition-search-wrapper">
                            <!-- Otsingu input datalist'iga -->
                            <input type="text" id="competition_search" class="form-input competition-search" 
                                   placeholder="Kirjuta võistluse nimi, kuupäev või asukoht..." 
                                   list="competitions_datalist" autocomplete="off"
                                   onchange="handleCompetitionSearch(this.value)">
                            
                            <!-- HTML5 datalist automaatseks autocomplete'iks -->
                            <datalist id="competitions_datalist">
                                <?php foreach ($competitions as $comp): ?>
                                    <option value="<?php echo htmlspecialchars($comp['name']); ?>" 
                                            data-id="<?php echo $comp['id']; ?>"
                                            data-disciplines="<?php echo htmlspecialchars(json_encode($comp['disciplines_array'])); ?>"
                                            data-single-discipline="<?php echo htmlspecialchars($comp['discipline']); ?>">
                                        <?php echo formatDate($comp['start_date'] ?: $comp['date']); ?> • <?php echo htmlspecialchars($comp['location'] ?: 'Asukoht määramata'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </datalist>
                            
                            <!-- Varundus dropdown - peidetud, aga töötab -->
                            <select id="competitionId" name="competitionId" class="form-select backup-select" 
                                    required onchange="updateAthleteCompetitionDisciplines()" style="display: none;">
                                <option value="">Vali võistlus</option>
                                <?php foreach ($competitions as $comp): ?>
                                    <option value="<?php echo $comp['id']; ?>" 
                                            data-disciplines="<?php echo htmlspecialchars(json_encode($comp['disciplines_array'])); ?>"
                                            data-single-discipline="<?php echo htmlspecialchars($comp['discipline']); ?>">
                                        <?php echo htmlspecialchars($comp['name']) . ' (' . formatDate($comp['start_date'] ?: $comp['date']) . ')'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            
                            <!-- Toggle nupp dropdown jaoks -->
                            <button type="button" class="search-toggle" onclick="toggleCompetitionMode()" 
                                    title="Lülita dropdown'i režiimile">
                                <i class="icon-list"></i>
                            </button>
                        </div>
                        
                        <!-- Valitud võistluse info -->
                        <div id="selected_competition_info" class="selected-competition" style="display: none;">
                            <div class="selected-comp-details">
                                <strong id="selected_comp_name"></strong>
                                <div id="selected_comp_meta"></div>
                            </div>
                            <button type="button" onclick="clearCompetitionSelection()" class="btn-clear">
                                <i class="icon-x"></i>
                            </button>
                        </div>
                        
                        <div class="form-help" id="competition_help">Kirjuta vähemalt 2 tähemärki või klõpsa dropdown nuppu</div>
                    </div>

                    <div class="form-grid">

                        <div class="form-group">
                            <label for="discipline" class="form-label">Distsipliin *</label>
                            <select id="discipline" name="discipline" class="form-select" required onchange="toggleDisciplineFields()">
                                <option value="">Vali esmalt võistlus</option>
                            </select>
                            <div class="form-help" id="disciplineHelp">Vali esmalt võistlus, siis kuvatakse selle distsipliinid</div>
                        </div>

                        <div class="form-group">
                            <label for="placement" class="form-label">Koht</label>
                            <input type="number" id="placement" name="placement" class="form-input" 
                                   min="1" max="100" placeholder="Koht võistlusel">
                        </div>
                    </div>

                    <!-- KASUTA SAMU DISTSIPLIINI VÄLJU MIS ADMINIL -->
                    <div id="dressageFields" class="discipline-fields" style="display: none;">
                        <h4 class="fields-title">Koolisõidu andmed</h4>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="percentage" class="form-label">Protsent *</label>
                                <input type="number" id="percentage" name="percentage" class="form-input" 
                                       step="any" min="0" max="100" placeholder="65.456">
                            </div>
                            <div class="form-group">
                                <label for="scheme" class="form-label">Skeem *</label>
                                <select id="scheme" name="scheme" class="form-select">
                                    <option value="">Vali skeem</option>
                                    <option value="L-skeem">L-skeem (kõige raskem)</option>
                                    <option value="A-skeem">A-skeem (raske)</option>
                                    <option value="ABC-skeem">ABC-skeem (keskmine)</option>
                                    <option value="NH4A-skeem">NH4A-skeem (noorhobuste skeem)</option>
                                    <option value="ST-skeem">ST-skeem (kõige kergem)</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- PARANDATUD: Takistussõidu väljad sama moodi kui adminil -->
                    <div id="jumpingFields" class="discipline-fields" style="display: none;">
                        <h4 class="fields-title">Takistussõit</h4>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="faultPoints" class="form-label">Karistuspunktid *</label>
                                <input type="number" id="faultPoints" name="faultPoints" class="form-input" 
                                       min="0" step="1" placeholder="0" required>
                                <div class="form-help">Kokku saadud karistuspunktid</div>
                            </div>

                            <!-- PARANDATUD: Numbriline kõrguse sisestus nagu adminil -->
                            <div class="form-group">
                                <label for="height" class="form-label">Takistuste kõrgus (cm)</label>
                                <input type="number" id="height" name="height" class="form-input" 
                                       min="50" max="200" step="5" placeholder="80">
                                <div class="form-help">Takistuste kõrgus sentimeetrites</div>
                            </div>

                            <!-- PARANDATUD: Takistussõidu aja väli -->
                            <div class="form-group">
                                <label for="time_input_jumping" class="form-label">Aeg (sekundites)</label>
                                <input type="text" id="time_input_jumping" name="time_input" 
                                       class="form-input time-input jumping-time-input" 
                                       placeholder="65.42" pattern="^(\d{1,3})(\.\d{1,2})?$">
                                <div class="form-help jumping-time">
                                    <strong>⏱️ AMETLIK FORMAAT:</strong> sekundid.sajandikud (nt. 65.42) 
                                    <br><small>Mitte minutid:sekundid!</small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Kõrguse kiirvalikud nagu adminil -->
                        <div class="height-presets">
                            <label class="form-label">Levinud kõrgused:</label>
                            <div class="preset-buttons">
                                <button type="button" class="btn-preset" onclick="setHeight(60, this)">60cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(80, this)">80cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(100, this)">100cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(120, this)">120cm</button>
                                <button type="button" class="btn-preset" onclick="setHeight(140, this)">140cm</button>
                            </div>
                        </div>
                    </div>

                    <!-- PARANDATUD: Kestvusratsutamise väljad -->
                    <div id="enduranceFields" class="discipline-fields" style="display: none;">
                        <h4 class="fields-title">Kestvusratsutamise andmed</h4>
                        <div class="form-grid">
                            <!-- PARANDATUD: Numbriline distantsi sisestus -->
                            <div class="form-group">
                                <label for="distance" class="form-label">Distants (km) *</label>
                                <input type="number" id="distance" name="distance" class="form-input" 
                                       min="5" max="200" step="0.1" placeholder="20.5" required>
                                <div class="form-help">Distants kilomeetrites (nt. 20.5)</div>
                            </div>

                            <div class="form-group">
                                <label for="time_input_endurance" class="form-label">Lõpuaeg</label>
                                <input type="text" id="time_input_endurance" name="time_input" class="form-input time-input" 
                                       placeholder="2:30:45" pattern="^(\d{1,2}):([0-5]\d):([0-5]\d)$">
                                <div class="form-help">Formaat: h:mm:ss (nt. 2:30:45)</div>
                            </div>

                            <div class="form-group">
                                <label for="pulse" class="form-label">Pulss pärast lõppu (l/min)</label>
                                <input type="number" id="pulse" name="pulse" class="form-input" 
                                       min="30" max="120" placeholder="64">
                                <div class="form-help">Pulss 10min pärast lõppu</div>
                            </div>
                        </div>
                        
                        <!-- LISATUD: Levinud distantside kiirvalikud -->
                        <div class="distance-presets">
                            <label class="form-label">Levinud distantsid:</label>
                            <div class="preset-buttons">
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(15, this)">15 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(20, this)">20 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(25, this)">25 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(30, this)">30 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(40, this)">40 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(60, this)">60 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(80, this)">80 km</button>
                                <button type="button" class="btn-preset" onclick="setAthleteDistance(100, this)">100 km</button>
                            </div>
                        </div>
                        
                        <!-- LISATUD: Kiiruse eelvaade -->
                        <div id="athlete_speed_preview" class="speed-preview" style="display: none;">
                            <strong>Keskmine kiirus:</strong> <span id="athlete_calculated_speed">-</span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="finished" id="finished" class="checkbox-input" checked>
                            <span class="checkbox-custom"></span>
                            <span class="checkbox-text">Lõpetasin võistluse</span>
                        </label>
                    </div>

                    <div class="form-group">
                        <label for="notes" class="form-label">Märkused</label>
                        <textarea id="notes" name="notes" class="form-textarea" rows="3" 
                                  placeholder="Lisainformatsioon tulemuse kohta..."></textarea>
                    </div>

                    <div class="modal-actions">
                        <button type="button" onclick="closeModal('resultModal')" class="btn btn-secondary">
                            Tühista
                        </button>
                        <button type="submit" name="save_result" class="btn btn-primary">
                            <i class="icon-save"></i>
                            <span id="saveButtonText">Lisa tulemus</span>
                        </button>
                        <button type="button" onclick="openModal('competitionModal')" class="btn btn-outline">
                            <i class="icon-plus"></i>
                            <span>Või loo uus võistlus</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- PARANDATUD: SAMA VÕISTLUSE MODAL MIS ADMINIL + MULTI-DAY TUGI -->
    <div id="competitionModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Loo uus võistlus</h3>
                    <button class="modal-close" onclick="closeModal('competitionModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form" id="competitionForm">
                    <div class="form-group">
                        <label for="name" class="form-label">Võistluse nimi *</label>
                        <input type="text" id="name" name="name" class="form-input" 
                               placeholder="Sisesta võistluse nimi" required>
                    </div>

                    <!-- PARANDATUD: Multi-day kuupäevade valik nagu adminil -->
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" id="is_multi_day" name="is_multi_day" class="checkbox-input">
                            <span class="checkbox-custom"></span>
                            <span class="checkbox-text">Mitme päeva pikkune võistlus</span>
                        </label>
                    </div>

                    <div id="single-date-field" class="form-group">
                        <label for="date" class="form-label">Kuupäev *</label>
                        <input type="date" id="date" name="date" class="form-input" required>
                    </div>

                    <div id="multi-date-fields" class="form-grid" style="display: none;">
                        <div class="form-group">
                            <label for="start_date" class="form-label">Alguskuupäev *</label>
                            <input type="date" id="start_date" name="start_date" class="form-input">
                        </div>
                        <div class="form-group">
                            <label for="end_date" class="form-label">Lõppkuupäev *</label>
                            <input type="date" id="end_date" name="end_date" class="form-input">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="location" class="form-label">Asukoht</label>
                        <input type="text" id="location" name="location" class="form-input" 
                               placeholder="Sisesta võistluse asukoht">
                    </div>

                    <!-- Mitme distsipliini valik nagu adminil -->
                    <div class="form-group">
                        <label class="form-label">Distsipliinid * <span class="label-help">(vali vähemalt üks)</span></label>
                        <div class="disciplines-selector">
                            <label class="discipline-checkbox">
                                <input type="checkbox" name="disciplines[]" value="koolisoit" class="checkbox-input">
                                <span class="checkbox-custom"></span>
                                <span class="discipline-badge koolisoit">Koolisõit</span>
                            </label>
                            
                            <label class="discipline-checkbox">
                                <input type="checkbox" name="disciplines[]" value="takistussoit" class="checkbox-input">
                                <span class="checkbox-custom"></span>
                                <span class="discipline-badge takistussoit">Takistussõit</span>
                            </label>
                            
                            <label class="discipline-checkbox">
                                <input type="checkbox" name="disciplines[]" value="kestvusratsutamine" class="checkbox-input">
                                <span class="checkbox-custom"></span>
                                <span class="discipline-badge kestvusratsutamine">Kestvusratsutamine</span>
                            </label>
                        </div>
                        <div class="form-help">Vali kõik distsipliinid, mis sellel võistlusel toimuvad</div>
                    </div>

                    <div class="form-group">
                        <label for="description" class="form-label">Kirjeldus</label>
                        <textarea id="description" name="description" class="form-textarea" rows="4" 
                                  placeholder="Võistluse kirjeldus, reeglid, lisainfo..."></textarea>
                    </div>

                    <div class="modal-actions">
                        <button type="button" onclick="closeModal('competitionModal')" class="btn btn-secondary">
                            Tühista
                        </button>
                        <button type="submit" name="save_competition" class="btn btn-primary">
                            <i class="icon-save"></i>
                            <span>Loo võistlus</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<!-- PARANDATUD CSS ja JavaScript -->
<style>
/* KASUTA SAMA CSS MIS ADMINIL + MÕNED PARANDUSED */
.athlete-results-main {
    padding: var(--spacing-8) 0;
    min-height: 100vh;
    background: var(--gray-50);
}

.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;
}

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

.results-header {
    margin-bottom: var(--spacing-6);
}

.results-title {
    margin: 0;
    font-size: var(--font-size-xl);
    font-weight: 600;
}

.empty-state {
    text-align: center;
    padding: var(--spacing-16) var(--spacing-8);
}

.empty-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto var(--spacing-6);
    background-color: var(--success-color);
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 2rem;
}

.empty-state h3 {
    margin-bottom: var(--spacing-3);
    color: var(--gray-900);
}

.empty-state p {
    color: var(--gray-600);
    margin-bottom: var(--spacing-6);
}

.results-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: var(--spacing-6);
}

.result-card {
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-lg);
    overflow: hidden;
    transition: all var(--transition-fast);
    box-shadow: var(--shadow-sm);
}

.result-card:hover {
    border-color: var(--primary-color);
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}

.result-header {
    padding: var(--spacing-4);
    background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: var(--spacing-3);
}

.result-competition {
    flex: 1;
}

.competition-name {
    margin: 0 0 var(--spacing-1);
    font-size: var(--font-size-lg);
    font-weight: 600;
    line-height: 1.2;
}

.competition-date {
    font-size: var(--font-size-sm);
    opacity: 0.9;
}

.result-discipline {
    flex-shrink: 0;
}

.discipline-badge {
    padding: var(--spacing-1) var(--spacing-2);
    border-radius: var(--radius-sm);
    font-size: var(--font-size-xs);
    font-weight: 500;
    color: white;
    background: rgba(255, 255, 255, 0.2);
}

.discipline-badge.koolisoit { background: var(--primary-color); }
.discipline-badge.takistussoit { background: var(--success-color); }
.discipline-badge.kestvusratsutamine { background: #8b5cf6; }

.result-body {
    padding: var(--spacing-5);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: var(--spacing-4);
}

.result-details {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: var(--spacing-3);
}

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

.detail-item.placement {
    grid-column: 1 / -1;
    flex-direction: row;
    align-items: center;
    gap: var(--spacing-2);
}

/* PARANDATUD: Täiesti tavaline kiiruse stiil ilma raamita */
.detail-value.speed-subtle {
    font-family: 'Courier New', monospace;
    font-weight: 500;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
}

.detail-label {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

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

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

.medal-icon {
    font-size: var(--font-size-lg);
}

.result-points {
    text-align: center;
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
    min-width: 80px;
}

.points-value {
    font-size: var(--font-size-xl);
    font-weight: 700;
    color: var(--primary-color);
    line-height: 1;
}

.points-label {
    font-size: var(--font-size-xs);
    color: var(--gray-600);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-top: var(--spacing-1);
}

.result-notes {
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-top: 1px solid var(--gray-200);
}

.notes-label {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: var(--spacing-2);
}

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

.result-actions {
    padding: var(--spacing-4);
    border-top: 1px solid var(--gray-200);
    display: flex;
    gap: var(--spacing-2);
    justify-content: flex-end;
}

/* PARANDATUD: Takistussõidu aja välja stiilid sama moodi kui adminil */
.jumping-time-input {
    font-family: 'Courier New', monospace;
    font-size: 1.2em;
    text-align: center;
    letter-spacing: 2px;
    font-weight: bold;
    background: #f8f9ff;
    border: 2px solid #007bff;
}

.jumping-time-input:focus {
    background: #ffffff;
    border-color: #0056b3;
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}

.jumping-time-input.error {
    border-color: #dc3545;
    background: #fff5f5;
}

.form-help.jumping-time {
    background: linear-gradient(135deg, #fff3cd, #ffeaa7);
    padding: 12px;
    border-radius: 6px;
    border-left: 4px solid #ffc107;
    margin-top: 8px;
    font-weight: 500;
    color: #856404;
}

/* LISATUD: Distantsi eelvaadete stiilid */
.distance-presets {
    margin-top: var(--spacing-4);
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
}

.speed-preview {
    margin-top: var(--spacing-3);
    padding: var(--spacing-2);
    text-align: right;
    font-size: var(--font-size-xs);
    color: var(--gray-500);
}

/* KASUTA SAMA MODAL CSS MIS ADMINIL */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    display: none;
}

.modal.show {
    display: flex;
}

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-4);
}

.modal-content {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-xl);
    width: 100%;
    max-width: 800px;
    max-height: 90vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-5) var(--spacing-6);
    border-bottom: 1px solid var(--gray-200);
}

.modal-title {
    margin: 0;
    font-size: var(--font-size-lg);
    font-weight: 600;
}

.modal-close {
    width: 32px;
    height: 32px;
    border: none;
    background: none;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: var(--gray-400);
    transition: all var(--transition-fast);
}

.modal-close:hover {
    background: var(--gray-100);
    color: var(--gray-600);
}

.modal-form {
    padding: var(--spacing-6);
}

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

.form-group {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
}

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

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

.form-input,
.form-select,
.form-textarea {
    padding: var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
    transition: border-color var(--transition-fast);
}

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

.form-textarea {
    resize: vertical;
    font-family: inherit;
}

.form-help {
    font-size: var(--font-size-xs);
    color: var(--gray-500);
    margin-top: var(--spacing-1);
}

.discipline-fields {
    margin-bottom: var(--spacing-6);
    padding: var(--spacing-5);
    background: var(--gray-50);
    border-radius: var(--radius-lg);
    border: 2px solid var(--gray-200);
}

.fields-title {
    margin: 0 0 var(--spacing-4);
    font-size: var(--font-size-lg);
    font-weight: 600;
    color: var(--gray-900);
    padding-bottom: var(--spacing-2);
    border-bottom: 2px solid var(--gray-300);
}

.time-input {
    font-family: monospace;
    font-size: 1.1em;
    text-align: center;
}

.height-presets {
    margin-top: var(--spacing-4);
    padding: var(--spacing-3);
    background: var(--gray-50);
    border-radius: var(--radius);
}

.preset-buttons {
    display: flex;
    gap: var(--spacing-2);
    flex-wrap: wrap;
    margin-top: var(--spacing-2);
}

.btn-preset {
    padding: var(--spacing-2) var(--spacing-3);
    background: white;
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    cursor: pointer;
    font-size: var(--font-size-sm);
    transition: all var(--transition-fast);
}

.btn-preset:hover {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    cursor: pointer;
    font-size: var(--font-size-sm);
    margin-bottom: var(--spacing-4);
}

.checkbox-input {
    display: none;
}

.checkbox-custom {
    width: 18px;
    height: 18px;
    border: 2px solid var(--gray-300);
    border-radius: var(--radius-sm);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all var(--transition-fast);
}

.checkbox-input:checked + .checkbox-custom {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.checkbox-input:checked + .checkbox-custom::after {
    content: '✓';
    color: white;
    font-size: 12px;
    font-weight: bold;
}

.disciplines-selector {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
    padding: var(--spacing-4);
    background: var(--gray-50);
    border-radius: var(--radius);
    border: 1px solid var(--gray-200);
}

.discipline-checkbox {
    display: flex;
    align-items: center;
    gap: var(--spacing-3);
    cursor: pointer;
    padding: var(--spacing-2);
    border-radius: var(--radius);
    transition: background-color var(--transition-fast);
}

.discipline-checkbox:hover {
    background: white;
}

.modal-actions {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-3);
    margin-top: var(--spacing-6);
    padding-top: var(--spacing-4);
    border-top: 1px solid var(--gray-200);
}

.btn {
    padding: var(--spacing-3) var(--spacing-4);
    border: 1px solid;
    border-radius: var(--radius);
    cursor: pointer;
    font-weight: 500;
    font-size: var(--font-size-sm);
    display: inline-flex;
    align-items: center;
    gap: var(--spacing-2);
    transition: all var(--transition-fast);
    text-decoration: none;
}

.btn-secondary {
    background: white;
    color: var(--gray-600);
    border-color: var(--gray-300);
}

.btn-secondary:hover {
    background: var(--gray-50);
    color: var(--gray-700);
    border-color: var(--gray-400);
}

.btn-primary {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

.btn-primary:hover {
    background: var(--primary-dark);
    border-color: var(--primary-dark);
}

.btn-outline {
    background: white;
    color: var(--primary-color);
    border-color: var(--primary-color);
}

.btn-outline:hover {
    background: var(--primary-color);
    color: white;
}

.btn-danger {
    background: var(--danger-color);
    color: white;
    border-color: var(--danger-color);
}

.btn-danger:hover {
    background: #dc2626;
    border-color: #dc2626;
}

.btn-sm {
    padding: var(--spacing-2) var(--spacing-3);
    font-size: var(--font-size-sm);
}

/* LISATUD: Competition Search Styles */
.competition-search-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
}

.competition-search {
    flex: 1;
    padding-right: var(--spacing-12); /* Ruumi toggle nupule */
}

.backup-select {
    flex: 1;
}

.search-toggle {
    position: absolute;
    right: var(--spacing-2);
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    border: none;
    background: var(--gray-100);
    color: var(--gray-600);
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all var(--transition-fast);
    z-index: 10;
}

.search-toggle:hover {
    background: var(--primary-color);
    color: white;
}

.selected-competition {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-3);
    padding: var(--spacing-3);
    background: color-mix(in srgb, var(--success-color) 5%, transparent);
    border: 1px solid color-mix(in srgb, var(--success-color) 20%, transparent);
    border-radius: var(--radius);
    margin-top: var(--spacing-2);
}

.selected-comp-details {
    flex: 1;
}

.selected-comp-details strong {
    display: block;
    color: var(--gray-900);
    font-weight: 600;
    margin-bottom: var(--spacing-1);
    font-size: var(--font-size-sm);
}

.selected-comp-details div {
    font-size: var(--font-size-xs);
    color: var(--gray-600);
    line-height: 1.3;
}

.btn-clear {
    width: 24px;
    height: 24px;
    border: none;
    background: color-mix(in srgb, var(--success-color) 20%, transparent);
    color: var(--success-color);
    border-radius: var(--radius-sm);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all var(--transition-fast);
    flex-shrink: 0;
}

.btn-clear:hover {
    background: color-mix(in srgb, var(--success-color) 30%, transparent);
}

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-4);
    }
    
    .results-grid {
        grid-template-columns: 1fr;
    }
    
    .result-header {
        flex-direction: column;
        gap: var(--spacing-2);
    }
    
    .result-body {
        flex-direction: column;
        gap: var(--spacing-4);
    }
    
    .result-details {
        grid-template-columns: 1fr;
    }
    
    .result-actions {
        flex-direction: column;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .modal-actions {
        flex-direction: column;
    }
    
    .preset-buttons {
        justify-content: center;
    }
    
    .btn-preset {
        flex: 0 0 calc(33.33% - var(--spacing-1));
        text-align: center;
    }
    
    /* Mobile time display optimization */
    .detail-value.speed-subtle {
        font-size: var(--font-size-base);
    }
}
</style>

<script>
// PARANDATUD: Sportlase results.php JavaScript koos takistussõidu aja valideerimisega
console.log('🏇 Loading FIXED athlete results with jumping time validation...');

// VÕISTLUSTE ANDMED
const availableCompetitions = <?php echo json_encode($competitions); ?>;
let isDropdownMode = false;

// PARANDATUD: Takistussõidu aja JavaScript funktsioonid
document.addEventListener('DOMContentLoaded', function() {
    const jumpingTimeInput = document.getElementById('time_input_jumping');
    
    if (jumpingTimeInput) {
        // Real-time valideerimise ja formateerimine
        jumpingTimeInput.addEventListener('input', function() {
            let value = this.value;
            
            // Eemaldame 's' lõpust automaatselt
            value = value.replace(/s$/g, '');
            
            // Asendame koma punktiga
            value = value.replace(',', '.');
            
            // Eemalda kõik mis pole number või punkt
            value = value.replace(/[^0-9.]/g, '');
            
            // Luba ainult üks punkt
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join('');
            }
            
            // Piira sajandikud 2 kohani
            if (parts.length === 2 && parts[1].length > 2) {
                value = parts[0] + '.' + parts[1].substring(0, 2);
            }
            
            // Piira sekundid 3 kohas
            if (parts[0].length > 3) {
                value = parts[0].substring(0, 3) + (parts[1] ? '.' + parts[1] : '');
            }
            
            this.value = value;
            
            // Visuaalne feedback
            validateJumpingTime(this);
        });
        
        jumpingTimeInput.addEventListener('blur', function() {
            validateJumpingTime(this, true);
        });
        
        jumpingTimeInput.addEventListener('focus', function() {
            this.classList.remove('error');
        });
    }
    
    // Vorm submiti valideerimine
    const resultForm = document.getElementById('resultForm');
    if (resultForm) {
        resultForm.addEventListener('submit', function(e) {
            const jumpingTimeInput = document.getElementById('time_input_jumping');
            const discipline = document.getElementById('discipline').value;
            
            if (discipline === 'takistussoit' && jumpingTimeInput && jumpingTimeInput.value) {
                if (!validateJumpingTimeFormat(jumpingTimeInput.value)) {
                    e.preventDefault();
                    jumpingTimeInput.focus();
                    alert('Palun sisesta takistussõidu aeg õiges formaadis: sekundid.sajandikud (nt. 65.42)');
                    return false;
                }
            }
        });
    }
    
    // LISATUD: Event listenerid kiiruse arvutamiseks
    const distanceInput = document.getElementById('distance');
    const timeInput = document.getElementById('time_input_endurance');
    
    if (distanceInput) {
        distanceInput.addEventListener('input', calculateAthleteSpeedPreview);
    }
    
    if (timeInput) {
        timeInput.addEventListener('input', calculateAthleteSpeedPreview);
    }
});

function validateJumpingTime(input, showAlert = false) {
    const value = input.value.trim();
    
    if (!value) {
        input.classList.remove('error');
        return true;
    }
    
    const isValid = validateJumpingTimeFormat(value);
    
    if (isValid) {
        input.classList.remove('error');
        if (showAlert) {
            const seconds = parseFloat(value);
            input.title = `${seconds.toFixed(2)} sekundit`;
        }
    } else {
        input.classList.add('error');
        if (showAlert) {
            input.title = 'Sisesta aeg formaadis: sekundid.sajandikud (nt. 65.42)';
        }
    }
    
    return isValid;
}

function validateJumpingTimeFormat(timeString) {
    if (!timeString) return true;
    
    const cleaned = timeString.replace(/s$/, '').replace(',', '.');
    
    if (!/^(\d{1,3})(\.\d{1,2})?$/.test(cleaned)) {
        return false;
    }
    
    const seconds = parseFloat(cleaned);
    return seconds >= 5 && seconds <= 600;
}

// LISATUD: Athlete distantsi seadmise funktsioon
function setAthleteDistance(distance, buttonElement) {
    const distanceInput = document.getElementById('distance');
    if (distanceInput) {
        distanceInput.value = distance;
        distanceInput.focus();
        
        // Visual feedback
        const presetButtons = document.querySelectorAll('.distance-presets .btn-preset');
        presetButtons.forEach(btn => btn.classList.remove('active'));
        
        if (buttonElement) {
            buttonElement.classList.add('active');
            setTimeout(() => buttonElement.classList.remove('active'), 200);
        }
        
        // Arvuta kiirus kui aeg on sisestatud
        calculateAthleteSpeedPreview();
    }
}

// LISATUD: Athlete kiiruse eelvaate arvutamine
function calculateAthleteSpeedPreview() {
    const distanceInput = document.getElementById('distance');
    const timeInput = document.getElementById('time_input_endurance');
    const speedPreview = document.getElementById('athlete_speed_preview');
    const calculatedSpeed = document.getElementById('athlete_calculated_speed');
    
    if (!distanceInput || !timeInput || !speedPreview || !calculatedSpeed) return;
    
    const distance = parseFloat(distanceInput.value);
    const timeString = timeInput.value.trim();
    
    if (distance > 0 && timeString) {
        // Parsi aeg sekunditeks
        const timeSeconds = parseAthleteTimeStringToSeconds(timeString);
        
        if (timeSeconds > 0) {
            // Arvuta kiirus
            const timeHours = timeSeconds / 3600;
            const speedKmh = distance / timeHours;
            
            calculatedSpeed.textContent = speedKmh.toFixed(2) + ' km/h';
            speedPreview.style.display = 'block';
        } else {
            speedPreview.style.display = 'none';
        }
    } else {
        speedPreview.style.display = 'none';
    }
}

// Helper funktsioon aja parsimiseks (athlete specific)
function parseAthleteTimeStringToSeconds(timeString) {
    const parts = timeString.split(':');
    
    if (parts.length === 3) {
        // h:mm:ss
        const hours = parseInt(parts[0]) || 0;
        const minutes = parseInt(parts[1]) || 0;
        const seconds = parseInt(parts[2]) || 0;
        return hours * 3600 + minutes * 60 + seconds;
    } else if (parts.length === 2) {
        // mm:ss
        const minutes = parseInt(parts[0]) || 0;
        const seconds = parseInt(parts[1]) || 0;
        return minutes * 60 + seconds;
    }
    
    return 0;
}

// PARANDATUD: editResult funktsioon 
function editResult(result) {
    console.log('✏️ Editing result:', result.id);
    
    // Fill basic form data
    document.getElementById('result_id').value = result.id;
    document.getElementById('placement').value = result.placement || '';
    document.getElementById('finished').checked = result.finished == 1;
    document.getElementById('notes').value = result.notes || '';
    
    // PARANDATUD: Leia ja vali võistlus
    const competition = availableCompetitions.find(c => c.id == result.competitionId);
    if (competition) {
        if (isDropdownMode) {
            document.getElementById('competitionId').value = result.competitionId;
        } else {
            document.getElementById('competition_search').value = competition.name;
        }
        selectCompetition(competition);
    }
    
    // PARANDATUD: Set discipline after delay - kasuta õiget ID-d
    setTimeout(() => {
        const disciplineSelect = document.getElementById('discipline');
        if (disciplineSelect) {
            disciplineSelect.value = result.discipline;
            toggleDisciplineFields();
            
            // Fill discipline-specific fields
            setTimeout(() => {
                if (result.discipline === 'koolisoit') {
                    document.getElementById('percentage').value = result.percentage || '';
                    document.getElementById('scheme').value = result.scheme || '';
                } else if (result.discipline === 'takistussoit') {
                    document.getElementById('faultPoints').value = result.faultPoints || '';
                    document.getElementById('height').value = result.height || '';
                    
                    // PARANDATUD: Takistussõidu aja täitmine
                    if (result.time_seconds) {
                        const jumpingTimeInput = document.getElementById('time_input_jumping');
                        if (jumpingTimeInput) {
                            // Kuvame sekundites kahe kümnendkohaga
                            jumpingTimeInput.value = parseFloat(result.time_seconds).toFixed(2);
                        }
                    }
                } else if (result.discipline === 'kestvusratsutamine') {
                    document.getElementById('distance').value = result.distance || '';
                    document.getElementById('pulse').value = result.pulse || '';
                    
                    // Kestvusratsutamise aeg jääb samaks
                    if (result.time_seconds) {
                        const enduranceTimeInput = document.getElementById('time_input_endurance');
                        if (enduranceTimeInput) {
                            enduranceTimeInput.value = formatSecondsToInput(result.time_seconds, true);
                        }
                    }
                    
                    // LISATUD: Arvuta kiirus eelvaatesse
                    setTimeout(calculateAthleteSpeedPreview, 100);
                }
            }, 100);
        }
    }, 200);
    
    // Update modal
    document.getElementById('modalTitle').textContent = 'Muuda tulemust';
    document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
    
    openModal('resultModal');
}

// PARANDATUD: Competition search functions
function handleCompetitionSearch(searchValue) {
    console.log('🔍 Competition search:', searchValue);
    
    // Otsi võistlust nime järgi
    const competition = availableCompetitions.find(comp => 
        comp.name.toLowerCase() === searchValue.toLowerCase()
    );
    
    if (competition) {
        selectCompetition(competition);
    } else {
        // Kui ei leia täpset vastet, tühjenda valik
        clearCompetitionSelection();
    }
}

function selectCompetition(competition) {
    console.log('✅ Competition selected:', competition.name);
    
    // Vali peidetud select elemendis
    document.getElementById('competitionId').value = competition.id;
    
    // Näita valitud võistluse infot
    showSelectedCompetition(competition);
    
    // PARANDATUD: Uuenda distsipliine - kasutab õiget funktsiooni
    updateAthleteCompetitionDisciplines();
}

function showSelectedCompetition(competition) {
    const selectedDiv = document.getElementById('selected_competition_info');
    const nameSpan = document.getElementById('selected_comp_name');
    const metaSpan = document.getElementById('selected_comp_meta');
    
    if (selectedDiv && nameSpan && metaSpan) {
        nameSpan.textContent = competition.name;
        
        const disciplinesText = competition.disciplines_array ? 
            competition.disciplines_array.map(d => getDisciplineName(d)).join(', ') :
            getDisciplineName(competition.discipline);
        
        metaSpan.innerHTML = `
            ${formatDate(competition.start_date || competition.date)} • ${competition.location || 'Asukoht määramata'}<br>
            Distsipliinid: ${disciplinesText}
        `;
        
        selectedDiv.style.display = 'block';
    }
}

function clearCompetitionSelection() {
    console.log('🗑️ Clearing competition selection');
    
    document.getElementById('competitionId').value = '';
    document.getElementById('competition_search').value = '';
    document.getElementById('selected_competition_info').style.display = 'none';
    
    // Reset distsipliini dropdown
    const disciplineSelect = document.getElementById('discipline');
    if (disciplineSelect) {
        disciplineSelect.innerHTML = '<option value="">Vali esmalt võistlus</option>';
    }
    
    // Peida distsipliini väljad
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
}

function toggleCompetitionMode() {
    console.log('🔄 Toggling competition mode');
    
    const searchInput = document.getElementById('competition_search');
    const selectElement = document.getElementById('competitionId');
    const toggleBtn = document.querySelector('.search-toggle');
    const helpText = document.getElementById('competition_help');
    
    isDropdownMode = !isDropdownMode;
    
    if (isDropdownMode) {
        // Dropdown režiim
        searchInput.style.display = 'none';
        selectElement.style.display = 'block';
        toggleBtn.innerHTML = '<i class="icon-search"></i>';
        helpText.textContent = 'Dropdown režiim - vali nimekirjast';
    } else {
        // Otsingu režiim
        searchInput.style.display = 'block';
        selectElement.style.display = 'none';
        toggleBtn.innerHTML = '<i class="icon-list"></i>';
        helpText.textContent = 'Otsingu režiim - kirjuta võistluse nimi';
    }
}

// PARANDATUD: Reset functions
function resetResultForm() {
    console.log('🔄 Resetting result form');
    
    document.getElementById('resultForm').reset();
    document.getElementById('result_id').value = '';
    document.getElementById('modalTitle').textContent = 'Lisa tulemus';
    document.getElementById('saveButtonText').textContent = 'Lisa tulemus';
    document.getElementById('finished').checked = true;
    
    // Reset competition selection
    clearCompetitionSelection();
    
    // Reset discipline dropdown
    document.getElementById('discipline').innerHTML = '<option value="">Vali esmalt võistlus</option>';
    document.getElementById('disciplineHelp').textContent = 'Vali esmalt võistlus, siis kuvatakse selle distsipliinid';
    
    // Hide discipline fields
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
}

function resetCompetitionForm() {
    document.getElementById('competitionForm').reset();
    
    // Reset multi-day fields - kasutab main.js funktsiooni
    document.getElementById('is_multi_day').checked = false;
    if (typeof toggleDateFields === 'function') {
        toggleDateFields();
    }
    
    // Reset disciplines
    document.querySelectorAll('input[name="disciplines[]"]').forEach(checkbox => {
        checkbox.checked = false;
    });
}

function setHeight(height, buttonElement) {
    const heightInput = document.getElementById('height');
    if (heightInput) {
        heightInput.value = height;
        heightInput.focus();
        
        // Visual feedback
        const presetButtons = document.querySelectorAll('.btn-preset');
        presetButtons.forEach(btn => btn.classList.remove('active'));
        
        if (buttonElement) {
            buttonElement.classList.add('active');
            setTimeout(() => buttonElement.classList.remove('active'), 200);
        }
    }
}

// PARANDATUD: updateAthleteCompetitionDisciplines - kasutab õigeid ID-sid
function updateAthleteCompetitionDisciplines() {
    console.log('🎯 Athlete updateCompetitionDisciplines called');
    
    const competitionSelect = document.getElementById('competitionId');
    const disciplineSelect = document.getElementById('discipline');
    const disciplineHelp = document.getElementById('disciplineHelp');
    
    if (!competitionSelect || !disciplineSelect) {
        console.error('❌ Athlete elements not found');
        return false;
    }
    
    const selectedOption = competitionSelect.options[competitionSelect.selectedIndex];
    
    if (selectedOption && selectedOption.value) {
        try {
            let disciplines = [];
            const disciplinesData = selectedOption.dataset.disciplines;
            const singleDiscipline = selectedOption.dataset.singleDiscipline;
            
            if (disciplinesData) {
                try {
                    disciplines = JSON.parse(disciplinesData);
                    if (!Array.isArray(disciplines)) {
                        throw new Error('Parsed data is not an array');
                    }
                } catch (parseError) {
                    console.warn('⚠️ JSON parse failed, using fallback:', parseError);
                    disciplines = singleDiscipline ? [singleDiscipline] : [];
                }
            } else if (singleDiscipline) {
                disciplines = [singleDiscipline];
            }
            
            // Clear and populate discipline dropdown
            disciplineSelect.innerHTML = '';
            
            if (disciplines.length === 0) {
                disciplineSelect.innerHTML = '<option value="">Viga distsipliinide laadimisel</option>';
                if (disciplineHelp) disciplineHelp.textContent = 'Viga võistluse distsipliinide laadimisel';
                
            } else if (disciplines.length === 1) {
                // Single discipline - auto-select
                const discipline = disciplines[0];
                const disciplineName = getDisciplineName(discipline);
                disciplineSelect.innerHTML = `<option value="${discipline}" selected>${disciplineName}</option>`;
                if (disciplineHelp) disciplineHelp.textContent = 'Automaatselt valitud (ainuke distsipliin sellel võistlusel)';
                
                // Auto-show discipline fields
                setTimeout(() => toggleDisciplineFields(), 100);
                
            } else {
                // Multiple disciplines - show selection
                disciplineSelect.innerHTML = '<option value="">Vali distsipliin</option>';
                disciplines.forEach(discipline => {
                    const option = document.createElement('option');
                    option.value = discipline;
                    option.textContent = getDisciplineName(discipline);
                    disciplineSelect.appendChild(option);
                });
                if (disciplineHelp) disciplineHelp.textContent = `Sellel võistlusel on ${disciplines.length} distsipliini. Vali sobiv.`;
            }
            
            console.log('✅ Athlete disciplines updated successfully');
            return true;
            
        } catch (error) {
            console.error('❌ Error in athlete updateCompetitionDisciplines:', error);
            disciplineSelect.innerHTML = '<option value="">Süsteemi viga</option>';
            if (disciplineHelp) disciplineHelp.textContent = 'Süsteemi viga distsipliinide laadimisel';
            return false;
        }
    } else {
        // No competition selected
        disciplineSelect.innerHTML = '<option value="">Vali esmalt võistlus</option>';
        if (disciplineHelp) disciplineHelp.textContent = 'Vali esmalt võistlus, siis kuvatakse selle distsipliinid';
    }
    
    // Hide all discipline fields when competition changes
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
    
    return true;
}

// PARANDATUD: toggleDisciplineFields - kasutab õigeid ID-sid
function toggleDisciplineFields() {
    console.log('🔄 toggleDisciplineFields called');
    
    const discipline = document.getElementById('discipline')?.value;
    console.log('Athlete discipline selected:', discipline);
    
    if (!discipline) {
        console.log('No discipline selected, hiding all fields');
        document.querySelectorAll('.discipline-fields').forEach(field => {
            field.style.display = 'none';
        });
        return;
    }
    
    // Hide all fields first
    document.querySelectorAll('.discipline-fields').forEach(field => {
        field.style.display = 'none';
    });
    
    // Show relevant fields and set required attributes
    if (discipline === 'koolisoit') {
        const dressageFields = document.getElementById('dressageFields');
        if (dressageFields) {
            dressageFields.style.display = 'block';
            console.log('✅ Showing dressage fields');
        }
        setFieldRequired('percentage', true);
        setFieldRequired('scheme', true);
        setFieldRequired('faultPoints', false);
        setFieldRequired('distance', false);
        
    } else if (discipline === 'takistussoit') {
        const jumpingFields = document.getElementById('jumpingFields');
        if (jumpingFields) {
            jumpingFields.style.display = 'block';
            console.log('✅ Showing jumping fields');
        }
        setFieldRequired('faultPoints', true);
        setFieldRequired('percentage', false);
        setFieldRequired('scheme', false);
        setFieldRequired('distance', false);
        
    } else if (discipline === 'kestvusratsutamine') {
        const enduranceFields = document.getElementById('enduranceFields');
        if (enduranceFields) {
            enduranceFields.style.display = 'block';
            console.log('✅ Showing endurance fields');
        }
        setFieldRequired('distance', true);
        setFieldRequired('percentage', false);
        setFieldRequired('scheme', false);
        setFieldRequired('faultPoints', false);
    }
}

function setFieldRequired(fieldId, required) {
    const field = document.getElementById(fieldId);
    if (field) {
        if (required) {
            field.setAttribute('required', 'required');
        } else {
            field.removeAttribute('required');
        }
    }
}

function getDisciplineName(discipline) {
    const names = {
        'koolisoit': 'Koolisõit',
        'takistussoit': 'Takistussõit', 
        'kestvusratsutamine': 'Kestvusratsutamine'
    };
    return names[discipline] || discipline;
}

function formatSecondsToInput(seconds, includeHours = false) {
    if (!seconds) return '';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    
    if (includeHours) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    } else {
        return `${minutes}:${secs.toString().padStart(2, '0')}`;
    }
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('et-EE');
}

// PARANDATUD: Event listeners
document.addEventListener('DOMContentLoaded', function() {
    console.log('🏇 Athlete results page loading...');
    
    // Reset forms when opening modals
    const addResultButtons = document.querySelectorAll('button[onclick="openModal(\'resultModal\')"]');
    addResultButtons.forEach(button => {
        button.addEventListener('click', resetResultForm);
    });
    
    // Competition modal reset
    const addCompetitionButtons = document.querySelectorAll('button[onclick="openModal(\'competitionModal\')"]');
    addCompetitionButtons.forEach(button => {
        button.addEventListener('click', resetCompetitionForm);
    });
    
    // Multi-day checkbox listener - kasutab main.js funktsiooni
    const multiDayCheckbox = document.getElementById('is_multi_day');
    if (multiDayCheckbox) {
        multiDayCheckbox.addEventListener('change', function() {
            if (typeof toggleDateFields === 'function') {
                toggleDateFields();
            }
        });
    }
    
    // Competition dropdown change listener - PARANDATUD
    const competitionSelect = document.getElementById('competitionId');
    if (competitionSelect) {
        competitionSelect.addEventListener('change', updateAthleteCompetitionDisciplines);
    }
    
    // Discipline change listener - PARANDATUD
    const disciplineSelect = document.getElementById('discipline');
    if (disciplineSelect) {
        disciplineSelect.addEventListener('change', toggleDisciplineFields);
    }
    
    // Competition search listeners
    const searchInput = document.getElementById('competition_search');
    if (searchInput) {
        searchInput.addEventListener('change', function() {
            handleCompetitionSearch(this.value);
        });
        
        // Auto-focus search when modal opens
        const modal = document.getElementById('resultModal');
        if (modal) {
            modal.addEventListener('show', function() {
                setTimeout(() => {
                    if (!isDropdownMode) {
                        searchInput.focus();
                    }
                }, 100);
            });
        }
    }
    
    console.log('✅ Athlete results initialized with FIXED jumping time validation!');
});

// Make functions global
window.editResult = editResult;
window.resetResultForm = resetResultForm;
window.resetCompetitionForm = resetCompetitionForm;
window.setHeight = setHeight;
window.setAthleteDistance = setAthleteDistance;
window.handleCompetitionSearch = handleCompetitionSearch;
window.selectCompetition = selectCompetition;
window.clearCompetitionSelection = clearCompetitionSelection;
window.toggleCompetitionMode = toggleCompetitionMode;
window.updateAthleteCompetitionDisciplines = updateAthleteCompetitionDisciplines;
window.toggleDisciplineFields = toggleDisciplineFields;
window.validateJumpingTime = validateJumpingTime;
window.validateJumpingTimeFormat = validateJumpingTimeFormat;
window.calculateAthleteSpeedPreview = calculateAthleteSpeedPreview;

console.log('🔧 FIXED athlete results with jumping time validation loaded successfully!');
</script>

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