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

// Add this new block to handle AJAX overwrite score submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['overwrite_score_id']) && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    $score_id = $_POST['overwrite_score_id'];
    $new_score_value = $_POST['overwrite_score_value'] !== '' ? floatval($_POST['overwrite_score_value']) : null;
    $new_status = $_POST['overwrite_status'];
    $new_figures_json = $_POST['overwrite_figures_json'] ?? '';
    
    // Get judge_id using users table
    $user_type = $_SESSION['user_type'];
    $user_id = $_SESSION['user_id'];
    
    if ($user_type == 'admin') {
        // For admin, use their user_id directly or a specific judge_id
        $current_judge_id = $user_id; // Or use a specific judge_id if needed
    } else {
        // For judge, use their user_id as judge_id
        $current_judge_id = $user_id;
    }
    
    // Validate that this score belongs to the current judge
    $validate_stmt = $pdo->prepare("SELECT id FROM scores WHERE id = ? AND judge_id = ?");
    $validate_stmt->execute([$score_id, $current_judge_id]);
    if (!$validate_stmt->fetch()) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid score ID or you don\'t have permission to edit this score.'
        ]);
        exit;
    }
    
    try {
        // Resolve event + heat for this score to compute current control_point_id
        $score_ctx = $pdo->prepare("SELECT ep.event_id, ep.heat_number
                                    FROM scores s
                                    JOIN runs r ON s.run_id = r.id
                                    JOIN event_participants ep ON r.event_participant_id = ep.id
                                    WHERE s.id = ? AND s.judge_id = ?");
        $score_ctx->execute([$score_id, $current_judge_id]);
        $ctx = $score_ctx->fetch(PDO::FETCH_ASSOC) ?: null;

        $control_point_id = null;
        if ($ctx && !empty($ctx['event_id'])) {
            try {
                $cp_stmt = $pdo->prepare("
                    SELECT ecp.id
                    FROM judge_assignments ja
                    JOIN event_control_points ecp ON ecp.id = ja.event_control_point_id
                    WHERE ja.event_id = ?
                      AND ja.judge_id = ?
                      AND (ja.heat_number = ? OR ja.heat_number IS NULL)
                    ORDER BY (ja.heat_number = ?) DESC, ja.heat_number DESC
                    LIMIT 1
                ");
                $cp_stmt->execute([$ctx['event_id'], $current_judge_id, $ctx['heat_number'], $ctx['heat_number']]);
                $control_point_id = $cp_stmt->fetchColumn() ?: null;
            } catch (Exception $e) {
                $control_point_id = null;
            }
        }

        // Check if columns exist
        $hasCPCol = false;
        $hasFiguresCol = false;
        try { $pdo->query("SELECT control_point_id FROM scores WHERE 1=0"); $hasCPCol = true; } catch (Exception $e) { $hasCPCol = false; }
        try { $pdo->query("SELECT figures_json FROM scores WHERE 1=0"); $hasFiguresCol = true; } catch (Exception $e) { $hasFiguresCol = false; }

        // Update the score with conditional column support
        if ($hasCPCol && $hasFiguresCol) {
            $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, control_point_id = ?, figures_json = ?, updated_at = NOW() WHERE id = ? AND judge_id = ?");
            $update_stmt->execute([$new_score_value, $new_status, $control_point_id, $new_figures_json ?: null, $score_id, $current_judge_id]);
        } elseif ($hasCPCol && !$hasFiguresCol) {
            $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, control_point_id = ?, updated_at = NOW() WHERE id = ? AND judge_id = ?");
            $update_stmt->execute([$new_score_value, $new_status, $control_point_id, $score_id, $current_judge_id]);
        } elseif (!$hasCPCol && $hasFiguresCol) {
            $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, figures_json = ?, updated_at = NOW() WHERE id = ? AND judge_id = ?");
            $update_stmt->execute([$new_score_value, $new_status, $new_figures_json ?: null, $score_id, $current_judge_id]);
        } else {
            $update_stmt = $pdo->prepare("UPDATE scores SET score_value = ?, status = ?, updated_at = NOW() WHERE id = ? AND judge_id = ?");
            $update_stmt->execute([$new_score_value, $new_status, $score_id, $current_judge_id]);
        }
        
        // Fetch updated score details for response
        $fetch_stmt = $pdo->prepare("
            SELECT s.id AS score_id, s.score_value, s.status, s.figures_json, r.run_number, ep.heat_number, ep.bib_number as bib, 
                   p.first_name, p.last_name, s.created_at
            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
            WHERE s.id = ?
        ");
        $fetch_stmt->execute([$score_id]);
        $updated_score = $fetch_stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'message' => 'Score updated successfully!',
            'score' => $updated_score
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $e->getMessage()
        ]);
    }
    
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_score'])) {
    $stmt = $pdo->prepare("
        DELETE s FROM scores s
        JOIN runs r ON s.run_id = r.id
        JOIN event_participants ep ON r.event_participant_id = ep.id
        WHERE s.judge_id = ? AND ep.event_id = ?
    ");
    $stmt->execute([$_POST['judge_id'], $_POST['event_id']]);
    header("Location: score.php?event_id=" . intval($_POST['event_id']) . "&reset=1");
    exit;
}

// Handle AJAX score submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ep_id']) && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    try {
        $run_number = $_POST['run_number'];
        $ep_id = $_POST['ep_id'];
        $p_bib = $_POST['p_bib'];
        $heat_number = $_POST['heat_number'];
    $score_value = $_POST['score_value'] !== '' ? floatval($_POST['score_value']) : null;
    $status = $_POST['status'];
    $sel_figure_cat = $_POST['figure_category'] ?? '';
    $sel_figure_item = $_POST['figure_item'] ?? '';
    $figures_json = $_POST['figures_json'] ?? '';

        // Process criteria scores if provided
        $criteria_scores_json = $_POST['criteria_scores_json'] ?? '';
        $criteria_scores_data = [];
        if (!empty($criteria_scores_json)) {
            try {
                $criteria_scores_data = json_decode($criteria_scores_json, true) ?: [];
            } catch (Exception $e) {
                $criteria_scores_data = [];
            }
        }

        // Judge identity
        $user_type = $_SESSION['user_type'];
        $user_id = $_SESSION['user_id'];
        $judge_id = $user_id;

        // Resolve event_id for this participant
        $evStmt = $pdo->prepare("SELECT event_id FROM event_participants WHERE id = ?");
        $evStmt->execute([$ep_id]);
        $event_id = (int)$evStmt->fetchColumn();

        // Validate participant
        $validate_stmt = $pdo->prepare("SELECT 1 FROM event_participants WHERE id = ?");
        $validate_stmt->execute([$ep_id]);
        if (!$validate_stmt->fetch()) {
            echo json_encode(['success' => false, 'message' => 'Participant not assigned to event/heat.']);
            exit;
        }

        // Create or get run
        $run_stmt = $pdo->prepare("SELECT id FROM runs WHERE event_participant_id = ? AND run_number = ?");
        $run_stmt->execute([$ep_id, $run_number]);
        $run = $run_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$run) {
            $insert_run = $pdo->prepare("INSERT INTO runs (event_participant_id, run_number) VALUES (?, ?)");
            $insert_run->execute([$ep_id, $run_number]);
            $run_id = $pdo->lastInsertId();
        } else {
            $run_id = $run['id'];
        }

        // Resolve current control point for judge (match by event and prefer exact heat)
        $control_point_id = null;
        if ($event_id) {
            $cp_stmt = $pdo->prepare("
                SELECT ecp.id
                FROM judge_assignments ja
                JOIN event_control_points ecp ON ecp.id = ja.event_control_point_id
                WHERE ja.event_id = ?
                  AND ja.judge_id = ?
                  AND (ja.heat_number = ? OR ja.heat_number IS NULL)
                ORDER BY (ja.heat_number = ?) DESC, ja.heat_number DESC
                LIMIT 1
            ");
            $cp_stmt->execute([$event_id, $judge_id, $heat_number, $heat_number]);
            $control_point_id = $cp_stmt->fetchColumn() ?: null;
        }

        // Insert or update score with control_point_id (if column exists) and figures_json (if column exists)
        $hasFiguresCol = false; $hasCPCol = false; $hasCriteriaCol = false;
        try { $pdo->query("SELECT figures_json FROM scores WHERE 1=0"); $hasFiguresCol = true; } catch (Exception $e) { $hasFiguresCol = false; }
        try { $pdo->query("SELECT control_point_id FROM scores WHERE 1=0"); $hasCPCol = true; } catch (Exception $e) { $hasCPCol = false; }
        try { $pdo->query("SELECT criteria_scores FROM scores WHERE 1=0"); $hasCriteriaCol = true; } catch (Exception $e) { $hasCriteriaCol = false; }

        // Prepare criteria scores JSON for storage
        $criteria_scores_for_db = null;
        if ($hasCriteriaCol && !empty($criteria_scores_data)) {
            $criteria_scores_for_db = json_encode($criteria_scores_data);
        }

        // Handle different column combinations
        if ($hasCPCol && $hasFiguresCol && $hasCriteriaCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, control_point_id, score_value, status, figures_json, criteria_scores) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $control_point_id, $score_value, $status, $figures_json ?: null, $criteria_scores_for_db]);
        } elseif ($hasCPCol && $hasFiguresCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, control_point_id, score_value, status, figures_json) VALUES (?, ?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $control_point_id, $score_value, $status, $figures_json ?: null]);
        } elseif ($hasCPCol && $hasCriteriaCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, control_point_id, score_value, status, criteria_scores) VALUES (?, ?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $control_point_id, $score_value, $status, $criteria_scores_for_db]);
        } elseif ($hasFiguresCol && $hasCriteriaCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, score_value, status, figures_json, criteria_scores) VALUES (?, ?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $score_value, $status, $figures_json ?: null, $criteria_scores_for_db]);
        } elseif ($hasCPCol && !$hasFiguresCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, control_point_id, score_value, status) VALUES (?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $control_point_id, $score_value, $status]);
        } elseif (!$hasCPCol && $hasFiguresCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, score_value, status, figures_json) VALUES (?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $score_value, $status, $figures_json ?: null]);
        } elseif (!$hasCPCol && $hasCriteriaCol) {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, score_value, status, criteria_scores) VALUES (?, ?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $score_value, $status, $criteria_scores_for_db]);
        } else {
            $stmtIns = $pdo->prepare("REPLACE INTO scores (run_id, judge_id, score_value, status) VALUES (?, ?, ?, ?)");
            $stmtIns->execute([$run_id, $judge_id, $score_value, $status]);
        }

        // Fetch the newly created/updated score with participant details
        $fetch_stmt = $pdo->prepare("
            SELECT s.id AS score_id, s.score_value, s.status, r.run_number, ep.heat_number, ep.bib_number as bib, 
                   p.first_name, p.last_name, s.created_at
            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
            WHERE s.run_id = ? AND s.judge_id = ?
        ");
        $fetch_stmt->execute([$run_id, $judge_id]);
        $new_score = $fetch_stmt->fetch(PDO::FETCH_ASSOC);

        $figureNote = '';
        if (!empty($sel_figure_cat) && !empty($sel_figure_item)) {
            $catEsc = htmlspecialchars($sel_figure_cat, ENT_QUOTES, 'UTF-8');
            $itemEsc = htmlspecialchars($sel_figure_item, ENT_QUOTES, 'UTF-8');
            $figureNote = " <span class=\"badge bg-success ms-2\"><i class=\"fas fa-shapes me-1\"></i>{$catEsc}: {$itemEsc}</span>";
        }

        echo json_encode([
            'success' => true,
            'message' => "Score submitted! BIB <strong>{$p_bib}</strong>. Score: <strong>" . ($score_value === null ? '-' : $score_value) . "</strong>" . $figureNote,
            'score' => $new_score
        ]);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Main logic - UPDATED to use users table
$user_type = $_SESSION['user_type'];
$user_id = $_SESSION['user_id'];

if ($user_type == 'admin') {
    // For admin, use their user_id directly
    $judge_id = $user_id;
} else {
    // For judge, use their user_id as judge_id
    $judge_id = $user_id;
}

$message = '';
$manual_mode = isset($_GET['manual']) && $_GET['manual'] == 1;

// Get assigned events - UPDATED to use users table
$assigned_event_stmt = $pdo->prepare("SELECT e.id, e.name FROM events e
    JOIN judge_assignments ja ON e.id = ja.event_id
    WHERE ja.judge_id = ?");
$assigned_event_stmt->execute([$judge_id]);
$assigned_events = $assigned_event_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get selected event
$event_id = $manual_mode ? ($_POST['event_id'] ?? $_GET['event_id'] ?? '') : ($assigned_events[0]['id'] ?? null);

// Get judge name - UPDATED to use users table
$judge_name = '';
$judge_stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
$judge_stmt->execute([$judge_id]);
$judge_name = $judge_stmt->fetchColumn() ?? 'Unknown';

// Get event date
$event_date = '';
if ($event_id) {
    $event_info_stmt = $pdo->prepare("SELECT date FROM events WHERE id = ?");
    $event_info_stmt->execute([$event_id]);
    $event_date = $event_info_stmt->fetchColumn();
}

// Fetch event scoring format + related metadata (for Format Info card)
$format_info = null;
$uses_figures = false;
$figure_categories = [];
$figure_items_by_category = [];
$format_icon_url = null;
// Diversity rules + mode configs (attempts/tricks) for validation UI
$diversity_rules = [];
$mode_attempts = ['max' => null, 'bestN' => null];
$mode_tricks = ['attempts' => null, 'bestN' => null];
if ($event_id) {
    $fmtStmt = $pdo->prepare("SELECT e.scoring_format,
                                     sf.name AS format_name,
                                     sf.sport,
                                     sf.mode,
                                     jf.min_judges, jf.max_judges, jf.scale_min, jf.scale_max, jf.scale_type, jf.precision_decimal, jf.drop_rule,
                                     (SELECT COUNT(*) FROM scoring_format_criteria sc WHERE sc.format_id = sf.format_id) AS criteria_count,
                                     (SELECT COUNT(*) FROM scoring_format_results sr WHERE sr.format_id = sf.format_id) AS results_count
                              FROM events e
                              LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
                              LEFT JOIN scoring_format_judges jf ON sf.format_id = jf.format_id
                              WHERE e.id = ?");
    $fmtStmt->execute([$event_id]);
    $format_info = $fmtStmt->fetch(PDO::FETCH_ASSOC) ?: null;

    if ($format_info && !empty($format_info['scoring_format'])) {
        // Resolve SVG icon from ../assets/img/SVG/[format_id].svg or .SVG
        $fid = $format_info['scoring_format'];
        $slug = preg_replace('/[^a-zA-Z0-9_-]+/', '_', strtolower($fid));
        $svgRel = "../assets/img/SVG/{$slug}.svg";
        $SVGRel = "../assets/img/SVG/{$slug}.SVG";
        $svgFs = __DIR__ . "/../assets/img/SVG/{$slug}.svg";
        $SVGFs = __DIR__ . "/../assets/img/SVG/{$slug}.SVG";
        if (file_exists($svgFs)) {
            $format_icon_url = $svgRel;
        } elseif (file_exists($SVGFs)) {
            $format_icon_url = $SVGRel;
        }

        // Load diversity rules for this format (for UI summary/validation)
        try {
            $divQ = $pdo->prepare("SELECT rule_type, scope, group_name, min_distinct, is_optional FROM scoring_format_diversity_rules WHERE format_id = ? ORDER BY rule_type ASC, group_name ASC");
            $divQ->execute([$format_info['scoring_format']]);
            $diversity_rules = $divQ->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Exception $e) {
            $diversity_rules = [];
        }

        // Load attempts/tricks configs used by some diversity rules (bestN, attempts count)
        try {
            $cfgStmt = $pdo->prepare("SELECT config_type, config_key, config_value FROM scoring_format_mode_config WHERE format_id = ? AND (config_type IN ('attempts','tricks'))");
            $cfgStmt->execute([$format_info['scoring_format']]);
            $rowsCfg = $cfgStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
            foreach ($rowsCfg as $cfg) {
                if ($cfg['config_type'] === 'attempts') {
                    if ($cfg['config_key'] === 'max') $mode_attempts['max'] = (int)$cfg['config_value'];
                    if ($cfg['config_key'] === 'bestN') $mode_attempts['bestN'] = (int)$cfg['config_value'];
                }
                if ($cfg['config_type'] === 'tricks') {
                    if ($cfg['config_key'] === 'attempts') $mode_tricks['attempts'] = (int)$cfg['config_value'];
                    if ($cfg['config_key'] === 'bestN') $mode_tricks['bestN'] = (int)$cfg['config_value'];
                }
            }
        } catch (Exception $e) {
            // ignore
        }

        // Determine if sport has figures available
        if (!empty($format_info['sport'])) {
            $figCheck = $pdo->prepare("SELECT COUNT(*)
                                       FROM figure_categories fc
                                       JOIN figure_items fi ON fi.sport_name = fc.sport_name AND fi.category_name = fc.category_name
                                       WHERE fc.sport_name = ? AND fc.is_active = 1 AND fi.is_active = 1");
            $figCheck->execute([$format_info['sport']]);
            $uses_figures = (int)$figCheck->fetchColumn() > 0;

            if ($uses_figures) {
                // Load categories
                $catStmt = $pdo->prepare("SELECT category_name FROM figure_categories WHERE sport_name = ? AND is_active = 1 ORDER BY sort_order, category_name");
                $catStmt->execute([$format_info['sport']]);
                $figure_categories = $catStmt->fetchAll(PDO::FETCH_COLUMN) ?: [];

                // Load items grouped by category
                $itemsStmt = $pdo->prepare("SELECT category_name, item_name FROM figure_items WHERE sport_name = ? AND is_active = 1 ORDER BY category_name, sort_order, item_name");
                $itemsStmt->execute([$format_info['sport']]);
                $rows = $itemsStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
                foreach ($rows as $r) {
                    $c = $r['category_name'];
                    if (!isset($figure_items_by_category[$c])) $figure_items_by_category[$c] = [];
                    $figure_items_by_category[$c][] = $r['item_name'];
                }
            }
        }
    }
}

// Load scoring criteria for this event
$scoring_criteria = [];
if ($event_id && !empty($format_info['scoring_format'])) {
    try {
        $criteriaStmt = $pdo->prepare("
            SELECT criteria_type, criteria_name, sort_order 
            FROM scoring_format_criteria 
            WHERE format_id = ? 
            ORDER BY sort_order ASC, criteria_type ASC, criteria_name ASC
        ");
        $criteriaStmt->execute([$format_info['scoring_format']]);
        $scoring_criteria = $criteriaStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Exception $e) {
        $scoring_criteria = [];
    }
}

// Fetch event settings for min/max
$heats_total = 10;
$runs_per_heat = 3;
if ($event_id) {
    $event_settings_stmt = $pdo->prepare("SELECT heats_total, runs_per_heat FROM events WHERE id = ?");
    $event_settings_stmt->execute([$event_id]);
    $event_settings = $event_settings_stmt->fetch(PDO::FETCH_ASSOC);
    if ($event_settings) {
        $heats_total = intval($event_settings['heats_total']);
        $runs_per_heat = intval($event_settings['runs_per_heat']);
    }
}

// Fetch participants and runs
$participants = [];
if ($event_id) {
    $stmt = $pdo->prepare("SELECT ep.id as ep_id, p.first_name, p.last_name, ep.bib_number as bib, ep.heat_number
                           FROM event_participants ep 
                           JOIN participants p ON ep.participant_id = p.id
                           WHERE ep.event_id = ? ORDER BY ep.sort_order ASC, ep.bib_number ASC");
    $stmt->execute([$event_id]);
    $participants = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $scored_runs = $pdo->prepare("
        SELECT DISTINCT r.event_participant_id, r.run_number
        FROM scores s
        JOIN runs r ON s.run_id = r.id
        WHERE s.judge_id = ?
    ");
    $scored_runs->execute([$judge_id]);
    $locked_scores = [];
    foreach ($scored_runs as $row) {
        $locked_scores[$row['event_participant_id']][$row['run_number']] = true;
    }
}

$run_number = 1;
$heat_number = 1;

// Fetch 4 latest scores for this judge and event
$latest_scores = [];
if ($event_id && $judge_id) {
    $latest_stmt = $pdo->prepare("
        SELECT s.id AS score_id, s.score_value, s.status, s.figures_json, r.run_number, ep.heat_number, ep.bib_number as bib, p.first_name, p.last_name, s.created_at
        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
        WHERE s.judge_id = ? AND ep.event_id = ?
        ORDER BY s.created_at DESC
        LIMIT 4
    ");
    $latest_stmt->execute([$judge_id, $event_id]);
    $latest_scores = $latest_stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Fetch heats for this event
$heats = [];
if ($event_id) {
    $heat_stmt = $pdo->prepare("SELECT heat_number, heat_name, scoring_type, runs_count FROM event_heat_settings WHERE event_id = ? ORDER BY heat_number ASC");
    $heat_stmt->execute([$event_id]);
    $heats = $heat_stmt->fetchAll(PDO::FETCH_ASSOC);
     //$runs_per_heat = intval($heats['runs_count']);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Judge Scoring</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    
    <style>
        .text-primary { --bs-text-opacity: 1; color: var(--bs-teal) #2ed3be !important;
}
.text-ui-bigger { font-size: 1rem !important; }
        .score-status-buttons label {
    display: flex
;
    align-content: center;
    justify-content: center;
    align-items: center;
}
 .score-status-buttons .btn-group {
   
  
}
.score-criteria ::-webkit-slider-thumb {
 
/*   width: 25px; Set a specific slider handle width 
  height: 25px;  Slider handle height 
  background: #76ba69; Green background 
  margin-top:-10px;*/
}
        /* Mobile-first responsive design */
        body {
           
            font-size: 16px; /* Better for mobile touch */
        }
        
        .score-container {
           
            margin: 0 auto;
            padding: 1rem;
        }
        
        /* Large touch-friendly buttons */
        .heat-btn, .run-btn {
          
        }
        
        /* Large form inputs for mobile */
        .form-control, .form-select {
            
            font-size: 1rem;           
        }
        
        .score-input {
            min-height: 80px;
            min-height: 80px;
            font-size: 2rem !important;
            font-weight: bold !important;
            text-align: center;
            border: 3px solid #0d6efd;
        }
        
        .bib-input {
            font-size: 1.5rem;
            font-weight: bold;
            text-align: center;
        }
        
        /* Status buttons */
        .status-btn {
            
            font-size: 14px;
            flex: 1;
        }
        
        /* Submit button */
        .submit-btn {
            min-height: 70px;
            font-size: 1.5rem;
            font-weight: bold;
            border-radius: 15px;
        }
        
        /* Compact cards */
        
        
        /* Sticky header */
        .judge-info {
           
        }
        
        /* Latest scores table */
        .scores-table {
            font-size: 0.9rem;
        }
        
        .scores-table td, .scores-table th {
            padding: 0.5rem;
            vertical-align: middle;
        }
        
        /* Quick action badges */
        .quick-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
        }
        .criteria-input {
    font-size: 1.8em;
    font-weight: bold !important;
    text-align: center;
    border: 2px solid #0d6efd;
}
        /* Mobile keyboard optimization */
        input[type="number"] {
            -webkit-appearance: none;
            -moz-appearance: textfield;
        }
        
        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        
        /* Responsive adjustments */
        @media (max-width: 576px) {
            .container-fluid {
                padding-left: 0.5rem;
                padding-right: 0.5rem;
            }
            
            .score-input {
                font-size: 1.8rem;
                min-height: 70px;
            }
            
            .submit-btn {
                min-height: 60px;
                font-size: 1.3rem;
            }
            
            .heat-btn, .run-btn {
                min-height: 45px;
                font-size: 1rem;
            }
            
            /* Stack cards vertically on mobile with less spacing */
            .score-container .row {
                margin: 0 -0.5rem;
            }
            
            .score-container .row > [class*="col-"] {
                padding: 0 0.5rem;
                margin-bottom: 1rem;
            }
            
            /* Adjust card spacing on mobile */
            .score-container .card {
                margin-bottom: 0.75rem;
            }
        }
        
        @media (min-width: 577px) and (max-width: 991px) {
            /* Tablet adjustments */
            .score-container .card {
                margin-bottom: 1rem;
            }
            
            .form-control, .form-select {
                min-height: 45px;
                font-size: 1rem;
                   
            }
            
            /* Better spacing for tablet */
            .score-container .row {
                margin: 0 -0.75rem;
            }
            
            .score-container .row > [class*="col-"] {
                padding: 0 0.75rem;
            }
        }
        
        @media (min-width: 992px) {
            /* Desktop adjustments */
            .score-container .row {
                align-items: start;
            }
            
            /* Optimize column heights on desktop */
            .score-container .col-12 {
                display: flex;
                flex-direction: column;
            }
        }
        
        /* Loading states */
        .loading {
            opacity: 0.7;
            pointer-events: none;
        }
        
        /* Success animation */
        .score-submitted {
            animation: successPulse 0.6s ease-in-out;
        }
        
        @keyframes successPulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); background-color: #d1e7dd; }
            100% { transform: scale(1); }
        }
        .pulse-animation {
    animation: pulse 0.5s ease-in-out;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.form-check-input:checked {
    background-color: #198754;
    border-color: #198754;
}

/* Figure toggle chips - Enhanced for better UX */
.figure-row { 
    border: 1px dashed rgba(0,0,0,.1); 
    
    background: rgba(255,255,255,.8); 
    transition: all 0.2s ease;
}
.figure-row:hover {
    background: rgba(255,255,255,.95);
    border-color: rgba(0,0,0,.2);
}

/* Category-specific colors */
.figure-row[data-category="Rotation"] { border-left: 4px solid #007bff; }
.figure-row[data-category="Direction"] { border-left: 4px solid #28a745; }
.figure-row[data-category="Axis"] { border-left: 4px solid #dc3545; }
.figure-row[data-category="Grab"] { border-left: 4px solid #fd7e14; }
.figure-row[data-category="Feature"] { border-left: 4px solid #6610f2; }
.figure-row[data-category="Rail"] { border-left: 4px solid #20c997; }

.figure-chip { 
    border-radius: 8px !important; 
    font-weight: 500;
    min-width: 60px;
    transition: all 0.15s ease;
    position: relative;
}
.figure-chip:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.figure-chip.active { 
    color: #fff !important; 
    background-color: #198754 !important; 
    border-color: #198754 !important;
    box-shadow: 0 2px 8px rgba(25,135,84,0.3);
}
.figure-chip.has-history { 
    position: relative; 
    font-weight: 500; 
    color: #664d03; 
    background-color: #fff3cd; 
    border-color: #ffecb5; 
}
.figure-chip.has-history.active { 
    color: #fff !important; 
    background-color: #198754 !important; 
    border-color: #198754 !important; 
}
.figure-chip.has-history .text-muted { font-size: 0.75em; font-weight: normal; }
.figure-chip.historical { color: #664d03; background-color: #fff3cd; border-color: #ffecb5; opacity: 0.8; position: relative; }
.figure-chip.historical::after { content: " (" attr(data-run) ")"; font-size: 0.75em; opacity: 0.7; white-space: nowrap; }

.figure-category-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    font-weight: 600;
    color: #495057;
}

.figure-category-icon {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    color: white;
    font-size: 12px;
}

.clear-cat { 
    border-radius: 8px !important; 
    min-width: 40px;
}
.clear-cat:hover {
    background-color: #dc3545 !important;
    border-color: #dc3545 !important;
    color: white !important;
}

/* Figures card toggle styling */
.figures-card-header {
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.figures-card-header:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.toggle-icon {
    transition: transform 0.3s ease;
}

.toggle-icon.collapsed {
    transform: rotate(180deg);
}

#figuresCardBody {
    transition: all 0.3s ease;
    overflow: hidden;
}

#figuresCardBody.collapsed {
    max-height: 0;
    padding-top: 0;
    padding-bottom: 0;
    opacity: 0;
}

/* Diversity validation styling */
#diversityValidation {
    transition: all 0.3s ease;
}

#diversityValidation .alert {
    margin-bottom: 0.5rem;
}

#diversityValidation .alert:last-child {
    margin-bottom: 0;
}

.diversity-requirement-item {
    background: rgba(255,255,255,0.8);
    border-left: 4px solid #dee2e6;
    transition: border-color 0.3s ease;
}

.diversity-requirement-item.error {
    border-left-color: #dc3545;
}

.diversity-requirement-item.warning {
    border-left-color: #ffc107;
}

.diversity-requirement-item.success {
    border-left-color: #198754;
}

.submit-btn.btn-warning {
    animation: pulse-warning 2s infinite;
}

@keyframes pulse-warning {
    0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.4); }
    70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
    100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
}

/* Edit Modal Figure Selection Styling */
#editFigureGrid .figure-row {
    border: 1px dashed rgba(0,0,0,.1);
    
    background: rgba(255,255,255,.7);
}

#editFigureGrid .figure-chip {
    border-radius: 999px;
    transition: all 0.2s ease;
}

#editFigureGrid .figure-chip.active {
    color: #0b5137;
    background-color: #d1e7dd;
    border-color: #badbcc;
    font-weight: 600;
}

#editFigureGrid .figure-chip:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

#editFigureGrid .clear-cat {
    border-radius: 999px;
}

#editFigureSummary {
    border-left: 4px solid #0dcaf0;
}

.criteria-input-grid {
    display: grid;
    grid-template-columns: auto auto;
}
.criteria_input_field {
    box-shadow: none !important;
    border-width: 1px !important;
     
}
input.score-input, input.criteria-input {
    color: #000cff !important;
    background-color: transparent;
    max-width: 100px;
    margin-left: auto;
    margin-right: auto;
}
.score-input-wrapper {
    width: 50%;
    margin-left: auto;
    margin-right: auto;
    border: 1px solid #000cff;
}
div#otherHeatScores tbody{
    display: block;
    max-height: 15vh;
    overflow: auto;
}

div#otherHeatScores thead, div#otherHeatScores tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;/* even columns width , fix width of table too*/
}
div#otherHeatScores thead {
    width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
    </style>
</head>

<body class="body-bg-aurora-bright">
    
    
    <div class="container-fluid container-StyleScore p-2 p-md-4">
        
        <!-- Debug Information Boxes -->
        <div class="row mb-3" id="debugSection" style="display: none;">
            <div class="col-md-6">
                <!-- Incoming Data Debug Box -->
                <div class="card border-info">
                    <div class="card-header bg-info text-white py-2">
                        <h6 class="mb-0">
                            <i class="fas fa-download me-2"></i>Incoming Data
                            <button type="button" class="btn btn-sm btn-outline-light float-end" onclick="refreshIncomingData()">
                                <i class="fas fa-refresh"></i>
                            </button>
                        </h6>
                    </div>
                    <div class="card-body p-2">
                        <div class="small" style="font-family: monospace; background: #f8f9fa; padding: 10px; border-radius: 4px; max-height: 300px; overflow-y: auto;">
                            <div id="incomingDataContent">Loading...</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <!-- Outgoing API Calls Debug Box -->
                <div class="card border-warning">
                    <div class="card-header bg-warning text-dark py-2">
                        <h6 class="mb-0">
                            <i class="fas fa-upload me-2"></i>Outgoing API Calls
                            <button type="button" class="btn btn-sm btn-outline-dark float-end" onclick="clearApiLog()">
                                <i class="fas fa-trash"></i>
                            </button>
                        </h6>
                    </div>
                    <div class="card-body p-2">
                        <div class="small" style="font-family: monospace; background: #f8f9fa; padding: 10px; border-radius: 4px; max-height: 300px; overflow-y: auto;">
                            <div id="apiCallsContent">No API calls yet...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Debug Toggle Button -->
        <div class="text-center mb-2">
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="toggleDebugSection()">
                <i class="fas fa-bug me-1"></i>Toggle Debug Info
            </button>
        </div>
        
        <div class="score-container p-0">
            <!-- Main Scoring Form -->
            <form method="post" id="scoreForm" class="mb-3">
                <div class="row g-3">
                    <div class="col-12 col-lg-4">
                        <!-- Judge Info Header -->
                        <div class="judge-info card score-card mb-3">                
                            <div class="border-0 shadow-none card-body p-2">
                                
                                    
                                        <small class="text-muted">Judge:</small>
                                        <strong> <?= htmlspecialchars($judge_name) ?></strong>
                                        <span class="badge bg-primary ms-1"><?= $judge_id ?></span>
                                    
                                        <small class="text-muted">Event: </small>
                                        <strong><?= htmlspecialchars($assigned_events[0]['name'] ?? 'No Event') ?></strong>
                                        <?php if ($event_date): ?>
                                            <small class="text-muted"><?= date('M d, Y', strtotime($event_date)) ?></small>
                                        <?php endif; ?>
                                    
                                
                                
                                <!-- Mode Toggle -->
                            
                                    <div class="btn-group btn-group-sm">
                                        <a href="score.php" class="btn btn-<?= !$manual_mode ? 'primary' : 'outline-primary' ?> btn-sm">
                                            <i class="fas fa-magic me-1"></i>Auto
                                        </a>
                                        <a href="?manual=1" class="btn btn-<?= $manual_mode ? 'primary' : 'outline-primary' ?> btn-sm">
                                            <i class="fas fa-hand-paper me-1"></i>Manual
                                        </a>
                                    </div>
                                
                            </div>
                        </div>

                        <!-- Format Info Card -->
                        <?php if ($format_info): ?>
                        <div class="border-0 shadow-none card score-card mb-3">
                            <div class="border-0 shadow-none card-header d-flex align-items-center gap-2 p-2">
                                <?php if ($format_icon_url): ?>
                                    <img src="<?= htmlspecialchars($format_icon_url) ?>" alt="format icon" style="width:32px;height:32px;object-fit:contain;" onerror="this.style.display='none'">
                                <?php else: ?>
                                    <i class="fas fa-puzzle-piece text-info"></i>
                                <?php endif; ?>
                                <strong><?= htmlspecialchars($format_info['format_name'] ?: $format_info['scoring_format']) ?></strong>
                                <span class="badge bg-light text-dark"><?= htmlspecialchars($format_info['sport'] ?: '—') ?></span>
                                <?php if (!empty($format_info['mode'])): ?>
                                    <span class="badge bg-primary"><?= htmlspecialchars(str_replace('_',' ', $format_info['mode'])) ?></span>
                                <?php endif; ?>
                                <?php if ($uses_figures): ?>
                                    <span class="badge bg-success"><i class="fas fa-shapes me-1"></i>Figures</span>
                                <?php endif; ?>
                            </div>
                            <div class="border-0 shadow-none card-body p-2">
                                <div class="d-flex flex-wrap gap-2 align-items-center small">
                                    <?php if (isset($format_info['min_judges'])): ?>
                                        <span class="badge bg-secondary">Judges: <?= htmlspecialchars($format_info['min_judges']) ?><?= $format_info['max_judges'] ? '–'.htmlspecialchars($format_info['max_judges']) : '' ?></span>
                                    <?php endif; ?>
                                    <?php if ($format_info['scale_min'] !== null): ?>
                                        <span class="badge bg-dark">Scale: <?= htmlspecialchars($format_info['scale_min']) ?>–<?= htmlspecialchars($format_info['scale_max']) ?><?= ($format_info['precision_decimal'] ?? 0) ? ' (decimals)' : '' ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($format_info['drop_rule']) && strtolower($format_info['drop_rule']) !== 'none'): ?>
                                        <span class="badge bg-warning text-dark">Drop: <?= htmlspecialchars($format_info['drop_rule']) ?></span>
                                    <?php endif; ?>
                                    <span class="badge bg-info text-dark">Criteria: <?= (int)($format_info['criteria_count'] ?? 0) ?></span>
                                    <span class="badge bg-info text-dark">Results: <?= (int)($format_info['results_count'] ?? 0) ?></span>
                                </div>
                            </div>
                            
                            <!-- Detailed Format Configuration Sections -->
                            <div class="border-0 shadow-none card-body border-top p-2">
                                <div class="row g-3 small">
                                    <!-- Tiebreak Rules -->
                                    <div class="col-md-6">
                                        <div class="d-flex align-items-center mb-2">
                                            <span class="me-2">⚖️</span>
                                            <strong class="text-primary">Tiebreak Rules</strong>
                                        </div>
                                        <div class="text-muted small">
                                            <?php 
                                            try {
                                                $tiebreakStmt = $pdo->prepare("SELECT tiebreak_rule FROM scoring_format_tiebreak WHERE format_id = ? ORDER BY sort_order");
                                                $tiebreakStmt->execute([$format_info['scoring_format']]);
                                                $tiebreakRules = $tiebreakStmt->fetchAll(PDO::FETCH_COLUMN);
                                                if (!empty($tiebreakRules)): ?>
                                                    <ol class="mb-0 ps-3">
                                                        <?php foreach ($tiebreakRules as $rule): ?>
                                                            <li><?= htmlspecialchars($rule) ?></li>
                                                        <?php endforeach; ?>
                                                    </ol>
                                                <?php else: ?>
                                                    <em>Standard highest score wins</em>
                                                <?php endif;
                                            } catch (Exception $e) { 
                                                echo '<em>Standard highest score wins</em>';
                                            } ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Diversity Rules -->
                                    <div class="col-md-6">
                                        <div class="d-flex align-items-center mb-2">
                                            <span class="me-2">🎯</span>
                                            <strong class="text-success">Diversity Rules</strong>
                                        </div>
                                        <div class="text-muted small">
                                            <?php if (!empty($diversity_rules)): ?>
                                                <ul class="mb-0 ps-3">
                                                    <?php foreach ($diversity_rules as $rule): ?>
                                                        <li>
                                                            <strong><?= htmlspecialchars($rule['rule_type']) ?></strong>
                                                            <?php if ($rule['group_name']): ?>
                                                                in <em><?= htmlspecialchars($rule['group_name']) ?></em>
                                                            <?php endif; ?>
                                                            <?php if ($rule['min_distinct']): ?>
                                                                (min: <?= (int)$rule['min_distinct'] ?>)
                                                            <?php endif; ?>
                                                            <?php if ($rule['scope']): ?>
                                                                <span class="badge bg-light text-dark ms-1"><?= htmlspecialchars($rule['scope']) ?></span>
                                                            <?php endif; ?>
                                                            <?php if ($rule['is_optional']): ?>
                                                                <span class="badge bg-warning text-dark ms-1">optional</span>
                                                            <?php endif; ?>
                                                        </li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            <?php else: ?>
                                                <em>No diversity restrictions</em>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Rounds Configuration -->
                                    <div class="col-md-6">
                                        <div class="d-flex align-items-center mb-2">
                                            <span class="me-2">🔄</span>
                                            <strong class="text-info">Rounds Configuration</strong>
                                        </div>
                                        <div class="text-muted small">
                                            <?php 
                                            try {
                                                $roundsStmt = $pdo->prepare("SELECT round_name, runs, aggregation FROM scoring_format_rounds WHERE format_id = ? ORDER BY sort_order");
                                                $roundsStmt->execute([$format_info['scoring_format']]);
                                                $rounds = $roundsStmt->fetchAll(PDO::FETCH_ASSOC);
                                                if (!empty($rounds)): ?>
                                                    <ul class="mb-0 ps-3">
                                                        <?php foreach ($rounds as $round): ?>
                                                            <li>
                                                                <strong><?= htmlspecialchars($round['round_name']) ?></strong>
                                                                <?php if ($round['runs']): ?>
                                                                    (<?= (int)$round['runs'] ?> runs)
                                                                <?php endif; ?>
                                                                <?php if ($round['aggregation']): ?>
                                                                    <span class="badge bg-light text-dark ms-1"><?= htmlspecialchars($round['aggregation']) ?></span>
                                                                <?php endif; ?>
                                                            </li>
                                                        <?php endforeach; ?>
                                                    </ul>
                                                <?php else: ?>
                                                    <em>Single round format</em>
                                                <?php endif;
                                            } catch (Exception $e) { 
                                                echo '<em>Single round format</em>';
                                            } ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Mode Configuration -->
                                    <div class="col-md-6">
                                        <div class="d-flex align-items-center mb-2">
                                            <span class="me-2">⚙️</span>
                                            <strong class="text-warning">Mode Configuration</strong>
                                        </div>
                                        <div class="text-muted small">
                                            <?php 
                                            try {
                                                $modeStmt = $pdo->prepare("SELECT config_type, config_key, config_value FROM scoring_format_mode_config WHERE format_id = ? ORDER BY config_type, config_key");
                                                $modeStmt->execute([$format_info['scoring_format']]);
                                                $modeConfigs = $modeStmt->fetchAll(PDO::FETCH_ASSOC);
                                                if (!empty($modeConfigs)): ?>
                                                    <ul class="mb-0 ps-3">
                                                        <?php 
                                                        $groupedConfigs = [];
                                                        foreach ($modeConfigs as $config) {
                                                            $groupedConfigs[$config['config_type']][$config['config_key']] = $config['config_value'];
                                                        }
                                                        foreach ($groupedConfigs as $type => $configs): ?>
                                                            <li>
                                                                <strong><?= htmlspecialchars(ucfirst($type)) ?></strong>: 
                                                                <?php foreach ($configs as $key => $value): ?>
                                                                    <?= htmlspecialchars($key) ?>=<?= htmlspecialchars($value) ?>
                                                                    <?php if ($key !== array_key_last($configs)): ?>, <?php endif; ?>
                                                                <?php endforeach; ?>
                                                            </li>
                                                        <?php endforeach; ?>
                                                    </ul>
                                                <?php else: ?>
                                                    <em>Default mode settings</em>
                                                <?php endif;
                                            } catch (Exception $e) { 
                                                echo '<em>Default mode settings</em>';
                                            } ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Manual Event Selection -->
                        <?php if ($manual_mode): ?>
                        <div class="border-0 shadow-none card score-card mb-3">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-calendar me-2"></i>Select Event
                            </div>
                            <div class="border-0 shadow-none card-body p-2">
                                <select class="form-select" name="event_id" onchange="this.form.submit()">
                                    <option value="">-- Select Event --</option>
                                    <?php foreach ($assigned_events as $ev): ?>
                                        <option value="<?= $ev['id'] ?>" <?= $event_id == $ev['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($ev['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Heat & Run Selection -->
                        <div class="border-0 shadow-none card score-card mb-3">
                            <div class="border-0 shadow-none card-header p-2 d-flex justify-content-between align-items-center ">
                                <span><i class="fas fa-fire me-2"></i>Heat & Run Selection</span>
                                <div class="d-flex align-items-center gap-2">
                                    <span id="heatRunBadge" class="badge bg-warning" style="display:none;">
                                        <i class="fas fa-history me-1"></i>Restored
                                    </span>
                                    <span id="autoModeIndicator" class="badge bg-success" style="display:none;">
                                        <i class="fas fa-sync-alt me-1"></i>Auto
                                    </span>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="autoModeToggle" checked>
                                        <label class="form-check-label small" for="autoModeToggle">Auto</label>
                                    </div>
                                </div>
                            </div>
                            <div class="border-0 shadow-none card-body p-2">

                                <!-- Auto Mode Status Display -->
                                <div id="autoModeStatus" class="alert alert-info mb-3" style="display:none;">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <i class="fas fa-robot me-2"></i>
                                            <strong>Auto Mode Active</strong>
                                            <div class="small text-muted mt-1">
                                                Automatically selecting active heat and run from event flow
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <div class="small text-muted">Last update:</div>
                                            <div id="lastUpdateTime" class="small">--:--</div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Manual Override Notice -->
                                <div id="manualOverrideNotice" class="alert alert-warning mb-3" style="display:none;">
                                    <i class="fas fa-hand-paper me-2"></i>
                                    <strong>Manual Override Active</strong>
                                    <div class="small">You have manually selected heat/run. Auto mode is disabled.</div>
                                </div>
                                
                                <!-- Active Heat Info Display -->
                                <div id="activeHeatInfo" class="alert alert-success mb-3" style="display:none;">
                                    <div class="row align-items-center">
                                        <div class="col">
                                            <div class="d-flex align-items-center">
                                                <i class="fas fa-fire text-success me-2"></i>
                                                <div>
                                                    <strong id="activeHeatDisplay">Heat --</strong>
                                                    <div class="small text-muted" id="activeHeatName">--</div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <div class="text-center">
                                                <div class="badge bg-success" id="activeRunDisplay">Run --</div>
                                                <div class="small text-muted">Active</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row mt-2" id="activeHeatProgress" style="display:none;">
                                        <div class="col">
                                            <div class="small text-muted">
                                                Progress: <span id="progressText">-- / --</span>
                                                (<span id="progressPercentage">--%</span>)
                                            </div>
                                            <div class="progress" style="height: 4px;">
                                                <div class="progress-bar bg-success" id="progressBar" style="width: 0%"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Heat Selection -->
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Heat Number</label>
                                    <select class="form-select" name="heat_number" id="heatSelect" onchange="handleHeatChange()" required>
                                        <option value="">-- Select Heat --</option>
                                        <?php foreach ($heats as $heat): ?>
                                            <option value="<?= $heat['heat_number'] ?>" <?= $heat_number == $heat['heat_number'] ? 'selected' : '' ?>>
                                                Heat <?= $heat['heat_number'] ?><?= $heat['heat_name'] ? ' – ' . htmlspecialchars($heat['heat_name']) : '' ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <!-- Run Selection -->
                                <div class="">
                                    <label class="form-label fw-bold">Run Number</label>
                                    <div class="d-grid gap-2">
                                        <div class="btn-group" role="group" id="runButtonGroup">
                                            <?php for ($r = 1; $r <= $runs_per_heat; $r++): ?>
                                                <input type="radio" class="btn-check" name="run_number" id="run<?= $r ?>" 
                                                    value="<?= $r ?>" <?= $run_number == $r ? 'checked' : '' ?> 
                                                    onchange="handleRunChange()" required>
                                                <label class="btn btn-outline-success run-btn" for="run<?= $r ?>">
                                                    <i class="fas fa-play me-2"></i>Run <?= $r ?>
                                                </label>
                                            <?php endfor; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Connection Status -->
                                <div class="mt-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-muted">
                                            <i class="fas fa-wifi me-1" id="connectionIcon"></i>
                                            <span id="connectionStatus">Connecting...</span>
                                        </small>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="forceRefreshHeatData()">
                                            <i class="fas fa-sync-alt me-1"></i>Refresh
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Message Display -->
                        <?php if ($message): ?>
                            <div class="alert alert-success alert alert-dismissible fade show" role="alert">
                                <?= $message ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="col-12 col-lg-4">
                        <div class="border-0 shadow-none card m-0 p-1">
                        <!-- Participant Selection Card -->
                        <div class="border-0 shadow-none card mb-1">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-user me-2"></i>Participant Selection
                            </div>
                            <div class="border-0 shadow-none card-body p-2">
                                <!-- BIB Quick Entry -->
                                <div class="mb-3">
                                    <label class="form-label fw-bold">BIB Number</label>
                                    <input type="number" class="form-control bib-input ss-f-number" name="p_bib" id="bibInput" 
                                        inputmode="numeric" pattern="[0-9]*" placeholder="Enter BIB #" 
                                        autocomplete="off">
                                    <div class="form-text">Type BIB number for quick participant selection</div>
                                </div>
                                
                                <!-- Participant Dropdown -->
                                <div class="mb-0">
                                    <label class="form-label fw-bold">Select Participant</label>
                                    <select class="text-ui-bigger form-select" name="ep_id" id="ep_id" required>
                                        <option value="" disabled>-- Select Participant --</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                             <!-- Status Selection -->
                                <div class="p-2 m-0">                                    
                                    <div class="d-grid gap-1 score-status-buttons">
                                        <div class="btn-group" role="group">
                                            <input type="radio" class="btn-check" name="status" id="statusOK" value="OK" checked>
                                            <label class="btn btn-outline-success status-btn" for="statusOK">
                                                <i class="fas fa-check me-2"></i>OK
                                            </label>
                                            
                                            <input type="radio" class="btn-check" name="status" id="statusDNS" value="DNS">
                                            <label class="btn btn-outline-warning status-btn" for="statusDNS">
                                                <i class="fas fa-ban me-2"></i>DNS
                                            </label>
                                        
                                            <input type="radio" class="btn-check" name="status" id="statusDNF" value="DNF">
                                            <label class="btn btn-outline-danger status-btn" for="statusDNF">
                                                <i class="fas fa-flag me-2"></i>DNF
                                            </label>
                                            
                                            <input type="radio" class="btn-check" name="status" id="statusDSQ" value="DSQ">
                                            <label class="btn btn-outline-dark status-btn" for="statusDSQ">
                                                <i class="fas fa-times-circle me-2"></i>DSQ
                                            </label>
                                        </div>
                                    </div>
                                </div>

                              <!-- Additional Cards Wrapper - Hidden when status is not OK -->
                              <div id="additionalCardsWrapper">
                                <!-- Other Heat Scores Card -->
                        <div class="border-0 shadow-none card mb-3" id="otherHeatScoresCard" style="display: none;">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-users me-2"></i>Other Heat Scores
                            </div>
                            <div class="border-0 shadow-none card-body p-0">
                                <div id="otherHeatScores"></div>
                            </div>
                        </div>
                              <!-- Figure History Display Card -->
                        <div class="border-0 shadow-none card mb-2" id="figureHistoryCard" style="display: none;">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-history me-2"></i>Figure History
                            </div>
                            <div class="border-0 shadow-none card-body p-2">
                                <div id="figureHistoryDisplay"></div>
                            </div>
                        </div>

                              <!-- Score Criteria -->
                        <?php if (!empty($scoring_criteria)): ?>
                        <div class="border-0 shadow-none card score-criteria mb-1">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-star me-2"></i>Score Criteria 
                                <span class="badge bg-light text-dark"><?= count($scoring_criteria) ?></span>
                            </div>
                            <div class="border-0 shadow-none card-body p-0 criteria-input-grid"> 
                                <!-- Dynamic Score Criteria Inputs -->
                                <?php foreach ($scoring_criteria as $index => $criterion): ?>
                                <div class="p-2 criteria_input_field scale-<?= $index + 1 ?>">
                                    <label class="form-label fw-bold">
                                        <?= htmlspecialchars($criterion['criteria_name']) ?>
                                        <span class="badge bg-secondary ms-1"><?= htmlspecialchars(strtoupper($criterion['criteria_type'])) ?></span>
                                    </label>
                                    <input type="number" 
                                        class="form-control criteria-input fs-2 ss-f-number" 
                                        name="criteria_scores[<?= $index ?>][value]" 
                                        data-criteria-type="<?= htmlspecialchars($criterion['criteria_type']) ?>"
                                        data-criteria-name="<?= htmlspecialchars($criterion['criteria_name']) ?>"
                                        min="0" max="<?= htmlspecialchars($format_info['scale_max'] ?? 99) ?>" 
                                        step="<?= ($format_info['precision_decimal'] ?? 0) ? '0.1' : '1' ?>" 
                                        inputmode="numeric" 
                                        placeholder="0" 
                                        autocomplete="off" 
                                        oninput="updateCriteriaRange(this, <?= $index ?>)">
                                    <input type="range" 
                                        class="form-range mt-2" 
                                        name="criteria_scores[<?= $index ?>][range]" 
                                        min="0" 
                                        max="<?= htmlspecialchars($format_info['scale_max'] ?? 99) ?>" 
                                        step="<?= ($format_info['precision_decimal'] ?? 0) ? '0.1' : '1' ?>"
                                        oninput="updateCriteriaInput(this, <?= $index ?>)">
                                    <!-- Hidden fields for criteria metadata -->
                                    <input type="hidden" name="criteria_scores[<?= $index ?>][type]" value="<?= htmlspecialchars($criterion['criteria_type']) ?>">
                                    <input type="hidden" name="criteria_scores[<?= $index ?>][name]" value="<?= htmlspecialchars($criterion['criteria_name']) ?>">
                                    <input type="hidden" name="criteria_scores[<?= $index ?>][sort_order]" value="<?= htmlspecialchars($criterion['sort_order']) ?>">
                                </div>
                                <?php endforeach; ?>
                                </div>
                                <!-- Final Calculated Score Display -->
                                <div class=" p-0 m-0 bg-light">
                                    <div class="d-flex justify-content-between align-items-center  score-input-wrapper">                                      
                                       
                                        <div class="border-0 shadow-none card-body p-2">
                                <!-- Score Input -->
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">
                                            Score (0-99)
                                            <i class="fas fa-info-circle text-muted ms-1" 
                                               title="Changing this score will proportionally adjust all criteria scores to maintain their ratio" 
                                               data-bs-toggle="tooltip"></i>
                                        </label>
                                        <input type="number" class="form-control fs-2 score-input ss-f-number" name="score_value" 
                                            min="0" max="99" step="1" inputmode="numeric" placeholder="0" 
                                            autocomplete="off" required  oninput="updateMainScoreAndCriteria(this, 'range')">
                                    </div>
                                    <div class="mb-0">
                                        <input type="range" class="form-range" name="score_range" min="0" max="99" id="customRange2" oninput="updateMainScoreAndCriteria(this, 'input')">
                                    </div>
                                </div>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center mt-1">
                                      
                                        <button type="button" class="btn btn-outline-secondary" onclick="clearScoreInputsOnly()" title="Clear only score inputs (criteria and main score)">
                                            <i class="fas fa-eraser me-1"></i>Clear Scores
                                        </button>
                                    </div>
                                </div>
                            </div>
                       
                        <?php else: ?>
                        <!-- Fallback: Single Score Criteria -->
                        <div class="border-0 shadow-none card score-criteria mb-3">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-star me-2"></i>Score Criteria 
                            </div>
                            <div class="border-0 shadow-none card-body p-2">
                                <!-- Score Criteria Input -->
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Criteria (0-<?= htmlspecialchars($format_info['scale_max'] ?? 99) ?>)</label>
                                    <input type="number" class="form-control criteria-input" name="criteria_value" 
                                        min="0" max="<?= htmlspecialchars($format_info['scale_max'] ?? 99) ?>" 
                                        step="<?= ($format_info['precision_decimal'] ?? 0) ? '0.1' : '1' ?>" 
                                        inputmode="numeric" placeholder="0" 
                                        autocomplete="off" required  oninput="this.form.criteria_range.value=this.value">
                                </div>
                                <div class="mb-0">
                                    <input type="range" class="form-range" name="criteria_range" min="0" max="<?= htmlspecialchars($format_info['scale_max'] ?? 99) ?>" id="customRange2" oninput="this.form.criteria_value.value=this.value">
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>  

                     

                        <!-- Figures Card -->
                        <?php if ($uses_figures && !empty($figure_categories)): ?>
                        <div class="border-0 shadow-none card mb-1">
                            <div class="border-0 shadow-none card-header p-2" style="cursor: pointer;" onclick="toggleFiguresCard()" id="figuresCardHeader">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span>
                                        <i class="fas fa-shapes me-2"></i>Figures (tap to toggle)
                                    </span>
                                    <i class="fas fa-chevron-up toggle-icon" id="figuresToggleIcon"></i>
                                </div>
                            </div>
                            <div class="border-0 shadow-none card-body p-0" id="figuresCardBody">
                                <!-- Toggle chips per category -->
                                <div id="figureToggleGrid" class="d-flex flex-column gap-2">
                                    <?php 
                                    // Category icons mapping
                                    $category_icons = [
                                        'Rotation' => 'fas fa-sync-alt',
                                        'Direction' => 'fas fa-arrows-alt-h', 
                                        'Axis' => 'fas fa-globe',
                                        'Grab' => 'fas fa-hand-rock',
                                        'Feature' => 'fas fa-mountain',
                                        'Rail' => 'fas fa-minus'
                                    ];
                                    $category_colors = [
                                        'Rotation' => '#007bff',
                                        'Direction' => '#28a745',
                                        'Axis' => '#dc3545', 
                                        'Grab' => '#fd7e14',
                                        'Feature' => '#6610f2',
                                        'Rail' => '#20c997'
                                    ];
                                    ?>
                                    <?php foreach ($figure_categories as $cat): $items = $figure_items_by_category[$cat] ?? []; ?>
                                        <div class="figure-row p-2" data-category="<?= htmlspecialchars($cat) ?>">
                                            <div class="figure-category-header">
                                                <div class="figure-category-icon" style="background-color: <?= $category_colors[$cat] ?? '#6c757d' ?>;">
                                                    <i class="<?= $category_icons[$cat] ?? 'fas fa-cube' ?>"></i>
                                                </div>
                                                <span><?= htmlspecialchars($cat) ?></span>
                                                <span class="badge bg-light text-dark ms-auto"><?= count($items) ?></span>
                                            </div>
                                            <div class="d-flex flex-wrap gap-2">
                                                <?php foreach ($items as $it): ?>
                                                    <button type="button" class="btn btn-sm btn-outline-secondary figure-chip" 
                                                            data-cat="<?= htmlspecialchars($cat) ?>" 
                                                            data-item="<?= htmlspecialchars($it) ?>"
                                                            title="Select <?= htmlspecialchars($it) ?> in <?= htmlspecialchars($cat) ?>">
                                                        <?= htmlspecialchars($it) ?>
                                                    </button>
                                                <?php endforeach; ?>
                                                <button type="button" class="btn btn-sm btn-outline-danger ms-2 clear-cat" 
                                                        data-cat="<?= htmlspecialchars($cat) ?>"
                                                        title="Clear all <?= htmlspecialchars($cat) ?> selections">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                    
                                    <!-- Quick Actions Row -->
                                    <div class="d-flex justify-content-between align-items-center m-1 pt-2 border-top">
                                        <button type="button" class="btn btn-outline-info btn-sm" onclick="showFiguresSummary()">
                                            <i class="fas fa-list me-1"></i>Summary
                                        </button>
                                        <button type="button" class="btn btn-outline-warning btn-sm" onclick="clearAllFigures()">
                                            <i class="fas fa-eraser me-1"></i>Clear All
                                        </button>
                                        <button type="button" class="btn btn-outline-success btn-sm" onclick="copyFromLastRun()">
                                            <i class="fas fa-copy me-1"></i>Copy Last
                                        </button>
                                    </div>
                                </div>

                                <!-- Hidden fields to include with score submission -->
                                <input type="hidden" name="figure_category" id="figure_category_hidden">
                                <input type="hidden" name="figure_item" id="figure_item_hidden">
                                <input type="hidden" name="figures_json" id="figures_json_hidden">
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        
                        </div>
                        <!-- End Additional Cards Wrapper -->
                        
                        <!-- Score Status & Submit Card -->
                        <div class="border-0 shadow-none card score-card m-0">                           
                            <div class="border-0 shadow-none card-body  p-2">
                               
                                
                                <!-- Submit Button -->
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-success submit-btn" id="submitBtn">
                                        <i class="fas fa-save me-2"></i>Submit Score
                                    </button>
                                </div>
                                
                                <!-- Validation Summary -->
                                <div id="validationSummary" class="mt-2" style="display: none;">
                                    <div class="alert alert-sm mb-0" role="alert" style="display: none;">
                                        <div class="small">
                                            <i class="fas fa-info-circle me-1"></i>
                                            <span id="validationSummaryText">Checking diversity rules...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                                                </div>
                    
                        
                        


                    </div>
                    <div class="col-12 col-lg-4">    
                        <!-- Diversity Validation Card -->
                        <div class="border-0 shadow-none card mb-3" id="diversityValidationCard" style="display: none;">
                            <div class="border-0 shadow-none card-header p-2">
                                <i class="fas fa-check-circle me-2"></i>Validation
                            </div>
                            <div class="border-0 shadow-none card-body p-2">
                                <div id="diversityValidation" class="mt-0 small"></div>
                            </div>
                        </div>           
                        
                        <!-- Latest Scores -->
                        <div class="border-0 shadow-none card score-card mb-3">
                            <div class="border-0 shadow-none card-header p-2 d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-history me-2"></i>Latest Scores</span>
                                <span class="badge bg-light text-dark"><?= count($latest_scores) ?>/4</span>
                            </div>
                            <div class="border-0 shadow-none card-body p-0">
                                <?php if (count($latest_scores)): ?>
                                    <div class="table-responsive">
                                        <table  id="latestScoresTable" class="table table-sm scores-table mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>BIB</th>
                                                    <th>Name</th>
                                                    <th>H/R</th>
                                                    <th>Score</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($latest_scores as $i => $row): ?>
                                                <tr>
                                                    <td>
                                                        <span class="badge bg-secondary"><?= htmlspecialchars($row['bib']) ?></span>
                                                    </td>
                                                    <td>
                                                        <small><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></small>
                                                    </td>
                                                    <td>
                                                        <small><?= $row['heat_number'] ?>/<?= $row['run_number'] ?></small>
                                                    </td>
                                                    <td>
                                                        <strong class="text-primary"><?= htmlspecialchars($row['score_value']) ?></strong>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?= $row['status'] === 'OK' ? 'success' : 'warning' ?> quick-badge">
                                                            <?= htmlspecialchars($row['status']) ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-warning btn-sm" onclick="showOverwriteModal(<?= $i ?>)">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center text-muted p-4">
                                        <i class="fas fa-clipboard-list fa-2x mb-2 opacity-50"></i>
                                        <p class="mb-0">No scores entered yet</p>
                                        <small>Scores will appear here after submission</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Reset Scores -->
                        <div class="border-0 shadow-none card text-center mb-3">
                            <div class="border-0 shadow-none card-body p-0">
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#judgeOverviewModal">
                                        <i class="fas fa-chart-line me-1"></i>My Scores Overview
                                    </button>
                                    <button type="button" class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#eventSummaryModal">
                                        <i class="fas fa-trophy me-1"></i>Event Results
                                    </button>
                                </div>
                                <div class="mt-2">
                                    
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form><form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to reset all your scores for this event?');">
                                        <input type="hidden" name="reset_score" value="1">
                                        <input type="hidden" name="judge_id" value="<?= $judge_id ?>">
                                        <input type="hidden" name="event_id" value="<?= $event_id ?>">
                                        <button type="submit" class="btn btn-outline-danger btn-sm">
                                            <i class="fas fa-trash me-2"></i>Reset All My Scores
                                        </button>
                                    </form>
        </div>
    </div>

<!-- Overwrite Score Modal -->
<div class="modal fade" id="overwriteScoreModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="post" id="overwriteScoreForm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-edit me-2"></i>Edit Score
                        <span id="editScoreParticipant" class="text-muted"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="overwrite_score_id" id="overwrite_score_id">
                    <input type="hidden" name="ajax" value="1">
                    <?php if ($manual_mode): ?>
                        <input type="hidden" name="event_id" value="<?= $event_id ?>">
                    <?php endif; ?>
                    
                    <!-- Score Value -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="overwrite_score_value" class="form-label fw-bold">Score (0-99)</label>
                            <input type="number" class="form-control score-input" 
                                   id="overwrite_score_value" name="overwrite_score_value" 
                                   min="0" max="99" step="1" required>
                        </div>
                        <div class="col-md-6">
                            <label for="overwrite_status" class="form-label fw-bold">Status</label>
                            <select class="form-select" id="overwrite_status" name="overwrite_status" required>
                                <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>
                    
                    <!-- Figure Selection (shown only if figures are available) -->
                    <div id="editFigureSelection" style="display: none;">
                        <hr>
                        <h6><i class="fas fa-shapes me-2"></i>Figure Selection</h6>
                        <input type="hidden" name="overwrite_figures_json" id="overwrite_figures_json">
                        
                        <!-- Figure Categories Grid -->
                        <div id="editFigureGrid" class="mb-3">
                            <!-- Dynamically populated -->
                        </div>
                        
                        <!-- Current Figure Summary -->
                        <div id="editFigureSummary" class="alert alert-info" style="display: none;">
                            <strong>Selected Figures:</strong>
                            <div id="editFigureSummaryContent"></div>
                        </div>
                        
                        <!-- Figure Validation -->
                        <div id="editDiversityValidation" class="mt-2" style="display: none;">
                            <!-- Validation messages will be inserted here -->
                        </div>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Warning:</strong> This will permanently update the score. Make sure the values are correct.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-warning">
                        <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>
        </form>
    </div>
</div>

<!-- Judge Overview Modal -->
<div class="modal fade" id="judgeOverviewModal" tabindex="-1" aria-labelledby="judgeOverviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="judgeOverviewModalLabel">
                    <i class="fas fa-chart-line me-2"></i>My Scores Overview - <?= htmlspecialchars($judge_name) ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="judgeOverviewContent">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <div class="mt-2">Loading your scores...</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshJudgeOverview()">
                    <i class="fas fa-sync-alt me-1"></i>Refresh
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Event Summary Modal -->
<div class="modal fade" id="eventSummaryModal" tabindex="-1" aria-labelledby="eventSummaryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="eventSummaryModalLabel">
                    <i class="fas fa-trophy me-2"></i>Event Results Summary
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="btn-group w-100" role="group" aria-label="Summary type">
                            <input type="radio" class="btn-check" name="summaryType" id="summaryFinal" value="final" checked>
                            <label class="btn btn-outline-primary" for="summaryFinal">Final Results</label>
                            
                            <input type="radio" class="btn-check" name="summaryType" id="summaryByHeat" value="by_heat">
                            <label class="btn btn-outline-primary" for="summaryByHeat">By Heat</label>
                            
                            <input type="radio" class="btn-check" name="summaryType" id="summaryByRun" value="by_run">
                            <label class="btn btn-outline-primary" for="summaryByRun">By Run</label>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="btn-group w-100" role="group" aria-label="Display options">
                            <input type="radio" class="btn-check" name="displayFormat" id="displayTable" value="table" checked>
                            <label class="btn btn-outline-secondary" for="displayTable">
                                <i class="fas fa-table me-1"></i>Table
                            </label>
                            
                            <input type="radio" class="btn-check" name="displayFormat" id="displayGrid" value="grid">
                            <label class="btn btn-outline-secondary" for="displayGrid">
                                <i class="fas fa-th me-1"></i>Grid
                            </label>
                        </div>
                    </div>
                </div>
                
                <div id="eventSummaryContent">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <div class="mt-2">Loading event results...</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshEventSummary()">
                    <i class="fas fa-sync-alt me-1"></i>Refresh
                </button>
                <button type="button" class="btn btn-outline-success btn-sm" onclick="exportSummary()">
                    <i class="fas fa-download me-1"></i>Export
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

    
    <!-- Your existing JavaScript functions with mobile enhancements -->
    <script>
    // Current judge context for client-side logic
    const CURRENT_JUDGE_ID = <?= json_encode($judge_id) ?>;
    const CURRENT_JUDGE_NAME = <?= json_encode($judge_name) ?>;
    // Heat -> runs_count mapping (fallback to event runs_per_heat if missing)
    const HEAT_RUNS_MAP = <?= json_encode(array_column($heats, 'runs_count', 'heat_number')) ?>;
    const DEFAULT_RUNS_PER_HEAT = <?= json_encode($runs_per_heat) ?>;

    // Keep track of latest scores - declare globally
    let latestScores = <?= json_encode($latest_scores) ?>;

    // Embed figure data (if any) for client-side selection
    const FIGURE_DATA = <?= json_encode([
        'available' => (bool)$uses_figures,
        'categories' => $figure_categories,
        'itemsByCategory' => $figure_items_by_category,
    ]) ?>;
    // Embed diversity and attempts/tricks config for validation
    const FIGURE_UI = <?= json_encode([
        'diversityRules' => $diversity_rules,
        'attempts' => $mode_attempts,
        'tricks' => $mode_tricks,
        'mode' => $format_info['mode'] ?? null,
    ]) ?>;
    
    // Debug figure data
    console.log('FIGURE_DATA:', FIGURE_DATA);
    console.log('FIGURE_UI:', FIGURE_UI);

    // Auto refresh for "Scores for this participant"
    let otherScoresInterval = null;
    
    // Store figure selections across runs for diversity validation
    let figureHistoryByRun = {}; // { run_number: { category: Set(items) } }
    let currentParticipantId = null;
    
    function startOtherScoresInterval(periodMs = 10000) {
        stopOtherScoresInterval();
        otherScoresInterval = setInterval(() => {
            if (document.hidden) return; // pause when tab is hidden
            const ep = document.getElementById('ep_id')?.value;
            const heat = document.querySelector('[name=heat_number]')?.value;
            if (ep && heat) loadOtherScoresForParticipant();
        }, periodMs);
    }
    function stopOtherScoresInterval() {
        if (otherScoresInterval) {
            clearInterval(otherScoresInterval);
            otherScoresInterval = null;
        }
    }
    window.addEventListener('beforeunload', stopOtherScoresInterval);
    document.addEventListener('visibilitychange', () => {
        // Optional: restart on focus to refresh immediately
        if (!document.hidden && otherScoresInterval) {
            loadOtherScoresForParticipant();
        }
    });

    function loadParticipants() {
        const heat = document.querySelector('[name=heat_number]').value;
        const run = document.querySelector('[name=run_number]:checked')?.value;
        const target = document.querySelector('[name=ep_id]');
        const eventId = <?= json_encode($event_id) ?>;
        
        if (!heat || !eventId || !run) return;
        
        // Add loading state
        target.classList.add('loading');
        target.innerHTML = '<option disabled>Loading participants...</option>';
        
        fetch('get_participants.php?event_id=' + eventId + '&heat_number=' + heat + '&run_number=' + run)
            .then(res => res.json())
            .then(data => {
                target.classList.remove('loading');
                target.innerHTML = '<option disabled value="">-- Select Participant --</option>';
                data.forEach(p => {
                    const lock = p.locked ? '🔒' : '✅';
                    const option = document.createElement('option');
                    option.value = p.ep_id;
                    option.textContent = `${p.bib} ${p.first_name} ${p.last_name} (Heat ${p.heat_number}) ${lock}`;
                    if (p.locked) option.disabled = true;
                    target.appendChild(option);
                });
                
                // Auto-select first available option
                const firstAvailable = target.querySelector('option:not([disabled])');
                if (firstAvailable && firstAvailable.value) {
                    firstAvailable.selected = true;
                    loadOtherScoresForParticipant();
                }
            })
            .catch(err => {
                target.classList.remove('loading');
                target.innerHTML = '<option disabled>Error loading participants</option>';
            });
            
        saveHeatRunSelection();
    }

    function saveHeatRunSelection() {
        const eventId = <?= json_encode($event_id) ?>;
        const heat = document.querySelector('[name=heat_number]').value;
        const run = document.querySelector('[name=run_number]:checked')?.value;
        if (eventId && heat && run) {
            localStorage.setItem('event_' + eventId + '_heat_run', JSON.stringify({heat, run}));
            const heatRunBadge = document.getElementById('heatRunBadge');
            if (heatRunBadge) {
                heatRunBadge.style.display = 'inline-block';
            }
        }
    }

    function updateScoreInTable(scoreIndex, updatedScore) {
        // Enhanced validation
        if (typeof scoreIndex !== 'number' || isNaN(scoreIndex) || scoreIndex < 0 || !updatedScore) {
            console.error('Invalid parameters for updateScoreInTable:', 
                         'scoreIndex:', scoreIndex, 
                         'type:', typeof scoreIndex, 
                         'isNaN:', isNaN(scoreIndex),
                         'updatedScore:', updatedScore);
            return false;
        }
        
        // Check if latestScores array exists and has the index
        if (!latestScores || !Array.isArray(latestScores) || scoreIndex >= latestScores.length) {
            console.error('Score index out of bounds:', scoreIndex, 'Array length:', latestScores?.length);
            return false;
        }
        
        // Update the latestScores array
        latestScores[scoreIndex] = updatedScore;
        
        // Get the table rows
        const rows = document.querySelectorAll('#latestScoresTable tbody tr');
        if (!rows || scoreIndex >= rows.length) {
            console.error('Table row not found for index:', scoreIndex, 'Available rows:', rows.length);
            return false;
        }
        
        const row = rows[scoreIndex];
        
        try {
            // Update BIB - with null safety
            row.cells[0].innerHTML = `<span class="badge bg-secondary">${updatedScore.bib || 'N/A'}</span>`;
            
            // Update Name - with null safety
            const firstName = updatedScore.first_name || '';
            const lastName = updatedScore.last_name || '';
            row.cells[1].innerHTML = `<small>${firstName} ${lastName}</small>`;
            
            // Update H/R - with null safety
            const heatNumber = updatedScore.heat_number || '?';
            const runNumber = updatedScore.run_number || '?';
            row.cells[2].innerHTML = `<small>${heatNumber}/${runNumber}</small>`;
            
            // Update Score - handle null/empty values
            const scoreValue = updatedScore.score_value !== null && updatedScore.score_value !== undefined ? 
                              updatedScore.score_value : '-';
            row.cells[3].innerHTML = `<strong class="text-primary">${scoreValue}</strong>`;
            
            // Update Status - with better badge logic
            let statusBadge = 'secondary';
            switch(updatedScore.status) {
                case 'OK':
                    statusBadge = 'success';
                    break;
                case 'DNS':
                case 'DNF':
                    statusBadge = 'warning';
                    break;
                case 'DSQ':
                    statusBadge = 'danger';
                    break;
                default:
                    statusBadge = 'secondary';
            }
            row.cells[4].innerHTML = `<span class="badge bg-${statusBadge} quick-badge">${updatedScore.status || 'Unknown'}</span>`;
            
            // Update the edit button to maintain the correct index
            row.cells[5].innerHTML = `<button type="button" class="btn btn-warning btn-sm" onclick="showOverwriteModal(${scoreIndex})"><i class="fas fa-edit"></i></button>`;
            
            // Initialize Lucide icons for the updated row
            if (window.initializeLucideIcons) {
                window.initializeLucideIcons(row);
            }
            
            // Add enhanced flash effect with animation
            row.classList.add('table-success');
            row.style.backgroundColor = '#d1e7dd';
            row.style.transition = 'background-color 0.3s ease';
            
            // Remove flash effect after animation
            setTimeout(() => {
                row.style.backgroundColor = '';
                setTimeout(() => {
                    row.classList.remove('table-success');
                    row.style.transition = '';
                }, 300);
            }, 1500);
            
            console.log('Successfully updated table row at index:', scoreIndex);
            return true;
            
        } catch (error) {
            console.error('Error updating table row:', error);
            return false;
        }
    }

    function addNewScoreToTable(newScore) {
        // Add to the beginning of latestScores array
        latestScores.unshift(newScore);
        
        // Keep only 4 latest scores
        if (latestScores.length > 4) {
            latestScores = latestScores.slice(0, 4);
        }
        
        // Check if table exists or show it if hidden
        const tableContainer = document.querySelector('#latestScoresTable').closest('.table-responsive');
        const emptyState = tableContainer.nextElementSibling;
        if (emptyState && emptyState.classList.contains('text-center')) {
            tableContainer.style.display = 'block';
            emptyState.style.display = 'none';
        }
        
        // Rebuild the table
        const tbody = document.querySelector('#latestScoresTable tbody');
        tbody.innerHTML = '';
        
        latestScores.forEach((score, index) => {
            const row = tbody.insertRow();
            row.innerHTML = `
                <td><span class="badge bg-secondary">${score.bib}</span></td>
                <td><small>${score.first_name} ${score.last_name}</small></td>
                <td><small>${score.heat_number}/${score.run_number}</small></td>
                <td><strong class="text-success-emphasis">${score.score_value}</strong></td>
                <td><span class="badge bg-${score.status === 'OK' ? 'success' : 'warning'} quick-badge">${score.status}</span></td>
                <td><button type="button" class="btn btn-warning btn-sm" onclick="showOverwriteModal(${index})"><i class="fas fa-edit"></i></button></td>
            `;
            
            // Add flash effect to new row
            if (index === 0) {
                row.style.backgroundColor = '#d1e7dd';
                setTimeout(() => {
                    row.style.backgroundColor = '';
                }, 2000);
            }
        });
        
        // Initialize Lucide icons for the rebuilt table
        if (window.initializeLucideIcons) {
            window.initializeLucideIcons(tbody);
        }
        
        // Update the count badge
        document.querySelector('.card-header .badge').textContent = latestScores.length + '/4';
    }

    // Criteria scoring functions
    function updateCriteriaRange(inputElement, index) {
        const rangeElement = document.querySelector(`[name="criteria_scores[${index}][range]"]`);
        if (rangeElement) {
            rangeElement.value = Math.round(inputElement.value);
            inputElement.value = Math.round(inputElement.value);
        }
        calculateFinalScore(true); // Update main score when manually adjusting criteria
    }

    function updateCriteriaInput(rangeElement, index) {
        const inputElement = document.querySelector(`[name="criteria_scores[${index}][value]"]`);
        if (inputElement) {
            const roundedValue = Math.round(rangeElement.value);
            inputElement.value = roundedValue;
            rangeElement.value = roundedValue;
        }
        calculateFinalScore(true); // Update main score when manually adjusting criteria
    }

    function calculateFinalScore(updateMainScore = true) {
        const criteriaInputs = document.querySelectorAll('[name^="criteria_scores"][name$="[value]"]');
        let total = 0;
        let count = 0;
        
        criteriaInputs.forEach(input => {
            const value = parseFloat(input.value) || 0;
            if (value > 0) {
                total += value;
                count++;
            }
        });
        
        const average = count > 0 ? Math.round(total / count) : 0;
        const calculatedScoreElement = document.getElementById('calculatedScore');
        if (calculatedScoreElement) {
            calculatedScoreElement.textContent = average;
        }
        
        // Only update the main score field if explicitly requested (to avoid loops)
        if (updateMainScore) {
            const mainScoreInput = document.querySelector('[name="score_value"]');
            if (mainScoreInput && count > 0) {
                mainScoreInput.value = average;
                // Update the range slider too
                const mainScoreRange = document.querySelector('[name="score_range"]');
                if (mainScoreRange) {
                    mainScoreRange.value = average;
                }
                
                // Add subtle animation to show the change
                mainScoreInput.style.transition = 'background-color 0.1s ease';
                mainScoreInput.style.backgroundColor = '#dcf900a3';
                setTimeout(() => {
                    mainScoreInput.style.backgroundColor = '';
                    setTimeout(() => {
                        mainScoreInput.style.transition = '';
                    }, 300);
                }, 300);
            }
        }
        
        return average;
    }

    // Handle main score changes and adjust criteria proportionally
    function updateMainScoreAndCriteria(element, updateType) {
        const mainScoreInput = document.querySelector('[name="score_value"]');
        const mainScoreRange = document.querySelector('[name="score_range"]');
        
        // Update the corresponding field
        if (updateType === 'range') {
            // Input changed, update range
            mainScoreRange.value = element.value;
        } else {
            // Range changed, update input
            mainScoreInput.value = element.value;
        }
        
        const newMainScore = parseFloat(element.value) || 0;
        
        // Check if we have criteria inputs to adjust
        const criteriaInputs = document.querySelectorAll('[name^="criteria_scores"][name$="[value]"]');
        if (criteriaInputs.length === 0) return;
        
        // Calculate current criteria average to determine ratio
        let currentCriteriaTotal = 0;
        let criteriaCount = 0;
        let hasExistingValues = false;
        
        criteriaInputs.forEach(input => {
            const value = parseFloat(input.value) || 0;
            if (value > 0) {
                currentCriteriaTotal += value;
                criteriaCount++;
                hasExistingValues = true;
            }
        });
        
        // Only adjust if there are existing criteria values and a new main score
        if (hasExistingValues && newMainScore > 0 && criteriaCount > 0) {
            const currentCriteriaAverage = currentCriteriaTotal / criteriaCount;
            
            // Avoid division by zero
            if (currentCriteriaAverage > 0) {
                const ratio = newMainScore / currentCriteriaAverage;
                
                // Apply ratio to all criteria inputs
                criteriaInputs.forEach((input, index) => {
                    const currentValue = parseFloat(input.value) || 0;
                    if (currentValue > 0) {
                        const newValue = Math.min(Math.round(currentValue * ratio), parseFloat(input.max) || 99);
                        input.value = newValue;
                        
                        // Update corresponding range slider
                        const rangeElement = document.querySelector(`[name="criteria_scores[${index}][range]"]`);
                        if (rangeElement) {
                            rangeElement.value = newValue;
                        }
                        
                        // Add subtle animation to show the change
                        input.style.transition = 'background-color 0.1s ease';
                        input.style.backgroundColor = '#dcf900a3';
                        setTimeout(() => {
                            input.style.backgroundColor = '';
                            setTimeout(() => {
                                input.style.transition = '';
                            }, 300);
                        }, 300);
                    }
                });
                
                // Recalculate final score to show updated average (without updating main score)
                calculateFinalScore(false);
            }
        }
    }

    function clearScoreForm() {
        // Clear the score input
        const scoreInput = document.querySelector('[name=score_value]');
        const scoreRange = document.querySelector('[name=score_range]');
        if (scoreInput) scoreInput.value = '';
        if (scoreRange) scoreRange.value = '0';
        
        // Clear all criteria inputs
        const criteriaInputs = document.querySelectorAll('[name^="criteria_scores"][name$="[value]"]');
        const criteriaRanges = document.querySelectorAll('[name^="criteria_scores"][name$="[range]"]');
        
        criteriaInputs.forEach(input => input.value = '');
        criteriaRanges.forEach(range => range.value = '0');
        
        // Reset calculated score display
        const calculatedScoreElement = document.getElementById('calculatedScore');
        if (calculatedScoreElement) {
            calculatedScoreElement.textContent = '0.0';
        }
        
        // Reset status to OK
        document.getElementById('statusOK').checked = true;
        
        // Clear BIB input
        document.getElementById('bibInput').value = '';
        
        // Reset participant selection to first option (disabled)
        document.getElementById('ep_id').selectedIndex = 0;
        
        // Focus back to BIB input
        document.getElementById('bibInput').focus();
    }

    function clearScoreInputsOnly() {
        // Clear the main score input
        const scoreInput = document.querySelector('[name=score_value]');
        const scoreRange = document.querySelector('[name=score_range]');
        if (scoreInput) scoreInput.value = '';
        if (scoreRange) scoreRange.value = '0';
        
        // Clear all criteria inputs
        const criteriaInputs = document.querySelectorAll('[name^="criteria_scores"][name$="[value]"]');
        const criteriaRanges = document.querySelectorAll('[name^="criteria_scores"][name$="[range]"]');
        
        criteriaInputs.forEach(input => input.value = '');
        criteriaRanges.forEach(range => range.value = '0');
        
        // Reset calculated score display
        const calculatedScoreElement = document.getElementById('calculatedScore');
        if (calculatedScoreElement) {
            calculatedScoreElement.textContent = '0';
        }
        
        // Focus back to the main score input for immediate entry
        if (scoreInput) scoreInput.focus();
    }

    // Enhanced figure selection helper functions
    function showFiguresSummary() {
        if (!window.__FIGURE_SELECTIONS__ || Object.keys(window.__FIGURE_SELECTIONS__).length === 0) {
            showToast('No Selections', 'No figures selected yet', 'info');
            return;
        }
        
        let summary = 'Selected Figures:\n';
        Object.entries(window.__FIGURE_SELECTIONS__).forEach(([category, items]) => {
            if (items.size > 0) {
                summary += `• ${category}: ${Array.from(items).join(', ')}\n`;
            }
        });
        
        alert(summary);
    }

    function clearAllFigures() {
        if (confirm('Clear all figure selections?')) {
            // Clear all selections
            window.__FIGURE_SELECTIONS__ = {};
            
            // Clear all active chips
            document.querySelectorAll('.figure-chip.active').forEach(chip => {
                chip.classList.remove('active');
            });
            
            // Update hidden fields
            if (typeof updateFiguresJson === 'function') updateFiguresJson();
            
            showToast('Cleared', 'All figure selections cleared', 'success');
        }
    }

    function copyFromLastRun() {
        const currentRun = document.querySelector('[name="run_number"]:checked')?.value;
        if (!currentRun || currentRun <= 1) {
            showToast('No Previous Run', 'No previous run to copy from', 'warning');
            return;
        }
        
        const lastRun = parseInt(currentRun) - 1;
        if (figureHistoryByRun[lastRun]) {
            // Copy selections from last run
            Object.entries(figureHistoryByRun[lastRun]).forEach(([category, items]) => {
                if (!window.__FIGURE_SELECTIONS__[category]) {
                    window.__FIGURE_SELECTIONS__[category] = new Set();
                }
                items.forEach(item => {
                    window.__FIGURE_SELECTIONS__[category].add(item);
                    // Update UI
                    const chip = document.querySelector(`.figure-chip[data-cat="${category}"][data-item="${item}"]`);
                    if (chip) chip.classList.add('active');
                });
            });
            
            // Update hidden fields
            if (typeof updateFiguresJson === 'function') updateFiguresJson();
            
            showToast('Copied', `Figures copied from Run ${lastRun}`, 'success');
        } else {
            showToast('No Data', `No figures found for Run ${lastRun}`, 'warning');
        }
    }

    function showOverwriteModal(idx) {
        const score = latestScores[idx];
        if (!score) return;
        
        // Populate basic score data
        document.getElementById('overwrite_score_id').value = score.score_id || '';
        document.getElementById('overwrite_score_value').value = score.score_value;
        document.getElementById('overwrite_status').value = score.status;
        
        // Set participant info in header
        const participantInfo = `${score.first_name} ${score.last_name} (Bib ${score.bib}) - Run ${score.run_number}`;
        const editScoreParticipant = document.getElementById('editScoreParticipant');
        if (editScoreParticipant) {
            editScoreParticipant.textContent = participantInfo;
        }
        
        // Store the index for later use
        document.getElementById('overwriteScoreForm').dataset.scoreIndex = idx.toString();
        
        // Handle figures if available
        setupEditFigureSelection(score);
        
        var modal = new bootstrap.Modal(document.getElementById('overwriteScoreModal'));
        modal.show();
        
        // Focus on score input when modal opens
        modal._element.addEventListener('shown.bs.modal', function() {
            document.getElementById('overwrite_score_value').focus();
            document.getElementById('overwrite_score_value').select();
        });
    }

    // Setup figure selection for edit modal
    function setupEditFigureSelection(score) {
        const figureSection = document.getElementById('editFigureSelection');
        const figureGrid = document.getElementById('editFigureGrid');
        const figuresJsonField = document.getElementById('overwrite_figures_json');
        
        // Clear previous state
        window.__EDIT_FIGURE_SELECTIONS__ = {};
        figuresJsonField.value = '';
        
        if (!FIGURE_DATA.available) {
            figureSection.style.display = 'none';
            return;
        }
        
        // Show figure section
        figureSection.style.display = 'block';
        
        // Parse existing figures from score if available
        let existingFigures = {};
        if (score.figures_json) {
            try {
                const parsedData = JSON.parse(score.figures_json);
                console.log('Parsed existing figures:', parsedData);
                console.log('Type of parsedData:', typeof parsedData);
                console.log('Keys of parsedData:', Object.keys(parsedData));
                
                // Handle different possible formats
                if (parsedData.figures && typeof parsedData.figures === 'object') {
                    // Format: {"figures": {"category": ["item1", "item2"]}, "validation": {...}}
                    existingFigures = parsedData.figures;
                    console.log('Using figures property:', existingFigures);
                } else if (typeof parsedData === 'object' && !Array.isArray(parsedData)) {
                    // Direct format: {"category": ["item1", "item2"]}
                    // But exclude non-figure properties like "validation"
                    Object.entries(parsedData).forEach(([key, value]) => {
                        if (key !== 'validation' && key !== 'timestamp' && 
                            (Array.isArray(value) || typeof value === 'string')) {
                            existingFigures[key] = value;
                        }
                    });
                    console.log('Using filtered direct format:', existingFigures);
                } else {
                    console.warn('Unexpected figures_json format:', parsedData);
                }
                
                // Debug each category's data
                Object.entries(existingFigures).forEach(([cat, items]) => {
                    console.log(`Edit Modal Category "${cat}":`, items, 'Type:', typeof items, 'IsArray:', Array.isArray(items));
                });
            } catch (e) {
                console.warn('Could not parse existing figures_json:', e);
                console.log('Raw figures_json:', score.figures_json);
            }
        }
        
        // Build figure grid
        let gridHTML = '';
        FIGURE_DATA.categories.forEach(category => {
            const items = FIGURE_DATA.itemsByCategory[category] || [];
            if (items.length === 0) return;
            
            gridHTML += `
                <div class="figure-row mb-3 p-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="mb-0"><i class="fas fa-tag me-2"></i>${category}</h6>
                        <button type="button" class="btn btn-sm btn-outline-secondary clear-cat" 
                                onclick="clearEditFigureCategory('${category}')">
                            <i class="fas fa-times"></i> Clear
                        </button>
                    </div>
                    <div class="figure-chips d-flex flex-wrap gap-2">
            `;
            
            items.forEach(item => {
                // Check if item is selected - handle different data formats
                let isSelected = false;
                if (existingFigures[category]) {
                    if (Array.isArray(existingFigures[category])) {
                        isSelected = existingFigures[category].includes(item);
                    } else if (typeof existingFigures[category] === 'string') {
                        isSelected = existingFigures[category] === item;
                    } else if (existingFigures[category] && typeof existingFigures[category] === 'object') {
                        // Handle object case - check if item exists as key or value
                        isSelected = Object.values(existingFigures[category]).includes(item) || 
                                   Object.keys(existingFigures[category]).includes(item);
                    }
                }
                
                const activeClass = isSelected ? 'active' : '';
                gridHTML += `
                    <button type="button" 
                            class="btn btn-sm btn-outline-primary figure-chip ${activeClass}" 
                            data-cat="${category}" 
                            data-item="${item}"
                            onclick="toggleEditFigureChip(this, '${category}', '${item}')">
                        ${item}
                    </button>
                `;
            });
            
            gridHTML += `
                    </div>
                </div>
            `;
        });
        
        figureGrid.innerHTML = gridHTML;
        
        // Initialize selections from existing data
        window.__EDIT_FIGURE_SELECTIONS__ = {};
        Object.entries(existingFigures).forEach(([category, items]) => {
            // Ensure items is an array before creating Set
            if (Array.isArray(items)) {
                window.__EDIT_FIGURE_SELECTIONS__[category] = new Set(items);
            } else if (typeof items === 'string') {
                // Handle case where items might be a single string
                window.__EDIT_FIGURE_SELECTIONS__[category] = new Set([items]);
            } else if (items && typeof items === 'object') {
                // Handle case where items might be an object - try to get its values or keys
                const itemArray = Array.isArray(items) ? items : 
                                 items.hasOwnProperty('length') ? Array.from(items) :
                                 Object.values(items).length > 0 ? Object.values(items) : 
                                 Object.keys(items);
                window.__EDIT_FIGURE_SELECTIONS__[category] = new Set(itemArray);
            } else {
                // Fallback: create empty set
                console.warn('Unexpected items format for category', category, ':', items);
                window.__EDIT_FIGURE_SELECTIONS__[category] = new Set();
            }
        });
        
        // Update hidden field and summary
        updateEditFiguresJson();
        updateEditFigureSummary();
        
        console.log('Initialized edit figure selections:', window.__EDIT_FIGURE_SELECTIONS__);
    }

    // Toggle figure chip in edit modal
    function toggleEditFigureChip(button, category, item) {
        if (!window.__EDIT_FIGURE_SELECTIONS__[category]) {
            window.__EDIT_FIGURE_SELECTIONS__[category] = new Set();
        }
        
        const isActive = button.classList.contains('active');
        
        if (isActive) {
            // Remove selection
            button.classList.remove('active');
            window.__EDIT_FIGURE_SELECTIONS__[category].delete(item);
            
            // Remove category if empty
            if (window.__EDIT_FIGURE_SELECTIONS__[category].size === 0) {
                delete window.__EDIT_FIGURE_SELECTIONS__[category];
            }
        } else {
            // Add selection
            button.classList.add('active');
            window.__EDIT_FIGURE_SELECTIONS__[category].add(item);
        }
        
        updateEditFiguresJson();
        updateEditFigureSummary();
        
        console.log('Updated edit figure selections:', window.__EDIT_FIGURE_SELECTIONS__);
    }

    // Clear entire category in edit modal
    function clearEditFigureCategory(category) {
        // Remove from selections
        delete window.__EDIT_FIGURE_SELECTIONS__[category];
        
        // Update UI
        document.querySelectorAll(`#editFigureGrid .figure-chip[data-cat="${category}"]`).forEach(chip => {
            chip.classList.remove('active');
        });
        
        updateEditFiguresJson();
        updateEditFigureSummary();
        
        console.log('Cleared edit figure category:', category);
    }

    // Update hidden figures_json field for edit modal
    function updateEditFiguresJson() {
        const figuresJsonField = document.getElementById('overwrite_figures_json');
        
        // Convert Sets to arrays for JSON serialization
        const figuresData = {};
        Object.entries(window.__EDIT_FIGURE_SELECTIONS__ || {}).forEach(([category, itemSet]) => {
            if (itemSet.size > 0) {
                figuresData[category] = Array.from(itemSet);
            }
        });
        
        figuresJsonField.value = Object.keys(figuresData).length > 0 ? JSON.stringify(figuresData) : '';
        console.log('Updated edit figures JSON:', figuresJsonField.value);
    }

    // Update figure summary display in edit modal
    function updateEditFigureSummary() {
        const summaryDiv = document.getElementById('editFigureSummary');
        const summaryContent = document.getElementById('editFigureSummaryContent');
        
        const selections = window.__EDIT_FIGURE_SELECTIONS__ || {};
        const categories = Object.keys(selections);
        
        if (categories.length === 0) {
            summaryDiv.style.display = 'none';
            return;
        }
        
        let summaryHTML = '';
        categories.forEach(category => {
            const items = Array.from(selections[category]);
            summaryHTML += `<div><strong>${category}:</strong> ${items.join(', ')}</div>`;
        });
        
        summaryContent.innerHTML = summaryHTML;
        summaryDiv.style.display = 'block';
    }

// In the overwrite form submission handler, fix the parsing:
// AJAX overwrite form submission
const overwriteForm = document.getElementById('overwriteScoreForm');
if (overwriteForm) {
    overwriteForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('ajax', '1'); // Add AJAX flag
        
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        // FIX: Better parsing of scoreIndex with validation
        const scoreIndexStr = this.dataset.scoreIndex;
        const scoreIndex = parseInt(scoreIndexStr, 10);
        
        // Validate scoreIndex
        if (isNaN(scoreIndex) || scoreIndex < 0 || scoreIndex >= latestScores.length) {
            console.error('Invalid score index:', scoreIndexStr, 'parsed as:', scoreIndex);
            showToast('Error', 'Invalid score reference. Please refresh the page.', 'error');
            return;
        }
        
        // Show loading state
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Updating...';
        
        // Initialize Lucide icons for the loading button
        if (window.initializeLucideIcons) {
            window.initializeLucideIcons(submitBtn);
        }
        
        // Submit via AJAX
        const overwriteRequestData = Object.fromEntries(formData.entries());
        
        fetch(window.location.href, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Log the API call for debugging
            logApiCall('POST', window.location.href + ' (overwrite)', overwriteRequestData, data);
            
            if (data.success) {
                // Update the table without page reload
                const updateSuccess = updateScoreInTable(scoreIndex, data.score);
                
                if (updateSuccess) {
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('overwriteScoreModal'));
                    modal.hide();
                    
                    // Show success message
                    showToast('Success!', data.message, 'success');
                } else {
                    showToast('Warning', 'Score updated but table refresh failed. Please reload page.', 'error');
                }
                
            } else {
                throw new Error(data.message || 'Update failed');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            
            // Log the API call error for debugging
            logApiCall('POST', window.location.href + ' (overwrite)', overwriteRequestData, { 
                error: error.message || 'Unknown error',
                status: 'error',
                timestamp: new Date().toISOString()
            });
            
            showToast('Error', error.message || 'Error updating score. Please try again.', 'error');
        })
        .finally(() => {
            // Restore button state
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
            
            // Initialize Lucide icons for the restored button
            if (window.initializeLucideIcons) {
                window.initializeLucideIcons(submitBtn);
            }
        });
    });
}

