<?php
include '../includes/auth.php';
include '../includes/db.php';

$judge_id = $_SESSION['judge_id'];
$user_role = $_SESSION['role'] ?? '';

// Check if user is a head judge in users table OR is admin
$is_head_stmt = $pdo->prepare("SELECT judge_id FROM users WHERE id = ? AND judge_id = 1");
$is_head_stmt->execute([$judge_id]);
$is_head = $is_head_stmt->fetchColumn();

if (!$is_head && $user_role !== 'admin') {
    die('<div class="alert alert-danger">Access denied: Not a head judge or admin.</div>');
}
// Add this new AJAX action for getting event categories
    if (isset($_POST['action']) && $_POST['action'] === 'get_event_categories') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                // Get categories from event_categories table for this event
                $categories_stmt = $pdo->prepare("
                    SELECT DISTINCT ec.category_name as category
                    FROM event_categories ec
                    WHERE ec.event_id = ?
                    ORDER BY ec.category_name
                ");
                $categories_stmt->execute([$event_id]);
                $categories = $categories_stmt->fetchAll(PDO::FETCH_COLUMN);
                
                echo json_encode([
                    'success' => true,
                    'categories' => $categories
                ]);
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error fetching categories: ' . $e->getMessage()
                ]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event_id']);
        }
        exit;
    }

