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

// Get judge_id from session - use user_id as fallback
$judge_id = $_SESSION['judge_id'] ?? $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';

// 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 participant details for notification
            $participant_stmt = $pdo->prepare("
                SELECT p.first_name, p.last_name, ep.bib_number
                FROM event_participants ep
                JOIN participants p ON ep.participant_id = p.id
                WHERE ep.id = ?
            ");
            $participant_stmt->execute([$participant_id]);
            $participant_details = $participant_stmt->fetch(PDO::FETCH_ASSOC);
            
            // 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);
            
            // Prepare notification data for frontend
            $notification_data = null;
            if ($participant_details) {
                $participant_name = $participant_details['first_name'] . ' ' . $participant_details['last_name'];
                $notification_data = [
                    'bib' => $participant_details['bib_number'],
                    'participant_name' => $participant_name,
                    'count' => count($score_ids),
                    'heat' => $heat_number,
                    'run' => $run_number
                ];
            }
            
            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);
                
                // Send to notification API if we have participant details
                if ($participant_details) {
                    // Get all judge scores for this participant after approval
                    $all_scores_stmt = $pdo->prepare("
                        SELECT s.score_value, s.status, u.username as judge_name, s.is_approved
                        FROM scores s
                        JOIN runs r ON s.run_id = r.id
                        JOIN event_participants ep ON r.event_participant_id = ep.id
                        JOIN users u ON s.judge_id = u.id
                        WHERE ep.id = ? AND ep.heat_number = ? AND r.run_number = ?
                        ORDER BY u.username
                    ");
                    $all_scores_stmt->execute([$participant_id, $heat_number, $run_number]);
                    $all_judge_scores = $all_scores_stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    // Calculate final result and rank
                    $approved_scores = [];
                    $all_scores_info = [];
                    foreach ($all_judge_scores as $judge_score) {
                        $judge_display = $judge_score['status'] === 'OK' ? $judge_score['score_value'] : $judge_score['status'];
                        $all_scores_info[] = [
                            'judge' => $judge_score['judge_name'],
                            'score' => $judge_display,
                            'approved' => (bool)$judge_score['is_approved']
                        ];
                        
                        if ($judge_score['is_approved'] && $judge_score['status'] === 'OK' && $judge_score['score_value'] !== null) {
                            $approved_scores[] = floatval($judge_score['score_value']);
                        }
                    }
                    
                    $final_result = null;
                    $approved_count = count($approved_scores);
                    if ($approved_count > 0) {
                        // Apply drop rule if enough scores
                        if ($approved_count >= 3) {
                            sort($approved_scores);
                            array_shift($approved_scores); // Remove lowest
                            array_pop($approved_scores);   // Remove highest
                        }
                        $final_result = $approved_count > 0 ? round(array_sum($approved_scores) / count($approved_scores), 3) : null;
                    }
                    
                    // Calculate final rank position
                    $rank_position = null;
                    if ($final_result !== null) {
                        $ranking_stmt = $pdo->prepare("
                            SELECT ep.bib_number, ep.id as participant_id,
                                   AVG(CASE WHEN s.is_approved = 1 AND s.status = 'OK' THEN s.score_value END) as avg_score,
                                   COUNT(CASE WHEN s.is_approved = 1 AND s.status = 'OK' THEN 1 END) as approved_count
                            FROM event_participants ep
                            JOIN runs r ON ep.id = r.event_participant_id
                            JOIN scores s ON r.id = s.run_id
                            WHERE ep.event_id = ? AND ep.heat_number = ? AND r.run_number = ?
                            GROUP BY ep.id, ep.bib_number
                            HAVING approved_count > 0
                            ORDER BY avg_score DESC
                        ");
                        $ranking_stmt->execute([$event_id, $heat_number, $run_number]);
                        $rankings = $ranking_stmt->fetchAll(PDO::FETCH_ASSOC);
                        
                        foreach ($rankings as $index => $ranking) {
                            if ($ranking['participant_id'] == $participant_id) {
                                $rank_position = $index + 1;
                                break;
                            }
                        }
                    }
                    
                    // Update notification data with detailed information
                    $notification_data['all_scores'] = $all_scores_info;
                    $notification_data['final_result'] = $final_result;
                    $notification_data['rank_position'] = $rank_position;
                    $notification_data['total_judges'] = count($all_judge_scores);
                    
                    // Enhanced notification message
                    $result_text = $final_result !== null ? " | Final Result: {$final_result}" : "";
                    $rank_text = $rank_position !== null ? " | Final Rank: #{$rank_position}" : "";
                    
                    $api_data = [
                        'type' => 'success',
                        'title' => 'All Scores Approved',
                        'message' => sprintf(
                            "All %d scores approved for Bib #%s (%s) - Heat %s, Run %s%s%s",
                            count($score_ids),
                            $participant_details['bib_number'],
                            $participant_name,
                            $heat_number,
                            $run_number,
                            $result_text,
                            $rank_text
                        ),
                        'category' => 'judge',
                        'event_id' => $event_id,
                        'user_id' => $notification_user_id ?? 'head_judge',
                        'data' => json_encode([
                            'participant_id' => $participant_id,
                            'participant_bib' => $participant_details['bib_number'],
                            'participant_name' => $participant_name,
                            'scores_count' => count($score_ids),
                            'heat' => $heat_number,
                            'run' => $run_number,
                            'score_ids' => $score_ids,
                            'all_judge_scores' => $all_scores_info,
                            'final_result' => $final_result,
                            'rank_position' => $rank_position,
                            'total_judges' => count($all_judge_scores)
                        ])
                    ];
                    
                    // Send to notification API
                    $api_url = '../api/notification_api.php';
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $api_url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_data + ['action' => 'send_notification']));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                    curl_exec($ch);
                    curl_close($ch);
                }
                
                echo json_encode([
                    'success' => true, 
                    'message' => 'All scores approved for participant',
                    'count' => count($score_ids),
                    'notification_data' => $notification_data
                ]);
            } else {
                echo json_encode([
                    'success' => true, 
                    'message' => 'No pending scores to approve',
                    'count' => 0,
                    'notification_data' => $notification_data
                ]);
            }
            
        } 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) {
            try {
                // UPDATED: Get all judges for this event from users table
                $judges_stmt = $pdo->prepare("
                    SELECT DISTINCT u.id, u.username as name, u.judge_id as is_head, 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);
                
                // Build WHERE clause based on what filters are provided
                $where_conditions = ["ep.event_id = ?"];
                $params = [$event_id];
                
                if ($heat_number) {
                    $where_conditions[] = "ep.heat_number = ?";
                    $params[] = $heat_number;
                }
                
                $where_clause = implode(" AND ", $where_conditions);
                
                // Get all participants based on filters - 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, ep.heat_number,
                           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 {$where_clause}
                    ORDER BY ep.heat_number ASC, ep.sort_order ASC, ep.bib_number ASC
                ");
                $participants_stmt->execute($params);
                $participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Get scores based on filters 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
                }
                
                // Build scores WHERE clause
                $scores_where_conditions = ["ep.event_id = ?"];
                $scores_params = [$event_id];
                
                if ($heat_number) {
                    $scores_where_conditions[] = "ep.heat_number = ?";
                    $scores_params[] = $heat_number;
                }
                
                if ($run_number) {
                    $scores_where_conditions[] = "r.run_number = ?";
                    $scores_params[] = $run_number;
                }
                
                $scores_where_clause = implode(" AND ", $scores_where_conditions);
                
                $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, r.run_number, ep.heat_number{$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 {$scores_where_clause}
                ");
                $scores_stmt->execute($scores_params);
                $scores_raw = $scores_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Organize scores by participant, run, and judge
                $scores = [];
                foreach ($scores_raw as $score) {
                    $run_key = $score['run_number'];
                    if (!isset($scores[$score['ep_id']])) {
                        $scores[$score['ep_id']] = [];
                    }
                    if (!isset($scores[$score['ep_id']][$run_key])) {
                        $scores[$score['ep_id']][$run_key] = [];
                    }
                    $scores[$score['ep_id']][$run_key][$score['judge_id']] = $score;
                }
                
                echo json_encode([
                    'success' => true,
                    'judges' => $judges,
                    'participants' => $participants,
                    'scores' => $scores,
                    'heat_number' => $heat_number,
                    'run_number' => $run_number
                ]);
                
            } catch (Exception $e) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $e->getMessage()
                ]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Missing event_id']);
        }
        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();
            
            // Get score details for notification
            $score_details_stmt = $pdo->prepare("
                SELECT s.score_value, s.status, u.username as judge_name, 
                       p.first_name, p.last_name, ep.bib_number, ep.event_id,
                       ep.heat_number, r.run_number, ep.id as participant_id
                FROM scores s
                JOIN runs r ON s.run_id = r.id
                JOIN event_participants ep ON r.event_participant_id = ep.id
                JOIN participants p ON ep.participant_id = p.id
                JOIN users u ON s.judge_id = u.id
                WHERE s.id = ?
            ");
            $score_details_stmt->execute([$score_id]);
            $score_details = $score_details_stmt->fetch(PDO::FETCH_ASSOC);
            
            $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]);
            
            // Prepare notification data for frontend
            $notification_data = null;
            if ($score_details) {
                $participant_name = $score_details['first_name'] . ' ' . $score_details['last_name'];
                $score_display = $score_details['status'] === 'OK' ? $score_details['score_value'] : $score_details['status'];
                
                // Get all judge scores for this participant/heat/run
                $all_scores_stmt = $pdo->prepare("
                    SELECT s.score_value, s.status, u.username as judge_name, s.is_approved,
                           u.id as judge_id
                    FROM scores s
                    JOIN runs r ON s.run_id = r.id
                    JOIN event_participants ep ON r.event_participant_id = ep.id
                    JOIN users u ON s.judge_id = u.id
                    WHERE ep.id = ? AND ep.heat_number = ? AND r.run_number = ?
                    ORDER BY u.username
                ");
                $all_scores_stmt->execute([
                    $score_details['participant_id'], 
                    $score_details['heat_number'], 
                    $score_details['run_number']
                ]);
                $all_judge_scores = $all_scores_stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Calculate current result (average of approved scores)
                $approved_scores = [];
                $all_scores_info = [];
                foreach ($all_judge_scores as $judge_score) {
                    $judge_display = $judge_score['status'] === 'OK' ? $judge_score['score_value'] : $judge_score['status'];
                    $all_scores_info[] = [
                        'judge' => $judge_score['judge_name'],
                        'score' => $judge_display,
                        'approved' => (bool)$judge_score['is_approved']
                    ];
                    
                    if ($judge_score['is_approved'] && $judge_score['status'] === 'OK' && $judge_score['score_value'] !== null) {
                        $approved_scores[] = floatval($judge_score['score_value']);
                    }
                }
                
                $current_result = null;
                $approved_count = count($approved_scores);
                if ($approved_count > 0) {
                    // Apply drop rule if enough scores (simplified version)
                    if ($approved_count >= 3) {
                        // Drop highest and lowest
                        sort($approved_scores);
                        array_shift($approved_scores); // Remove lowest
                        array_pop($approved_scores);   // Remove highest
                    }
                    $current_result = $approved_count > 0 ? round(array_sum($approved_scores) / count($approved_scores), 3) : null;
                }
                
                // Calculate current rank position
                $rank_position = null;
                if ($current_result !== null) {
                    // Get all participants' current results for ranking
                    $ranking_stmt = $pdo->prepare("
                        SELECT ep.bib_number, ep.id as participant_id,
                               AVG(CASE WHEN s.is_approved = 1 AND s.status = 'OK' THEN s.score_value END) as avg_score,
                               COUNT(CASE WHEN s.is_approved = 1 AND s.status = 'OK' THEN 1 END) as approved_count
                        FROM event_participants ep
                        JOIN runs r ON ep.id = r.event_participant_id
                        JOIN scores s ON r.id = s.run_id
                        WHERE ep.event_id = ? AND ep.heat_number = ? AND r.run_number = ?
                        GROUP BY ep.id, ep.bib_number
                        HAVING approved_count > 0
                        ORDER BY avg_score DESC
                    ");
                    $ranking_stmt->execute([
                        $score_details['event_id'],
                        $score_details['heat_number'],
                        $score_details['run_number']
                    ]);
                    $rankings = $ranking_stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    foreach ($rankings as $index => $ranking) {
                        if ($ranking['participant_id'] == $score_details['participant_id']) {
                            $rank_position = $index + 1;
                            break;
                        }
                    }
                }
                
                $notification_data = [
                    'bib' => $score_details['bib_number'],
                    'participant_name' => $participant_name,
                    'score' => $score_display,
                    'judge' => $score_details['judge_name'],
                    'heat' => $score_details['heat_number'],
                    'run' => $score_details['run_number'],
                    'all_scores' => $all_scores_info,
                    'current_result' => $current_result,
                    'rank_position' => $rank_position,
                    'approved_count' => $approved_count,
                    'total_judges' => count($all_judge_scores)
                ];
                
                // Enhanced notification message
                $result_text = $current_result !== null ? " | Current Result: {$current_result}" : "";
                $rank_text = $rank_position !== null ? " | Rank: #{$rank_position}" : "";
                $progress_text = " | Scores: {$approved_count}/" . count($all_judge_scores);
                
                // Send to notification API
                $api_data = [
                    'type' => 'success',
                    'title' => 'Score Approved',
                    'message' => sprintf(
                        "Bib #%s (%s) - %s approved: %s (Heat %s, Run %s)%s%s%s",
                        $score_details['bib_number'],
                        $participant_name,
                        $score_details['judge_name'],
                        $score_display,
                        $score_details['heat_number'],
                        $score_details['run_number'],
                        $result_text,
                        $rank_text,
                        $progress_text
                    ),
                    'category' => 'judge',
                    'event_id' => $score_details['event_id'],
                    'user_id' => $notification_user_id ?? 'head_judge',
                    'data' => json_encode([
                        'score_id' => $score_id,
                        'participant_bib' => $score_details['bib_number'],
                        'participant_name' => $participant_name,
                        'judge' => $score_details['judge_name'],
                        'approved_score' => $score_display,
                        'heat' => $score_details['heat_number'],
                        'run' => $score_details['run_number'],
                        'all_judge_scores' => $all_scores_info,
                        'current_result' => $current_result,
                        'rank_position' => $rank_position,
                        'approved_count' => $approved_count,
                        'total_judges' => count($all_judge_scores)
                    ])
                ];
                
                // Send to notification API
                $api_url = '../api/notification_api.php';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_data + ['action' => 'send_notification']));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                curl_exec($ch);
                curl_close($ch);
            }
            
            echo json_encode([
                'success' => true, 
                'message' => 'Score approved successfully',
                'notification_data' => $notification_data
            ]);
        } 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'; ?>
    <!-- Lucide Icons and translation utility are now included globally via stylesheets.php and footer.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;
        }
              
        