// Toast notification function
function showToast(title, message, type = 'info') {
    // Create toast container if it doesn't exist
    let toastContainer = document.getElementById('toastContainer');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toastContainer';
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    // Create toast
    const toastId = 'toast_' + Date.now();
    const bgClass = type === 'success' ? 'bg-success' : type === 'error' ? 'bg-danger' : 'bg-info';
    
    const toastHTML = `
        <div id="${toastId}" class="toast ${bgClass} text-white" role="alert">
            <div class="toast-header ${bgClass} text-white border-0">
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} me-2"></i>
                <strong class="me-auto">${title}</strong>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    
    toastContainer.insertAdjacentHTML('beforeend', toastHTML);
    
    // Show toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
    toast.show();
    
    // Remove from DOM after hiding
    toastElement.addEventListener('hidden.bs.toast', function() {
        this.remove();
    });
}

function loadOtherScoresForParticipant() {
    const ep_id = document.getElementById('ep_id').value;
    const heat = document.querySelector('[name=heat_number]').value;
    if (!ep_id || !heat) {
        // Hide the card when no participant selected
        const otherHeatScoresCard = document.getElementById('otherHeatScoresCard');
        if (otherHeatScoresCard) {
            otherHeatScoresCard.style.display = 'none';
        }
        return;
    }

    // Store current participant for figure history
    currentParticipantId = ep_id;

    fetch(`ajax_get_other_scores.php?ep_id=${encodeURIComponent(ep_id)}&heat_number=${encodeURIComponent(heat)}&include_judges=1&include_cp=1&current_judge_id=${encodeURIComponent(CURRENT_JUDGE_ID)}`)
        .then(res => res.json())
        .then(scores => {
            const container = document.getElementById('otherHeatScores');
            const card = document.getElementById('otherHeatScoresCard');
            
            if (!Array.isArray(scores) || scores.length === 0) {
                container.innerHTML = '<div class="text-muted"><em>No other scores available for this participant</em></div>';
                card.style.display = 'block';
                return;
            }

            // Show the card since we have data
            card.style.display = 'block';

            // Load figure history for this participant after loading scores
            loadFigureHistoryForParticipant(ep_id);

            // Normalize
            const norm = scores.map(s => ({
                judge_id: String(s.judge_id ?? s.judgeId ?? s.judge?.id ?? ''),
                judge_name: s.judge_name ?? s.judgeName ?? s.judge?.name ?? '',
                control_point: s.control_point_name ?? s.cp_name ?? s.checkpoint ?? s.control_point ?? '—',
                run_number: Number(s.run_number ?? s.run ?? 0),
                score_value: s.score_value !== undefined && s.score_value !== null ? Number(s.score_value) : null,
                status: s.status ?? 'OK',
                updated_at: s.updated_at ?? s.created_at ?? null
            }));

            // Dedupe by judge_id + run_number (keep latest)
            const mapLatest = new Map();
            for (const it of norm) {
                const key = `${it.judge_id}-${it.run_number}`;
                const prev = mapLatest.get(key);
                if (!prev) {
                    mapLatest.set(key, it);
                } else {
                    const tPrev = prev.updated_at ? new Date(prev.updated_at).getTime() : 0;
                    const tNew = it.updated_at ? new Date(it.updated_at).getTime() : 0;
                    if (tNew >= tPrev) mapLatest.set(key, it);
                }
            }
            const deduped = Array.from(mapLatest.values());

            // Build rows: one per judge, columns per run
            const heatNum = Number(heat);
            const runsCount = Number(HEAT_RUNS_MAP?.[heatNum] ?? DEFAULT_RUNS_PER_HEAT ?? 3);

            // judge -> { judge_name, control_point, runs: {run_number: {score,status}} }
            const rowsByJudge = new Map();
            for (const s of deduped) {
                if (!rowsByJudge.has(s.judge_id)) {
                    rowsByJudge.set(s.judge_id, {
                        judge_id: s.judge_id,
                        judge_name: s.judge_name || (`Judge ${s.judge_id || '?'}`),
                        control_point: s.control_point,
                        runs: {}
                    });
                }
                rowsByJudge.get(s.judge_id).runs[s.run_number] = {
                    value: s.score_value,
                    status: s.status
                };
            }

            // Order: current judge first, then others by judge_name
            const myId = String(CURRENT_JUDGE_ID ?? '');
            const allRows = Array.from(rowsByJudge.values());
            const mine = allRows.filter(r => r.judge_id === myId);
            const others = allRows.filter(r => r.judge_id !== myId)
                                  .sort((a, b) => a.judge_name.localeCompare(b.judge_name));
            const ordered = [...mine, ...others];

            // Build table
            let thead = `
                <thead class="table-light">
                    <tr>
                        <th style="white-space:nowrap;">Judge</th>
                        
                        ${Array.from({length: runsCount}, (_, i) => `<th class="text-center" style="white-space:nowrap;">Run ${i+1}</th>`).join('')}
                    </tr>
                </thead>`;

            const renderCell = (cell) => {
                if (!cell) return '—';
                const val = (cell.value !== null && cell.value !== undefined) ? Number(cell.value).toFixed(2) : '—';
                const status = cell.status || 'OK';
                const badge = status === 'OK' ? 'success' : (status === 'DSQ' ? 'danger' : 'warning');
                return `<div><strong>${val}</strong></div><div><span class="badge bg-${badge}">${status}</span></div>`;
            };

            const tbodyRows = ordered.map(row => {
                const isYou = row.judge_id === myId;
                const judgeCell = isYou
                    ? `<span class="badge bg-success me-2">You</span><span>${row.judge_name}</span>`
                    : `<span class="badge bg-secondary me-2">Judge</span><span>${row.judge_name}</span>`;
                const runCells = Array.from({length: runsCount}, (_, i) => {
                    const rno = i + 1;
                    return `<td class="text-center align-middle">${renderCell(row.runs[rno])}</td>`;
                }).join('');
                return `
                    <tr>
                        <td class="align-middle">${judgeCell} <small>${row.control_point || '—'}</small></td>
                        ${runCells}
                    </tr>`;
            }).join('');

            const tableHTML = `
                <div class="table-responsive">
                    <table class="table table-sm scores-table mb-0">
                        ${thead}
                        <tbody>
                            ${tbodyRows}
                        </tbody>
                    </table>
                </div>`;

            container.innerHTML = tableHTML;
        })
        .catch(err => {
            console.log('Could not load other scores:', err);
        });
}

/**
 * Load existing figure selections for current judge's score
 */
function loadExistingFigureSelections() {
    if (!FIGURE_DATA.available) return;
    
    const ep_id = document.getElementById('ep_id').value;
    const runNumber = document.querySelector('[name="run_number"]:checked')?.value;
    const heat = document.querySelector('[name=heat_number]').value;
    
    if (!ep_id || !runNumber || !heat) return;
    
    console.log('Loading existing figures for participant:', ep_id, 'run:', runNumber);
    
    // Fetch current judge's existing score for this participant and run
    fetch(`ajax_get_other_scores.php?ep_id=${encodeURIComponent(ep_id)}&heat_number=${encodeURIComponent(heat)}&current_judge_only=1&run_number=${encodeURIComponent(runNumber)}&current_judge_id=${encodeURIComponent(CURRENT_JUDGE_ID)}`)
        .then(res => res.json())
        .then(scores => {
            // Clear current selections first
            if (window.__FIGURE_SELECTIONS__) {
                window.__FIGURE_SELECTIONS__ = {};
                document.querySelectorAll('.figure-chip.active').forEach(chip => {
                    chip.classList.remove('active');
                });
            }
            
            if (!Array.isArray(scores) || scores.length === 0) {
                console.log('No existing score found for current judge');
                updateFiguresJson();
                return;
            }
            
            // Find the score for the current run
            const currentScore = scores.find(s => Number(s.run_number || s.run) === Number(runNumber));
            if (!currentScore || !currentScore.figures_json) {
                console.log('No figures found in existing score');
                updateFiguresJson();
                return;
            }
            
            try {
                const parsedData = JSON.parse(currentScore.figures_json);
                console.log('Parsed existing figures for current score:', parsedData);
                
                let existingFigures = {};
                
                // Handle different possible formats
                if (parsedData.figures && typeof parsedData.figures === 'object') {
                    // Format: {"figures": {"category": ["item1", "item2"]}, "validation": {...}}
                    existingFigures = parsedData.figures;
                    console.log('Using figures property:', existingFigures);
                } else if (typeof parsedData === 'object' && !Array.isArray(parsedData)) {
                    // Direct format: {"category": ["item1", "item2"]}
                    // But exclude non-figure properties like "validation"
                    Object.entries(parsedData).forEach(([key, value]) => {
                        if (key !== 'validation' && key !== 'timestamp' && 
                            (Array.isArray(value) || typeof value === 'string')) {
                            existingFigures[key] = value;
                        }
                    });
                    console.log('Using filtered direct format:', existingFigures);
                } else {
                    console.warn('Unexpected figures_json format for main selection:', parsedData);
                }
                
                // Initialize figure selections
                window.__FIGURE_SELECTIONS__ = {};
                
                // Load existing selections and mark chips as active
                Object.entries(existingFigures).forEach(([category, items]) => {
                    if (Array.isArray(items)) {
                        window.__FIGURE_SELECTIONS__[category] = new Set(items);
                        
                        // Mark chips as active
                        items.forEach(item => {
                            const chip = document.querySelector(`.figure-chip[data-cat="${CSS.escape(category)}"][data-item="${CSS.escape(item)}"]`);
                            if (chip) {
                                chip.classList.add('active');
                                console.log('Marked chip as active:', category, item);
                            }
                        });
                    } else if (typeof items === 'string') {
                        window.__FIGURE_SELECTIONS__[category] = new Set([items]);
                        
                        // Mark chip as active
                        const chip = document.querySelector(`.figure-chip[data-cat="${CSS.escape(category)}"][data-item="${CSS.escape(items)}"]`);
                        if (chip) {
                            chip.classList.add('active');
                            console.log('Marked chip as active:', category, items);
                        }
                    }
                });
                
                // Update hidden fields and display
                updateFiguresJson();
                updateDiversityValidationWithHistory();
                
                console.log('Loaded existing figure selections:', window.__FIGURE_SELECTIONS__);
                
            } catch (e) {
                console.warn('Could not parse existing figures_json:', e);
                console.log('Raw figures_json:', currentScore.figures_json);
                updateFiguresJson();
            }
        })
        .catch(err => {
            console.error('Error loading existing figure selections:', err);
        });
}

// Load figure history for participant across all runs
function loadFigureHistoryForParticipant(ep_id) {
    console.log('loadFigureHistoryForParticipant called with ep_id:', ep_id);
    
    if (!FIGURE_DATA.available || !ep_id) {
        console.log('Figure data not available or no ep_id provided');
        figureHistoryByRun = {};
        return;
    }

    const eventId = <?= json_encode($event_id) ?>;
    console.log('Event ID:', eventId);
    if (!eventId) return;

    const url = `ajax_get_figure_history.php?ep_id=${encodeURIComponent(ep_id)}&judge_id=${encodeURIComponent(CURRENT_JUDGE_ID)}`;
    console.log('Fetching figure history from:', url);

    fetch(url)
        .then(res => {
            console.log('Response status:', res.status);
            return res.json();
        })
        .then(data => {
            console.log('Raw figure history data received:', data);
            figureHistoryByRun = {};
            
            if (Array.isArray(data)) {
                data.forEach(score => {
                    const runNum = score.run_number;
                    const figuresJson = score.figures_json;
                    
                    console.log(`Processing run ${runNum}, figures_json:`, figuresJson);
                    
                    if (figuresJson) {
                        try {
                            const parsedData = JSON.parse(figuresJson);
                            console.log(`Parsed figures for run ${runNum}:`, parsedData);
                            
                            if (!figureHistoryByRun[runNum]) {
                                figureHistoryByRun[runNum] = {};
                            }
                            
                            let figures = {};
                            
                            // Handle different possible formats (same logic as other functions)
                            if (parsedData.figures && typeof parsedData.figures === 'object') {
                                // Format: {"figures": {"category": ["item1", "item2"]}, "validation": {...}}
                                figures = parsedData.figures;
                                console.log(`Using figures property for run ${runNum}:`, figures);
                            } else if (typeof parsedData === 'object' && !Array.isArray(parsedData)) {
                                // Direct format: {"category": ["item1", "item2"]}
                                // But exclude non-figure properties like "validation"
                                Object.entries(parsedData).forEach(([key, value]) => {
                                    if (key !== 'validation' && key !== 'timestamp' && 
                                        (Array.isArray(value) || typeof value === 'string')) {
                                        figures[key] = value;
                                    }
                                });
                                console.log(`Using filtered direct format for run ${runNum}:`, figures);
                            } else {
                                console.warn(`Unexpected figures_json format for run ${runNum}:`, parsedData);
                            }
                            
                            // Parse figures into category->Set(items) structure
                            Object.entries(figures).forEach(([category, items]) => {
                                if (Array.isArray(items)) {
                                    figureHistoryByRun[runNum][category] = new Set(items);
                                } else if (typeof items === 'string') {
                                    figureHistoryByRun[runNum][category] = new Set([items]);
                                }
                                console.log(`Added to figureHistoryByRun[${runNum}][${category}]:`, figureHistoryByRun[runNum][category]);
                            });
                        } catch (e) {
                            console.log('Failed to parse figures JSON for run', runNum, ':', e);
                        }
                    }
                });
            }
            
            console.log('Final figureHistoryByRun:', figureHistoryByRun);
            
            // Update diversity validation with historical data
            console.log('Updating diversity validation with loaded figure history...');
            updateDiversityValidationWithHistory();
            
            // Show figure history in UI
            displayFigureHistory();
        })
        .catch(err => {
            console.log('Could not load figure history:', err);
            figureHistoryByRun = {};
        });
}

// Display figure history in the UI
function displayFigureHistory() {
    const historyContainer = document.getElementById('figureHistoryDisplay');
    const historyCard = document.getElementById('figureHistoryCard');
    if (!historyContainer || !FIGURE_DATA.available) return;
    
    const currentRun = document.querySelector('[name="run_number"]:checked')?.value || 1;
    const runNumbers = Object.keys(figureHistoryByRun).map(Number).sort();
    
    // Clear existing historical markings
    document.querySelectorAll('.figure-chip.has-history').forEach(chip => {
        chip.classList.remove('has-history');
        // Restore original text
        const originalText = chip.getAttribute('data-original-text');
        if (originalText) {
            chip.textContent = originalText;
        }
        chip.removeAttribute('data-run');
        chip.removeAttribute('data-runs');
    });
    
    // Track which figures appear in which runs for multi-run marking
    const figureRunMap = {}; // { "category:item": [run1, run2, ...] }
    
    // Build figure->runs mapping
    runNumbers.forEach(runNum => {
        if (runNum >= currentRun) return; // Only previous runs
        
        const runFigures = figureHistoryByRun[runNum];
        Object.entries(runFigures).forEach(([category, itemSet]) => {
            itemSet.forEach(item => {
                const figureKey = `${category}:${item}`;
                if (!figureRunMap[figureKey]) {
                    figureRunMap[figureKey] = [];
                }
                figureRunMap[figureKey].push(runNum);
            });
        });
    });
    
    // Mark chips with historical data, showing all runs where they were used
    Object.entries(figureRunMap).forEach(([figureKey, runs]) => {
        const [category, item] = figureKey.split(':', 2);
        const chip = document.querySelector(`.figure-chip[data-cat="${CSS.escape(category)}"][data-item="${CSS.escape(item)}"]`);
        if (chip) {
            // Store original text if not already stored
            if (!chip.hasAttribute('data-original-text')) {
                chip.setAttribute('data-original-text', chip.textContent.trim());
            }
            
            // Add run indicators to the chip text (but don't block selection)
            const originalText = chip.getAttribute('data-original-text');
            const runIndicator = runs.length > 1 ? `R${runs.join(',R')}` : `R${runs[0]}`;
            
            // Update chip text to include run indicator
            chip.innerHTML = `${originalText} <small class="text-muted">(${runIndicator})</small>`;
            
            // Store run data for reference
            chip.setAttribute('data-runs', runs.join(','));
            chip.setAttribute('data-run', runIndicator);
            
            // Add a subtle visual indicator class (but keep chips selectable)
            chip.classList.add('has-history');
            
            console.log(`Marked chip '${originalText}' with runs: ${runIndicator}`);
        }
    });
    
    if (runNumbers.length === 0) {
        historyContainer.innerHTML = '<div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>No previous figure selections for this participant.</div>';
        historyCard.style.display = 'none';
        return;
    }
    
    // Show the history card since we have data
    historyCard.style.display = 'block';
    
    let html = '<div class="mb-3"><h6><i class="fas fa-history me-2"></i>Previous Figure Selections</h6>';
    
    // Show ALL previous runs, not just those with selections
    for (let runNum = 1; runNum < currentRun; runNum++) {
        const runFigures = figureHistoryByRun[runNum];
        
        html += `<div class="mb-2">
            <strong class="text-primary">Run ${runNum}:</strong>`;
        
        if (runFigures && Object.keys(runFigures).length > 0) {
            const categories = Object.keys(runFigures);
            categories.forEach(category => {
                const items = Array.from(runFigures[category]);
                if (items.length > 0) {
                    html += ` <span class="badge bg-secondary me-1">${category}: ${items.join(', ')}</span>`;
                }
            });
        } else {
            html += ' <span class="text-muted">No figures selected</span>';
        }
        
        html += '</div>';
    }
    
    // Show duplicate figure summary if any figures were used multiple times
    const duplicateFigures = Object.entries(figureRunMap).filter(([figureKey, runs]) => runs.length > 1);
    if (duplicateFigures.length > 0) {
        html += '<div class="small text-info mt-2 mb-2">';
        html += '<i class="fas fa-repeat me-1"></i><strong>Figures used multiple times:</strong><br>';
        duplicateFigures.forEach(([figureKey, runs]) => {
            const [category, item] = figureKey.split(':', 2);
            html += `• ${category}: ${item} <span class="badge bg-info">R${runs.join(', R')}</span><br>`;
        });
        html += '</div>';
    }
    
    html += '<div class="small text-muted mt-2"><i class="fas fa-info-circle me-1"></i>Previous selections are marked with yellow background and run numbers. Multiple runs shown as R1,R2.</div>';
    html += '</div>';
    historyContainer.innerHTML = html;
}

// Enhanced diversity validation with historical data
function updateDiversityValidationWithHistory() {
    console.log('updateDiversityValidationWithHistory called');
    console.log('Current figureHistoryByRun:', figureHistoryByRun);
    console.log('Current window.__FIGURE_SELECTIONS__:', window.__FIGURE_SELECTIONS__);
    
    const box = document.getElementById('diversityValidation');
    const validationCard = document.getElementById('diversityValidationCard');
    
    if (!box || !FIGURE_UI || !Array.isArray(FIGURE_UI.diversityRules) || FIGURE_UI.diversityRules.length === 0) {
        console.log('No diversity validation box or rules found');
        if (validationCard) validationCard.style.display = 'none';
        // Reset submit button if no diversity rules - ensure validation details are cleared
        window.__DIVERSITY_VALIDATION_DETAILS__ = {
            overallCompliant: true,
            validationErrors: [],
            validationWarnings: [],
            validationPassed: [],
            rulesChecked: 0,
            currentRun: document.querySelector('[name="run_number"]:checked')?.value || 1,
            totalRuns: 0,
            timestamp: Date.now()
        };
        updateSubmitButtonState(true);
        return;
    }
    
    console.log('Running diversity validation with history...');
    const isValid = runDiversityValidationWithHistory(box);
    updateSubmitButtonState(isValid);
    
    // Show validation card if there are rules and content
    if (validationCard && box.innerHTML.trim()) {
        validationCard.style.display = 'block';
    }
}

// Update submit button appearance based on validation state
function updateSubmitButtonState(isValid) {
    const submitBtn = document.getElementById('submitBtn');
    const validationSummary = document.getElementById('validationSummary');
    const validationSummaryText = document.getElementById('validationSummaryText');
    
    if (!submitBtn) return;
    
    // Store validation state globally for use during submission
    window.__DIVERSITY_VALIDATION_STATE__ = {
        isValid: isValid,
        timestamp: Date.now(),
        currentRun: document.querySelector('[name="run_number"]:checked')?.value || 1
    };
    
    // Get validation details for summary
    const validationDetails = window.__DIVERSITY_VALIDATION_DETAILS__ || {};
    const rulesChecked = validationDetails.rulesChecked || 0;
    const errorCount = validationDetails.validationErrors?.length || 0;
    const warningCount = validationDetails.validationWarnings?.length || 0;
    const passedCount = validationDetails.validationPassed?.length || 0;
    const currentRun = validationDetails.currentRun || 1;
    const totalRuns = validationDetails.totalRuns || 3;
    
    // Build detailed validation summary from the actual rule results
    function buildDetailedSummary() {
        if (rulesChecked === 0) return '';
        
        let summaryHtml = '';
        const allRules = [
            ...(validationDetails.validationErrors || []),
            ...(validationDetails.validationWarnings || []),
            ...(validationDetails.validationPassed || [])
        ];
        
        allRules.forEach((rule, index) => {
            const isLast = index === allRules.length - 1;
            const group = rule.group || '';
            const contextDesc = rule.contextDesc || '';
            const currentCount = rule.currentCount || 0;
            const minDistinct = rule.minDistinct || 0;
            const selectedItems = rule.selectedItems || [];
            const availableItems = rule.availableItems || [];
            const runInfo = rule.runInfo || `Run ${currentRun} of ${totalRuns}`;
            const isLastRun = rule.isLastRun || false;
            const validationLevel = rule.validationLevel || 'passed';
            
            // Build status indicator
            let statusIcon = '';
            let statusText = '';
            if (validationLevel === 'error') {
                statusIcon = '❌';
                statusText = isLastRun ? 'FINAL RUN - Must meet requirement!' : 'Error';
            } else if (validationLevel === 'warning') {
                statusIcon = '⚠️';
                statusText = 'Warning';
            } else {
                statusIcon = '✅';
                statusText = `${currentCount}/${minDistinct} ✓`;
            }
            
            // Build main line
            summaryHtml += `<div class="mb-1">`;
            summaryHtml += `<strong>${group}</strong> (${contextDesc})`;
            if (runInfo) summaryHtml += ` • ${runInfo}`;
            if (isLastRun && validationLevel === 'error') summaryHtml += ` • <span class="text-danger fw-bold">FINAL RUN - Must meet requirement!</span>`;
            summaryHtml += `</div>`;
            
            // Build details line
            summaryHtml += `<div class="small text-muted mb-2">`;
            if (selectedItems.length > 0) {
                summaryHtml += `Selected: ${selectedItems.join(', ')} `;
            } else {
                summaryHtml += `Selected: None `;
            }
            summaryHtml += `${statusIcon} ${statusText}`;
            
            // Add suggestions for failed rules
            if ((validationLevel === 'error' || validationLevel === 'warning') && availableItems.length > 0) {
                const suggestions = availableItems.filter(item => !selectedItems.includes(item)).slice(0, 5);
                if (suggestions.length > 0) {
                    summaryHtml += `<br>Suggestions: ${suggestions.join(', ')}`;
                }
            }
            summaryHtml += `</div>`;
            
            if (!isLast) summaryHtml += `<hr class="my-2">`;
        });
        
        return summaryHtml;
    }
    
    if (isValid) {
        submitBtn.classList.remove('btn-warning', 'btn-danger');
        submitBtn.classList.add('btn-success');
        submitBtn.innerHTML = '<i class="fas fa-save me-2"></i>Submit Score';
        submitBtn.title = 'All requirements met - ready to submit';
        
        // Update validation summary
        if (rulesChecked > 0) {
            validationSummary.style.display = 'block';
            const summaryAlert = validationSummary.querySelector('.alert');
            summaryAlert.className = 'alert alert-success alert-sm mb-0';
            
            const detailedSummary = buildDetailedSummary();
            if (detailedSummary) {
                validationSummaryText.innerHTML = detailedSummary;
            } else {
                validationSummaryText.innerHTML = `<i class="fas fa-check-circle me-1"></i>All ${rulesChecked} diversity rules satisfied`;
            }
        } else {
            validationSummary.style.display = 'none';
        }
    } else {
        submitBtn.classList.remove('btn-success', 'btn-danger');
        submitBtn.classList.add('btn-warning');
        submitBtn.innerHTML = '<i class="fas fa-exclamation-triangle me-2"></i>Submit Score (Rules Warning)';
        submitBtn.title = 'Diversity requirements not fully met - score will be submitted with validation status';
        
        // Update validation summary
        if (rulesChecked > 0) {
            validationSummary.style.display = 'block';
            const summaryAlert = validationSummary.querySelector('.alert');
            
            // Use danger for errors, warning for warnings only
            if (errorCount > 0) {
                summaryAlert.className = 'alert alert-danger alert-sm mb-0';
            } else {
                summaryAlert.className = 'alert alert-warning alert-sm mb-0';
            }
            
            const detailedSummary = buildDetailedSummary();
            if (detailedSummary) {
                validationSummaryText.innerHTML = detailedSummary;
            } else {
                let summaryParts = [];
                if (errorCount > 0) summaryParts.push(`${errorCount} error${errorCount > 1 ? 's' : ''}`);
                if (warningCount > 0) summaryParts.push(`${warningCount} warning${warningCount > 1 ? 's' : ''}`);
                if (passedCount > 0) summaryParts.push(`${passedCount} passed`);
                
                const summaryText = summaryParts.length > 0 ? summaryParts.join(', ') : 'diversity issues';
                validationSummaryText.innerHTML = `<i class="fas fa-exclamation-triangle me-1"></i>Diversity rules: ${summaryText} (${rulesChecked} checked)`;
            }
        } else {
            validationSummary.style.display = 'none';
        }
    }
    
    // Never disable the submit button - always allow submission
    submitBtn.disabled = false;
}

function runDiversityValidationWithHistory(outBox) {
    if (!outBox || !FIGURE_UI || !Array.isArray(FIGURE_UI.diversityRules) || FIGURE_UI.diversityRules.length === 0) {
        outBox.style.display = 'none';
        const validationCard = document.getElementById('diversityValidationCard');
        if (validationCard) validationCard.style.display = 'none';
        return true;
    }

    // Get current run and heat info
    const runRadio = document.querySelector('[name="run_number"]:checked');
    const currentRun = runRadio ? parseInt(runRadio.value, 10) : 1;
    const heatSel = document.getElementById('heatSelect');
    const heatNum = heatSel ? parseInt(heatSel.value || '0', 10) : 0;
    const runsCount = Number(HEAT_RUNS_MAP?.[heatNum] ?? DEFAULT_RUNS_PER_HEAT ?? 3);
    const bestN = Number(FIGURE_UI?.attempts?.bestN || FIGURE_UI?.tricks?.bestN || 2);

    // Combine current selections with historical data
    const allRunsData = {}; // { run_number: { category: Set(items) } }
    
    // Add historical data
    Object.entries(figureHistoryByRun).forEach(([runNum, runData]) => {
        allRunsData[runNum] = runData;
    });
    
    console.log('Raw figureHistoryByRun:', figureHistoryByRun);
    console.log('All runs data from history:', allRunsData);
    
    // Add current run selections
    if (window.__FIGURE_SELECTIONS__ && Object.keys(window.__FIGURE_SELECTIONS__).length > 0) {
        allRunsData[currentRun] = window.__FIGURE_SELECTIONS__;
        console.log('Added current run selections for run', currentRun, ':', window.__FIGURE_SELECTIONS__);
    } else {
        console.log('No current selections found or empty object');
        console.log('window.__FIGURE_SELECTIONS__ exists:', !!window.__FIGURE_SELECTIONS__);
        console.log('Keys length:', Object.keys(window.__FIGURE_SELECTIONS__ || {}).length);
        // Initialize empty selections for current run
        allRunsData[currentRun] = {};
    }
    
    console.log('All runs data combined (for diversity validation):', allRunsData);
    console.log('Current run being processed:', currentRun);

    let msgs = [];
    let validationErrors = [];
    let validationWarnings = [];
    let validationPassed = [];
    let ok = true;
    const mode = FIGURE_UI.mode || '';

    // Build aggregate counts across all runs for diversity validation
    const aggregateCounts = {}; // { category: total_unique_items }
    const aggregateItems = {}; // { category: Set(all_items) }
    const runCounts = {}; // { run_number: { category: count } }
    
    Object.entries(allRunsData).forEach(([runNum, runData]) => {
        runCounts[runNum] = {};
        Object.entries(runData).forEach(([category, itemSet]) => {
            const count = itemSet ? itemSet.size : 0;
            runCounts[runNum][category] = count;
            
            // For aggregate, collect all unique items across runs
            if (!aggregateCounts[category]) {
                aggregateCounts[category] = new Set();
                aggregateItems[category] = new Set();
            }
            if (itemSet) {
                itemSet.forEach(item => {
                    aggregateCounts[category].add(item);
                    aggregateItems[category].add(item);
                });
            }
        });
    });
    
    // Convert aggregate sets to counts
    Object.keys(aggregateCounts).forEach(category => {
        aggregateCounts[category] = aggregateCounts[category].size;
    });

    // Evaluate diversity rules with historical context
    for (const r of FIGURE_UI.diversityRules) {
        const ruleType = r.rule_type || r.ruleType || '';
        const scope = r.scope || 'run';
        const group = r.group_name || r.group || '';
        const minDistinct = Number(r.min_distinct || 0);
        const isOptional = Boolean(r.is_optional);
        
        console.log('Processing diversity rule:', { ruleType, scope, group, minDistinct, isOptional });
        console.log('Rule object:', r);
        
        if (!group || minDistinct <= 0) continue;
        
        let currentCount = 0;
        let contextDesc = '';
        let selectedItems = [];
        let availableInCategory = [];
        
        // Get available items for this category to show suggestions
        if (FIGURE_DATA.itemsByCategory && FIGURE_DATA.itemsByCategory[group]) {
            availableInCategory = FIGURE_DATA.itemsByCategory[group];
        }
        
        // Handle different scope types with progressive validation logic
        if (scope === 'run' || scope === 'attempts' || scope === 'attempt') {
            // For attempts scope, show both current + historical for user context
            const currentSelections = window.__FIGURE_SELECTIONS__?.[group];
            let currentOnlyCount = currentSelections ? currentSelections.size : 0;
            const currentItems = currentSelections ? Array.from(currentSelections) : [];
            
            // Also check historical data for this category to show complete picture
            const historicalItems = new Set();
            Object.entries(figureHistoryByRun).forEach(([runNum, runData]) => {
                if (runNum < currentRun && runData[group]) {
                    console.log(`Historical data for group '${group}' in run ${runNum}:`, runData[group]);
                    runData[group].forEach(item => historicalItems.add(item));
                }
            });
            
            console.log(`Historical items for group '${group}':`, Array.from(historicalItems));
            
            // For display purposes, show total unique across all runs
            const allItems = new Set([...currentItems, ...Array.from(historicalItems)]);
            
            if (scope === 'attempts' && historicalItems.size > 0) {
                // Show combined count for attempts to give full context
                currentCount = allItems.size;
                selectedItems = Array.from(allItems);
                contextDesc = `Total across runs 1-${currentRun} (${historicalItems.size} historical + ${currentOnlyCount} current)`;
            } else {
                // Pure current run only
                currentCount = currentOnlyCount;
                selectedItems = currentItems;
                contextDesc = scope === 'attempts' || scope === 'attempt' ? `Current attempt (Run ${currentRun})` : `Run ${currentRun}`;
            }
            
            console.log(`Scope '${scope}' - group: ${group}, currentCount: ${currentCount}, selectedItems:`, selectedItems);
        } else if (scope === 'total' || scope === 'aggregate') {
            // Check across all runs INCLUDING current run
            const allUniqueItems = new Set();
            
            console.log(`Processing '${scope}' scope for group '${group}'`);
            
            // Add historical items from all previous runs
            Object.entries(figureHistoryByRun).forEach(([runNum, runData]) => {
                if (runData[group]) {
                    console.log(`Adding historical items from run ${runNum} for group '${group}':`, Array.from(runData[group]));
                    runData[group].forEach(item => allUniqueItems.add(item));
                }
            });
            
            // Add current run selections
            if (window.__FIGURE_SELECTIONS__?.[group]) {
                console.log(`Adding current run items for group '${group}':`, Array.from(window.__FIGURE_SELECTIONS__[group]));
                window.__FIGURE_SELECTIONS__[group].forEach(item => allUniqueItems.add(item));
            }
            
            currentCount = allUniqueItems.size;
            selectedItems = Array.from(allUniqueItems);
            contextDesc = `Total across all runs`;
            
            console.log(`Final '${scope}' scope results for group '${group}': count=${currentCount}, items:`, selectedItems);
        } else if (scope === 'bestN') {
            // Check best N runs (complex logic for best scoring runs)
            const relevantRuns = Object.keys(runCounts)
                .map(Number)
                .filter(runNum => runNum <= currentRun)
                .slice(-bestN); // Take last N runs as approximation
            
            const bestNSet = new Set();
            relevantRuns.forEach(runNum => {
                const runData = allRunsData[runNum];
                if (runData && runData[group]) {
                    runData[group].forEach(item => bestNSet.add(item));
                }
            });
            currentCount = bestNSet.size;
            selectedItems = Array.from(bestNSet);
            contextDesc = `Best ${bestN} runs`;
        } else {
            // Unknown scope - treat as 'total' to include all historical + current data
            console.warn(`Unknown scope '${scope}', treating as 'total'`);
            
            const allUniqueItems = new Set();
            
            // Add historical items from all previous runs
            Object.entries(figureHistoryByRun).forEach(([runNum, runData]) => {
                if (runData[group]) {
                    runData[group].forEach(item => allUniqueItems.add(item));
                }
            });
            
            // Add current run selections
            if (window.__FIGURE_SELECTIONS__?.[group]) {
                window.__FIGURE_SELECTIONS__[group].forEach(item => allUniqueItems.add(item));
            }
            
            currentCount = allUniqueItems.size;
            selectedItems = Array.from(allUniqueItems);
            contextDesc = `All runs (unknown scope: ${scope})`;
        }
        
        const status = currentCount >= minDistinct;
        const shortfall = Math.max(0, minDistinct - currentCount);
        const remainingRuns = runsCount - currentRun;
        const isLastRun = currentRun >= runsCount;
        
        // Progressive validation logic - modified to never block submission
        let validationLevel = 'passed';
        let allowSubmission = true;
        
        if (!status) {
            if (isLastRun || remainingRuns === 0) {
                // Final run - mark as error but still allow submission
                validationLevel = 'error';
                if (!isOptional) {
                    ok = false; // Track compliance for display/logging but don't block
                    allowSubmission = true; // Always allow submission
                }
            } else {
                // Earlier runs - warning but allow submission
                validationLevel = 'warning';
                allowSubmission = true;
                // Don't set ok = false for earlier runs
            }
        } else {
            validationLevel = 'success';
        }
        
        // Build detailed validation message
        let validationInfo = {
            group: group,
            ruleType: ruleType,
            scope: scope,
            contextDesc: contextDesc,
            status: status,
            validationLevel: validationLevel,
            isOptional: isOptional,
            currentCount: currentCount,
            minDistinct: minDistinct,
            shortfall: shortfall,
            selectedItems: selectedItems,
            availableItems: availableInCategory,
            remainingRuns: remainingRuns,
            isLastRun: isLastRun,
            runInfo: `Run ${currentRun} of ${runsCount}`,
            allowSubmission: allowSubmission
        };
        
        if (validationLevel === 'error') {
            validationErrors.push(validationInfo);
        } else if (validationLevel === 'warning') {
            validationWarnings.push(validationInfo);
        } else {
            validationPassed.push(validationInfo);
        }
    }

    // Build comprehensive validation display
    if (validationErrors.length > 0) {
        msgs.push(`
            <div class="alert alert-danger">
                <h6 class="alert-heading mb-2">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Diversity Requirements Not Met
                </h6>
                <div class="small mb-2">
                    ${validationErrors.some(info => info.isLastRun) ? 
                        'This is the final run. All diversity requirements must be satisfied before submission.' : 
                        'The following requirements must be satisfied before submission:'}
                </div>
        `);
        
        validationErrors.forEach(info => {
            const suggestions = info.availableItems.filter(item => !info.selectedItems.includes(item)).slice(0, 5);
            msgs.push(`
                <div class="border rounded p-2 mb-2 bg-light">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                        <strong class="text-danger">${info.group}</strong>
                        <span class="badge bg-danger">${info.currentCount}/${info.minDistinct}</span>
                    </div>
                    <div class="small text-muted mb-1">
                        ${info.contextDesc} • ${info.runInfo || `Run ${currentRun}`} • 
                        ${info.isLastRun ? 'FINAL RUN - Must meet requirement!' : 
                          info.remainingRuns ? `${info.remainingRuns} run(s) remaining` : 'Need ' + info.shortfall + ' more distinct items'}
                    </div>
                    ${info.selectedItems.length > 0 ? `
                        <div class="small mb-1">
                            <strong>Selected:</strong> ${info.selectedItems.join(', ')}
                        </div>
                    ` : '<div class="small mb-1 text-muted">No items selected yet</div>'}
                    ${suggestions.length > 0 ? `
                        <div class="small">
                            <strong>Suggestions:</strong> ${suggestions.join(', ')}${info.availableItems.length > 5 ? ` (+${info.availableItems.length - 5} more)` : ''}
                        </div>
                    ` : ''}
                </div>
            `);
        });
        
        msgs.push('</div>');
    }

    if (validationWarnings.length > 0) {
        msgs.push(`
            <div class="alert alert-warning">
                <h6 class="alert-heading mb-2">
                    <i class="fas fa-info-circle me-2"></i>
                    Optional Diversity Progress
                </h6>
                <div class="small mb-2">You can still submit, but consider meeting these requirements in remaining runs.</div>
        `);
        
        validationWarnings.forEach(info => {
            const suggestions = info.availableItems.filter(item => !info.selectedItems.includes(item)).slice(0, 3);
            msgs.push(`
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <div>
                        <strong>${info.group}</strong> <small class="text-muted">(${info.contextDesc})</small>
                        ${suggestions.length > 0 ? `<br><small class="text-muted">Try: ${suggestions.join(', ')}</small>` : ''}
                    </div>
                    <span class="badge bg-warning ">${info.currentCount}/${info.minDistinct}</span>
                </div>
            `);
        });
        
        msgs.push('</div>');
    }

    if (validationPassed.length > 0) {
        msgs.push(`
            <div class="alert alert-success">
                <h6 class="alert-heading mb-2">
                    <i class="fas fa-check-circle me-2"></i>
                    Diversity Requirements Satisfied
                </h6>
        `);
        
        validationPassed.forEach(info => {
            msgs.push(`
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <div>
                        <strong>${info.group}</strong> <small class="text-muted">(${info.contextDesc})</small>
                        ${info.selectedItems.length > 0 ? `<br><small class="text-success">Selected: ${info.selectedItems.slice(0, 5).join(', ')}${info.selectedItems.length > 5 ? ` (+${info.selectedItems.length - 5} more)` : ''}</small>` : ''}
                    </div>
                    <span class="badge bg-success">${info.currentCount}/${info.minDistinct} ✓</span>
                </div>
            `);
        });
        
        msgs.push('</div>');
    }

    // Show historical context
    if (Object.keys(figureHistoryByRun).length > 0) {
        const pastRuns = Object.keys(figureHistoryByRun).map(Number).sort();
        msgs.push(`
            <div class="alert alert-info">
                <div class="d-flex align-items-center mb-2">
                    <i class="fas fa-history me-2"></i>
                    <strong>Including Previous Runs: ${pastRuns.join(', ')}</strong>
                </div>
                <div class="small">
                    Validation includes figures selected in previous runs for this participant.
                    ${currentRun <= runsCount ? `Current: Run ${currentRun} of ${runsCount}` : ''}
                </div>
            </div>
        `);
    } else if (currentRun === 1) {
        msgs.push(`
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i>
                <strong>First Run:</strong> No previous figure history available. 
                Select figures according to diversity requirements for this run.
            </div>
        `);
    }

    // Overall validation status with progressive logic
    const isLastRun = currentRun >= runsCount;
    const remainingRuns = runsCount - currentRun;
    
    if (ok) {
        if (validationWarnings.length > 0) {
            msgs.unshift(`
                <div class="alert alert-success border-success">
                    <i class="fas fa-check-circle me-2"></i>
                    <strong>Ready to submit!</strong> All requirements met or can be completed in remaining runs.
                    ${!isLastRun ? `<div class="small mt-1">Run ${currentRun} of ${runsCount} • ${remainingRuns} run(s) remaining</div>` : ''}
                </div>
            `);
        } else {
            msgs.unshift(`
                <div class="alert alert-success border-success">
                    <i class="fas fa-shield-check me-2"></i>
                    <strong>All diversity requirements met!</strong> You can proceed with submission.
                    ${!isLastRun ? `<div class="small mt-1">Run ${currentRun} of ${runsCount} • Excellent progress!</div>` : ''}
                </div>
            `);
        }
    } else {
        msgs.unshift(`
            <div class="alert alert-danger border-danger">
                <i class="fas fa-shield-alt me-2"></i>
                <strong>${isLastRun ? 'Final run - Requirements must be met!' : 'Diversity validation failed!'}</strong> 
                ${isLastRun ? 'This is your last chance to meet all requirements.' : 'Please address the requirements below before submission.'}
                <div class="small mt-1">Run ${currentRun} of ${runsCount}</div>
            </div>
        `);
    }

    outBox.style.display = 'block';
    outBox.style.visibility = 'visible';
    outBox.style.opacity = '1';
    outBox.innerHTML = msgs.join('');
    
    // Force a DOM update/reflow
    outBox.offsetHeight;
    
    // Store detailed validation results for API usage
    window.__DIVERSITY_VALIDATION_DETAILS__ = {
        overallCompliant: ok,
        validationErrors: validationErrors,
        validationWarnings: validationWarnings,
        validationPassed: validationPassed,
        rulesChecked: FIGURE_UI.diversityRules.length,
        currentRun: currentRun,
        totalRuns: runsCount,
        timestamp: Date.now()
    };
    
    // Always return true to never block form submission
    // The validation state is stored in window.__DIVERSITY_VALIDATION_STATE__ for submission
    return true;
}

// Heat Flow API Integration
let heatFlowData = null;
let autoModeEnabled = true;
let manualOverride = false;
let heatFlowInterval = null;
let lastActiveHeat = null;
let lastActiveRun = null;

// Initialize heat flow monitoring
function initializeHeatFlow() {
    const eventId = <?= json_encode($event_id) ?>;
    if (!eventId) {
        console.log('No event ID available for heat flow monitoring');
        return;
    }
    
    // Load initial data
    loadHeatFlowData();
    
    // Set up auto-refresh every 5 seconds
    if (heatFlowInterval) clearInterval(heatFlowInterval);
    heatFlowInterval = setInterval(loadHeatFlowData, 5000);
    
    // Set up auto mode toggle
    const autoToggle = document.getElementById('autoModeToggle');
    if (autoToggle) {
        autoToggle.addEventListener('change', function() {
            autoModeEnabled = this.checked;
            updateAutoModeDisplay();
            
            if (autoModeEnabled && !manualOverride) {
                applyActiveHeatRun();
            }
        });
    }
}

async function loadHeatFlowData() {
    const eventId = <?= json_encode($event_id) ?>;
    if (!eventId) return;
    
    try {
        updateConnectionStatus('connecting');
        
        const response = await fetch(`../admin/heat_flow_api.php?event_id=${eventId}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        
        const data = await response.json();
        heatFlowData = data;
        
        updateConnectionStatus('connected');
        updateLastUpdateTime();
        
        // Process active heat data
        const activeHeat = findActiveHeat(data);
        if (activeHeat) {
            updateActiveHeatDisplay(activeHeat);
            
            // Auto-apply if enabled and no manual override
            if (autoModeEnabled && !manualOverride) {
                applyActiveHeatRun(activeHeat);
            }
        } else {
            clearActiveHeatDisplay();
        }
        
    } catch (error) {
        console.error('Error loading heat flow data:', error);
        updateConnectionStatus('error');
    }
}