// Add AJAX action for getting format figures
    if (isset($_POST['action']) && $_POST['action'] === 'get_format_figures') {
        $event_id = $_POST['event_id'] ?? null;
        
        if ($event_id) {
            try {
                // Get the scoring format for this event
                $format_stmt = $pdo->prepare("
                    SELECT sf.format_id, sf.name
                    FROM events e
                    LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
                    WHERE e.id = ?
                ");
                $format_stmt->execute([$event_id]);
                $format = $format_stmt->fetch(PDO::FETCH_ASSOC);
                
                // Debug: Add format info to response
                $debug_info = [
                    'event_id' => $event_id,
                    'format_found' => $format && !empty($format['format_id']),
                    'format_details' => $format
                ];
                
                if ($format && !empty($format['format_id'])) {
                    // Get figure categories and items for this format's sport
                    // First get the sport for this format
                    $sport_stmt = $pdo->prepare("SELECT sport FROM scoring_formats WHERE format_id = ?");
                    $sport_stmt->execute([$format['format_id']]);
                    $sport_info = $sport_stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($sport_info && !empty($sport_info['sport'])) {
                        $categories_stmt = $pdo->prepare("
                            SELECT fc.id, fc.category_name, fi.id as item_id, fi.item_name
                            FROM figure_categories fc
                            LEFT JOIN figure_items fi ON fc.sport_name = fi.sport_name AND fc.category_name = fi.category_name
                            WHERE fc.sport_name = ? AND fc.is_active = 1
                            ORDER BY fc.sort_order ASC, fi.sort_order ASC
                        ");
                        $categories_stmt->execute([$sport_info['sport']]);
                        $figures_raw = $categories_stmt->fetchAll(PDO::FETCH_ASSOC);
                        
                        $debug_info['sport'] = $sport_info['sport'];
                        $debug_info['figures_raw_count'] = count($figures_raw);
                        $debug_info['figures_raw'] = $figures_raw;
                    
                        // Organize by categories
                        $figures = [];
                        foreach ($figures_raw as $row) {
                            $cat_name = $row['category_name'];
                            if (!isset($figures[$cat_name])) {
                                $figures[$cat_name] = [];
                            }
                            if ($row['item_id']) {
                                $figures[$cat_name][] = [
                                    'id' => $row['item_id'],
                                    'name' => $row['item_name']
                                ];
                            }
                        }
                        
                        // Check if we have any figures configured
                        $has_figures = false;
                        foreach ($figures as $items) {
                            if (count($items) > 0) {
                                $has_figures = true;
                                break;
                            }
                        }
                        
                        echo json_encode([
                            'success' => true,
                            'format' => $format,
                            'figures' => $figures,
                            'has_figures' => $has_figures,
                            'debug' => $debug_info
                        ]);
                    } else {
                        echo json_encode([
                            'success' => false,
                            'message' => 'No sport information found for this scoring format',
                            'debug' => $debug_info
                        ]);
                    }
                } else {
                    echo json_encode([
                        'success' => true,
                        'format' => null,
                        'figures' => [],
                        'debug' => $debug_info,
                        'message' => 'No format found for event'
                    ]);
                }
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error fetching format figures: ' . $e->getMessage()
                ]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event_id']);
        }
        exit;
    }
// Handle approve all participants action
if (isset($_POST['action']) && $_POST['action'] === 'approve_all_participant') {
        $event_id = $_POST['event_id'];
        $heat_number = $_POST['heat_number'];
        $run_number = $_POST['run_number'];
        $participant_id = $_POST['participant_id'];
        
        try {
            // Get the judge_id from users table for the approved_by field
            $judge_lookup_stmt = $pdo->prepare("SELECT judge_id FROM users WHERE id = ?");
            $judge_lookup_stmt->execute([$judge_id]);
            $approved_by_judge_id = $judge_lookup_stmt->fetchColumn();
            
            // Get all unapproved scores for this participant in this heat/run
            $scores_stmt = $pdo->prepare("
                SELECT s.id
                FROM scores s
                JOIN runs r ON s.run_id = r.id
                JOIN event_participants ep ON r.event_participant_id = ep.id
                WHERE ep.event_id = ? AND ep.heat_number = ? AND r.run_number = ? 
                AND ep.id = ? AND s.is_approved = 0
            ");
            $scores_stmt->execute([$event_id, $heat_number, $run_number, $participant_id]);
            $score_ids = $scores_stmt->fetchAll(PDO::FETCH_COLUMN);
            
            if (count($score_ids) > 0) {
                // Approve all scores for this participant - using judge_id instead of user id
                $placeholders = str_repeat('?,', count($score_ids) - 1) . '?';
                $approve_stmt = $pdo->prepare("
                    UPDATE scores 
                    SET is_approved = 1, approved_by = ?, approved_at = NOW() 
                    WHERE id IN ($placeholders)
                ");
                $params = array_merge([$approved_by_judge_id], $score_ids);
                $approve_stmt->execute($params);
                
                echo json_encode([
                    'success' => true, 
                    'message' => 'All scores approved for participant',
                    'count' => count($score_ids)
                ]);
            } else {
                echo json_encode([
                    'success' => true, 
                    'message' => 'No pending scores to approve',
                    'count' => 0
                ]);
            }
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Error approving scores: ' . $e->getMessage()
            ]);
        }
        exit;
    }

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    if (isset($_POST['action']) && $_POST['action'] === 'get_scores') {
        $event_id = $_POST['event_id'] ?? null;
        $heat_number = $_POST['heat_number'] ?? null;
        $run_number = $_POST['run_number'] ?? null;
        
        if ($event_id && $heat_number && $run_number) {
            try {
                // UPDATED: Get all judges for this event from users table
                $judges_stmt = $pdo->prepare("
                    SELECT DISTINCT u.id, u.username as name, cp.control_point_name as control_point_name, cp.id as control_point_id
                    FROM users u
                    JOIN judge_assignments ja ON u.id = ja.judge_id
                    LEFT JOIN event_control_points cp ON ja.control_point_id = cp.id
                    WHERE ja.event_id = ? 
                    ORDER BY cp.control_point_name ASC, u.username ASC
                ");
                $judges_stmt->execute([$event_id]);
                $judges = $judges_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Get all participants in this heat - UPDATED to get category from event_categories
                $participants_stmt = $pdo->prepare("
                    SELECT ep.id, ep.bib_number, ep.sort_order, ep.category as event_category,
                           p.first_name, p.last_name, p.club, p.category as base_category, p.gender,
                           COALESCE(ec.category_name, ep.category, p.category) as category
                    FROM event_participants ep
                    JOIN participants p ON ep.participant_id = p.id
                    LEFT JOIN event_categories ec ON ep.category_id = ec.id
                    WHERE ep.event_id = ? AND ep.heat_number = ?
                    ORDER BY ep.sort_order ASC, ep.bib_number ASC
                ");
                $participants_stmt->execute([$event_id, $heat_number]);
                $participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
                // Get scores for this heat/run combination with approval status AND created_at for sorting
                // Check if figures_json column exists
                $figures_column = '';
                try {
                    $check_column = $pdo->query("SHOW COLUMNS FROM scores LIKE 'figures_json'");
                    if ($check_column->rowCount() > 0) {
                        $figures_column = ', s.figures_json';
                    }
                } catch (Exception $e) {
                    // Column doesn't exist, continue without it
                }
                
                $scores_stmt = $pdo->prepare("
                    SELECT s.judge_id, ep.id as ep_id, s.score_value, s.status, s.id as score_id, 
                           COALESCE(s.is_approved, 0) as is_approved, s.created_at{$figures_column}
                    FROM scores s
                    JOIN runs r ON s.run_id = r.id
                    JOIN event_participants ep ON r.event_participant_id = ep.id
                    WHERE ep.event_id = ? AND ep.heat_number = ? AND r.run_number = ?
                ");
                $scores_stmt->execute([$event_id, $heat_number, $run_number]);
                $scores_raw = $scores_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Organize scores by participant and judge
                $scores = [];
                foreach ($scores_raw as $score) {
                    $scores[$score['ep_id']][$score['judge_id']] = $score;
                }
                
                echo json_encode([
                    'success' => true,
                    'judges' => $judges,
                    'participants' => $participants,
                    'scores' => $scores
                ]);
                
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $e->getMessage()
                ]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing parameters']);
        }
        exit;
    }
    
       if (isset($_POST['action']) && $_POST['action'] === 'approve_score') {
        $score_id = $_POST['score_id'];
        
        try {
            // Get the judge_id from users table for the approved_by field
            $judge_lookup_stmt = $pdo->prepare("SELECT judge_id FROM users WHERE id = ?");
            $judge_lookup_stmt->execute([$judge_id]);
            $approved_by_judge_id = $judge_lookup_stmt->fetchColumn();
            
            $approve_stmt = $pdo->prepare("UPDATE scores SET is_approved = 1, approved_by = ?, approved_at = NOW() WHERE id = ?");
            $approve_stmt->execute([$approved_by_judge_id, $score_id]);
            
            echo json_encode(['success' => true, 'message' => 'Score approved successfully']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error approving score: ' . $e->getMessage()]);
        }
        exit;
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'update_score') {
        $score_id = $_POST['score_id'];
        $new_score = $_POST['score_value'] !== '' ? floatval($_POST['score_value']) : null;
        $status = $_POST['status'];
        $figures_json = $_POST['figures_json'] ?? null;
        
        try {
            // Check if figures_json column exists
            $figures_column_exists = false;
            try {
                $check_column = $pdo->query("SHOW COLUMNS FROM scores LIKE 'figures_json'");
                $figures_column_exists = $check_column->rowCount() > 0;
            } catch (Exception $e) {
                // Column doesn't exist
            }
            
            if ($figures_column_exists && isset($_POST['figures_json'])) {
                // Handle figures_json data
                $figures_value = null;
                if ($figures_json === 'null' || $figures_json === '') {
                    $figures_value = null;
                } else {
                    // Validate it's proper JSON and not empty object with empty arrays
                    try {
                        $decoded = json_decode($figures_json, true);
                        if ($decoded && is_array($decoded)) {
                            // Check if any category has non-empty data
                            $hasData = false;
                            foreach ($decoded as $category => $items) {
                                if (is_array($items) && count($items) > 0) {
                                    $hasData = true;
                                    break;
                                }
                            }
                            $figures_value = $hasData ? $figures_json : null;
                        } else {
                            $figures_value = null;
                        }
                    } catch (Exception $e) {
                        $figures_value = null;
                    }
                }
                
                // Update with figures_json
                $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, figures_json = ?, updated_at = NOW(), is_approved = 0 WHERE id = ?");
                $update_stmt->execute([$new_score, $status, $figures_value, $score_id]);
            } else {
                // Update without figures_json
                $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, updated_at = NOW(), is_approved = 0 WHERE id = ?");
                $update_stmt->execute([$new_score, $status, $score_id]);
            }
            
            echo json_encode(['success' => true, 'message' => 'Score updated successfully (requires re-approval)']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error updating score: ' . $e->getMessage()]);
        }
        exit;
    }
    
    // NEW: Handle create empty score action
    if (isset($_POST['action']) && $_POST['action'] === 'create_score') {
        $event_id = $_POST['event_id'];
        $heat_number = $_POST['heat_number'];
        $run_number = $_POST['run_number'];
        $participant_id = $_POST['participant_id'];
        $judge_id_target = $_POST['judge_id'];
        $score_value = $_POST['score_value'] !== '' ? floatval($_POST['score_value']) : null;
        $status = $_POST['status'];
        $figures_json = isset($_POST['figures_json']) ? $_POST['figures_json'] : null;
        
        try {
            // First, find or create the run for this participant/heat/run combination
            $run_stmt = $pdo->prepare("
                SELECT r.id 
                FROM runs r 
                JOIN event_participants ep ON r.event_participant_id = ep.id 
                WHERE ep.id = ? AND r.run_number = ?
            ");
            $run_stmt->execute([$participant_id, $run_number]);
            $run_id = $run_stmt->fetchColumn();
            
            if (!$run_id) {
                // Create the run if it doesn't exist
                $create_run_stmt = $pdo->prepare("INSERT INTO runs (event_participant_id, run_number) VALUES (?, ?)");
                $create_run_stmt->execute([$participant_id, $run_number]);
                $run_id = $pdo->lastInsertId();
            }
            
            // Check if scores table has figures_json column
            $hasColumnsQuery = "SHOW COLUMNS FROM scores LIKE 'figures_json'";
            $hasColumnsStmt = $pdo->query($hasColumnsQuery);
            $hasFiguresColumn = $hasColumnsStmt->rowCount() > 0;
            
            // Process figures_json data
            $figures_value = null;
            if ($hasFiguresColumn && $figures_json) {
                try {
                    $decoded = json_decode($figures_json, true);
                    if ($decoded && is_array($decoded)) {
                        // Check if any category has non-empty data
                        $hasData = false;
                        foreach ($decoded as $category => $items) {
                            if (is_array($items) && count($items) > 0) {
                                $hasData = true;
                                break;
                            }
                        }
                        $figures_value = $hasData ? $figures_json : null;
                    } else {
                        $figures_value = null;
                    }
                } catch (Exception $e) {
                    $figures_value = null;
                }
            }
            
            // Create the score with or without figures_json based on column existence
            if ($hasFiguresColumn) {
                $create_score_stmt = $pdo->prepare("
                    INSERT INTO scores (run_id, judge_id, score_value, status, figures_json, created_at, is_approved) 
                    VALUES (?, ?, ?, ?, ?, NOW(), 0)
                ");
                $create_score_stmt->execute([$run_id, $judge_id_target, $score_value, $status, $figures_value]);
            } else {
                $create_score_stmt = $pdo->prepare("
                    INSERT INTO scores (run_id, judge_id, score_value, status, created_at, is_approved) 
                    VALUES (?, ?, ?, ?, NOW(), 0)
                ");
                $create_score_stmt->execute([$run_id, $judge_id_target, $score_value, $status]);
            }
            
            echo json_encode(['success' => true, 'message' => 'Score created successfully (requires approval)']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error creating score: ' . $e->getMessage()]);
        }
        exit;
    }
    
    // If no action matched, return error
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

// UPDATED: Get events - admins see all events, head judges see only assigned events
if ($user_role === 'admin') {
    // Admin sees all events
    $events_stmt = $pdo->prepare("
        SELECT DISTINCT e.id, e.name, e.date
        FROM events e
        ORDER BY e.date DESC, e.name
    ");
    $events_stmt->execute();
} else {
    // Head judges see only assigned events
    $events_stmt = $pdo->prepare("
        SELECT DISTINCT e.id, e.name, e.date
        FROM events e
        JOIN judge_assignments ja ON e.id = ja.event_id
        WHERE ja.judge_id = ?
        ORDER BY e.date DESC, e.name
    ");
    $events_stmt->execute([$judge_id]);
}
$events = $events_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Head Judge Panel</title>
    <!-- style skin holder -->
 <?php include_once '../includes/stylesheets.php'; ?>
    
    <style>
        .card-hover:hover {
            transform: translateY(-2px);
            transition: transform 0.2s ease-in-out;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .cursor-pointer {
            cursor: pointer;
        }
              
        .scale-6  { box-shadow: inset 15px 0 30px  hsla(0, 100%, 50%, 0.15),   inset 0px 0px 0px hsla(0, 100%, 50%, 0.15) !important; }
        .scale-10  { box-shadow: inset 15px 0 30px  hsla(30, 100%, 50%, 0.15),  inset 0px 0px 0px hsla(30, 100%, 50%, 0.15) !important; }
        .scale-3  { box-shadow: inset 15px 0 30px  hsla(60, 100%, 50%, 0.15),  inset 0px 0px 0px hsla(60, 100%, 50%, 0.15) !important; }
        .scale-4  { box-shadow: inset 15px 0 30px  hsla(90, 100%, 50%, 0.15),  inset 0px 0px 0px hsla(90, 100%, 50%, 0.15) !important; }
        .scale-5  { box-shadow: inset 15px 0 30px  hsla(120, 100%, 50%, 0.15), inset 0px 0px 0px hsla(120, 100%, 50%, 0.15) !important; }
        .scale-7  { box-shadow: inset 15px 0 30px  hsla(150, 100%, 50%, 0.15), inset 0px 0px 0px hsla(150, 100%, 50%, 0.15) !important; }
        .scale-1  { box-shadow: inset 15px 0 30px  hsla(180, 100%, 50%, 0.15), inset 0px 0px 0px hsla(180, 100%, 50%, 0.15) !important; }
        .scale-8  { box-shadow: inset 15px 0 30px  hsla(210, 100%, 50%, 0.15), inset 0px 0px 0px hsla(210, 100%, 50%, 0.15) !important; }
        .scale-9  { box-shadow: inset 15px 0 30px  hsla(240, 100%, 50%, 0.15), inset 0px 0px 0px hsla(240, 100%, 50%, 0.15) !important; }
        .scale-2 { box-shadow: inset 15px 0 30px  hsla(270, 100%, 50%, 0.15), inset 0px 0px 0px hsla(270, 100%, 50%, 0.15) !important; }
        .scale-11 { box-shadow: inset 15px 0 30px  hsla(300, 100%, 50%, 0.15), inset 0px 0px 0px hsla(300, 100%, 50%, 0.15) !important; }
        .scale-12 { box-shadow: inset 15px 0 30px  hsla(330, 100%, 50%, 0.15), inset 0px 0px 0px hsla(330, 100%, 50%, 0.15) !important; }

.bg-approved {
    /* background-color: gray;*/
    background: linear-gradient(180deg, #00aa0740 0%, #00ff0a00 10%, #00ff0a00 90%, #00aa0740 100%); 
}
.bg-pending {
    /* background-color: gray; */
    background: linear-gradient(180deg, #67676740 0%, rgba(0, 51, 170, 0) 5%, rgba(0, 51, 170, 0) 95%, #67676740 100%);
}
.bg-empty {
    background: linear-gradient(180deg, #6c757d87 0%, rgba(108, 117, 125, 0) 25%, rgba(108, 117, 125, 0) 75%, #6c757d87 100%)
}
tr.bg-approved .resultCom,  tr.bg-approved .scoreCol{

    background: linear-gradient(180deg, #00b30773 0%, #00b30700 30%, #00b30700 70%, #00b30773 100%) !important;
}
.figures-display {
    
    border-radius: 0.375rem;
    padding: 0.5rem;
    grid-template-columns: auto auto auto;
    align-self: center !important;
}
.row.score-figure {
    display: flex !important;
    grid-template-columns: auto auto;
    justify-items: center !important;
    min-height: auto;
    flex-wrap: wrap;
    flex-direction: row;
}

.table-responsive td .figures-display, .figure-s {
    transition: transform 0.4s ease-in-out;
    cursor: pointer;
}

.table-responsive td:hover .figures-display, .figure-s:hover{
    transform: scale(1.2);
    z-index: 10;
    position: relative;
}


.bg-empty .row.score-figure {
    display: grid !important;
    grid-template-columns: auto;
    align-items: center !important;
    justify-items: center !important;
}
.scores-col2 {
    align-self: center !important;
    justify-self: center !important;
}
.scores-col1 {
    align-self: center !important;
    justify-self: center !important;
}

/* Center align all table cell content */
.table td {
    vertical-align: middle !important;
    text-align: center !important;
}

/* Ensure the first column (participant info) is left-aligned for readability */
.table td:first-child {
    text-align: left !important;
}

/* Center all content within score cells */
.table td .row.score-figure {
    justify-content: center !important;
    align-items: center !important;
    width: 100% !important;
    margin: 0 !important;
}

/* Center the grid columns */
.scores-col1, .scores-col2 {
    display: flex !important;
    flex-direction: column !important;
    align-items: center !important;
    justify-content: center !important;
}

/* Center figures display content */
.figures-display {
    text-align: center !important;
    display: flex !important;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-evenly;
}

/* Center empty score cells */
.bg-empty .row.score-figure > div {
    
}
.pendingActions {
    backdrop-filter: blur(11px);
    width: 100px !important;
}
.OK .approval-clickable{
    display: none;
}
.editScoreButton {
    display: none !important;
}
.bg-pending .bg-danger.approval-clickable {
    display: block;
}
div#scoresContainer td {
    padding: 5px;
}
#scoresWrapper {
    max-height: 90vh;
    overflow: auto;
    scroll-behavior: smooth;
}
td.participantCol {
    width: 280px;
}

td.resultCom.text-center {
    width: 100px;
}

td.actionsCol.text-center {
    width: 100px;
}

/* Figure chip styles */
.figure-chip {
    transition: all 0.2s ease;
    border: 1px solid #6c757d !important;
    color: #6c757d !important;
}

.figure-chip:hover {
    border-color: #0d6efd !important;
    color: #0d6efd !important;
    background-color: rgba(13, 110, 253, 0.1) !important;
}

.figure-chip.active {
    background-color: #0d6efd !important;
    border-color: #0d6efd !important;
    color: white !important;
}

.figure-chip.active:hover {
    background-color: #0b5ed7 !important;
    border-color: #0b5ed7 !important;
}

.figure-category h6 {
    font-weight: 600;
}

.figure-chips {
    min-height: 2.5rem;
}

/* Edit Score Modal Styles */
#editScoreInfo {
    background: linear-gradient(135deg, #e8f4fd 0%, #f0f8ff 100%);
    border: 1px solid #b3d9f2;
    border-radius: 8px;
}

#editScoreInfo h6 {
    color: #1e3a8a;
    font-weight: 600;
    border-bottom: 1px solid rgba(30, 58, 138, 0.2);
    padding-bottom: 0.5rem;
}

#editScoreInfo .mb-2 {
    margin-bottom: 0.75rem !important;
    padding: 0.25rem 0;
    border-radius: 4px;
    transition: background-color 0.2s ease;
}

#editScoreInfo .mb-2:hover {
    background-color: rgba(59, 130, 246, 0.05);
    padding-left: 0.5rem;
    margin-left: -0.5rem;
    margin-right: -0.5rem;
}

#editScoreInfo .badge {
    font-size: 0.75rem;
    padding: 0.35em 0.6em;
}

#editScoreInfo .text-muted {
    opacity: 0.7;
}

    </style>
</head>

<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>

    <div class="container-fluid mt-4">
            <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include '../admin/event_actions_menu.php'; 
        ?>
    </div>
</div>
        <div class="row">
            <div class="col-12">
                <!-- Control Panel -->
                <div class="card bg-primary text-white mb-3">
                    <div class="card-body py-2">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h6 class="mb-0 fw-bold">
                                <i class="fas fa-crown me-1"></i>
                                <?php if ($user_role === 'admin'): ?>
                                    Admin Panel
                                    <span class="badge bg-danger ms-1 small">Admin</span>
                                <?php else: ?>
                                    Head Judge Panel
                                    <span class="badge bg-warning ms-1 small">Judge</span>
                                <?php endif; ?>
                            </h6>
                            <span class="badge bg-success small">Live</span>
                        </div>
                        <div class="row g-2">
                            <div class="col-md-3">
                                <select class="form-select form-select-sm" id="eventSelect">
                                    <option value="">Select Event</option>
                                    <?php foreach ($events as $event): ?>
                                        <option value="<?= $event['id'] ?>"><?= htmlspecialchars($event['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <select class="form-select form-select-sm" id="heatSelect" disabled>
                                    <option value="">Heat</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <select class="form-select form-select-sm" id="runSelect" disabled>
                                    <option value="">Run</option>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="d-flex gap-1">
                                    <button class="btn btn-light btn-sm" id="refreshBtn">
                                        <i class="fas fa-sync-alt"></i> Refresh
                                    </button>
                                    <button class="btn btn-outline-secondary btn-sm" id="clearSelectionsBtn" title="Clear selections">
                                        <i class="fas fa-eraser"></i>
                                    </button>
                                    <button class="btn btn-outline-info btn-sm" id="testAutoPopulateBtn" title="Auto-populate">
                                        <i class="fas fa-magic"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="autoRefresh" checked>
                                    <label class="form-check-label small" for="autoRefresh">
                                        Auto-refresh
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Score Grid -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="mb-0">
                            <i class="fas fa-table me-2"></i>Heat/Run Overview
                            <?php if ($user_role === 'admin'): ?>
                                <span class="badge bg-danger ms-2">Admin Override Enabled</span>
                            <?php endif; ?>
                        </h4>
                        <div class="spinner-border spinner-border-sm text-primary d-none" id="loadingSpinner">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                    
                    <div class="card-body">
                        <!-- Sort Controls -->
                        <!-- Sort Controls -->
                        <div class="sort-controls d-none" id="sortControls">
                            <div class="d-flex align-items-center justify-content-between flex-wrap gap-3 mb-3">
                                <div class="d-flex align-items-center gap-2">
                                    <span class="fw-bold text-muted">
                                        <i class="fas fa-sort me-1"></i>Sort Order:
                                    </span>
                                    <div class="btn-group" role="group">
                                        <button type="button" class="btn btn-sm btn-outline-primary active" data-sort="default">
                                            <i class="fas fa-list-ol me-1"></i>Default Order
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-primary" data-sort="average">
                                            <i class="fas fa-trophy me-1"></i>By Average (High-Low)
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-primary" data-sort="latest">
                                            <i class="fas fa-clock me-1"></i>By Latest Score
                                        </button>
                                    </div>
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    <span class="badge bg-info" id="sortableCount">0 complete participants</span>
                                    <small class="text-muted">Only participants with all judge scores can be sorted</small>
                                </div>
                            </div>

                            <!-- Filter Controls -->
                            <div class="border-top pt-3">
                                <div class="row g-2 align-items-end">
                                    <div class="col-md-3">
                                        <label class="form-label fw-bold text-muted">
                                            <i class="fas fa-filter me-1"></i>Filters:
                                        </label>
                                        <select class="form-select form-select-sm" id="genderFilter">
                                            <option value="">All Genders</option>
                                            <option value="M">Male Only</option>
                                            <option value="F">Female Only</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <select class="form-select form-select-sm" id="categoryFilter">
                                            <option value="">All Categories</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Approval Status:</label>
                                        <div class="d-flex gap-2 flex-wrap">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="showToApprove" checked>
                                                <label class="form-check-label" for="showToApprove">
                                                    <span class="badge bg-warning">To Approve</span>
                                                </label>
                                            </div>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="showAllApproved" checked>
                                                <label class="form-check-label" for="showAllApproved">
                                                    <span class="badge bg-success">All Approved</span>
                                                </label>
                                            </div>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="showWaiting" checked>
                                                <label class="form-check-label" for="showWaiting">
                                                    <span class="badge bg-secondary">Waiting</span>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="mt-2">
                                    <div class="d-flex align-items-center justify-content-between">
                                        <small class="text-muted">
                                            <span id="filteredCount">0</span> of <span id="totalCount">0</span> participants shown
                                        </small>
                                        <button class="btn btn-outline-secondary btn-sm" id="clearFilters">
                                            <i class="fas fa-times me-1"></i>Clear All Filters
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center text-muted py-5" id="noDataMessage">
                            <i class="fas fa-clipboard-list fa-3x mb-3 opacity-50"></i>
                            <h5>Select Event, Heat, and Run to view scores</h5>
                            <p>Use the controls above to navigate to specific scoring sessions</p>
                        </div>
                        <div id="scoresWrapper">
                            <div id="scoresContainer" style="display: none;">
                                <!-- Dynamic content will be loaded here -->
                            </div>
                        </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Success Toast -->
    <div class="toast-container position-fixed top-0 end-0 p-3">
        <div id="successToast" class="toast" role="alert">
            <div class="toast-header bg-success text-white">
                <i class="fas fa-check-circle me-2"></i>
                <strong class="me-auto">Success</strong>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                Updated successfully
            </div>
        </div>
    </div>
    
    <!-- Edit Score Modal -->
    <div class="modal fade" id="editScoreModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-edit me-2"></i>
                        <?php echo $user_role === 'admin' ? 'Admin Override - Edit Score' : 'Head Judge Override - Edit Score'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- Participant and Context Information -->
                    <div class="alert alert-info mb-3" id="editScoreInfo">
                        <div class="text-center text-muted">
                            <i class="fas fa-spinner fa-spin me-2"></i>Loading participant information...
                        </div>
                    </div>
                    
                    <form id="editScoreForm">
                        <input type="hidden" id="editScoreId">
                        
                        <div class="mb-3">
                            <label class="form-label">Score (0-99)</label>
                            <input type="number" class="form-control" id="editScoreValue" min="0" max="99" step="1">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" id="editScoreStatus">
                                <option value="OK">OK - Valid Score</option>
                                <option value="DNS">DNS - Did Not Start</option>
                                <option value="DNF">DNF - Did Not Finish</option>
                                <option value="DSQ">DSQ - Disqualified</option>
                            </select>
                        </div>
                        
                        <div class="mb-3" id="editScoreFigures" style="display:none;">
                            <label class="form-label">Figures</label>
                            <div class="small text-muted mb-2" id="editScoreFiguresContent"></div>
                            <div id="editFiguresEditor" style="display:none;">
                                <div class="border rounded p-3 bg-light">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <small class="fw-bold text-muted">Edit Figures:</small>
                                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="cancelEditFigures()">
                                            <i class="fas fa-times"></i> Cancel
                                        </button>
                                    </div>
                                    <div id="editFigureCategories"></div>
                                    <button type="button" class="btn btn-sm btn-success mt-2" onclick="saveFiguresEdit()">
                                        <i class="fas fa-save"></i> Save Figures
                                    </button>
                                </div>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-primary mt-2" id="editFiguresBtn" onclick="startEditFigures()" style="display:none;">
                                <i class="fas fa-edit"></i> Edit Figures
                            </button>
                        </div>
                        
                        <div class="alert alert-<?php echo $user_role === 'admin' ? 'danger' : 'warning'; ?>">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong><?php echo $user_role === 'admin' ? 'Admin Override:' : 'Head Judge Override:'; ?></strong> 
                            This will permanently modify the judge's score and require re-approval.
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="saveScoreBtn">
                        <i class="fas fa-save me-2"></i>Update Score
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Score Modal -->
    <div class="modal fade" id="createScoreModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-plus me-2"></i>
                        <?php echo $user_role === 'admin' ? 'Admin - Create Score' : 'Head Judge - Create Score'; ?>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Creating score for:</strong>
                        <div id="createScoreInfo" class="mt-2"></div>
                    </div>
                    
                    <form id="createScoreForm">
                        <input type="hidden" id="createParticipantId">
                        <input type="hidden" id="createJudgeId">
                        
                        <div class="mb-3">
                            <label class="form-label">Score (0-99)</label>
                            <input type="number" class="form-control" id="createScoreValue" min="0" max="99" step="1" placeholder="Enter score">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" id="createScoreStatus">
                                <option value="OK">OK - Valid Score</option>
                                <option value="DNS">DNS - Did Not Start</option>
                                <option value="DNF">DNF - Did Not Finish</option>
                                <option value="DSQ">DSQ - Disqualified</option>
                            </select>
                        </div>
                        
                        <!-- Figures Section -->
                        <div class="mb-3" id="createFiguresSection" style="display: none;">
                            <label class="form-label">
                                <i class="fas fa-star me-1"></i>Figures
                                <span class="badge bg-secondary ms-1">Optional</span>
                            </label>
                            <div id="createFiguresContainer">
                                <div class="text-muted">Loading figure options...</div>
                            </div>
                        </div>
                        
                        <div class="alert alert-<?php echo $user_role === 'admin' ? 'danger' : 'warning'; ?>">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong><?php echo $user_role === 'admin' ? 'Admin:' : 'Head Judge:'; ?></strong> 
                            This will create a new score entry that requires approval.
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" id="createScoreBtn">
                        <i class="fas fa-plus me-2"></i>Create Score
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    
    
    <script>
         let autoRefreshInterval;
        let currentData = null;
        let currentSortMode = 'default';
        let currentFilters = {
            gender: '',
            category: '',
            showToApprove: true,
            showAllApproved: true,
            showWaiting: true
        };
        
        document.addEventListener('DOMContentLoaded', function() {
            const eventSelect = document.getElementById('eventSelect');
            const heatSelect = document.getElementById('heatSelect');
            const runSelect = document.getElementById('runSelect');
            const refreshBtn = document.getElementById('refreshBtn');
            const autoRefreshCheck = document.getElementById('autoRefresh');
            
            // Initialize Event Selection Manager for this page
            if (window.EventSelectionManager) {
                window.EventSelectionManager.init();
            }
            
            // Sort button handlers
            document.querySelectorAll('.btn-outline-primary[data-sort]').forEach(btn => {
                btn.addEventListener('click', function() {
                    if (this.classList.contains('disabled')) return;
                    
                    // Update active state
                    document.querySelectorAll('.btn-outline-primary[data-sort]').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    // Update sort mode and re-render
                    currentSortMode = this.getAttribute('data-sort');
                    if (currentData) {
                        renderScoreGrid(currentData);
                    }
                });
            });

            // Filter handlers
            document.getElementById('genderFilter').addEventListener('change', function() {
                currentFilters.gender = this.value;
                if (currentData) {
                    renderScoreGrid(currentData);
                }
            });

            document.getElementById('categoryFilter').addEventListener('change', function() {
                currentFilters.category = this.value;
                if (currentData) {
                    renderScoreGrid(currentData);
                }
            });

            document.getElementById('showToApprove').addEventListener('change', function() {
                currentFilters.showToApprove = this.checked;
                if (currentData) {
                    renderScoreGrid(currentData);
                }
            });

            document.getElementById('showAllApproved').addEventListener('change', function() {
                currentFilters.showAllApproved = this.checked;
                if (currentData) {
                    renderScoreGrid(currentData);
                }
            });

            document.getElementById('showWaiting').addEventListener('change', function() {
                currentFilters.showWaiting = this.checked;
                if (currentData) {
                    renderScoreGrid(currentData);
                }
            });

            document.getElementById('clearFilters').addEventListener('click', function() {
                // Reset filters
                currentFilters = {
                    gender: '',
                    category: '',
                    showToApprove: true,
                    showAllApproved: true,
                    showWaiting: true
                };
                
                // Reset form controls
                document.getElementById('genderFilter').value = '';
                document.getElementById('categoryFilter').value = '';
                document.getElementById('showToApprove').checked = true;
                document.getElementById('showAllApproved').checked = true;
                document.getElementById('showWaiting').checked = true;
                
                // Re-render
                if (currentData) {
                    renderScoreGrid(currentData);
                }
            });
            
            // Event selection handler - modified to work with localStorage
            eventSelect.addEventListener('change', function() {
                const eventId = this.value;
                heatSelect.disabled = !eventId;
                runSelect.disabled = true;
                
                if (eventId) {
                    loadHeats(eventId);
                    loadEventCategories(eventId); // Load event-specific categories
                } else {
                    heatSelect.innerHTML = '<option value="">Select Heat</option>';
                    runSelect.innerHTML = '<option value="">Select Run</option>';
                    document.getElementById('categoryFilter').innerHTML = '<option value="">All Categories</option>';
                    clearScoreGrid();
                }
            });
            
            // Heat selection handler - modified to work with localStorage
            heatSelect.addEventListener('change', function() {
                const heatNumber = this.value;
                runSelect.disabled = !heatNumber;
                
                if (heatNumber) {
                    loadRuns();
                } else {
                    runSelect.innerHTML = '<option value="">Select Run</option>';
                    clearScoreGrid();
                }
            });
            
            // Run selection handler - modified to work with localStorage
            runSelect.addEventListener('change', function() {
                if (this.value) {
                    loadScores();
                } else {
                    clearScoreGrid();
                }
            });
            
            // Refresh button
            refreshBtn.addEventListener('click', function() {
                if (runSelect.value) {
                    loadScores();
                }
            });
            
            // Clear selections button
            document.getElementById('clearSelectionsBtn').addEventListener('click', function() {
                if (window.EventSelectionManager) {
                    window.EventSelectionManager.clearAllSelections();
                    
                    // Reset form elements
                    eventSelect.value = '';
                    heatSelect.innerHTML = '<option value="">Select Heat</option>';
                    heatSelect.disabled = true;
                    runSelect.innerHTML = '<option value="">Select Run</option>';
                    runSelect.disabled = true;
                    document.getElementById('categoryFilter').innerHTML = '<option value="">All Categories</option>';
                    clearScoreGrid();
                    
                    // Show visual feedback
                    const btn = this;
                    const originalHTML = btn.innerHTML;
                    btn.innerHTML = '<i class="fas fa-check text-success"></i>';
                    btn.classList.add('btn-success');
                    btn.classList.remove('btn-outline-secondary');
                    
                    setTimeout(() => {
                        btn.innerHTML = originalHTML;
                        btn.classList.remove('btn-success');
                        btn.classList.add('btn-outline-secondary');
                    }, 1500);
                }
            });
            
            // Test auto-populate button
            document.getElementById('testAutoPopulateBtn').addEventListener('click', function() {
                if (window.EventSelectionManager) {
                    const selections = window.EventSelectionManager.populateAllForms();
                    
                    // Show feedback
                    const btn = this;
                    const originalHTML = btn.innerHTML;
                    btn.innerHTML = '<i class="fas fa-check text-success"></i>';
                    btn.classList.add('btn-success');
                    btn.classList.remove('btn-outline-info');
                    
                    // Show selections in console
                    console.log('Auto-populated forms with:', selections);
                    
                    // Show toast notification
                    const toast = document.createElement('div');
                    toast.className = 'position-fixed top-0 start-50 translate-middle-x mt-3 alert alert-success alert-dismissible fade show';
                    toast.style.zIndex = '9999';
                    toast.innerHTML = `
                        <i class="fas fa-magic me-2"></i>
                        Auto-populated forms with: Event ${selections.event || 'none'}, Heat ${selections.heat || 'none'}, Run ${selections.run || 'none'}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.body.appendChild(toast);
                    
                    setTimeout(() => {
                        btn.innerHTML = originalHTML;
                        btn.classList.remove('btn-success');
                        btn.classList.add('btn-outline-info');
                        if (toast.parentNode) {
                            toast.remove();
                        }
                    }, 3000);
                }
            });
            
            // Auto-refresh toggle
            autoRefreshCheck.addEventListener('change', function() {
                if (this.checked) {
                    startAutoRefresh();
                } else {
                    stopAutoRefresh();
                }
            });
            
            // Start auto-refresh by default
            startAutoRefresh();
        });

         function updateCategoryFilter(participants) {
            const categoryFilter = document.getElementById('categoryFilter');
            const currentValue = categoryFilter.value;
            
            // Get unique categories from participants
            const categories = [...new Set(participants.map(p => p.category))].filter(c => c).sort();
            
            // Rebuild options
            categoryFilter.innerHTML = '<option value="">All Categories</option>';
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category;
                option.textContent = category;
                if (category === currentValue) {
                    option.selected = true;
                }
                categoryFilter.appendChild(option);
            });
        }

        // Add function to load event categories
        function loadEventCategories(eventId) {
            if (!eventId) {
                document.getElementById('categoryFilter').innerHTML = '<option value="">All Categories</option>';
                return;
            }
            
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'get_event_categories');
            formData.append('event_id', eventId);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const categoryFilter = document.getElementById('categoryFilter');
                    const currentValue = categoryFilter.value;
                    
                    categoryFilter.innerHTML = '<option value="">All Categories</option>';
                    data.categories.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category;
                        option.textContent = category;
                        if (category === currentValue) {
                            option.selected = true;
                        }
                        categoryFilter.appendChild(option);
                    });
                }
            })
            .catch(error => {
                console.error('Error loading categories:', error);
            });
        }

        function getApprovalStatus(participant, judges, scores) {
            let hasAnyScores = false;
            let hasPendingScores = false;
            let hasAllScores = true;
            
            judges.forEach(judge => {
                const score = scores[participant.id] && scores[participant.id][judge.id] ? scores[participant.id][judge.id] : null;
                if (score) {
                    hasAnyScores = true;
                    if (score.is_approved == 0) {
                        hasPendingScores = true;
                    }
                } else {
                    hasAllScores = false;
                }
            });
            
            if (!hasAnyScores) {
                return 'waiting';
            } else if (hasPendingScores) {
                return 'to_approve';
            } else if (hasAnyScores && !hasPendingScores) {
                return 'all_approved';
            }
            return 'waiting';
        }

        function passesFilters(participant, approvalStatus) {
            // Gender filter
            if (currentFilters.gender && participant.gender !== currentFilters.gender) {
                return false;
            }
            
            // Category filter
            if (currentFilters.category && participant.category !== currentFilters.category) {
                return false;
            }
            
            // Approval status filters
            if (approvalStatus === 'to_approve' && !currentFilters.showToApprove) {
                return false;
            }
            if (approvalStatus === 'all_approved' && !currentFilters.showAllApproved) {
                return false;
            }
            if (approvalStatus === 'waiting' && !currentFilters.showWaiting) {
                return false;
            }
            
            return true;
        }
        
        function loadHeats(eventId) {
            fetch('get_event_heats.php?event_id=' + eventId)
                .then(response => response.json())
                .then(data => {
                    const heatSelect = document.getElementById('heatSelect');
                    heatSelect.innerHTML = '<option value="">Select Heat</option>';
                    
                    data.forEach(heat => {
                        const option = document.createElement('option');
                        option.value = heat.heat_number;
                        option.textContent = `Heat ${heat.heat_number}${heat.heat_name ? ' - ' + heat.heat_name : ''}`;
                        heatSelect.appendChild(option);
                    });
                    
                    // Restore heat selection if available
                    if (window.EventSelectionManager) {
                        setTimeout(() => {
                            window.EventSelectionManager.restoreHeatSelection();
                        }, 100);
                    }
                })
                .catch(error => console.error('Error loading heats:', error));
        }
        
        function loadRuns() {
            const runSelect = document.getElementById('runSelect');
            runSelect.innerHTML = '<option value="">Select Run</option>';
            
            for (let i = 1; i <= 3; i++) {
                const option = document.createElement('option');
                option.value = i;
                option.textContent = `Run ${i}`;
                runSelect.appendChild(option);
            }
            
            // Restore run selection if available
            if (window.EventSelectionManager) {
                setTimeout(() => {
                    window.EventSelectionManager.restoreRunSelection();
                }, 100);
            }
        }
        
        function loadScores() {
            const eventId = document.getElementById('eventSelect').value;
            const heatNumber = document.getElementById('heatSelect').value;
            const runNumber = document.getElementById('runSelect').value;
            
            if (!eventId || !heatNumber || !runNumber) return;
            
            showLoading(true);
            
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'get_scores');
            formData.append('event_id', eventId);
            formData.append('heat_number', heatNumber);
            formData.append('run_number', runNumber);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    currentData = data;
                    renderScoreGrid(data);
                    showSuccessToast();
                } else {
                    console.error('Error loading scores:', data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            })
            .finally(() => {
                showLoading(false);
            });
        }
        
        function renderScoreGrid(data) {
    // Preserve scroll position before updating
    preserveScrollPosition();
    
    const container = document.getElementById('scoresContainer');
    const noDataMessage = document.getElementById('noDataMessage');
    const sortControls = document.getElementById('sortControls');
    
    if (!data.participants.length) {
        container.style.display = 'none';
        sortControls.classList.add('d-none');
        noDataMessage.style.display = 'block';
        noDataMessage.innerHTML = `
            <i class="fas fa-users-slash fa-3x mb-3 opacity-50"></i>
            <h5>No participants found</h5>
            <p>No participants are registered for Heat ${document.getElementById('heatSelect').value}</p>
        `;
        return;
    }

    // Update category filter options
    updateCategoryFilter(data.participants);
    
    // Group judges by control points
    const controlPointGroups = {};
    const controlPointColors = ["scale-1",
  "scale-2",
  "scale-3",
  "scale-4",
  "scale-5",
  "scale-6",
  "scale-7",
  "scale-8",
  "scale-9",
  "scale-10",
  "scale-11",
  "scale-12"];
    
    data.judges.forEach(judge => {
        const cpName = judge.control_point_name || 'Unassigned';
        if (!controlPointGroups[cpName]) {
            controlPointGroups[cpName] = {
                judges: [],
                color: controlPointColors[Object.keys(controlPointGroups).length % controlPointColors.length]
            };
        }
        controlPointGroups[cpName].judges.push(judge);
    });
    
    // Prepare participants with calculated data and filter them
    let processedParticipants = data.participants.map(participant => {
        let hasAllScores = true;
        let scoreValues = [];
        let latestScoreTime = null;
        
        // Check if all judges have scored this participant
        data.judges.forEach(judge => {
            const score = data.scores[participant.id] && data.scores[participant.id][judge.id] ? data.scores[participant.id][judge.id] : null;
            if (!score) {
                hasAllScores = false;
            } else {
                // Add to score values for average calculation if it's a valid numeric score
                if (score.score_value !== null && score.status === 'OK') {
                    scoreValues.push(parseFloat(score.score_value));
                }
                
                // Track latest score time
                if (score.created_at) {
                    const scoreTime = new Date(score.created_at);
                    if (!latestScoreTime || scoreTime > latestScoreTime) {
                        latestScoreTime = scoreTime;
                    }
                }
            }
        });
        
        const average = scoreValues.length > 0 ? scoreValues.reduce((a, b) => a + b, 0) / scoreValues.length : 0;
        const approvalStatus = getApprovalStatus(participant, data.judges, data.scores);
        
        return {
            ...participant,
            hasAllScores,
            average,
            latestScoreTime,
            canSort: hasAllScores && scoreValues.length > 0,
            approvalStatus,
            passesFilter: passesFilters(participant, approvalStatus)
        };
    });

    // Filter participants
    const filteredParticipants = processedParticipants.filter(p => p.passesFilter);
    
    // Apply sorting
    const sortableParticipants = filteredParticipants.filter(p => p.canSort);
    const unsortableParticipants = filteredParticipants.filter(p => !p.canSort);
    
    // Sort the sortable participants based on current mode
    switch (currentSortMode) {
        case 'average':
            sortableParticipants.sort((a, b) => b.average - a.average);
            break;
        case 'latest':
            sortableParticipants.sort((a, b) => {
                if (!a.latestScoreTime && !b.latestScoreTime) return 0;
                if (!a.latestScoreTime) return 1;
                if (!b.latestScoreTime) return -1;
                return b.latestScoreTime - a.latestScoreTime;
            });
            break;
        case 'default':
        default:
            sortableParticipants.sort((a, b) => {
                if (a.sort_order !== b.sort_order) {
                    return a.sort_order - b.sort_order;
                }
                return a.bib_number - b.bib_number;
            });
            break;
    }
    
    // Combine sorted and unsorted participants
    const finalParticipants = [...sortableParticipants, ...unsortableParticipants];
    
    // Update sort controls and counters
    sortControls.classList.remove('d-none');
    document.getElementById('sortableCount').textContent = `${sortableParticipants.length} complete participants`;
    document.getElementById('filteredCount').textContent = filteredParticipants.length;
    document.getElementById('totalCount').textContent = data.participants.length;
    
    // Enable/disable sort buttons
    const hasAnyComplete = sortableParticipants.length > 0;
    document.querySelectorAll('.btn-outline-primary[data-sort="average"], .btn-outline-primary[data-sort="latest"]').forEach(btn => {
        btn.classList.toggle('disabled', !hasAnyComplete);
    });
    
    noDataMessage.style.display = 'none';
    container.style.display = 'block';

    // Show "no results" message if all participants are filtered out
    if (filteredParticipants.length === 0) {
        container.innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="fas fa-filter fa-3x mb-3 opacity-50"></i>
                <h5>No participants match current filters</h5>
                <p>Try adjusting your filter settings to see more participants</p>
                <button class="btn btn-outline-primary" onclick="document.getElementById('clearFilters').click()">
                    <i class="fas fa-times me-1"></i>Clear All Filters
                </button>
            </div>
        `;
        return;
    }
    
    // Build the grid HTML using Bootstrap table
    let html = '<div class="table-responsive"><table class="table table-bordered table-hover table-striped" id="scoresTable">';
    
    // Header row with control point groups and judge names
    html += '<thead class="table-dark">';
    
    // Control point header row
    html += '<th class="" rowspan="2" class="text-center align-middle">Participant</th>';
    Object.keys(controlPointGroups).forEach(cpName => {
        const group = controlPointGroups[cpName];
        html += `<th colspan="${group.judges.length}" class="text-center ${group.color}">
            <i class="fas fa-map-marker-alt me-2"></i>${cpName}
            <span class="badge bg-light text-dark ms-2">${group.judges.length} judges</span>
        </th>`;
    });
    html += '<th rowspan="2" class="text-center align-middle">Average</th>';
    html += '<th rowspan="2" class="text-center align-middle">Actions</th></tr>';
    
    // Judge names row
    html += '';
    Object.keys(controlPointGroups).forEach(cpName => {
        const group = controlPointGroups[cpName];
        group.judges.forEach(judge => {
            html += `<th class="text-center ${group.color} bg-opacity-25">
                <div class="small fw-bold">${judge.name}</div>
            </th>`;
        });
    });
    html += '</th></thead><tbody>';
    
    // Participant rows
    finalParticipants.forEach((participant, index) => {
        const rowClass = participant.canSort ? 'bg-approved bg-opacity-25' : '';
        html += `<tr class="${rowClass}">`;
        
        // Position indicator for sorted participants
        const positionBadge = participant.canSort && currentSortMode !== 'default' ? 
            `<span class="badge bg-warning me-1">#${sortableParticipants.indexOf(participant) + 1}</span>` : '';
        
        html += `<td class="participantCol">
            ${positionBadge}
            <span class="badge bg-primary fs-6 mb-1">${participant.bib_number}</span>
            <strong>${participant.first_name} ${participant.last_name}</strong> 
            <span class="badge bg-${participant.gender === 'M' ? 'info' : 'pink'} bg-opacity-20 text-dark">
                ${participant.gender}
            </span>
            <br><small><span class="badge text-muted">${participant.club}</span><br><span class="badge text-dark">${participant.category}</span></small>
        </td>`;
        
        let hasPendingScores = false;
        let hasAnyScores = false;
        let scoreValues = [];
        
        // Render judge scores grouped by control points
        Object.keys(controlPointGroups).forEach(cpName => {
            const group = controlPointGroups[cpName];
            group.judges.forEach(judge => {
                const score = data.scores[participant.id] && data.scores[participant.id][judge.id] ? data.scores[participant.id][judge.id] : null;
                 
                if (score) {
                    hasAnyScores = true;
                    const isApproved = score.is_approved == 1;
                    if (!isApproved) hasPendingScores = true;
                    
                    // Add to score values for average calculation if it's a valid numeric score
                    if (score.score_value !== null && score.status === 'OK') {
                        scoreValues.push(parseFloat(score.score_value));
                    }
                    
                    // Determine background class based on approval status
                    let bgClass = '';
                    if (isApproved) {
                        bgClass = 'bg-approved';
                    } else {
                        bgClass = 'bg-pending';
                    }
                    
                    html += `<td class="scoreCol text-center ${group.color} bg-opacity-10 ${bgClass}" data-score-value="${score.score_value || ''}" data-status="${score.status}"><div class="row score-figure">`;
                    const scoreValue = score.score_value || score.status;
                    const badgeClass = getStatusBadgeClass(score.status);
                    
                    html += `<div class="scores-col1 ${score.status}" onclick="editScore(${score.score_id}, ${score.score_value || 0}, '${score.status}', '${encodeURIComponent(score.figures_json || '')}', '${participant.first_name.replace(/'/g, "\\'")} ${participant.last_name.replace(/'/g, "\\'")}', '${participant.bib_number}', '${participant.category.replace(/'/g, "\\'")}', '${judge.name.replace(/'/g, "\\'")}', '${cpName.replace(/'/g, "\\'")}')">
                        <h4 class="fs-4 fw-bold score_value m-0 text-${badgeClass === 'success' ? 'primary' : badgeClass === 'danger' ? 'danger' : 'warning'}${isApproved ? '': ' text-warning-emphasis'}">${scoreValue}</h4>
                       
                        ${isApproved ? 
                            '<span class="badge bg-success approval-clickable" style="cursor: pointer; pointer-events: auto;" title="Click to unapprove"><i class="fas fa-check-circle me-1"></i>Approved</span>' : 
                            '<span class="badge bg-danger approval-clickable" onclick="approveScore(\'' + score.score_id + '\')" style="cursor: pointer;" title="Click to approve"><i class="fas fa-times-circle me-1"></i>Not Approved</span>'
                        }
                        <div class="btn-group btn-group-sm" role="group">
                            <span class="badge bg-warning editScoreButton"  title="Click to edit score" style="cursor: pointer; pointer-events: auto;" onclick="editScore(${score.score_id}, ${score.score_value || 0}, '${score.status}', '${encodeURIComponent(score.figures_json || '')}', '${participant.first_name.replace(/'/g, "\\'")} ${participant.last_name.replace(/'/g, "\\'")}', '${participant.bib_number}', '${participant.category.replace(/'/g, "\\'")}', '${judge.name.replace(/'/g, "\\'")}', '${cpName.replace(/'/g, "\\'")}')">
                                <i class="fas fa-edit"></i> Edit score
                            </span>
                        </div></div>
                    `;
                    
                    // Display figures information if available
                    if (score.figures_json) {
                        try {
                            const figuresData = JSON.parse(score.figures_json);
                            const figuresParts = [];
                            Object.keys(figuresData || {}).forEach(category => {
                                const items = Array.isArray(figuresData[category]) ? figuresData[category] : [];
                                if (items.length > 0) {
                                    figuresParts.push(`${category}: ${items.join(', ')}`);
                                }
                            });
                            if (figuresParts.length > 0) {
                                html += `<div class="scores-col2">
                                    <div class="figures-display mt-0 border-top p-0 small">
                                        ${Object.keys(figuresData).map(cat => {
                                            const items = Array.isArray(figuresData[cat]) ? figuresData[cat] : [];
                                            if (!items.length) return '';
                                            return `
                                                <div class="m-0 figure-s">
                                                    ${items.map(item => `<span class=\"fw-bold badge bg-light text-primary\"><small class="small m-0 p-0 text-dark-emphasis fig-cat fig-cat-${cat}">${cat.substring(0, 3)}:</small><strong>${item}</strong></span>`).join(' ')}
                                                </div>
                                            `;
                                        }).join('')}
                                    </div></div>
                                `;
                            }
                        } catch (e) {
                            // Ignore JSON parse errors
                        }
                    }
                } else {
                    // Empty score cell - no score exists
                    html += `<td class="scoreCol text-center ${group.color} bg-opacity-10 bg-empty" data-score-value="" data-status=""><div class="row score-figure">`;
                    // Empty score cell - clickable for head judges/admins
                    html += `
                        <div class="pendingActions p-2 border border-2 border-dashed border-secondary rounded text-center cursor-pointer" onclick="createScore(${participant.id}, ${judge.id}, '${participant.first_name} ${participant.last_name}', '${judge.name}')" title="Click to add score for this judge">
                            
                            <span class="badge bg-secondary">Pending</span>
                            <div class="mt-1">
                                <small class="text-muted"><i class="fas fa-plus-circle me-1"></i>Add</small>
                            </div>
                        </div>
                    `;
                }
                
                html += `</div></td>`;
            });
        });
        
        // Average column
        html += `<td class="resultCom text-center"><div class="row score-figure">`;
        if (scoreValues.length > 0) {
            const average = scoreValues.reduce((a, b) => a + b, 0) / scoreValues.length;
            html += `
                <h3 class="mb-2 text-dark fs-3 fw-bold">${average.toFixed(2)}</h3>
                <span class="badge text-dark">${scoreValues.length} scores</span>
            `;
        } else {
            html += `
                <h4 class="mb-2 text-muted">—</h4>
                <span class="badge bg-secondary">No valid scores</span>
            `;
        }
        html += `</td>`;
        
        // Actions column
        html += `<td class="actionsCol text-center"><div class="row score-figure">`;
        if (hasAnyScores && hasPendingScores) {
            html += `
                <button class="btn btn-primary btn-sm mb-1" onclick="approveAllParticipant(${participant.id})" title="Approve all scores for this participant">
                    <i class="fas fa-check-double me-1"></i>Approve All
                </button>
            `;
        } else if (hasAnyScores && !hasPendingScores) {
            html += `
                <span class="badge bg-success">
                    <i class="fas fa-check-circle me-1"></i>All Approved
                </span>
            `;
        } else {
            html += `
                <span class="text-muted">
                    <i class="fas fa-clock me-1"></i>Waiting for scores
                </span>
            `;
        }
        html += `</td>`;
        
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    container.innerHTML = html;
    
    // Restore scroll position after updating
    restoreScrollPosition();
}

function createScore(participantId, judgeId, participantName, judgeName) {
    // Find the judge's control point from current data
    let controlPointName = 'Unknown Control Point';
    if (currentData && currentData.judges) {
        const judge = currentData.judges.find(j => j.id == judgeId);
        if (judge && judge.control_point_name) {
            controlPointName = judge.control_point_name;
        }
    }
    
    document.getElementById('createParticipantId').value = participantId;
    document.getElementById('createJudgeId').value = judgeId;
    document.getElementById('createScoreValue').value = '';
    document.getElementById('createScoreStatus').value = 'OK';
    
    // Set info text with control point
    document.getElementById('createScoreInfo').innerHTML = `
        <strong>Participant:</strong> ${participantName}<br>
        <strong>Judge:</strong> ${judgeName}<br>
        <strong>Control Point:</strong> <span class="badge bg-info">${controlPointName}</span>
    `;
    
    // Reset create figures data
    window.createFiguresData = {};
    
    // Load figure options for create score
    loadCreateFigures();
    
    const modal = new bootstrap.Modal(document.getElementById('createScoreModal'));
    modal.show();
}

function approveScore(scoreId) {
    const formData = new FormData();
    formData.append('ajax', '1');
    formData.append('action', 'approve_score');
    formData.append('score_id', scoreId);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccessToast('Score approved successfully');
            // Refresh grid to show updated approval status
            if (document.getElementById('runSelect').value) {
                loadScores();
            }
        } else {
            alert('Error approving score: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error approving score');
    });
}

// Add the new approve all function
function approveAllParticipant(participantId) {
    const eventId = document.getElementById('eventSelect').value;
    const heatNumber = document.getElementById('heatSelect').value;
    const runNumber = document.getElementById('runSelect').value;
    
    const formData = new FormData();
    formData.append('ajax', '1');
    formData.append('action', 'approve_all_participant');
    formData.append('event_id', eventId);
    formData.append('heat_number', heatNumber);
    formData.append('run_number', runNumber);
    formData.append('participant_id', participantId);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccessToast(`${data.count} scores approved`);
            // Refresh grid
            if (document.getElementById('runSelect').value) {
                loadScores();
            }
        } else {
            alert('Error approving scores: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error approving scores');
    });
}

// Update the showSuccessToast function to accept custom messages
function showSuccessToast(message = 'Updated successfully') {
    const toastEl = document.getElementById('successToast');
    const toastBody = toastEl.querySelector('.toast-body');
    toastBody.textContent = message;
    const toast = new bootstrap.Toast(toastEl);
    toast.show();
}
        
        function getStatusBadgeClass(status) {
            switch(status) {
                case 'OK': return 'success';
                case 'DNS': case 'DNF': return 'warning';
                case 'DSQ': return 'danger';
                default: return 'secondary';
            }
        }
        
        function editScore(scoreId, scoreValue, status, figuresEncoded = '', participantName = '', bibNumber = '', category = '', judgeName = '', controlPoint = '') {
            document.getElementById('editScoreId').value = scoreId;
            document.getElementById('editScoreValue').value = scoreValue;
            document.getElementById('editScoreStatus').value = status;
            
            // Update the participant and context information in the modal
            const eventSelect = document.getElementById('eventSelect');
            const heatSelect = document.getElementById('heatSelect');
            const runSelect = document.getElementById('runSelect');
            
            const eventName = eventSelect.options[eventSelect.selectedIndex]?.text || 'Unknown Event';
            const heatNumber = heatSelect.value || 'Unknown';
            const runNumber = runSelect.value || 'Unknown';
            
            document.getElementById('editScoreInfo').innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="mb-3 text-primary">
                            <i class="fas fa-user me-2"></i>Participant Information
                        </h6>
                        <div class="mb-2">
                            <i class="fas fa-id-badge me-2 text-muted"></i>
                            <strong>Name:</strong> ${participantName}
                        </div>
                        <div class="mb-2">
                            <i class="fas fa-hashtag me-2 text-muted"></i>
                            <strong>Bib #:</strong> <span class="badge bg-primary ms-1">${bibNumber}</span>
                        </div>
                        <div class="mb-2">
                            <i class="fas fa-tags me-2 text-muted"></i>
                            <strong>Category:</strong> <span class="badge bg-info ms-1">${category}</span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6 class="mb-3 text-success">
                            <i class="fas fa-clipboard-list me-2"></i>Score Context
                        </h6>
                        <div class="mb-2">
                            <i class="fas fa-calendar-alt me-2 text-muted"></i>
                            <strong>Event:</strong> ${eventName}
                        </div>
                        <div class="mb-2">
                            <i class="fas fa-layer-group me-2 text-muted"></i>
                            <strong>Heat:</strong> ${heatNumber} <span class="text-muted mx-1">|</span> <strong>Run:</strong> ${runNumber}
                        </div>
                        <div class="mb-2">
                            <i class="fas fa-user-tie me-2 text-muted"></i>
                            <strong>Judge:</strong> ${judgeName}
                        </div>
                        <div class="mb-2">
                            <i class="fas fa-map-marker-alt me-2 text-muted"></i>
                            <strong>Control Point:</strong> <span class="badge bg-success ms-1">${controlPoint}</span>
                        </div>
                    </div>
                </div>
            `;
            
            // Store original figures data globally for editing
            window.originalFiguresData = null;
            window.currentFiguresData = null;
            
            // Populate figures if provided
            const figWrap = document.getElementById('editScoreFigures');
            const figContent = document.getElementById('editScoreFiguresContent');
            const editBtn = document.getElementById('editFiguresBtn');
            const editor = document.getElementById('editFiguresEditor');
            
            figContent.innerHTML = '';
            editor.style.display = 'none';
            
            // Always show the figures section, even if no figures exist
            figWrap.style.display = 'block';
            editBtn.style.display = 'inline-block';
            
            if (figuresEncoded) {
                try {
                    const raw = decodeURIComponent(figuresEncoded);
                    if (raw) {
                        const figuresData = JSON.parse(raw);
                        window.originalFiguresData = figuresData;
                        window.currentFiguresData = JSON.parse(JSON.stringify(figuresData)); // Deep clone
                        
                        const parts = [];
                        Object.keys(figuresData || {}).forEach(cat => {
                            const items = Array.isArray(figuresData[cat]) ? figuresData[cat] : [];
                            if (items.length) {
                                parts.push(`<span class="badge bg-success-subtle me-1 text-dark fs-6">${cat}: ${items.join(', ')}</span>`);
                            }
                        });
                        if (parts.length) {
                            figContent.innerHTML = parts.join(' ');
                        } else {
                            figContent.innerHTML = '<span class="text-muted">No figures selected</span>';
                        }
                    }
                } catch (e) { 
                    // If JSON parse fails, show empty state
                    figContent.innerHTML = '<span class="text-muted">No figures selected</span>';
                }
            } else {
                // No figures data provided, show empty state
                figContent.innerHTML = '<span class="text-muted">No figures selected</span>';
            }
            
            const modal = new bootstrap.Modal(document.getElementById('editScoreModal'));
            modal.show();
        }
        
        function startEditFigures() {
            const editor = document.getElementById('editFiguresEditor');
            const editBtn = document.getElementById('editFiguresBtn');
            const categoriesContainer = document.getElementById('editFigureCategories');
            
            editBtn.style.display = 'none';
            categoriesContainer.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading format options...</div>';
            editor.style.display = 'block';
            
            // Get current event ID
            const eventId = document.getElementById('eventSelect').value;
            
            if (!eventId) {
                categoriesContainer.innerHTML = '<div class="alert alert-warning">Please select an event first</div>';
                return;
            }
            
            // Fetch format figures from server
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'get_format_figures');
            formData.append('event_id', eventId);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Format figures response:', data); // Debug logging
                
                if (data.success && data.figures && Object.keys(data.figures).length > 0) {
                    buildFiguresEditor(data.figures);
                } else {
                    let message = 'No figure options available for this scoring format';
                    if (data.message) {
                        message = data.message;
                    }
                    if (data.debug) {
                        console.log('Debug info:', data.debug);
                        if (data.debug.format_found === false) {
                            message = 'Event not found or has no scoring format assigned';
                        } else if (data.debug.figures_raw_count === 0) {
                            message = `No figure categories/items configured for format "${data.debug.format_details.name}"`;
                        } else if (!data.has_figures) {
                            message = `Format "${data.debug.format_details.name}" has categories but no figure items configured`;
                        }
                    }
                    categoriesContainer.innerHTML = `<div class="alert alert-info">${message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading figures:', error);
                categoriesContainer.innerHTML = '<div class="alert alert-danger">Error loading figure options</div>';
            });
        }
        
        function buildFiguresEditor(availableFigures) {
            const categoriesContainer = document.getElementById('editFigureCategories');
            categoriesContainer.innerHTML = '';
            
            Object.keys(availableFigures).forEach(category => {
                const items = availableFigures[category] || [];
                const currentSelected = window.currentFiguresData ? (window.currentFiguresData[category] || []) : [];
                
                const categoryDiv = document.createElement('div');
                categoryDiv.className = 'figure-category mb-3';
                
                // Build chips for this category
                let chipsHtml = '';
                items.forEach(item => {
                    const isActive = currentSelected.includes(item.name) ? 'active' : '';
                    chipsHtml += `
                        <button type="button" class="btn btn-sm btn-outline-primary figure-chip ${isActive}" 
                                data-category="${category}" data-item="${item.name}" onclick="toggleFigureChip(this)">
                            ${item.name}
                        </button>
                    `;
                });
                
                categoryDiv.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="mb-0 text-primary">
                            <i class="fas fa-tag me-2"></i>${category}
                        </h6>
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearFigureCategory('${category}')">
                            <i class="fas fa-times"></i> Clear
                        </button>
                    </div>
                    <div class="figure-chips d-flex flex-wrap gap-2">
                        ${chipsHtml}
                    </div>
                `;
                categoriesContainer.appendChild(categoryDiv);
            });
        }
        
        // Figure chip interaction functions
        function toggleFigureChip(button) {
            const category = button.getAttribute('data-category');
            const item = button.getAttribute('data-item');
            
            // Toggle active state
            button.classList.toggle('active');
            
            // Initialize currentFiguresData if needed
            if (!window.currentFiguresData) {
                window.currentFiguresData = {};
            }
            
            // Initialize category array if needed
            if (!window.currentFiguresData[category]) {
                window.currentFiguresData[category] = [];
            }
            
            // Add or remove item from the category
            const itemIndex = window.currentFiguresData[category].indexOf(item);
            if (button.classList.contains('active')) {
                // Add item if not already present
                if (itemIndex === -1) {
                    window.currentFiguresData[category].push(item);
                }
            } else {
                // Remove item if present
                if (itemIndex > -1) {
                    window.currentFiguresData[category].splice(itemIndex, 1);
                }
            }
            
            // Clean up empty categories
            if (window.currentFiguresData[category].length === 0) {
                delete window.currentFiguresData[category];
            }
        }
        
        function clearFigureCategory(category) {
            // Remove all active states from chips in this category
            const categoryChips = document.querySelectorAll(`.figure-chip[data-category="${category}"]`);
            categoryChips.forEach(chip => {
                chip.classList.remove('active');
            });
            
            // Remove category from data
            if (window.currentFiguresData && window.currentFiguresData[category]) {
                delete window.currentFiguresData[category];
            }
        }
        
        function cancelEditFigures() {
            const editor = document.getElementById('editFiguresEditor');
            const editBtn = document.getElementById('editFiguresBtn');
            
            editor.style.display = 'none';
            editBtn.style.display = 'inline-block';
            
            // Reset current data to original
            if (window.originalFiguresData) {
                window.currentFiguresData = JSON.parse(JSON.stringify(window.originalFiguresData));
            }
        }
        
        function saveFiguresEdit() {
            // The data is already collected in window.currentFiguresData by the chip interactions
            // No need to collect from select elements anymore since we're using chips
            
            // Check if we have any meaningful data
            const hasAnyData = window.currentFiguresData && Object.keys(window.currentFiguresData).some(category => 
                Array.isArray(window.currentFiguresData[category]) && window.currentFiguresData[category].length > 0
            );
            
            // Update display
            const figContent = document.getElementById('editScoreFiguresContent');
            if (hasAnyData) {
                const parts = [];
                Object.keys(window.currentFiguresData).forEach(cat => {
                    const items = window.currentFiguresData[cat];
                    if (items.length) {
                        parts.push(`<span class="badge bg-light text-dark me-1">${cat}: ${items.join(', ')}</span>`);
                    }
                });
                figContent.innerHTML = parts.join(' ');
            } else {
                figContent.innerHTML = '<span class="text-muted">No figures selected</span>';
                // Set to null if no meaningful data
                window.currentFiguresData = null;
            }
            
            // Hide editor
            const editor = document.getElementById('editFiguresEditor');
            const editBtn = document.getElementById('editFiguresBtn');
            editor.style.display = 'none';
            editBtn.style.display = 'inline-block';
        }
        
        function loadCreateFigures() {
            const eventId = document.getElementById('eventSelect').value;
            const figuresSection = document.getElementById('createFiguresSection');
            const figuresContainer = document.getElementById('createFiguresContainer');
            
            if (!eventId) {
                figuresSection.style.display = 'none';
                return;
            }
            
            // Show loading
            figuresContainer.innerHTML = '<div class="text-muted"><i class="fas fa-spinner fa-spin me-2"></i>Loading figure options...</div>';
            figuresSection.style.display = 'block';
            
            const formData = new FormData();
            formData.append('action', 'get_format_figures');
            formData.append('event_id', eventId);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Create figures response:', data);
                
                if (data.success && data.figures && Object.keys(data.figures).length > 0) {
                    buildCreateFiguresEditor(data.figures);
                } else {
                    let message = 'No figure options available for this scoring format';
                    if (data.message) message = data.message;
                    figuresContainer.innerHTML = `<div class="alert alert-info mb-0">${message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading create figures:', error);
                figuresContainer.innerHTML = '<div class="alert alert-danger mb-0">Error loading figure options</div>';
            });
        }
        
        function buildCreateFiguresEditor(availableFigures) {
            const container = document.getElementById('createFiguresContainer');
            let html = '';
            
            Object.keys(availableFigures).forEach(category => {
                const items = availableFigures[category];
                if (items && items.length > 0) {
                    // Build chips for this category
                    let chipsHtml = '';
                    items.forEach(item => {
                        chipsHtml += `
                            <button type="button" class="btn btn-sm btn-outline-primary figure-chip" 
                                    data-category="${category}" data-item="${item.name}" onclick="toggleCreateFigureChip(this)">
                                ${item.name}
                            </button>
                        `;
                    });
                    
                    html += `
                        <div class="figure-category mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h6 class="mb-0 text-primary">
                                    <i class="fas fa-tag me-2"></i>${category}
                                </h6>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearCreateFigureCategory('${category}')">
                                    <i class="fas fa-times"></i> Clear
                                </button>
                            </div>
                            <div class="figure-chips d-flex flex-wrap gap-2">
                                ${chipsHtml}
                            </div>
                        </div>
                    `;
                }
            });
            
            if (html) {
                container.innerHTML = html;
            } else {
                container.innerHTML = '<div class="alert alert-info mb-0">No figure categories configured for this format</div>';
            }
        }
        
        // Create figure chip interaction functions
        window.createFiguresData = {};
        
        function toggleCreateFigureChip(button) {
            const category = button.getAttribute('data-category');
            const item = button.getAttribute('data-item');
            
            // Toggle active state
            button.classList.toggle('active');
            
            // Initialize category array if needed
            if (!window.createFiguresData[category]) {
                window.createFiguresData[category] = [];
            }
            
            // Add or remove item from the category
            const itemIndex = window.createFiguresData[category].indexOf(item);
            if (button.classList.contains('active')) {
                // Add item if not already present
                if (itemIndex === -1) {
                    window.createFiguresData[category].push(item);
                }
            } else {
                // Remove item if present
                if (itemIndex > -1) {
                    window.createFiguresData[category].splice(itemIndex, 1);
                }
            }
            
            // Clean up empty categories
            if (window.createFiguresData[category].length === 0) {
                delete window.createFiguresData[category];
            }
        }
        
        function clearCreateFigureCategory(category) {
            // Remove all active states from chips in this category
            const categoryChips = document.querySelectorAll(`#createFiguresContainer .figure-chip[data-category="${category}"]`);
            categoryChips.forEach(chip => {
                chip.classList.remove('active');
            });
            
            // Remove category from data
            if (window.createFiguresData && window.createFiguresData[category]) {
                delete window.createFiguresData[category];
            }
        }
        
        function getCreateFiguresData() {
            // Return the data collected by the chip interactions
            // Check if we have any meaningful data
            const hasAnyData = window.createFiguresData && Object.keys(window.createFiguresData).some(category => 
                Array.isArray(window.createFiguresData[category]) && window.createFiguresData[category].length > 0
            );
            
            // Return null if no meaningful data, otherwise return the data
            return hasAnyData ? window.createFiguresData : null;
        }
        
        function clearScoreGrid() {
            document.getElementById('scoresContainer').style.display = 'none';
            document.getElementById('sortControls').classList.add('d-none');
            document.getElementById('noDataMessage').style.display = 'block';
            document.getElementById('noDataMessage').innerHTML = `
                <i class="fas fa-clipboard-list fa-3x mb-3 opacity-50"></i>
                <h5>Select Event, Heat, and Run to view scores</h5>
                <p>Use the controls above to navigate to specific scoring sessions</p>
            `;
        }
        
        function showLoading(show) {
            const spinner = document.getElementById('loadingSpinner');
            spinner.classList.toggle('d-none', !show);
        }
        
        // Scroll position preservation functions
        function preserveScrollPosition() {
            const tableContainer = document.querySelector('#scoresContainer .table-responsive');
            if (tableContainer) {
                window.lastScrollTop = tableContainer.scrollTop;
                window.lastScrollLeft = tableContainer.scrollLeft;
            }
        }
        
        function restoreScrollPosition() {
            const tableContainer = document.querySelector('#scoresContainer .table-responsive');
            if (tableContainer && window.lastScrollTop !== undefined) {
                // Use requestAnimationFrame for smoother restoration
                requestAnimationFrame(() => {
                    tableContainer.scrollTop = window.lastScrollTop;
                    tableContainer.scrollLeft = window.lastScrollLeft || 0;
                    
                    // Double-check restoration after a short delay
                    setTimeout(() => {
                        if (tableContainer.scrollTop !== window.lastScrollTop) {
                            tableContainer.scrollTop = window.lastScrollTop;
                            tableContainer.scrollLeft = window.lastScrollLeft || 0;
                        }
                    }, 50);
                });
            }
        }
        
        function showSuccessToast() {
            const toastEl = document.getElementById('successToast');
            const toast = new bootstrap.Toast(toastEl);
            toast.show();
        }
        
        function startAutoRefresh() {
            stopAutoRefresh();
            autoRefreshInterval = setInterval(() => {
                if (document.getElementById('runSelect').value) {
                    loadScores();
                }
            }, 5000);
        }
        
        function stopAutoRefresh() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
            }
        }
        
        // Handle score update
        document.getElementById('saveScoreBtn').addEventListener('click', function() {
            const scoreId = document.getElementById('editScoreId').value;
            const scoreValue = document.getElementById('editScoreValue').value;
            const status = document.getElementById('editScoreStatus').value;
            
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'update_score');
            formData.append('score_id', scoreId);
            formData.append('score_value', scoreValue);
            formData.append('status', status);
            
            // Include figures data - send null for empty data
            if (window.currentFiguresData !== undefined) {
                // Send 'null' string for null values, JSON string for actual data
                const figuresValue = window.currentFiguresData === null ? 'null' : JSON.stringify(window.currentFiguresData);
                formData.append('figures_json', figuresValue);
            }
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editScoreModal'));
                    modal.hide();
                    
                    showSuccessToast();
                    
                    // Refresh grid
                    if (document.getElementById('runSelect').value) {
                        loadScores();
                    }
                } else {
                    alert('Error updating score: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating score');
            });
        });

        // Handle score creation
        // Handle score creation
document.getElementById('createScoreBtn').addEventListener('click', function() {
    const participantId = document.getElementById('createParticipantId').value;
    const judgeId = document.getElementById('createJudgeId').value;
    const scoreValue = document.getElementById('createScoreValue').value;
    const status = document.getElementById('createScoreStatus').value;
    const eventId = document.getElementById('eventSelect').value;
    const heatNumber = document.getElementById('heatSelect').value;
    const runNumber = document.getElementById('runSelect').value;
    
    // Get figures data
    const figuresData = getCreateFiguresData();
    
    const formData = new FormData();
    formData.append('ajax', '1');
    formData.append('action', 'create_score');
    formData.append('event_id', eventId);
    formData.append('heat_number', heatNumber);
    formData.append('run_number', runNumber);
    formData.append('participant_id', participantId);
    formData.append('judge_id', judgeId);
    formData.append('score_value', scoreValue);
    formData.append('status', status);
    
    // Add figures data if available
    if (figuresData) {
        formData.append('figures_json', JSON.stringify(figuresData));
    }
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const modal = bootstrap.Modal.getInstance(document.getElementById('createScoreModal'));
            modal.hide();
            
            showSuccessToast('Score created successfully');
            
            // Refresh grid
            if (document.getElementById('runSelect').value) {
                loadScores();
            }
        } else {
            alert('Error creating score: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error creating score');
    });
});

// NEW: Handle Enter key press in create score form
document.getElementById('createScoreForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Prevent default form submission
    document.getElementById('createScoreBtn').click(); // Trigger the create button
});

// NEW: Handle Enter key press in score value input
document.getElementById('createScoreValue').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault(); // Prevent default form submission
        document.getElementById('createScoreBtn').click(); // Trigger the create button
    }
});

// OPTIONAL: Also add the same for edit score form for consistency
document.getElementById('editScoreForm').addEventListener('submit', function(e) {
    e.preventDefault(); // Prevent default form submission
    document.getElementById('saveScoreBtn').click(); // Trigger the save button
});

document.getElementById('editScoreValue').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault(); // Prevent default form submission
        document.getElementById('saveScoreBtn').click(); // Trigger the save button
    }
});

        // Utility functions for debugging localStorage
        function debugSelections() {
            if (window.EventSelectionManager) {
                console.log('Current Selections:');
                console.log('Event:', window.EventSelectionManager.getSavedSelection('event'));
                console.log('Heat:', window.EventSelectionManager.getSavedSelection('heat'));  
                console.log('Run:', window.EventSelectionManager.getSavedSelection('run'));
            }
        }
        
        // Add debug function to window for console access
        window.debugEventSelections = debugSelections;
        
        // Show visual indicator when selections are restored
        function showRestoredIndicator(type, value) {
            const indicator = document.createElement('div');
            indicator.className = 'position-fixed top-0 start-50 translate-middle-x mt-3 alert alert-info alert-dismissible fade show';
            indicator.style.zIndex = '9999';
            indicator.innerHTML = `
                <i class="fas fa-history me-2"></i>
                Restored ${type}: <strong>${value}</strong>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(indicator);
            
            // Auto remove after 3 seconds
            setTimeout(() => {
                if (indicator.parentNode) {
                    indicator.remove();
                }
            }, 3000);
        }
        
        function clearScoreGrid() {
            const container = document.getElementById('scoresContainer');
            const noDataMessage = document.getElementById('noDataMessage');
            const sortControls = document.getElementById('sortControls');
            
            container.style.display = 'none';
            sortControls.classList.add('d-none');
            noDataMessage.style.display = 'block';
            currentData = null;
        }
    </script>
</body>
</html>