.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{

    }
#scoresTable th {
    padding: 5px !important;
}
#scoresTable td {
    border-top: 3px #00000063 solid;
}
/* Drop score styling */
.score_drop {
    opacity: 0.7;
}

.score_drop .score_value {
        color: #1f2225 !important;
   
}

.score_drop:hover .score_value {
    color: #495057 !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;
}

/* Control Point Summary Row Styles */
.control-point-summary {
    background-color: rgba(248, 249, 250, 0.8) !important;
    border-top: 2px solid #dee2e6 !important;
    font-size: 0.85rem;
}

.control-point-summary td {
    padding: 5px 5px !important;
    vertical-align: top !important;
}
.figures-summary{    display: flex
;}
.mb-1.figuresByCategory {
    display: flex
;
    flex-wrap: wrap;
    justify-content: center;
}
.control-point-summary .scores-summary .badge {
    font-size: 0.7rem;
    padding: 0.3em 0.5em;
}

.control-point-summary .figures-summary {
    font-size: 0.75rem;
}

.control-point-summary .figures-summary .badge {
    font-size: 0.65rem;
    padding: 0.2em 0.4em;
}

/* Enhanced figures display under scoreCol */
.scores-col2 .figures-display {
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    margin-top: 4px;
}

/* 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;
}

/* Notification System Styles */
.css-bib {
    font-weight: bold !important;
    font-size: 0.9em !important;
    padding: 0.3em 0.6em !important;
    margin: 0 0.2em !important;
}
span.badge.bg-danger.approval-clickable {
    max-width: 90px;
}
.judge_score {
    font-weight: bold !important;
    font-size: 0.85em !important;
    padding: 0.25em 0.5em !important;
    margin: 0 0.1em !important;
}