function findActiveHeat(data) {
    if (!data.flow_chains) return null;
    
    for (const chain of data.flow_chains) {
        for (const heat of chain) {
            if (heat.is_active) {
                return heat;
            }
        }
    }
    return null;
}

function updateActiveHeatDisplay(activeHeat) {
    const infoDiv = document.getElementById('activeHeatInfo');
    const heatDisplay = document.getElementById('activeHeatDisplay');
    const heatName = document.getElementById('activeHeatName');
    const runDisplay = document.getElementById('activeRunDisplay');
    const progressDiv = document.getElementById('activeHeatProgress');
    const progressText = document.getElementById('progressText');
    const progressPercentage = document.getElementById('progressPercentage');
    const progressBar = document.getElementById('progressBar');
    
    // Check if required elements exist
    if (!infoDiv || !heatDisplay || !heatName || !runDisplay) {
        console.warn('Active heat display elements not found in DOM');
        return;
    }
    
    if (!activeHeat) {
        infoDiv.style.display = 'none';
        return;
    }
    
    // Update heat info
    heatDisplay.textContent = `Heat ${activeHeat.heat_number}`;
    heatName.textContent = activeHeat.heat_name || 'No name';
    runDisplay.textContent = `Run ${activeHeat.active_run || 1}`;
    
    // Update progress if available and progress elements exist
    if (activeHeat.progress && progressDiv && progressText && progressPercentage && progressBar) {
        const progress = activeHeat.progress;
        progressText.textContent = `${progress.completed_participants} / ${progress.total_participants}`;
        progressPercentage.textContent = `${progress.completion_percentage}%`;
        progressBar.style.width = `${progress.completion_percentage}%`;
        progressDiv.style.display = 'block';
    } else if (progressDiv) {
        progressDiv.style.display = 'none';
    }
    
    infoDiv.style.display = 'block';
    
    // Store for comparison
    lastActiveHeat = activeHeat.heat_number;
    lastActiveRun = activeHeat.active_run || 1;
}

function clearActiveHeatDisplay() {
    const infoDiv = document.getElementById('activeHeatInfo');
    if (infoDiv) {
        infoDiv.style.display = 'none';
    }
    lastActiveHeat = null;
    lastActiveRun = null;
}

function applyActiveHeatRun(activeHeat = null) {
    if (!autoModeEnabled || manualOverride) return;
    
    const heat = activeHeat || (heatFlowData ? findActiveHeat(heatFlowData) : null);
    if (!heat) return;
    
    const heatSelect = document.getElementById('heatSelect');
    const currentHeat = heatSelect.value;
    const currentRun = document.querySelector('[name=run_number]:checked')?.value;
    
    // Only update if different from current selection
    if (currentHeat != heat.heat_number || currentRun != (heat.active_run || 1)) {
        // Update heat selection
        heatSelect.value = heat.heat_number;
        
        // Update run selection
        const runInput = document.getElementById(`run${heat.active_run || 1}`);
        if (runInput) {
            runInput.checked = true;
        }
        
        // Load participants for the new selection
        loadParticipants();
        
        // Show auto indicator briefly
        showAutoModeIndicator();
    }
}

function handleHeatChange() {
    manualOverride = true;
    updateAutoModeDisplay();
    loadParticipants();
    saveHeatRunSelection();
}