.judge_score.approved {
    background-color: #28a745 !important;
    border-color: #28a745 !important;
}

.notification-toast .toast-body {
   
}

.notification-toast .toast-body small.text-light {
   
}

    </style>
</head>

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

    <div class="container-fluid container-StyleScore p-4">
            <!-- event action menu. -->
<div class="row mb-3">
    <div class="col-12">
        <?php       
        $use_localStorage = false;
        $show_header = false;
        //$show_public_view = false;
        include '../admin/event_actions_menu.php'; 
        ?>
        <div class="d-flex justify-content-end mt-2">
            <button type="button" class="btn btn-outline-info btn-sm" onclick="openHeadJudgeHelp()">
                <i class="fas fa-circle-question me-1"></i> Help
            </button>
        </div>
    </div>
</div>
        <div class="row">
            <div class="col-12">
                <!-- Control Panel -->
                <div class="border-0 shadow-none card bg-primary text-white mb-3">
                    <div class="border-0 shadow-none 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="border-0 shadow-none card">
                    <div class="border-0 shadow-none 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="border-0 shadow-none 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>

    <!-- Help Modal -->
    <div class="modal fade" id="headJudgeHelpModal" tabindex="-1" aria-labelledby="headJudgeHelpTitle" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="headJudgeHelpTitle">
                        <i class="fas fa-circle-question me-2"></i>Head Judge Panel – Help
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <iframe id="headJudgeHelpIframe" style="width:100%; height:80vh; border:none;" title="Head Judge Help"></iframe>
                </div>
            </div>
        </div>
    </div>

    
    <script>
        function openHeadJudgeHelp() {
            const modalEl = document.getElementById('headJudgeHelpModal');
            const iframe = document.getElementById('headJudgeHelpIframe');
            if (iframe && !iframe.src) {
                iframe.src = '../help/head_judge_help.html';
            }
            const modal = new bootstrap.Modal(modalEl);
            modal.show();
        }
         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
                    loadScores(); // Load scores even without heat/run selection
                } 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();
                    loadScores(); // Load scores for selected heat (all runs)
                } else {
                    runSelect.innerHTML = '<option value="">Select Run</option>';
                    loadScores(); // Load all heats/runs when heat is deselected
                }
            });
            
            // Run selection handler - modified to work with localStorage
            runSelect.addEventListener('change', function() {
                loadScores(); // Always load scores, even if run is deselected
            });
            
            // Refresh button
            refreshBtn.addEventListener('click', function() {
                const eventId = document.getElementById('eventSelect').value;
                if (eventId) {
                    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');
                    
                    // Initialize Lucide icons for the button feedback
                    if (window.initializeLucideIcons) {
                        window.initializeLucideIcons();
                    }
                    
                    setTimeout(() => {
                        btn.innerHTML = originalHTML;
                        btn.classList.remove('btn-success');
                        btn.classList.add('btn-outline-secondary');
                        
                        // Initialize Lucide icons when restoring original content
                        if (window.initializeLucideIcons) {
                            window.initializeLucideIcons();
                        }
                    }, 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');
                    
                    // Initialize Lucide icons for the button feedback
                    if (window.initializeLucideIcons) {
                        window.initializeLucideIcons();
                    }
                    
                    // 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);
                    
                    // Initialize Lucide icons for the toast notification
                    if (window.initializeLucideIcons) {
                        window.initializeLucideIcons();
                    }
                    
                    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, targetRunNumber = null) {
            let hasAnyScores = false;
            let hasPendingScores = false;
            let hasAllScores = true;
            
            const participantScores = scores[participant.id] || {};
            
            if (targetRunNumber) {
                // Specific run - check only that run
                const runScores = participantScores[targetRunNumber] || {};
                judges.forEach(judge => {
                    const score = runScores[judge.id];
                    if (score) {
                        hasAnyScores = true;
                        if (score.is_approved == 0) {
                            hasPendingScores = true;
                        }
                    } else {
                        hasAllScores = false;
                    }
                });
            } else {
                // No specific run - check all runs
                Object.keys(participantScores).forEach(runNum => {
                    const runScores = participantScores[runNum] || {};
                    judges.forEach(judge => {
                        const score = runScores[judge.id];
                        if (score) {
                            hasAnyScores = true;
                            if (score.is_approved == 0) {
                                hasPendingScores = true;
                            }
                        }
                    });
                });
                // For multi-run, we don't require all scores
                hasAllScores = hasAnyScores;
            }
            
            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 no event selected, clear the grid
            if (!eventId) {
                clearScoreGrid();
                return;
            }
            
            showLoading(true);
            
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'get_scores');
            formData.append('event_id', eventId);
            
            // Only append heat/run if they are selected
            if (heatNumber) {
                formData.append('heat_number', heatNumber);
            }
            if (runNumber) {
                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);
                    // Only show toast if we have a specific heat/run loaded
                    if (heatNumber && runNumber) {
                        showSuccessToast();
                    }
                } else {
                    console.error('Error loading scores:', data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            })
            .finally(() => {
                showLoading(false);
            });
        }
        
        // Function to calculate run score with drop rules
        function calculateRunScoreWithDrops(judgeScores) {
            if (judgeScores.length === 0) {
                return { score: 0, dropInfo: null };
            }
            
            // For head_judge.php, we'll use a simple highest_and_lowest drop rule if there are enough scores
            // This mimics the summary_table_api.php logic but simplified for the head judge interface
            let dropInfo = {
                droppedHighest: null,
                droppedLowest: null,
                method: 'none'
            };
            
            if (judgeScores.length >= 3) {
                // Apply highest_and_lowest drop rule for 3+ judges
                const sortedScores = [...judgeScores].sort((a, b) => a.score - b.score);
                const droppedLowest = sortedScores[0];
                const droppedHighest = sortedScores[sortedScores.length - 1];
                const usedScores = sortedScores.slice(1, -1);
                
                dropInfo = {
                    droppedHighest: droppedHighest,
                    droppedLowest: droppedLowest,
                    method: 'highest_and_lowest'
                };
                
                // Calculate average of remaining scores
                const runScore = usedScores.reduce((sum, item) => sum + item.score, 0) / usedScores.length;
                return { score: runScore, dropInfo: dropInfo };
            } else {
                // Use all scores if less than 3 judges
                const runScore = judgeScores.reduce((sum, item) => sum + item.score, 0) / judgeScores.length;
                return { score: runScore, dropInfo: dropInfo };
            }
        }
        
        // Function to check if a judge score should be marked as dropped
        function isJudgeScoreDropped(judgeId, dropInfo) {
            if (!dropInfo || dropInfo.method === 'none') {
                return false;
            }
            
            return (dropInfo.droppedHighest && dropInfo.droppedHighest.judge_id == judgeId) ||
                   (dropInfo.droppedLowest && dropInfo.droppedLowest.judge_id == judgeId);
        }
        
        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';
        
        const heatValue = document.getElementById('heatSelect').value;
        const runValue = document.getElementById('runSelect').value;
        
        let message = '';
        if (!heatValue) {
            message = `
                <i class="fas fa-info-circle fa-3x mb-3 opacity-50"></i>
                <h5>Select a Heat to View Scores</h5>
                <p>Choose a heat from the dropdown above to display participants and their scores</p>
            `;
        } else if (!runValue) {
            message = `
                <i class="fas fa-info-circle fa-3x mb-3 opacity-50"></i>
                <h5>Select a Run to View Scores</h5>
                <p>Choose a run from the dropdown above to display scores for Heat ${heatValue}</p>
            `;
        } else {
            message = `
                <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 ${heatValue}</p>
            `;
        }
        
        noDataMessage.innerHTML = message;
        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);
    });
    
    // Load scoring format configuration for drop rule calculations
    let scoringFormat = null;
    const eventId = document.getElementById('eventSelect').value;
    
    // Prepare participants with calculated data and filter them
    let processedParticipants = data.participants.map(participant => {
        let hasAllScores = true;
        let scoreValues = [];
        let latestScoreTime = null;
        
        // Determine which run to display based on data.run_number
        const targetRunNumber = data.run_number;
        
        // Collect all judge scores for this participant (for the specific run if specified)
        let judgeScores = [];
        
        if (targetRunNumber) {
            // Specific run selected - use old logic
            data.judges.forEach(judge => {
                const score = data.scores[participant.id] && data.scores[participant.id][targetRunNumber] && data.scores[participant.id][targetRunNumber][judge.id] 
                    ? data.scores[participant.id][targetRunNumber][judge.id] : null;
                if (!score) {
                    hasAllScores = false;
                } else {
                    // Add to judge scores array with judge info for drop rule processing
                    if (score.score_value !== null && score.status === 'OK') {
                        judgeScores.push({
                            judge_id: judge.id,
                            judge_name: judge.name,
                            score: parseFloat(score.score_value)
                        });
                        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;
                        }
                    }
                }
            });
        } else {
            // No specific run - collect scores from all runs for this participant
            const participantScores = data.scores[participant.id] || {};
            Object.keys(participantScores).forEach(runNum => {
                data.judges.forEach(judge => {
                    const score = participantScores[runNum][judge.id];
                    if (score) {
                        if (score.score_value !== null && score.status === 'OK') {
                            judgeScores.push({
                                judge_id: judge.id,
                                judge_name: judge.name,
                                score: parseFloat(score.score_value),
                                run_number: runNum
                            });
                            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;
                            }
                        }
                    }
                });
            });
            // For multi-run view, we don't require all scores
            hasAllScores = judgeScores.length > 0;
        }
        
        // Calculate run score with drop rules
        let runScore = 0;
        let dropInfo = null;
        if (judgeScores.length > 0) {
            const result = calculateRunScoreWithDrops(judgeScores);
            runScore = result.score;
            dropInfo = result.dropInfo;
        }
        
        const average = runScore;
        const approvalStatus = getApprovalStatus(participant, data.judges, data.scores, targetRunNumber);
        
        return {
            ...participant,
            hasAllScores,
            average,
            runScore,
            dropInfo,
            judgeScores,
            latestScoreTime,
            canSort: hasAllScores && judgeScores.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="">';
    
    // 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 => {
            const headStar = judge.is_head == 1 ? '<i data-lucide="star" class="text-warning ms-1" title="Head Judge" style="width: 14px; height: 14px;"></i>' : '';
            html += `<th class="text-center ${group.color} bg-opacity-25">
                <div class="small fw-bold">${judge.name}${headStar}</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 ss-f-number">${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 => {
                // Determine which run's score to display
                const targetRunNumber = data.run_number;
                
                // If no specific run, show all runs for this judge
                if (!targetRunNumber) {
                    // Multi-run view - show all runs
                    const participantScores = data.scores[participant.id] || {};
                    const allRunScores = [];
                    
                    // Collect all run scores for this judge
                    Object.keys(participantScores).forEach(runNum => {
                        const runScore = participantScores[runNum][judge.id];
                        if (runScore) {
                            allRunScores.push({
                                run: runNum,
                                ...runScore
                            });
                        }
                    });
                    
                    html += `<td class="scoreCol text-center ${group.color} bg-opacity-10" data-score-value="" data-status=""><div class="row score-figure flex-column">`;
                    
                    if (allRunScores.length > 0) {
                        // Display all run scores vertically
                        allRunScores.forEach(runScore => {
                            hasAnyScores = true;
                            const isApproved = runScore.is_approved == 1;
                            if (!isApproved) hasPendingScores = true;
                            
                            if (runScore.score_value !== null && runScore.status === 'OK') {
                                scoreValues.push(parseFloat(runScore.score_value));
                            }
                            
                            const bgClass = isApproved ? 'bg-approved' : 'bg-pending';
                            let scoreValue = runScore.score_value || runScore.status;
                            if (runScore.score_value !== null && runScore.status === 'OK') {
                                const numValue = parseFloat(runScore.score_value);
                                scoreValue = numValue % 1 === 0 ? numValue.toString() : numValue.toFixed(2);
                            }
                            const badgeClass = getStatusBadgeClass(runScore.status);
                            
                            html += `<div class="mb-1 p-1 rounded ${bgClass} w-100" onclick="editScore(${runScore.score_id}, ${runScore.score_value || 0}, '${runScore.status}', '${encodeURIComponent(runScore.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, "\\'")}')" style="cursor: pointer;">
                                <small class="text-muted">R${runScore.run}</small>
                                <div class="fw-bold text-${badgeClass === 'success' ? 'primary' : badgeClass === 'danger' ? 'danger' : 'warning'}${isApproved ? '': ' text-warning-emphasis'}">${scoreValue}</div>
                                ${isApproved ? 
                                    '<small class="badge bg-success bg-opacity-50">✓</small>' : 
                                    '<small class="badge bg-danger bg-opacity-50">!</small>'
                                }
                            </div>`;
                        });
                    } else {
                        html += `<small class="text-muted">No scores</small>`;
                    }
                    
                    html += `</div></td>`;
                    return;
                }
                
                // Single run view - original logic
                const score = data.scores[participant.id] && data.scores[participant.id][targetRunNumber] && data.scores[participant.id][targetRunNumber][judge.id] 
                    ? data.scores[participant.id][targetRunNumber][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">`;
                    
                    // Check if this score is dropped based on drop rules
                    const isDropped = isJudgeScoreDropped(judge.id, participant.dropInfo);
                    // Format score value to remove unnecessary decimals
                    let scoreValue = score.score_value || score.status;
                    if (score.score_value !== null && score.status === 'OK') {
                        const numValue = parseFloat(score.score_value);
                        scoreValue = numValue % 1 === 0 ? numValue.toString() : numValue.toFixed(2);
                    }
                    const badgeClass = getStatusBadgeClass(score.status);
                    const dropClass = isDropped ? 'score_drop fs-4' : 'fs-2';
                    const dropIndicator = isDropped ? '(' : '';
                    const dropIndicatorEnd = isDropped ? ')' : '';
                    
                    html += `<div class="scores-col1 ${score.status} ${dropClass}" 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, "\\'")}')">
                                <span class="fw-bold score_value m-0 text-${badgeClass === 'success' ? 'primary' : badgeClass === 'danger' ? 'danger' : 'warning'}${isApproved ? '': ' text-warning-emphasis'}">${dropIndicator}${scoreValue}${dropIndicatorEnd}</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>
                             ${isApproved ? 
                            '<span class="badge text-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>'
                        }
                        `;
                    
                    // 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 w-100" style="display: none !important;">
                                    <div class="figures-display mt-1 border-top p-1 small w-100 hidden">
                                        ${Object.keys(figuresData).map(cat => {
                                            const items = Array.isArray(figuresData[cat]) ? figuresData[cat] : [];
                                            if (!items.length) return '';
                                            return `
                                                <div class="m-0 figure-s w-100 text-center">
                                                    ${items.map(item => `<span class=\"fw-bold badge bg-light text-primary mx-1\"><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 (participant.judgeScores && participant.judgeScores.length > 0) {
            // Use the calculated run score with drop rules and format appropriately
            const displayScore = participant.runScore;
            // Format to remove unnecessary decimals
            const formattedScore = displayScore % 1 === 0 ? displayScore.toString() : displayScore.toFixed(2);
            html += `
                <span class="mb-2 text-dark fs-2 fw-bold">${formattedScore}</span>
                <span class="badge text-dark">${participant.judgeScores.length} scores</span>
            `;
            
            // Show drop rule info if applicable
            if (participant.dropInfo && participant.dropInfo.method !== 'none') {
                //html += `<br><small class="text-muted">Drop: ${participant.dropInfo.method.replace('_', ' ')}</small>`;
            }
        } 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>';
        
        // Add merged control point summary row
        html += `<tr class="control-point-summary bg-light border-top-2">`;
        html += `<td class="text-muted small px-2 py-1">
            <i class="fas fa-layer-group me-1"></i>Control Point Summary
        </td>`;
        
        // Create merged cells for each control point
        Object.keys(controlPointGroups).forEach(cpName => {
            const group = controlPointGroups[cpName];
            const cpScores = [];
            const cpFigures = [];
            
            // Collect all scores and figures for this control point
            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) {
                    // Add score info
                    let scoreValue = score.score_value || score.status;
                    if (score.score_value !== null && score.status === 'OK') {
                        const numValue = parseFloat(score.score_value);
                        scoreValue = numValue % 1 === 0 ? numValue.toString() : numValue.toFixed(2);
                    }
                    const isApproved = score.is_approved == 1;
                    const badgeClass = getStatusBadgeClass(score.status);
                    cpScores.push({
                        judge: judge.name,
                        value: scoreValue,
                        status: score.status,
                        approved: isApproved,
                        badgeClass: badgeClass
                    });
                    
                    // Add figures info
                    if (score.figures_json) {
                        try {
                            const figuresData = JSON.parse(score.figures_json);
                            Object.keys(figuresData || {}).forEach(category => {
                                const items = Array.isArray(figuresData[category]) ? figuresData[category] : [];
                                if (items.length > 0) {
                                    cpFigures.push({
                                        judge: judge.name,
                                        category: category,
                                        items: items
                                    });
                                }
                            });
                        } catch (e) {
                            // Ignore JSON parse errors
                        }
                    }
                }
            });
            
            html += `<td colspan="${group.judges.length}" class="text-center ${group.color} bg-opacity-5 p-2">`;
            //
            if (cpScores.length > 0) {
                // Display scores summary

                /*
                html += `<div class="scores-summary mb-2">`;
                cpScores.forEach(scoreInfo => {
                    const approvedIcon = scoreInfo.approved ? '<i class="fas fa-check-circle text-success me-1"></i>' : '<i class="fas fa-clock text-warning me-1"></i>';
                    html += `<span class="badge bg-${scoreInfo.badgeClass} me-1 mb-1">
                        ${approvedIcon}${scoreInfo.judge}: ${scoreInfo.value}
                    </span>`;
                });
                html += `</div>`;
                */
                // Display figures summary if any
                if (cpFigures.length > 0) {
                    html += `<div class="figures-summary">`;
                    const figuresByCategory = {};
                    cpFigures.forEach(figInfo => {
                        if (!figuresByCategory[figInfo.category]) {
                            figuresByCategory[figInfo.category] = new Set();
                        }
                        figInfo.items.forEach(item => figuresByCategory[figInfo.category].add(item));
                    });
                    
                    Object.keys(figuresByCategory).forEach(category => {
                        const uniqueItems = Array.from(figuresByCategory[category]);
                        html += `<div class="mb-1 figuresByCategory">
                            <small class="text-muted">${category}:</small> 
                            ${uniqueItems.map(item => `<span class="badge bg-light text-dark border mx-1">${item}</span>`).join('')}
                        </div>`;
                    });
                    html += `</div>`;
                }
            } else {
                html += `<span class="text-muted small">No scores for ${cpName}</span>`;
            }
            
            html += `</td>`;
        });
        
        // Empty cells for average and actions columns
        html += `<td class="text-muted"></td>`;
        html += `<td class="text-muted"></td>`;
        html += `</tr>`;
    });
    
    html += '</tbody></table></div>';
    container.innerHTML = html;
    
    // Initialize Lucide icons for the new dynamic content
    if (window.initializeLucideIcons) {
        window.initializeLucideIcons();
    }
    
    // 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');
            
            // Send specific notification about score approval
            if (typeof notifyScoreApproval === 'function' && data.notification_data) {
                const nd = data.notification_data;
                // Pass enhanced data including all judge scores, current result, and rank
                const enhancedData = {
                    all_scores: nd.all_scores,
                    current_result: nd.current_result,
                    rank_position: nd.rank_position,
                    approved_count: nd.approved_count,
                    total_judges: nd.total_judges
                };
                notifyScoreApproval(nd.bib, nd.participant_name, nd.score, nd.judge, nd.heat, nd.run, enhancedData);
            } else if (typeof sendNotification === 'function') {
                sendNotification('success', 'Score Approved', 'Head judge approved a score', 'judge');
            }
            
            // 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`);
            
            // Send specific notification about bulk approval
            if (data.notification_data) {
                const nd = data.notification_data;
                // Try to use notification manager if available
                if (window.globalNotificationManager && typeof window.globalNotificationManager.notifyBulkScoreApproval === 'function') {
                    try {
                        window.globalNotificationManager.notifyBulkScoreApproval(nd.bib, nd.participant_name, nd.count, nd.heat, nd.run);
                    } catch (error) {
                        console.warn('Notification manager error:', error);
                        // Fall back to generic notification
                        if (typeof sendNotification === 'function') {
                            const countText = nd.count > 0 ? ` (${nd.count} scores)` : '';
                            sendNotification('success', 'All Scores Approved', `Head judge approved all scores for #${nd.bib} ${nd.participant_name}${countText}`, 'judge');
                        }
                    }
                } else if (typeof sendNotification === 'function') {
                    const countText = nd.count > 0 ? ` (${nd.count} scores)` : '';
                    sendNotification('success', 'All Scores Approved', `Head judge approved all scores for #${nd.bib} ${nd.participant_name}${countText}`, 'judge');
                }
            } else if (typeof sendNotification === 'function') {
                const countText = data.count > 0 ? ` (${data.count} scores)` : '';
                sendNotification('success', 'All Scores Approved', `Head judge approved all scores for participant${countText}`, 'judge');
            }
            
            // 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>';
            }
            
            // Initialize Lucide icons for the figure display content
            if (window.initializeLucideIcons) {
                window.initializeLucideIcons();
            }
        }
        
        // 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(() => {
                const eventId = document.getElementById('eventSelect').value;
                if (eventId) {
                    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>
    
    <?php
    // Render the notification system
    render_notification_system();
    ?>

    <?php include '../admin/footer.php'; ?>
</body>
</html>