function handleRunChange() {
    manualOverride = true;
    updateAutoModeDisplay();
    loadParticipants();
    saveHeatRunSelection();
    
    // Refresh figure history display when run changes
    if (currentParticipantId && FIGURE_DATA.available) {
        // Clear historical markings first
        document.querySelectorAll('.figure-chip.has-history').forEach(chip => {
            chip.classList.remove('has-history');
            // Restore original text
            const originalText = chip.getAttribute('data-original-text');
            if (originalText) {
                chip.textContent = originalText;
            }
            chip.removeAttribute('data-runs');
            chip.removeAttribute('data-run');
        });
        
        // Load existing figure selections for current score
        loadExistingFigureSelections();
        
        // Then update historical markings (with delay to ensure selections are loaded)
        setTimeout(() => {
            displayFigureHistory();
            updateDiversityValidationWithHistory();
        }, 100);
    }
}

function updateAutoModeDisplay() {
    const autoStatus = document.getElementById('autoModeStatus');
    const manualNotice = document.getElementById('manualOverrideNotice');
    const autoIndicator = document.getElementById('autoModeIndicator');
    
    // Only update elements that exist
    if (autoModeEnabled && !manualOverride) {
        if (autoStatus) autoStatus.style.display = 'block';
        if (manualNotice) manualNotice.style.display = 'none';
        if (autoIndicator) autoIndicator.style.display = 'inline-block';
    } else if (manualOverride) {
        if (autoStatus) autoStatus.style.display = 'none';
        if (manualNotice) manualNotice.style.display = 'block';
        if (autoIndicator) autoIndicator.style.display = 'none';
    } else {
        if (autoStatus) autoStatus.style.display = 'none';
        if (manualNotice) manualNotice.style.display = 'none';
        if (autoIndicator) autoIndicator.style.display = 'none';
    }
}

function showAutoModeIndicator() {
    const indicator = document.getElementById('autoModeIndicator');
    if (indicator) {
        indicator.style.display = 'inline-block';
        indicator.classList.add('pulse-animation');
        
        setTimeout(() => {
            if (indicator) {
                indicator.classList.remove('pulse-animation');
            }
        }, 2000);
    }
}

function updateConnectionStatus(status) {
    const statusText = document.getElementById('connectionStatus');
    const icon = document.getElementById('connectionIcon');
    
    // Check if elements exist before trying to update them
    if (!statusText || !icon) {
        console.warn('Connection status elements not found in DOM');
        return;
    }
    
    switch (status) {
        case 'connected':
            statusText.textContent = 'Connected';
            statusText.className = 'text-success';
            icon.className = 'fas fa-wifi text-success me-1';
            break;
        case 'connecting':
            statusText.textContent = 'Updating...';
            statusText.className = 'text-info';
            icon.className = 'fas fa-sync-alt fa-spin text-info me-1';
            break;
        case 'error':
            statusText.textContent = 'Connection Error';
            statusText.className = 'text-danger';
            icon.className = 'fas fa-wifi text-danger me-1';
            break;
        default:
            statusText.textContent = 'Unknown';
            statusText.className = 'text-muted';
            icon.className = 'fas fa-question text-muted me-1';
    }
}

function updateLastUpdateTime() {
    const timeElement = document.getElementById('lastUpdateTime');
    if (timeElement) {
        const now = new Date();
        timeElement.textContent = now.toLocaleTimeString();
    }
}

function forceRefreshHeatData() {
    // Reset manual override to allow auto selection
    manualOverride = false;
    updateAutoModeDisplay();
    
    // Force immediate refresh
    loadHeatFlowData();
    
    // Show feedback
    showToast('Refreshed', 'Heat data refreshed and auto mode restored', 'info');
}

// Enhanced loadParticipants function with heat flow integration
function loadParticipants() {
    const heat = document.querySelector('[name=heat_number]').value;
    const run = document.querySelector('[name=run_number]:checked')?.value;
    const target = document.querySelector('[name=ep_id]');
    const eventId = <?= json_encode($event_id) ?>;
    
    if (!heat || !eventId || !run) return;
    
    // Add loading state
    target.classList.add('loading');
    target.innerHTML = '<option disabled>Loading participants...</option>';
    
    fetch('get_participants.php?event_id=' + eventId + '&heat_number=' + heat + '&run_number=' + run)
        .then(res => res.json())
        .then(data => {
            target.classList.remove('loading');
            target.innerHTML = '<option disabled value="">-- Select Participant --</option>';
            data.forEach(p => {
                const lock = p.locked ? '🔒' : '✅';
                const option = document.createElement('option');
                option.value = p.ep_id;
                option.textContent = `${p.bib} ${p.first_name} ${p.last_name} (Heat ${p.heat_number}) ${lock}`;
                if (p.locked) option.disabled = true;
                target.appendChild(option);
            });
            
            // Auto-select first available option
            const firstAvailable = target.querySelector('option:not([disabled])');
            if (firstAvailable && firstAvailable.value) {
                firstAvailable.selected = true;
                loadOtherScoresForParticipant();
            }
            
            // Try to auto-select based on BIB on start from heat flow data
            if (heatFlowData && autoModeEnabled) {
                const activeHeat = findActiveHeat(heatFlowData);
                if (activeHeat && activeHeat.current_participant) {
                    const targetBip = activeHeat.current_participant.bib_number;
                    const options = target.querySelectorAll('option');
                    for (const option of options) {
                        if (option.textContent.startsWith(targetBip + ' ')) {
                            option.selected = true;
                            loadOtherScoresForParticipant();
                            break;
                        }
                    }
                }
            }
        })
        .catch(err => {
            target.classList.remove('loading');
            target.innerHTML = '<option disabled>Error loading participants</option>';
        });
        
    saveHeatRunSelection();
}

// Update the main DOMContentLoaded event listener
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Font Awesome to Lucide conversion on page load
    if (window.convertFontAwesomeToLucide) {
        window.convertFontAwesomeToLucide();
    }
    if (window.initializeLucideIcons) {
        window.initializeLucideIcons();
    }
    
    // Focus on BIB input when page loads
    document.getElementById('bibInput').focus();
    
    // Initialize figures card toggle state
    initializeFiguresCardState();
    
    // Initialize heat flow monitoring
    initializeHeatFlow();
    
    // Initialize Bootstrap tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Existing localStorage restoration code...
    const eventId = <?= json_encode($event_id) ?>;
    const stored = localStorage.getItem('event_' + eventId + '_heat_run');
    if (stored) {
        try {
            const obj = JSON.parse(stored);
            if (obj.heat) {
                const heatSelect = document.querySelector('[name=heat_number]');
                if (heatSelect) {
                    heatSelect.value = obj.heat;
                    manualOverride = true; // Mark as manual override
                }
            }
            if (obj.run) {
                const runRadio = document.getElementById('run' + obj.run);
                if (runRadio) {
                    runRadio.checked = true;
                    manualOverride = true; // Mark as manual override
                }
            }
            const heatRunBadge = document.getElementById('heatRunBadge');
            if (heatRunBadge) {
                heatRunBadge.style.display = 'inline-block';
                setTimeout(() => {
                    if (heatRunBadge) {
                        heatRunBadge.style.display = 'none';
                    }
                }, 3000);
            }
            
            updateAutoModeDisplay();
        } catch(e) {}
    }
    
    // Enhanced BIB input
    const bibInput = document.getElementById('bibInput');
    bibInput.addEventListener('input', function() {
        const bib = this.value;
        const options = document.querySelectorAll('[name=ep_id] option');
        options.forEach(opt => {
            if (opt.textContent.startsWith(bib + ' ')) {
                opt.selected = true;
                loadOtherScoresForParticipant();
            }
        });
    });
    
    // AJAX Score Form submission
    const scoreForm = document.getElementById('scoreForm');
    scoreForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Check diversity validation before submission if figures are available
        if (FIGURE_DATA?.available && FIGURE_UI?.diversityRules?.length > 0) {
            const validationBox = document.getElementById('diversityValidation');
            const isValid = runDiversityValidationWithHistory(validationBox);
            
            if (!isValid) {
                // Scroll to validation box to show errors
                validationBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
                
                // Show error toast
                showToast('Validation Failed', 'Please satisfy all diversity requirements before submitting.', 'error');
                
                // Highlight validation box with animation
                validationBox.style.border = '2px solid #dc3545';
                validationBox.style.boxShadow = '0 0 10px rgba(220, 53, 69, 0.3)';
                setTimeout(() => {
                    validationBox.style.border = '';
                    validationBox.style.boxShadow = '';
                }, 3000);
                
                return; // Stop submission
            }
        }
        
        const formData = new FormData(this);
        formData.append('ajax', '1'); // Add AJAX flag

        // Include figure selection if available
        try {
            if (FIGURE_DATA?.available) {
                // Legacy single selection (first active chip if any)
                const firstActive = document.querySelector('.figure-chip.active');
                const cat = firstActive?.dataset.cat || '';
                const item = firstActive?.dataset.item || '';
                formData.set('figure_category', cat);
                formData.set('figure_item', item);
                const hidCat = document.getElementById('figure_category_hidden');
                const hidItem = document.getElementById('figure_item_hidden');
                if (hidCat) hidCat.value = cat;
                if (hidItem) hidItem.value = item;
                
                // Full selection JSON (convert Set -> Array)
                const selections = window.__FIGURE_SELECTIONS__ || {};
                const serialized = {};
                for (const [k, v] of Object.entries(selections)) {
                    const arr = Array.isArray(v) ? v : Array.from(v || []);
                    if (arr.length > 0) serialized[k] = arr;
                }
                
                // Add validation status to figures_json for server-side checking
                const validationState = window.__DIVERSITY_VALIDATION_STATE__ || { isValid: true };
                const enrichedData = {
                    figures: serialized,
                    validation: {
                        diversity_valid: validationState.isValid,
                        validation_timestamp: validationState.timestamp || Date.now(),
                        run_number: validationState.currentRun || 1,
                        client_validated: true,
                        diversity_rules_checked: Array.isArray(FIGURE_UI?.diversityRules) ? FIGURE_UI.diversityRules.length : 0
                    }
                };
                
                const jsonSel = JSON.stringify(enrichedData);
                const hidJson = document.getElementById('figures_json_hidden');
                if (hidJson) hidJson.value = jsonSel;
                formData.set('figures_json', jsonSel);
            } else {
                // Even without figures, include validation metadata if diversity rules exist
                if (FIGURE_UI?.diversityRules && Array.isArray(FIGURE_UI.diversityRules) && FIGURE_UI.diversityRules.length > 0) {
                    const validationState = window.__DIVERSITY_VALIDATION_STATE__ || { isValid: true };
                    const validationOnlyData = {
                        figures: {},
                        validation: {
                            diversity_valid: validationState.isValid,
                            validation_timestamp: validationState.timestamp || Date.now(),
                            run_number: validationState.currentRun || 1,
                            client_validated: true,
                            diversity_rules_checked: FIGURE_UI.diversityRules.length,
                            no_figures_mode: true
                        }
                    };
                    const jsonSel = JSON.stringify(validationOnlyData);
                    formData.set('figures_json', jsonSel);
                }
            }
        } catch (_) { /* no-op */ }

        // Collect criteria scores if they exist
        try {
            const criteriaInputs = document.querySelectorAll('[name^="criteria_scores"][name$="[value]"]');
            if (criteriaInputs.length > 0) {
                const criteriaScores = {};
                criteriaInputs.forEach((input, index) => {
                    const value = parseFloat(input.value) || 0;
                    const typeInput = document.querySelector(`[name="criteria_scores[${index}][type]"]`);
                    const nameInput = document.querySelector(`[name="criteria_scores[${index}][name]"]`);
                    const sortInput = document.querySelector(`[name="criteria_scores[${index}][sort_order]"]`);
                    
                    if (typeInput && nameInput) {
                        criteriaScores[index] = {
                            value: value,
                            type: typeInput.value,
                            name: nameInput.value,
                            sort_order: parseInt(sortInput?.value || 0)
                        };
                    }
                });
                
                // Add criteria scores as JSON to form data
                formData.set('criteria_scores_json', JSON.stringify(criteriaScores));
                
                // Calculate and set final score as the main score
                const finalScore = calculateFinalScore();
                formData.set('score_value', finalScore.toFixed(2));
            }
        } catch (_) { /* no-op */ }
        
        const submitBtn = document.getElementById('submitBtn');
        const originalText = submitBtn.innerHTML;
        
        // Show loading state
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Submitting...';
        
        // Add success animation
        scoreForm.classList.add('score-submitted');
        
        // Submit via AJAX
        const requestData = Object.fromEntries(formData.entries());
        
        fetch(window.location.href, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Log the API call for debugging
            logApiCall('POST', window.location.href, requestData, data);
            
            if (data.success) {
                // Add new score to table
                addNewScoreToTable(data.score);
                
                // Clear the form
                clearScoreForm();
                
                // Close figures toggle/card after successful submission
                const figuresCardBody = document.getElementById('figuresCardBody');
                const figuresToggleIcon = document.getElementById('figuresToggleIcon');
                if (figuresCardBody && figuresToggleIcon) {                   
                    figuresToggleIcon.classList.add('collapsed');
                    figuresToggleIcon.style.transform = 'rotate(180deg)';
                }
                
                // Show success message
                showToast('Success!', data.message, 'success');
                loadParticipants();
            } else {
                throw new Error(data.message || 'Submission failed');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            
            // Log the API call error for debugging
            logApiCall('POST', window.location.href, requestData, { 
                error: error.message || 'Unknown error',
                status: 'error',
                timestamp: new Date().toISOString()
            });
            
            showToast('Error', error.message || 'Error submitting score. Please try again.', 'error');
        })
        .finally(() => {
            // Restore button state
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
            scoreForm.classList.remove('score-submitted');
        });
    });
    
    // Auto-focus score input when participant is selected
    const participantSelect = document.getElementById('ep_id');
    participantSelect.addEventListener('change', function() {
        if (this.value) {
            setTimeout(() => {
                document.querySelector('[name=score_value]').focus();
            }, 100);
            loadOtherScoresForParticipant();
            
            // Load figure history when participant changes
            if (FIGURE_DATA && FIGURE_DATA.available) {
                console.log('Loading figure history for participant:', this.value);
                
                // Clear current selections first
                if (window.__FIGURE_SELECTIONS__) {
                    console.log('Clearing current figure selections for new participant');
                    window.__FIGURE_SELECTIONS__ = {};
                    
                    // Clear UI state
                    document.querySelectorAll('.figure-chip.active, .figure-chip.has-history').forEach(chip => {
                        chip.classList.remove('active', 'has-history');
                        // Restore original text for history chips
                        const originalText = chip.getAttribute('data-original-text');
                        if (originalText) {
                            chip.textContent = originalText;
                        }
                        chip.removeAttribute('data-runs');
                        chip.removeAttribute('data-run');
                    });
                }
                
                // Load figure history first
                loadFigureHistoryForParticipant(this.value);
                
                // Then load existing figure selections for current score (with delay to ensure history is loaded)
                setTimeout(() => {
                    loadExistingFigureSelections();
                    
                    // Update validation and historical markings after both loads complete
                    setTimeout(() => {
                        displayFigureHistory();
                        updateDiversityValidationWithHistory();
                    }, 100);
                }, 300);
            }
        }
    });
    
    loadParticipants();
    startOtherScoresInterval();
    
    // Initialize figure data if participant is already selected on page load
    setTimeout(() => {
        const ep_id = document.getElementById('ep_id')?.value;
        const heat = document.querySelector('[name=heat_number]')?.value;
        
        if (ep_id && heat && FIGURE_DATA?.available) {
            console.log('Page loaded with existing participant selection, loading figure data...');
            currentParticipantId = ep_id;
            
            // Load figure history and existing selections
            loadFigureHistoryForParticipant(ep_id);
            
            setTimeout(() => {
                loadExistingFigureSelections();
                
                setTimeout(() => {
                    displayFigureHistory();
                    updateDiversityValidationWithHistory();
                }, 100);
            }, 300);
        } else if (FIGURE_DATA?.available) {
            // Still run initial diversity validation even without participant
            console.log('Running initial diversity validation...');
            updateDiversityValidationWithHistory();
        }
    }, 500);
});

       
// Handle status radio button changes
document.querySelectorAll('input[name="status"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const additionalCardsWrapper = document.getElementById('additionalCardsWrapper');
        
        if (this.checked && this.value !== 'OK') {
            const scoreInput = document.querySelector('.score-input');
            const rangeInput = document.querySelector('[name="score_range"]');
            
            scoreInput.value = 0;
            rangeInput.value = 0;
            
            // Hide additional cards wrapper when status is not OK
            if (additionalCardsWrapper) {
                additionalCardsWrapper.style.display = 'none';
            }
        } else if (this.checked && this.value === 'OK') {
            const scoreInput = document.querySelector('.score-input');
            const rangeInput = document.querySelector('[name="score_range"]');
            
            scoreInput.value = '';
            rangeInput.value = '';
            
            // Show additional cards wrapper when status is OK
            if (additionalCardsWrapper) {
                additionalCardsWrapper.style.display = 'block';
            }
        }
    });
});

// Figures UI wiring: toggle chips per category + diversity validation
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded, checking figure UI...');
    console.log('FIGURE_DATA.available:', FIGURE_DATA?.available);
    
    if (!FIGURE_DATA.available) {
        console.log('Figures not available, skipping UI setup');
        return;
    }
    
    window.__FIGURE_SELECTIONS__ = {}; // { category: Set(items) }
    console.log('Initialized figure selections:', window.__FIGURE_SELECTIONS__);

    const grid = document.getElementById('figureToggleGrid');
    const box = document.getElementById('diversityValidation');
    
    console.log('Grid element found:', grid);
    console.log('Validation box found:', box);
    
    if (!grid) {
        console.error('figureToggleGrid element not found!');
        return;
    }

    if (grid) {
        // Check if any chips exist
        const chips = grid.querySelectorAll('.figure-chip');
        console.log('Found', chips.length, 'figure chips');
        chips.forEach((chip, index) => {
            if (index < 3) { // Log first 3 for debugging
                console.log(`Chip ${index}:`, chip, 'data-cat:', chip.dataset.cat, 'data-item:', chip.dataset.item);
            }
        });
        
        // Add event listener to the grid with proper event delegation
        grid.addEventListener('click', (e) => {
            // Try direct click and closest() to catch the chip
            let chip = null;
            if (e.target.classList.contains('figure-chip')) {
                chip = e.target;
            } else {
                chip = e.target.closest('.figure-chip');
            }
            
            if (chip) {
                const c = chip.dataset.cat;
                const it = chip.dataset.item;
                
                if (!c || !it) {
                    console.warn('Missing category or item data:', { cat: c, item: it });
                    return;
                }
                
                if (!window.__FIGURE_SELECTIONS__[c]) {
                    window.__FIGURE_SELECTIONS__[c] = new Set();
                }
                
                if (chip.classList.contains('active')) {
                    chip.classList.remove('active');
                    window.__FIGURE_SELECTIONS__[c].delete(it);
                    
                    // Keep run indicator text visible after deselection
                    if (chip.classList.contains('has-history')) {
                        const originalText = chip.getAttribute('data-original-text');
                        const runIndicator = chip.getAttribute('data-run');
                        if (originalText && runIndicator) {
                            chip.innerHTML = `${originalText} <small class="text-muted">(${runIndicator})</small>`;
                        }
                    }
                } else {
                    chip.classList.add('active');
                    window.__FIGURE_SELECTIONS__[c].add(it);
                    
                    // Keep run indicator visible even when active
                    if (chip.classList.contains('has-history')) {
                        const originalText = chip.getAttribute('data-original-text');
                        const runIndicator = chip.getAttribute('data-run');
                        if (originalText && runIndicator) {
                            chip.innerHTML = `${originalText} <small class="text-muted">(${runIndicator})</small>`;
                        }
                    }
                }
                
                // Update diversity validation with historical context
                updateDiversityValidationWithHistory();
                return; // Prevent further processing
            }
            
            // Handle clear button
            let clearBtn = null;
            if (e.target.classList.contains('clear-cat')) {
                clearBtn = e.target;
            } else {
                clearBtn = e.target.closest('.clear-cat');
            }
            
            if (clearBtn) {
                const cat = clearBtn.dataset.cat;
                
                if (!cat) {
                    console.warn('Missing category data for clear button');
                    return;
                }
                
                // Only clear active selections, not historical ones
                grid.querySelectorAll(`.figure-chip[data-cat="${CSS.escape(cat)}"].active`).forEach(b => b.classList.remove('active'));
                if (window.__FIGURE_SELECTIONS__[cat]) {
                    window.__FIGURE_SELECTIONS__[cat].clear();
                }
                
                updateDiversityValidationWithHistory();
            }
        });
        
        // Also add direct event listeners to chips as backup
        chips.forEach(chip => {
            chip.addEventListener('click', function(e) {
                console.log('Direct chip click listener triggered for:', this);
                // The main handler above should catch this, but if not, this is a backup
            });
        });
    }

    function runDiversityValidation(outBox) {
        // Use the enhanced version with history
        return runDiversityValidationWithHistory(outBox);
    }

    // Initial validation render
    console.log('Running initial diversity validation...');
    runDiversityValidation(box);
    console.log('Initial diversity validation completed');
});

// API function to check diversity rules server-side
async function checkDiversityRulesAPI(ep_id, judge_id, event_id, heat_number = null) {
    try {
        const params = new URLSearchParams({
            ep_id: ep_id,
            judge_id: judge_id,
            event_id: event_id
        });
        
        if (heat_number) {
            params.append('heat_number', heat_number);
        }
        
        const response = await fetch(`../api/check_diversity_rules.php?${params}`);
        
        if (!response.ok) {
            throw new Error(`API request failed: ${response.status}`);
        }
        
        const result = await response.json();
        
        console.log('Diversity rules API result:', result);
        return result;
        
    } catch (error) {
        console.error('Error checking diversity rules via API:', error);
        return {
            error: error.message,
            compliance: null
        };
    }
}

// Helper function to run API check for current participant
async function checkCurrentParticipantDiversity() {
    const ep_id = document.getElementById('ep_id')?.value;
    const heat_number = document.querySelector('[name="heat_number"]')?.value;
    const event_id = <?= json_encode($event_id) ?>;
    const judge_id = <?= json_encode($judge_id) ?>;
    
    if (!ep_id || !event_id || !judge_id) {
        console.log('Missing required data for diversity check');
        return null;
    }
    
    console.log('Checking diversity rules for participant:', ep_id);
    const result = await checkDiversityRulesAPI(ep_id, judge_id, event_id, heat_number);
    
    if (result.error) {
        console.error('API error:', result.error);
    } else {
        console.log('Diversity compliance result:', result.compliance);
        console.log('Rules checked:', result.rules_checked);
        if (result.failed_rules) {
            console.log('Failed rules:', result.failed_rules);
        }
    }
    
    return result;
}

// Add button to manually trigger API check (for testing)
document.addEventListener('DOMContentLoaded', function() {
    const testButton = document.createElement('button');
    testButton.type = 'button';
    testButton.className = 'btn btn-outline-info btn-sm';
    testButton.innerHTML = '<i class="fas fa-check-circle me-1"></i>Test API Check';
    testButton.onclick = checkCurrentParticipantDiversity;
    testButton.title = 'Test server-side diversity rules checking (check console for results)';
    
    // Add to the reset scores area
    const resetArea = document.querySelector('.text-center.mb-3.mt-4');
    if (resetArea) {
        resetArea.appendChild(document.createTextNode(' '));
        resetArea.appendChild(testButton);
    }
});

// Judge Overview Modal Functions
async function loadJudgeOverview() {
    const eventId = <?= json_encode($event_id) ?>;
    const judgeId = <?= json_encode($judge_id) ?>;
    const content = document.getElementById('judgeOverviewContent');
    
    if (!eventId || !judgeId) {
        content.innerHTML = '<div class="alert alert-warning">No event or judge selected</div>';
        return;
    }
    
    try {
        const response = await fetch(`ajax_judge_overview.php?event_id=${eventId}&judge_id=${judgeId}`);
        if (!response.ok) throw new Error('Failed to load overview');
        
        const data = await response.json();
        
        if (data.error) {
            content.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
            return;
        }
        
        // Group scores by participant
        const participantGroups = {};
        data.scores.forEach(score => {
            const key = `${score.participant_name}_${score.bib_number}`;
            if (!participantGroups[key]) {
                participantGroups[key] = {
                    participant_name: score.participant_name,
                    bib_number: score.bib_number,
                    heat_number: score.heat_number,
                    scores: []
                };
            }
            participantGroups[key].scores.push(score);
        });
        
        // Build HTML
        let html = `
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="border-0 shadow-none card">
                        <div class="border-0 shadow-none card-body text-center">
                            <h4 class="card-title text-primary">${data.summary.total_scores}</h4>
                            <p class="card-text">Total Scores</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="border-0 shadow-none card">
                        <div class="border-0 shadow-none card-body text-center">
                            <h4 class="card-title text-success">${data.summary.average_score}</h4>
                            <p class="card-text">Average Score</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Add participant groups
        Object.values(participantGroups).forEach(group => {
            const sortedScores = group.scores.sort((a, b) => a.run_number - b.run_number);
            
            html += `
                <div class="border-0 shadow-none card mb-3">
                    <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                        <div>
                            <strong>${group.participant_name}</strong>
                            <span class="badge bg-secondary ms-2">BIB ${group.bib_number}</span>
                            <span class="badge bg-info ms-1">Heat ${group.heat_number}</span>
                        </div>
                        <div>
                            <span class="text-muted">${sortedScores.length} run${sortedScores.length !== 1 ? 's' : ''}</span>
                        </div>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Run</th>
                                        <th>Score</th>
                                        <th>Status</th>
                                        <th>Time</th>
                                        <th>Figures</th>
                                    </tr>
                                </thead>
                                <tbody>
            `;
            
            sortedScores.forEach(score => {
                const figures = score.figures_json ? 
                    (typeof score.figures_json === 'string' ? 
                        JSON.parse(score.figures_json) : score.figures_json) : null;
                
                let figuresDisplay = '—';
                if (figures && figures.figures) {
                    const figureList = Object.entries(figures.figures).map(([cat, items]) => 
                        `${cat}: ${Array.isArray(items) ? items.join(', ') : items}`
                    ).join('<br>');
                    figuresDisplay = figureList || '—';
                }
                
                const statusBadge = score.status === 'OK' ? 'success' : 
                    (score.status === 'DSQ' ? 'danger' : 'warning');
                
                html += `
                    <tr>
                        <td><span class="badge bg-primary">Run ${score.run_number}</span></td>
                        <td><strong class="text-primary">${score.score_value}</strong></td>
                        <td><span class="badge bg-${statusBadge}">${score.status}</span></td>
                        <td><small class="text-muted">${new Date(score.created_at).toLocaleTimeString()}</small></td>
                        <td><small>${figuresDisplay}</small></td>
                    </tr>
                `;
            });
            
            html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            `;
        });
        
        if (Object.keys(participantGroups).length === 0) {
            html += '<div class="alert alert-info">No scores recorded yet.</div>';
        }
        
        content.innerHTML = html;
        
    } catch (error) {
        console.error('Error loading judge overview:', error);
        content.innerHTML = `<div class="alert alert-danger">Error loading overview: ${error.message}</div>`;
    }
}

async function loadEventSummary() {
    const eventId = <?= json_encode($event_id) ?>;
    const content = document.getElementById('eventSummaryContent');
    
    if (!eventId) {
        content.innerHTML = '<div class="alert alert-warning">No event selected</div>';
        return;
    }
    
    const summaryType = document.querySelector('input[name="summaryType"]:checked')?.value || 'final';
    const displayFormat = document.querySelector('input[name="displayFormat"]:checked')?.value || 'table';
    
    try {
        const response = await fetch(`ajax_event_summary.php?event_id=${eventId}&type=${summaryType}&format=${displayFormat}`);
        if (!response.ok) throw new Error('Failed to load summary');
        
        const data = await response.json();
        
        if (data.error) {
            content.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
            return;
        }
        
        let html = '';
        
        if (summaryType === 'final') {
            // Final results table
            html = `
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead class="table-dark">
                            <tr>
                                <th>Rank</th>
                                <th>BIB</th>
                                <th>Participant</th>
                                <th>Heat</th>
                                <th>Best Score</th>
                                <th>Average</th>
                                <th>Runs</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            data.results.forEach((result, index) => {
                const rankBadge = index < 3 ? 
                    ['bg-warning', 'bg-secondary', 'bg-warning'][index] : 'bg-light text-dark';
                
                html += `
                    <tr>
                        <td><span class="badge ${rankBadge}">${index + 1}</span></td>
                        <td><span class="badge bg-secondary">${result.bib_number}</span></td>
                        <td><strong>${result.participant_name}</strong></td>
                        <td>Heat ${result.heat_number}</td>
                        <td><strong class="text-success">${result.best_score}</strong></td>
                        <td>${result.average_score}</td>
                        <td>${result.completed_runs}/${result.total_runs}</td>
                    </tr>
                `;
            });
            
            html += '</tbody></table></div>';
        } else {
            // Other summary types
            html = `<div class="alert alert-info">Summary type "${summaryType}" coming soon...</div>`;
        }
        
        content.innerHTML = html;
        
    } catch (error) {
        console.error('Error loading event summary:', error);
        content.innerHTML = `<div class="alert alert-danger">Error loading summary: ${error.message}</div>`;
    }
}

function refreshJudgeOverview() {
    const judgeOverviewContent = document.getElementById('judgeOverviewContent');
    if (!judgeOverviewContent) return;
    
    judgeOverviewContent.innerHTML = `
        <div class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <div class="mt-2">Refreshing your scores...</div>
        </div>
    `;
    loadJudgeOverview();
}

function refreshEventSummary() {
    const eventSummaryContent = document.getElementById('eventSummaryContent');
    if (!eventSummaryContent) return;
    
    eventSummaryContent.innerHTML = `
        <div class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <div class="mt-2">Refreshing event results...</div>
        </div>
    `;
    loadEventSummary();
}

function exportSummary() {
    const eventId = <?= json_encode($event_id) ?>;
    const summaryType = document.querySelector('input[name="summaryType"]:checked')?.value || 'final';
    
    if (!eventId) {
        alert('No event selected for export');
        return;
    }
    
    // Open export in new window
    window.open(`export_summary.php?event_id=${eventId}&type=${summaryType}`, '_blank');
}

// Figures card toggle functionality
function toggleFiguresCard() {
    const cardBody = document.getElementById('figuresCardBody');
    const toggleIcon = document.getElementById('figuresToggleIcon');
    
    if (cardBody && toggleIcon) {
        const isCollapsed = cardBody.classList.contains('collapsed');
        
        if (isCollapsed) {
            // Expand the card
            cardBody.classList.remove('collapsed');
            toggleIcon.classList.remove('collapsed');
            toggleIcon.className = 'fas fa-chevron-up toggle-icon';
            
            // Store state in localStorage
            localStorage.setItem('figuresCardCollapsed', 'false');
        } else {
            // Collapse the card
            cardBody.classList.add('collapsed');
            toggleIcon.classList.add('collapsed');
            toggleIcon.className = 'fas fa-chevron-down toggle-icon collapsed';
            
            // Store state in localStorage
            localStorage.setItem('figuresCardCollapsed', 'true');
        }
    }
}

// Initialize figures card state on page load
function initializeFiguresCardState() {
    const cardBody = document.getElementById('figuresCardBody');
    const toggleIcon = document.getElementById('figuresToggleIcon');
    
    if (cardBody && toggleIcon) {
        // Check localStorage for saved state
        const isCollapsed = localStorage.getItem('figuresCardCollapsed') === 'true';
        
        if (isCollapsed) {
            cardBody.classList.add('collapsed');
            toggleIcon.classList.add('collapsed');
            toggleIcon.className = 'fas fa-chevron-down toggle-icon collapsed';
        } else {
            cardBody.classList.remove('collapsed');
            toggleIcon.classList.remove('collapsed');
            toggleIcon.className = 'fas fa-chevron-up toggle-icon';
        }
    }
}

// Global functions for edit modal figure selection (referenced in onclick handlers)
function toggleEditFigureChip(button, category, item) {
    if (!window.__EDIT_FIGURE_SELECTIONS__[category]) {
        window.__EDIT_FIGURE_SELECTIONS__[category] = new Set();
    }
    
    const isActive = button.classList.contains('active');
    
    if (isActive) {
        // Remove selection
        button.classList.remove('active');
        window.__EDIT_FIGURE_SELECTIONS__[category].delete(item);
        
        // Remove category if empty
        if (window.__EDIT_FIGURE_SELECTIONS__[category].size === 0) {
            delete window.__EDIT_FIGURE_SELECTIONS__[category];
        }
    } else {
        // Add selection
        button.classList.add('active');
        window.__EDIT_FIGURE_SELECTIONS__[category].add(item);
    }
    
    updateEditFiguresJson();
    updateEditFigureSummary();
    
    console.log('Updated edit figure selections:', window.__EDIT_FIGURE_SELECTIONS__);
}

function clearEditFigureCategory(category) {
    // Remove from selections
    delete window.__EDIT_FIGURE_SELECTIONS__[category];
    
    // Update UI
    document.querySelectorAll(`#editFigureGrid .figure-chip[data-cat="${category}"]`).forEach(chip => {
        chip.classList.remove('active');
    });
    
    updateEditFiguresJson();
    updateEditFigureSummary();
    
    console.log('Cleared edit figure category:', category);
}

// Modal event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Load content when modals are shown
    document.getElementById('judgeOverviewModal').addEventListener('shown.bs.modal', loadJudgeOverview);
    document.getElementById('eventSummaryModal').addEventListener('shown.bs.modal', loadEventSummary);
    
    // Refresh summary when options change
    document.querySelectorAll('input[name="summaryType"], input[name="displayFormat"]').forEach(input => {
        input.addEventListener('change', loadEventSummary);
    });
});

// Debug functionality - Global scope for onclick handlers
let apiCallLog = [];

function toggleDebugSection() {
    const debugSection = document.getElementById('debugSection');
    if (debugSection.style.display === 'none') {
        debugSection.style.display = 'block';
        refreshIncomingData();
    } else {
        debugSection.style.display = 'none';
    }
}

function refreshIncomingData() {
    const content = document.getElementById('incomingDataContent');
    
    // Gather all incoming data
    const incomingData = {
        event_info: {
            event_id: '<?= $event_id ?? "Not set" ?>',
            event_name: '<?= htmlspecialchars($assigned_events[0]['name'] ?? 'No Event') ?>',
            event_date: '<?= $event_date ?? "Not set" ?>'
        },
        judge_info: {
            judge_id: '<?= $judge_id ?? "Not set" ?>',
            judge_name: '<?= htmlspecialchars($judge_name ?? 'Not set') ?>',
            user_type: '<?= $_SESSION['user_type'] ?? "Not set" ?>'
        },
        participant_info: {
            participant_id: document.getElementById('participant_id')?.value || 'Not selected',
            run_number: document.getElementById('run_number')?.value || 'Not set',
            heat_number: document.getElementById('heat_number')?.value || 'Not set',
            bib_number: document.querySelector('input[name="bib_number"]')?.value || 'Not set'
        },
        form_data: {
            total_score: document.getElementById('totalScore')?.textContent || 'Not calculated',
                    execution_score: document.getElementById('executionScore')?.textContent || '0',
                penalty_total: document.getElementById('penaltyTotal')?.textContent || '0',
                selected_figures: Array.from(document.querySelectorAll('input[name="figures[]"]:checked')).map(cb => ({
                    figure_id: cb.value,
                    figure_name: cb.closest('.figure-card')?.querySelector('.figure-name')?.textContent || 'Unknown'
                }))
            },
            current_status: {
                manual_mode: <?= $manual_mode ? 'true' : 'false' ?>,
                is_mobile: window.innerWidth <= 768,
                form_valid: document.getElementById('scoreForm')?.checkValidity() || false,
                timestamp: new Date().toISOString()
            }
        };
        
        content.innerHTML = '<pre>' + JSON.stringify(incomingData, null, 2) + '</pre>';
    }
    
    function logApiCall(method, url, data, response) {
        const logEntry = {
            timestamp: new Date().toISOString(),
            method: method,
            url: url,
            request_data: data,
            response: response,
            status: response?.status || 'Unknown'
        };
        
        apiCallLog.unshift(logEntry); // Add to beginning
        
        // Keep only last 10 entries
        if (apiCallLog.length > 10) {
            apiCallLog = apiCallLog.slice(0, 10);
        }
        
        updateApiCallsDisplay();
    }
    
    function updateApiCallsDisplay() {
        const content = document.getElementById('apiCallsContent');
        if (apiCallLog.length === 0) {
            content.innerHTML = 'No API calls yet...';
            return;
        }
        
        let html = '';
        apiCallLog.forEach((call, index) => {
            const statusColor = call.status >= 200 && call.status < 300 ? 'text-success' : 'text-danger';
            html += `
                <div class="border-bottom pb-2 mb-2">
                    <div class="d-flex justify-content-between">
                        <strong class="${statusColor}">${call.method} ${call.url}</strong>
                        <small class="text-muted">${new Date(call.timestamp).toLocaleTimeString()}</small>
                    </div>
                    <div class="mt-1">
                        <small><strong>Request:</strong></small>
                        <pre class="small mt-1 p-1 bg-light">${JSON.stringify(call.request_data, null, 1)}</pre>
                        <small><strong>Response:</strong></small>
                        <pre class="small mt-1 p-1 bg-light">${JSON.stringify(call.response, null, 1)}</pre>
                    </div>
                </div>
            `;
        });
        content.innerHTML = html;
    }
    
    function clearApiLog() {
        apiCallLog = [];
        updateApiCallsDisplay();
    }
    
    // Initialize debug data when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        refreshIncomingData();
        
        // Refresh incoming data periodically
        setInterval(refreshIncomingData, 5000);
    });
    </script>

        <?php include '../admin/footer.php'; ?>
            <!-- StyleScore JavaScript includes -->
    <?php include_once __DIR__ . '/../includes/scripts.php'; ?>

    <!-- Dashboard specific JavaScript -->
    <script>
        // Dashboard initialization
        document.addEventListener('DOMContentLoaded', function() {
            // Any dashboard-specific initialization can go here
            console.log('StyleScore Dashboard loaded successfully');
        });
    </script>

</body>
</html>