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

// Generate sample data for any header type
function generateSampleDataForHeader($header, $rowIndex = 1) {
    $header = strtolower($header);
    
    // Basic information
    if ($header === 'rank') {
        return $rowIndex;
    }
    
    if ($header === 'bib') {
        return 1000 + ($rowIndex * 11);
    }
    
    if ($header === 'name') {
        $names = [
            'Alex Johnson', 'Sarah Chen', 'Marcus Rodriguez', 'Emma Thompson',
            'Jake Williams', 'Sofia Martinez', 'Ryan O\'Connor', 'Mia Davis',
            'Lucas Anderson', 'Zoe Kim', 'Noah Wilson', 'Ava Brown'
        ];
        return $names[($rowIndex - 1) % count($names)];
    }
    
    // Battle format
    if (strpos($header, 'battle') !== false) {
        return "Battle " . $rowIndex;
    }
    
    if (strpos($header, 'bboy') !== false || strpos($header, 'bgirl') !== false) {
        if (strpos($header, 'a') !== false) return "Breaker A";
        if (strpos($header, 'b') !== false) return "Breaker B";
    }
    
    if ($header === 'winner') {
        return rand(0, 1) ? 'A' : 'B';
    }
    
    // Run scores
    if (strpos($header, 'run') !== false) {
        if (strpos($header, '1') !== false) return number_format(rand(600, 850) / 10, 1);
        if (strpos($header, '2') !== false) return number_format(rand(650, 900) / 10, 1);
        if (strpos($header, '3') !== false) return number_format(rand(700, 950) / 10, 1);
        return number_format(rand(600, 900) / 10, 1);
    }
    
    // Wave/Jump/Trick scores
    if (strpos($header, 'wave') !== false || strpos($header, 'jump') !== false || strpos($header, 'trick') !== false) {
        return number_format(rand(50, 95) / 10, 1);
    }
    
    // Best scores (usually higher)
    if (strpos($header, 'best') !== false) {
        if (strpos($header, 'two') !== false || strpos($header, '2') !== false) {
            return number_format(rand(1600, 1900) / 10, 1);
        }
        if (strpos($header, 'three') !== false || strpos($header, '3') !== false) {
            return number_format(rand(2400, 2850) / 10, 1);
        }
        return number_format(rand(800, 950) / 10, 1);
    }
    
    // Average scores
    if (strpos($header, 'average') !== false) {
        return number_format(rand(700, 850) / 10, 1);
    }
    
    // Total scores
    if (strpos($header, 'total') !== false) {
        if (strpos($header, '/20') !== false) {
            return number_format(rand(140, 190) / 10, 1) . '/20';
        }
        return number_format(rand(1500, 1900) / 10, 1);
    }
    
    // Section scores
    if (strpos($header, 'section') !== false) {
        if (strpos($header, '(σ)') !== false || strpos($header, 'sum') !== false) {
            return number_format(rand(450, 550) / 10, 1);
        }
        return number_format(rand(70, 95) / 10, 1);
    }
    
    // Overall Impression
    if (strpos($header, 'oi') !== false || strpos($header, 'overall') !== false) {
        return number_format(rand(350, 450) / 10, 1);
    }
    
    // Parkour E&D scores
    if (strpos($header, 'e total') !== false || $header === 'e') {
        return number_format(rand(100, 150) / 10, 1);
    }
    
    if (strpos($header, 'd') !== false && (strpos($header, '1') !== false || strpos($header, '2') !== false || strpos($header, '3') !== false)) {
        return number_format(rand(80, 120) / 10, 1);
    }
    
    // Deductions
    if (strpos($header, 'ded') !== false || strpos($header, 'deduction') !== false) {
        return '-' . number_format(rand(0, 30) / 10, 1);
    }
    
    // Final scores
    if ($header === 'final') {
        return number_format(rand(1200, 1600) / 10, 1);
    }
    
    // Breaking criteria (win/loss)
    if (in_array($header, ['technique', 'vocabulary', 'originality', 'execution', 'musicality'])) {
        return rand(0, 1) ? 'W' : 'L';
    }
    
    // Attempts (for big air, etc.)
    if (strpos($header, 'attempt') !== false) {
        return number_format(rand(600, 900) / 10, 1);
    }
    
    // Default numeric score
    return number_format(rand(600, 900) / 10, 1);
}

// Convert drop rule key to human-readable name
function getDropRuleName($dropRule) {
    $dropRuleNames = [
        'none' => 'None',
        'highest' => 'Drop Highest',
        'lowest' => 'Drop Lowest', 
        'highest_and_lowest' => 'Drop High/Low',
        'median' => 'Median Score',
        'drop high/low' => 'Drop High/Low',
        'drop high/low per wave' => 'Drop High/Low per Wave',
        'drop high/low per trick' => 'Drop High/Low per Trick',
        'components' => 'Components',
        'n/a' => 'N/A'
    ];
    
    return $dropRuleNames[$dropRule] ?? ucfirst(str_replace('_', ' ', $dropRule));
}

$formatId = $_GET['id'] ?? '';
if (empty($formatId)) {
    header('Location: scoring_formats.php');
    exit;
}

// Load format details with sport icon
$format = $pdo->prepare("
    SELECT sf.*, 
           sfj.min_judges, sfj.max_judges, sfj.scale_min, sfj.scale_max, 
           sfj.scale_type, sfj.scale_custom, sfj.precision_decimal, sfj.drop_rule,
           fsd.icon_path, fsd.slug
    FROM scoring_formats sf
    LEFT JOIN scoring_format_judges sfj ON sf.format_id = sfj.format_id
    LEFT JOIN figure_sports fs ON LOWER(sf.sport) = LOWER(fs.sport_name)
    LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
    WHERE sf.format_id = ?
");
$format->execute([$formatId]);
$format = $format->fetch(PDO::FETCH_ASSOC);

if (!$format) {
    header('Location: scoring_formats.php');
    exit;
}

// Load mode configuration
$modeConfig = $pdo->prepare("
    SELECT config_type, config_key, config_value
    FROM scoring_format_mode_config
    WHERE format_id = ?
    ORDER BY config_type, config_key
");
$modeConfig->execute([$formatId]);
$modeConfigs = [];
foreach ($modeConfig->fetchAll(PDO::FETCH_ASSOC) as $config) {
    $modeConfigs[$config['config_type']][$config['config_key']] = $config['config_value'];
}

// Load rounds
$rounds = $pdo->prepare("
    SELECT round_name, runs, aggregation
    FROM scoring_format_rounds
    WHERE format_id = ?
    ORDER BY round_name
");
$rounds->execute([$formatId]);
$rounds = $rounds->fetchAll(PDO::FETCH_ASSOC);

// Load criteria
$criteria = $pdo->prepare("
    SELECT criteria_type, criteria_name, sort_order
    FROM scoring_format_criteria
    WHERE format_id = ?
    ORDER BY criteria_type, sort_order
");
$criteria->execute([$formatId]);
$criteriaByType = [];
foreach ($criteria->fetchAll(PDO::FETCH_ASSOC) as $criterion) {
    $criteriaByType[$criterion['criteria_type']][] = $criterion['criteria_name'];
}

// Load results headers
$results = $pdo->prepare("
    SELECT header_name
    FROM scoring_format_results
    WHERE format_id = ?
    ORDER BY sort_order
");
$results->execute([$formatId]);
$resultHeaders = array_column($results->fetchAll(PDO::FETCH_ASSOC), 'header_name');

// Load flow stages
$flow = $pdo->prepare("
    SELECT flow_stage
    FROM scoring_format_flow
    WHERE format_id = ?
    ORDER BY sort_order
");
$flow->execute([$formatId]);
$flowStages = array_column($flow->fetchAll(PDO::FETCH_ASSOC), 'flow_stage');

// Load tiebreak rules
$tiebreak = $pdo->prepare("
    SELECT tiebreak_rule
    FROM scoring_format_tiebreak
    WHERE format_id = ?
    ORDER BY sort_order
");
$tiebreak->execute([$formatId]);
$tiebreakRules = array_column($tiebreak->fetchAll(PDO::FETCH_ASSOC), 'tiebreak_rule');

// Load diversity rules (with error handling)
$diversityRules = [];
try {
    $diversityQuery = $pdo->prepare("
        SELECT rule_type, scope, group_name, min_distinct, is_optional
        FROM scoring_format_diversity_rules
        WHERE format_id = ?
        ORDER BY rule_type, group_name
    ");
    $diversityQuery->execute([$formatId]);
    $diversityRules = $diversityQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // If no diversity rules exist for testing, create some sample ones
    if (empty($diversityRules) && $formatId === 'snowboard_slopestyle_sections_oi') {
        $sampleRules = [
            [
                'format_id' => $formatId,
                'rule_type' => 'figure_variety',
                'scope' => 'run',
                'group_name' => 'Grabs',
                'min_distinct' => 2,
                'is_optional' => 0
            ],
            [
                'format_id' => $formatId,
                'rule_type' => 'figure_variety',
                'scope' => 'run',
                'group_name' => 'Rotations',
                'min_distinct' => 1,
                'is_optional' => 1
            ],
            [
                'format_id' => $formatId,
                'rule_type' => 'figure_variety',
                'scope' => 'competition',
                'group_name' => 'Direction',
                'min_distinct' => 3,
                'is_optional' => 0
            ],
            [
                'format_id' => $formatId,
                'rule_type' => 'figure_variety',
                'scope' => 'competition',
                'group_name' => 'Rails',
                'min_distinct' => 2,
                'is_optional' => 1
            ]
        ];
        
        // Insert sample rules
        $insertRule = $pdo->prepare("
            INSERT IGNORE INTO scoring_format_diversity_rules 
            (format_id, rule_type, scope, group_name, min_distinct, is_optional) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        foreach ($sampleRules as $rule) {
            try {
                $insertRule->execute([
                    $rule['format_id'], $rule['rule_type'], $rule['scope'], 
                    $rule['group_name'], $rule['min_distinct'], $rule['is_optional']
                ]);
            } catch (PDOException $e) {
                // Ignore duplicate or constraint errors
            }
        }
        
        // Re-fetch rules
        $diversityQuery->execute([$formatId]);
        $diversityRules = $diversityQuery->fetchAll(PDO::FETCH_ASSOC);
    }
    
} catch (PDOException $e) {
    // Table might not exist yet, continue without diversity rules
    error_log("Diversity rules table error: " . $e->getMessage());
}

// Function to get comprehensive figures data
function getFiguresData($pdo, $sport = null) {
    $figuresData = [
        'sports' => [],
        'categories' => [],
        'items' => [],
        'by_sport' => [],
        'stats' => []
    ];
    
    try {
        // Get all sports
        $sportsQuery = $pdo->prepare("SELECT * FROM figure_sports WHERE is_active = 1 ORDER BY sport_name");
        $sportsQuery->execute();
        $figuresData['sports'] = $sportsQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Get categories (filtered by sport if provided)
        $categoriesQuery = $sport ? 
            $pdo->prepare("SELECT * FROM figure_categories WHERE sport_name = ? AND is_active = 1 ORDER BY sort_order, category_name") :
            $pdo->prepare("SELECT * FROM figure_categories WHERE is_active = 1 ORDER BY sport_name, sort_order, category_name");
        
        if ($sport) {
            $categoriesQuery->execute([$sport]);
        } else {
            $categoriesQuery->execute();
        }
        $figuresData['categories'] = $categoriesQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Get items (filtered by sport if provided)
        if ($sport) {
            $itemsQuery = $pdo->prepare("
                SELECT fi.*, fc.category_name, fc.sport_name 
                FROM figure_items fi
                JOIN figure_categories fc ON fi.sport_name = fc.sport_name AND fi.category_name = fc.category_name
                WHERE fi.sport_name = ? AND fi.is_active = 1 
                ORDER BY fc.sort_order, fi.sort_order, fi.item_name
            ");
            $itemsQuery->execute([$sport]);
        } else {
            $itemsQuery = $pdo->prepare("
                SELECT fi.*, fc.category_name 
                FROM figure_items fi
                JOIN figure_categories fc ON fi.sport_name = fc.sport_name AND fi.category_name = fc.category_name
                WHERE fi.is_active = 1 
                ORDER BY fi.sport_name, fc.sort_order, fi.sort_order, fi.item_name
            ");
            $itemsQuery->execute();
        }
        $figuresData['items'] = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Organize by sport and category
        foreach ($figuresData['items'] as $item) {
            $figuresData['by_sport'][$item['sport_name']][$item['category_name']][] = $item;
        }
        
        // Generate statistics
        $statsQuery = $pdo->prepare("
            SELECT 
                fs.sport_name,
                COUNT(DISTINCT fc.category_name) as category_count,
                COUNT(fi.item_name) as item_count
            FROM figure_sports fs
            LEFT JOIN figure_categories fc ON fs.sport_name = fc.sport_name AND fc.is_active = 1
            LEFT JOIN figure_items fi ON fc.sport_name = fi.sport_name AND fc.category_name = fi.category_name AND fi.is_active = 1
            WHERE fs.is_active = 1
            GROUP BY fs.sport_name
            ORDER BY fs.sport_name
        ");
        $statsQuery->execute();
        $figuresData['stats'] = $statsQuery->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        error_log("Figures data error: " . $e->getMessage());
    }
    
    return $figuresData;
}

// Load figures for this sport (with error handling)
$figuresBySport = [];
$allFiguresData = [];
try {
    // Get comprehensive figures data
    $allFiguresData = getFiguresData($pdo, $format['sport']);
    $figuresBySport = $allFiguresData['by_sport'][$format['sport']] ?? [];
    
    // If no figures exist for testing, create sample data
    if (empty($figuresBySport) && $format['sport'] === 'snowboard') {
        $figuresBySport = [
            'Grabs' => [
                ['item_id' => 'indy', 'item_name' => 'Indy Grab', 'difficulty' => '2.0', 'points' => '5'],
                ['item_id' => 'melon', 'item_name' => 'Melon Grab', 'difficulty' => '2.5', 'points' => '6'],
                ['item_id' => 'stalefish', 'item_name' => 'Stalefish', 'difficulty' => '3.0', 'points' => '7'],
                ['item_id' => 'method', 'item_name' => 'Method', 'difficulty' => '3.5', 'points' => '8']
            ],
            'Rotations' => [
                ['item_id' => '360', 'item_name' => '360 Spin', 'difficulty' => '2.0', 'points' => '4'],
                ['item_id' => '540', 'item_name' => '540 Spin', 'difficulty' => '3.0', 'points' => '6'],
                ['item_id' => '720', 'item_name' => '720 Spin', 'difficulty' => '4.0', 'points' => '8'],
                ['item_id' => '900', 'item_name' => '900 Spin', 'difficulty' => '5.0', 'points' => '10']
            ],
            'Direction' => [
                ['item_id' => 'frontside', 'item_name' => 'Frontside', 'difficulty' => '1.5', 'points' => '3'],
                ['item_id' => 'backside', 'item_name' => 'Backside', 'difficulty' => '1.5', 'points' => '3'],
                ['item_id' => 'switch', 'item_name' => 'Switch', 'difficulty' => '2.0', 'points' => '4'],
                ['item_id' => 'nollie', 'item_name' => 'Nollie', 'difficulty' => '2.5', 'points' => '5']
            ],
            'Flips' => [
                ['item_id' => 'frontflip', 'item_name' => 'Front Flip', 'difficulty' => '3.5', 'points' => '7'],
                ['item_id' => 'backflip', 'item_name' => 'Back Flip', 'difficulty' => '3.0', 'points' => '6'],
                ['item_id' => 'corkscrew', 'item_name' => 'Corkscrew', 'difficulty' => '4.5', 'points' => '9']
            ],
            'Rails' => [
                ['item_id' => '50-50', 'item_name' => '50-50 Grind', 'difficulty' => '1.5', 'points' => '3'],
                ['item_id' => 'boardslide', 'item_name' => 'Boardslide', 'difficulty' => '2.0', 'points' => '4'],
                ['item_id' => 'lipslide', 'item_name' => 'Lipslide', 'difficulty' => '2.5', 'points' => '5'],
                ['item_id' => 'bluntslide', 'item_name' => 'Bluntslide', 'difficulty' => '3.0', 'points' => '6']
            ]
        ];
    }
    
} catch (PDOException $e) {
    // Figures tables might not exist yet, continue without figures
    error_log("Figures tables error: " . $e->getMessage());
    
    // Create sample figures for testing
    if ($format['sport'] === 'snowboard') {
        $figuresBySport = [
            'Grabs' => [
                ['item_id' => 'indy', 'item_name' => 'Indy Grab', 'difficulty' => '2.0', 'points' => '5'],
                ['item_id' => 'melon', 'item_name' => 'Melon Grab', 'difficulty' => '2.5', 'points' => '6'],
                ['item_id' => 'method', 'item_name' => 'Method', 'difficulty' => '3.5', 'points' => '8']
            ],
            'Rotations' => [
                ['item_id' => '360', 'item_name' => '360 Spin', 'difficulty' => '2.0', 'points' => '4'],
                ['item_id' => '540', 'item_name' => '540 Spin', 'difficulty' => '3.0', 'points' => '6'],
                ['item_id' => '720', 'item_name' => '720 Spin', 'difficulty' => '4.0', 'points' => '8']
            ],
            'Direction' => [
                ['item_id' => 'frontside', 'item_name' => 'Frontside', 'difficulty' => '1.5', 'points' => '3'],
                ['item_id' => 'backside', 'item_name' => 'Backside', 'difficulty' => '1.5', 'points' => '3'],
                ['item_id' => 'switch', 'item_name' => 'Switch', 'difficulty' => '2.0', 'points' => '4']
            ],
            'Rails' => [
                ['item_id' => '50-50', 'item_name' => '50-50 Grind', 'difficulty' => '1.5', 'points' => '3'],
                ['item_id' => 'boardslide', 'item_name' => 'Boardslide', 'difficulty' => '2.0', 'points' => '4']
            ]
        ];
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($format['name']) ?> - Scoring Format Details</title>
<?php include_once '../includes/stylesheets.php'; ?>
    <style>
        .card-hover {
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        .card-hover:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .format-icon {
            display: inline-block;
            
        }
        
        .format-icon img {
            padding: 6px;
            width: 143px;  /* 40% bigger: 95px * 1.4 = 133px */
            height: 143px; /* 40% bigger: 95px * 1.4 = 133px */
            object-fit: contain;
            background: transparent;
           /* background: radial-gradient(closest-side, #122b50 0%, #191c32 95%, #f69d3c00 97%);*/
            border-radius: 50%;
           
        }
        
        .judge-panel-preview-container {
            max-height: 600px;
            overflow-y: auto;
        }
        
        .judge-panel-preview-container .card {
            margin-bottom: 1rem;
        }
        
        .judge-panel-preview-container .card:last-child {
            margin-bottom: 0;
        }
        
        .judge-panel-preview-container .form-control-sm,
        .judge-panel-preview-container .form-select-sm {
            font-size: 0.825rem;
        }
        
        .judge-panel-preview-container .card-header {
            padding: 0.5rem 0.75rem;
        }
        
        .judge-panel-preview-container .card-body {
            padding: 0.75rem;
        }
        
        @keyframes wobble {
            0% { transform: rotate(0deg); }
            15% { transform: rotate(5deg); }
            30% { transform: rotate(-5deg); }
            45% { transform: rotate(3deg); }
            60% { transform: rotate(-3deg); }
            75% { transform: rotate(1deg); }
            100% { transform: rotate(0deg); }
        }
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
		<?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
      
       <div class="row justify-content-center col-12">
		   
		   <div class="col-10">
        <!-- Header -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="border-0 shadow-none card border-0 shadow-sm">
                    <div class="border-0 shadow-none card-body p-3 rounded border" style="background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="format-icon me-4">
                                <?php 
                                // Generate icon filename based on sport name
                                $sportIcon = strtolower(str_replace(' ', '_', $format['sport']));
                                $iconPath = "../assets/img/SVG/{$format['format_id']}.svg";

                                // Fallback icons for common sports
                                $iconFallbacks = [
                                    'kitesurfing' => 'kitesurf_big_air.svg',
                                    'kiteboarding' => 'kitesurf_big_air.svg',
                                    'kitesurf' => 'kitesurf_big_air.svg',
                                    'snowboarding' => 'snowboard.svg',
                                    'skiing' => 'ski.svg',
                                    'skateboarding' => 'skateboard.svg',
                                    'surfing' => 'surf.svg',
                                    'wakeboarding' => 'wakeboard.svg',
                                    'windsurfing' => 'windsurf.svg'
                                ];
                                
                                if (isset($iconFallbacks[$sportIcon])) {
                                    $iconPath = "../assets/img/SVG/{$iconFallbacks[$sportIcon]}";
                                } elseif (!file_exists($iconPath)) {
                                    $iconPath = "../assets/img/SVG/kitesurf_big_air.svg"; // Default fallback
                                }
                                ?>
                                <img src="<?= $iconPath ?>" alt="<?= htmlspecialchars($format['sport']) ?>" title="<?= htmlspecialchars(ucfirst($format['sport'])) ?> Format" class="icon">
                            </div>
                            <div class="text-center flex-grow-1">
                                <h1 class="h3 fw-bold mb-3" style="color: #B4D8EC;">
                                    <?php if (!empty($format['icon_path']) && file_exists('../' . $format['icon_path'])): ?>
                                        <img src="../<?= htmlspecialchars($format['icon_path']) ?>" 
                                             alt="<?= htmlspecialchars($format['sport']) ?>" 
                                             style="width: 32px; height: 32px; object-fit: contain; filter: brightness(0) invert(1);" 
                                             class="me-3">
                                    <?php else: ?>
                                        <i class="fas fa-eye me-3"></i>
                                    <?php endif; ?>
                                    <span class="editable-field" data-field="name" data-type="text" data-value="<?= htmlspecialchars($format['name']) ?>">
                                        <?= htmlspecialchars($format['name']) ?>
                                    </span>
                                </h1>
                                <div class="d-flex justify-content-center align-items-center gap-2 flex-wrap">
                                    <span class="badge bg-<?= $format['is_active'] ? 'success' : 'secondary' ?> fs-6 editable-field" 
                                          data-field="is_active" data-type="boolean" data-value="<?= $format['is_active'] ?>">
                                        <i class="fas fa-<?= $format['is_active'] ? 'check-circle' : 'pause-circle' ?> me-1"></i>
                                        <?= $format['is_active'] ? 'Active' : 'Inactive' ?>
                                    </span>
                                    <span class="badge bg-info fs-6 editable-field" 
                                          data-field="sport" data-type="select" data-value="<?= htmlspecialchars($format['sport']) ?>"
                                          data-options='["snowboard","freeski","skateboard","bmx","inline","surf","kitesurf","parkour","breaking","wakeboard"]'>
                                        <i class="fas fa-running me-1"></i><?= ucfirst($format['sport']) ?>
                                    </span>
                                    <span class="badge bg-warning fs-6 editable-field" 
                                          data-field="mode" data-type="select" data-value="<?= htmlspecialchars($format['mode']) ?>"
                                          data-options='["slopestyle","halfpipe","big_air","rail_jam","street","park","vert","freestyle","battle","jam"]'>
                                        <i class="fas fa-trophy me-1"></i><?= str_replace('_', ' ', $format['mode']) ?>
                                    </span>
                                </div>
                                <small class="d-block mt-2" style="color: #B4D8EC; opacity: 0.8;">Format ID: <?= $format['format_id'] ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="border-0 shadow-none card border-0 shadow-sm">
                    <div class="border-0 shadow-none card-body">
                        <div class="d-flex justify-content-center gap-2 flex-wrap">
                            <button class="btn btn-success" onclick="toggleEditMode()">
                                <i class="fas fa-edit me-2"></i><span id="editButtonText">Enable Editing</span>
                            </button>
                            <button class="btn btn-warning d-none" id="saveChangesBtn" onclick="saveAllChanges()">
                                <i class="fas fa-save me-2"></i>Save All Changes
                            </button>
                            <button class="btn btn-secondary d-none" id="cancelEditBtn" onclick="cancelEdit()">
                                <i class="fas fa-times me-2"></i>Cancel
                            </button>
                            <a href="scoring_format_edit.php?id=<?= $formatId ?>" class="btn btn-info">
                                <i class="fas fa-cogs me-2"></i>Advanced Edit
                            </a>
                            <button class="btn btn-primary" onclick="exportJSON()">
                                <i class="fas fa-download me-2"></i>Export JSON
                            </button>
                            <a href="scoring_formats.php" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Back to List
                            </a>
                        </div>
                        <div class="mt-3 d-none" id="editModeAlert">
                            <div class="bg-warning-subtle text-body p-3 rounded">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <strong>Edit Mode Active:</strong> Click on editable fields to modify them. Changes are saved automatically.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4">
            <div class="col-lg-8">
                <!-- Scoring Formula Examples -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                    <div class="border-0 shadow-none card-header bg-info bg-opacity-10 border border-info rounded-top">
                        <h5 class="mb-0 text-info">
                            <i class="fas fa-calculator me-2"></i>Complete Event Scoring Formula
                        </h5>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <?php
                        // Generate comprehensive formula examples based on format settings
                        $numJudges = max($format['min_judges'], 3); // Use at least 3 for examples
                        $numRuns = !empty($rounds) ? max(array_column($rounds, 'runs')) : 3; // Default to 3 runs
                        
                        // Generate sample scores for multiple participants across multiple runs
                        $participants = [
                            ['name' => 'Alex Johnson', 'bib' => 101],
                            ['name' => 'Sarah Chen', 'bib' => 102], 
                            ['name' => 'Marcus Rodriguez', 'bib' => 103]
                        ];
                        
                        $participantData = [];
                        foreach ($participants as $participant) {
                            $participantData[$participant['bib']] = [
                                'name' => $participant['name'],
                                'bib' => $participant['bib'],
                                'runs' => [],
                                'runScores' => [],
                                'finalScore' => 0,
                                'rank' => 0
                            ];
                            
                            // Generate scores for each run
                            for ($run = 1; $run <= $numRuns; $run++) {
                                $judgeScores = [];
                                for ($j = 1; $j <= $numJudges; $j++) {
                                    if ($format['scale_type'] === 'numeric') {
                                        $min = $format['scale_min'];
                                        $max = $format['scale_max'];
                                        $decimals = $format['precision_decimal'];
                                        // Add some variation - better athletes tend to score higher
                                        $baseScore = $min + (($max - $min) * (0.6 + (rand(0, 40) / 100)));
                                        $score = round($baseScore, $decimals);
                                    } else {
                                        $customScales = explode(',', $format['scale_custom']);
                                        $score = trim($customScales[array_rand($customScales)]);
                                    }
                                    $judgeScores[] = $score;
                                }
                                
                                // Calculate run score based on drop rule
                                $runScore = calculateRunScore($judgeScores, $format);
                                $participantData[$participant['bib']]['runs'][$run] = [
                                    'judgeScores' => $judgeScores,
                                    'runScore' => $runScore
                                ];
                                $participantData[$participant['bib']]['runScores'][] = $runScore;
                            }
                        }
                        
                        // Calculate final scores and rankings
                        foreach ($participantData as $bib => &$data) {
                            if (!empty($rounds)) {
                                // Use the aggregation method from rounds configuration
                                $aggregationMethods = array_unique(array_column($rounds, 'aggregation'));
                                $primaryMethod = $aggregationMethods[0] ?? 'average';
                            } else {
                                $primaryMethod = 'average'; // Default
                            }
                            
                            if ($format['scale_type'] === 'numeric') {
                                switch ($primaryMethod) {
                                    case 'sum':
                                    case 'total':
                                        $data['finalScore'] = array_sum($data['runScores']);
                                        break;
                                    case 'best':
                                    case 'max':
                                    case 'highest':
                                        $data['finalScore'] = max($data['runScores']);
                                        break;
                                    case 'best_2':
                                        rsort($data['runScores']);
                                        $data['finalScore'] = array_sum(array_slice($data['runScores'], 0, 2));
                                        break;
                                    case 'average':
                                    default:
                                        $data['finalScore'] = array_sum($data['runScores']) / count($data['runScores']);
                                        break;
                                }
                                $data['finalScore'] = round($data['finalScore'], $format['precision_decimal']);
                            } else {
                                $data['finalScore'] = 'Custom Result';
                            }
                        }
                        
                        // Sort by final score for ranking
                        if ($format['scale_type'] === 'numeric') {
                            uasort($participantData, function($a, $b) {
                                return $b['finalScore'] <=> $a['finalScore']; // Descending order (higher is better)
                            });
                        }
                        
                        // Assign ranks
                        $rank = 1;
                        foreach ($participantData as $bib => &$data) {
                            $data['rank'] = $rank++;
                        }
                        
                        // Helper function to calculate individual run scores
                        function calculateRunScore($judgeScores, $format) {
                            if ($format['scale_type'] !== 'numeric') {
                                return 'Custom';
                            }
                            
                            $workingScores = $judgeScores;
                            
                            switch ($format['drop_rule']) {
                                case 'highest':
                                    rsort($workingScores);
                                    array_shift($workingScores);
                                    break;
                                case 'lowest':
                                    sort($workingScores);
                                    array_shift($workingScores);
                                    break;
                                case 'highest_and_lowest':
                                    sort($workingScores);
                                    array_shift($workingScores); // Remove lowest
                                    array_pop($workingScores);   // Remove highest
                                    break;
                                case 'median':
                                    sort($workingScores);
                                    $count = count($workingScores);
                                    if ($count % 2 == 1) {
                                        return $workingScores[floor($count/2)];
                                    } else {
                                        return round(($workingScores[$count/2-1] + $workingScores[$count/2]) / 2, $format['precision_decimal']);
                                    }
                                case 'none':
                                default:
                                    // Use all scores
                                    break;
                            }
                            
                            return count($workingScores) > 0 ? round(array_sum($workingScores) / count($workingScores), $format['precision_decimal']) : 0;
                        }
                        ?>
                        
                        <!-- Step 1: Individual Run Calculation -->
                        <div class="mb-4">
                            <h6 class="text-primary border-bottom pb-2">
                                <i class="fas fa-step-forward me-1"></i>Step 1: Individual Run Score Calculation
                            </h6>
                            <div class="row g-3">
                                <div class="col-md-8">
                                    <div class="bg-light p-3 rounded">
                                        <strong>Example: <?= $participantData[101]['name'] ?> - Run 1</strong>
                                        <div class="mt-2 d-flex flex-wrap gap-1">
                                            <?php 
                                            $judgeScores = $participantData[101]['runs'][1]['judgeScores'];
                                            $dropRule = $format['drop_rule'];
                                            $minScore = min($judgeScores);
                                            $maxScore = max($judgeScores);
                                            
                                            foreach ($judgeScores as $i => $score): 
                                                $badgeClass = 'bg-secondary';
                                                $isDropped = false;
                                                
                                                // Determine if this score should be marked as dropped
                                                if ($dropRule === 'highest_and_lowest') {
                                                    if ($score === $maxScore || $score === $minScore) {
                                                        $badgeClass = 'bg-danger text-decoration-line-through';
                                                        $isDropped = true;
                                                    }
                                                } elseif ($dropRule === 'highest' && $score === $maxScore) {
                                                    $badgeClass = 'bg-danger text-decoration-line-through';
                                                    $isDropped = true;
                                                } elseif ($dropRule === 'lowest' && $score === $minScore) {
                                                    $badgeClass = 'bg-danger text-decoration-line-through';
                                                    $isDropped = true;
                                                }
                                            ?>
                                                <span class="badge fa-1x <?= $badgeClass ?>" <?= $isDropped ? 'title="Dropped score"' : '' ?>>
                                                    J<?= $i + 1 ?>: <?= $score ?>
                                                    <?= $isDropped ? ' <i class="fas fa-times-circle ms-1"></i>' : '' ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                        <div class="mt-2">
                                            <small class="text-muted">
                                                Drop Rule: <strong><?= $format['drop_rule'] ?></strong>
                                                <?php if ($format['drop_rule'] !== 'none'): ?>
                                                    → Remove <?= $format['drop_rule'] == 'highest' ? 'highest' : 
                                                              ($format['drop_rule'] == 'lowest' ? 'lowest' : 
                                                              ($format['drop_rule'] == 'highest_and_lowest' ? 'highest & lowest' : 'apply rule')) ?>
                                                    <?php if ($format['drop_rule'] === 'highest_and_lowest'): ?>
                                                        <span class="text-danger fw-bold">(marked with red strikethrough)</span>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </small>
                                        </div>
                                        <div class="mt-2 text-center">
                                            <span class="badge bg-success fs-6">Run Score: <strong><?= $participantData[101]['runs'][1]['runScore'] ?></strong></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="alert alert-info mb-0">
                                        <small>
                                            <i class="fas fa-info-circle me-1"></i>
                                            <strong>Scale:</strong> <?= $format['scale_type'] === 'numeric' ? 
                                                $format['scale_min'] . '-' . $format['scale_max'] : $format['scale_custom'] ?><br>
                                            <strong>Judges:</strong> <?= $numJudges ?><br>
                                            <strong>Precision:</strong> <?= $format['precision_decimal'] ?> decimal(s)
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 2: Multi-Run Results -->
                        <div class="mb-4">
                            <h6 class="text-success border-bottom pb-2">
                                <i class="fas fa-layer-group me-1"></i>Step 2: Complete Results Table
                            </h6>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Rank</th>
                                            <th>Bib</th>
                                            <th>Participant</th>
                                            <?php for ($run = 1; $run <= $numRuns; $run++): ?>
                                                <th class="text-center">Run <?= $run ?></th>
                                            <?php endfor; ?>
                                            <th class="text-center bg-warning">Final Score</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($participantData as $data): ?>
                                            <tr>
                                                <td>
                                                    <span class="badge bg-primary"><?= $data['rank'] ?></span>
                                                </td>
                                                <td><strong><?= $data['bib'] ?></strong></td>
                                                <td><?= $data['name'] ?></td>
                                                <?php foreach ($data['runScores'] as $runScore): ?>
                                                    <td class="text-center">
                                                        <span class="badge bg-secondary"><?= $runScore ?></span>
                                                    </td>
                                                <?php endforeach; ?>
                                                <td class="text-center">
                                                    <span class="badge bg-warning  fs-6">
                                                        <strong><?= $data['finalScore'] ?></strong>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Step 3: Final Aggregation Formula -->
                        <div class="mb-4">
                            <h6 class="text-warning border-bottom pb-2">
                                <i class="fas fa-calculator me-1"></i>Step 3: Final Score Calculation
                            </h6>
                            <div class="row g-3">
                                <?php 
                                $aggregationMethod = !empty($rounds) ? $rounds[0]['aggregation'] ?? 'average' : 'average';
                                $exampleParticipant = array_values($participantData)[0];
                                ?>
                                <div class="col-md-6">
                                    <div class="bg-warning bg-opacity-10 p-3 rounded border">
                                        <strong>Aggregation Method: <?= ucwords(str_replace('_', ' ', $aggregationMethod)) ?></strong>
                                        <div class="mt-2">
                                            <small>Example: <?= $exampleParticipant['name'] ?></small><br>
                                            <span class="text-muted">Run Scores: <?= implode(', ', $exampleParticipant['runScores']) ?></span>
                                        </div>
                                        <div class="mt-2">
                                            <?php
                                            switch ($aggregationMethod) {
                                                case 'sum':
                                                case 'total':
                                                    echo "<code>Final = " . implode(' + ', $exampleParticipant['runScores']) . " = {$exampleParticipant['finalScore']}</code>";
                                                    break;
                                                case 'best':
                                                case 'max':
                                                case 'highest':
                                                    echo "<code>Final = MAX(" . implode(', ', $exampleParticipant['runScores']) . ") = {$exampleParticipant['finalScore']}</code>";
                                                    break;
                                                case 'best_2':
                                                    $sorted = $exampleParticipant['runScores'];
                                                    rsort($sorted);
                                                    echo "<code>Final = Best 2: " . $sorted[0] . " + " . $sorted[1] . " = {$exampleParticipant['finalScore']}</code>";
                                                    break;
                                                case 'average':
                                                default:
                                                    echo "<code>Final = (" . implode(' + ', $exampleParticipant['runScores']) . ") ÷ " . count($exampleParticipant['runScores']) . " = {$exampleParticipant['finalScore']}</code>";
                                                    break;
                                            }
                                            ?>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="bg-success bg-opacity-10 p-3 rounded border">
                                        <strong>Ranking Process</strong>
                                        <ol class="mt-2 mb-0">
                                            <li><small>Calculate final score for each participant</small></li>
                                            <li><small>Sort participants by final score (descending)</small></li>
                                            <li><small>Assign ranks (1st = highest score)</small></li>
                                            <?php if (!empty($tiebreakRules)): ?>
                                                <li><small>Apply tiebreak rules if scores are equal:
                                                    <?php 
                                                    $displayRules = array_slice($tiebreakRules, 0, 2);
                                                    $lastRule = end($displayRules);
                                                    foreach ($displayRules as $rule): ?>
                                                        <em><?= $rule ?></em><?= $rule !== $lastRule ? ', ' : '' ?>
                                                    <?php endforeach; ?>
                                                </small></li>
                                            <?php endif; ?>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 4: Diversity Rules Validation (if applicable) -->
                        <?php if (!empty($diversityRules)): ?>
                        <div class="mb-4">
                            <h6 class="text-danger border-bottom pb-2">
                                <i class="fas fa-shield-alt me-1"></i>Step 4: Diversity Rules Validation
                            </h6>
                            
                            <?php 
                            // Generate comprehensive examples for all runs showing both passing and failing cases
                            // Create realistic examples based on actual diversity rules
                            $figureCategories = [
                                'Rotation' => ['180', '360', '540', '720', '900', '1080'],
                                'Direction' => ['Frontside', 'Backside', 'Switch'],
                                'Axis' => ['Flat', 'Cork', 'Double Cork', 'Triple Cork'],
                                'Grab' => ['Tail', 'Indy', 'Nose', 'Melon', 'Method', 'Stalefish'],
                                'Feature' => ['Rail', 'Kicker', 'Box', 'Wall Ride', 'Quarter Pipe']
                            ];
                            
                            // Build passing example - ensure it meets all diversity requirements
                            $passingExample = [
                                'name' => 'Alex Johnson (PASSING Example)',
                                'runs' => []
                            ];
                            
                            // Build failing example - intentionally violate some rules
                            $failingExample = [
                                'name' => 'Sarah Chen (FAILING Example)', 
                                'runs' => []
                            ];
                            
                            // Generate runs based on actual diversity rules
                            for ($run = 1; $run <= $numRuns; $run++) {
                                // For passing example - use diverse selections
                                $passingRun = [];
                                $failingRun = [];
                                
                                foreach ($figureCategories as $category => $options) {
                                    // For passing: use different selections across runs
                                    $passingRun[$category] = $options[($run - 1) % count($options)];
                                    
                                    // For failing: use same selection in ALL runs to guarantee violations
                                    $failingRun[$category] = $options[0]; // Always use first option to create violations
                                }
                                
                                $passingExample['runs'][$run] = $passingRun;
                                $failingExample['runs'][$run] = $failingRun;
                            }
                            
                            // Enhanced validation function that properly checks diversity rules
                            function validateDiversityForExample($example, $diversityRules, $totalRuns) {
                                $results = [];
                                
                                foreach ($diversityRules as $rule) {
                                    $ruleType = $rule['rule_type'];
                                    $groupName = $rule['group_name'] ?? 'Figure';
                                    $minDistinct = (int)$rule['min_distinct'];
                                    $scope = $rule['scope'] ?? 'run';
                                    $isOptional = (bool)$rule['is_optional'];
                                    
                                    // Collect values based on the rule's group and scope
                                    $allValues = [];
                                    $scopeResults = [];
                                    
                                    if ($scope === 'attempts' || $scope === 'attempt') {
                                        // Check each run individually
                                        foreach ($example['runs'] as $runNum => $figures) {
                                            $runValues = [];
                                            
                                            // If group_name exists in figures, use it; otherwise use all figures
                                            if (isset($figures[$groupName])) {
                                                $runValues = [$figures[$groupName]];
                                            } else {
                                                $runValues = array_values($figures);
                                            }
                                            
                                            $uniqueCount = count(array_unique($runValues));
                                            $isPassing = $isOptional || ($uniqueCount >= $minDistinct);
                                            
                                            $scopeResults[] = [
                                                'rule' => $rule,
                                                'scope_detail' => "Run $runNum",
                                                'found_count' => $uniqueCount,
                                                'required_count' => $minDistinct,
                                                'is_passing' => $isPassing,
                                                'values' => $runValues,
                                                'rule_description' => $ruleType
                                            ];
                                        }
                                    } else {
                                        // Check across all runs (event/total scope)
                                        foreach ($example['runs'] as $runNum => $figures) {
                                            if (isset($figures[$groupName])) {
                                                $allValues[] = $figures[$groupName];
                                            } else {
                                                // If no specific group, collect all figure values
                                                $allValues = array_merge($allValues, array_values($figures));
                                            }
                                        }
                                        
                                        $uniqueCount = count(array_unique($allValues));
                                        $isPassing = $isOptional || ($uniqueCount >= $minDistinct);
                                        
                                        $scopeResults[] = [
                                            'rule' => $rule,
                                            'scope_detail' => ucwords($scope) . " (All Runs)",
                                            'found_count' => $uniqueCount,
                                            'required_count' => $minDistinct,
                                            'is_passing' => $isPassing,
                                            'values' => array_unique($allValues),
                                            'rule_description' => $ruleType
                                        ];
                                    }
                                    
                                    $results = array_merge($results, $scopeResults);
                                }
                                
                                return $results;
                            }
                            
                            $passingResults = validateDiversityForExample($passingExample, $diversityRules, $numRuns);
                            $failingResults = validateDiversityForExample($failingExample, $diversityRules, $numRuns);
                            
                            // Adjust examples if needed to ensure proper pass/fail demonstration
                            $hasPassingRule = false;
                            $hasFailingRule = false;
                            
                            foreach ($passingResults as $result) {
                                if ($result['is_passing']) $hasPassingRule = true;
                            }
                            
                            foreach ($failingResults as $result) {
                                if (!$result['is_passing']) $hasFailingRule = true;
                            }
                            
                            // If examples don't demonstrate the rules properly, create manual examples
                            if (!$hasPassingRule || !$hasFailingRule) {
                                // Override with manual examples that better demonstrate the rules
                                $passingExample = [
                                    'name' => 'Alex Johnson (PASSING Example)',
                                    'runs' => [
                                        1 => ['Category' => 'Spins', 'Figure' => '360 Frontside'],
                                        2 => ['Category' => 'Grabs', 'Figure' => '540 Backside Indy'],
                                        3 => ['Category' => 'Rails', 'Figure' => '270 Switch Nose']
                                    ]
                                ];
                                
                                $failingExample = [
                                    'name' => 'Sarah Chen (FAILING Example)',
                                    'runs' => [
                                        1 => ['Category' => 'Spins', 'Figure' => '360 Frontside'],
                                        2 => ['Category' => 'Spins', 'Figure' => '360 Frontside'], // Same figure - violation!
                                        3 => ['Category' => 'Spins', 'Figure' => '360 Frontside']  // Same figure again - more violations!
                                    ]
                                ];
                                
                                $passingResults = validateDiversityForExample($passingExample, $diversityRules, $numRuns);
                                $failingResults = validateDiversityForExample($failingExample, $diversityRules, $numRuns);
                            }
                            ?>
                            
                            <!-- Diversity Rules Examples Header -->
                            <div class="bg-info-subtle text-body p-4 rounded mb-4">
                                <h6 class="mb-3">
                                    <i class="fas fa-graduation-cap me-2"></i>Understanding Diversity Rules Through Examples
                                </h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <div class="d-flex align-items-start">
                                            <i class="fas fa-info-circle text-info me-2 mt-1"></i>
                                            <div>
                                                <strong>Purpose:</strong> Diversity rules ensure competitive balance by preventing repetitive routines and encouraging variety in figure/trick selection.
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="d-flex align-items-start">
                                            <i class="fas fa-chart-line text-success me-2 mt-1"></i>
                                            <div>
                                                <strong>Impact:</strong> Rules require a minimum number of distinct selections within specified scopes (per run, per attempt, or across entire event).
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row g-4 mt-4">
                                <!-- Passing Example -->
                                <div class="col-lg-6">
                                    <div class="bg-success bg-opacity-10 p-4 rounded border border-success">
                                        <h6 class="text-success mb-3">
                                            <i class="fas fa-check-circle me-2"></i><?= $passingExample['name'] ?>
                                        </h6>
                                        
                                        <!-- Show all runs for passing example -->
                                        <?php foreach ($passingExample['runs'] as $runNum => $figures): ?>
                                            <div class="mb-3">
                                                <strong class="text-primary">Run <?= $runNum ?> Figures:</strong>
                                                <div class="mt-2">
                                                    <?php foreach ($figures as $category => $figure): ?>
                                                        <span class="badge bg-primary me-1 mb-1"><?= $category ?>: <?= $figure ?></span>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                        
                                        <!-- Validation Results for Passing Example -->
                                        <div class="mt-3">
                                            <strong class="text-success">✓ Validation Results:</strong>
                                            <div class="mt-2">
                                                <?php 
                                                $groupedResults = [];
                                                foreach ($passingResults as $result) {
                                                    $key = ($result['rule']['group_name'] ?? 'General') . '_' . $result['rule']['scope'];
                                                    $groupedResults[$key][] = $result;
                                                }
                                                
                                                foreach ($groupedResults as $results): 
                                                    $firstResult = $results[0];
                                                    $rule = $firstResult['rule'];
                                                    $hasViolations = array_filter($results, function($r) { return !$r['is_passing']; });
                                                    $overallStatus = empty($hasViolations) ? 'success' : 'danger';
                                                ?>
                                                    <div class="mb-2 p-2 bg-white rounded border border-<?= $overallStatus ?>">
                                                        <div class="d-flex align-items-center mb-1">
                                                            <strong class="text-primary me-2"><?= $rule['rule_type'] ?? ($rule['group_name'] ?? 'Figure Rule') ?>:</strong>
                                                            <small class="text-muted">Need <?= $rule['min_distinct'] ?>+ distinct (<?= $rule['scope'] ?> scope)</small>
                                                            <?php if ($rule['is_optional']): ?>
                                                                <span class="badge bg-info ms-1">Optional</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-<?= $overallStatus === 'success' ? 'success' : 'danger' ?> ms-1">
                                                                    <?= $overallStatus === 'success' ? 'PASSED' : 'REQUIRED' ?>
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <?php foreach ($results as $result): ?>
                                                            <div class="d-flex align-items-center mb-1">
                                                                <span class="badge <?= $result['is_passing'] ? 'bg-success' : 'bg-danger' ?> me-2">
                                                                    <i class="fas <?= $result['is_passing'] ? 'fa-check' : 'fa-times' ?> me-1"></i>
                                                                    <?= $result['is_passing'] ? 'PASS' : 'FAIL' ?>
                                                                </span>
                                                                <small>
                                                                    <?= $result['scope_detail'] ?>: Found <strong><?= $result['found_count'] ?></strong> distinct
                                                                    (need <?= $result['required_count'] ?>)
                                                                    <?php if (!empty($result['values'])): ?>
                                                                        <br><em class="text-muted">Values: <?= implode(', ', array_slice(is_array($result['values']) ? $result['values'] : [$result['values']], 0, 5)) ?><?= count($result['values']) > 5 ? '...' : '' ?></em>
                                                                    <?php endif; ?>
                                                                </small>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php endforeach; ?>
                                                
                                                <?php if (empty($groupedResults)): ?>
                                                    <div class="text-muted">
                                                        <i class="fas fa-info-circle me-1"></i>
                                                        No diversity rules configured for this format.
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Failing Example -->
                                <div class="col-lg-6">
                                    <div class="bg-danger bg-opacity-10 p-4 rounded border border-danger">
                                        <h6 class="text-danger mb-3">
                                            <i class="fas fa-times-circle me-2"></i><?= $failingExample['name'] ?>
                                        </h6>
                                        
                                        <!-- Show all runs for failing example -->
                                        <?php foreach ($failingExample['runs'] as $runNum => $figures): ?>
                                            <div class="mb-3">
                                                <strong class="text-primary">Run <?= $runNum ?> Figures:</strong>
                                                <div class="mt-2">
                                                    <?php foreach ($figures as $category => $figure): ?>
                                                        <?php 
                                                        // Highlight repeated selections
                                                        $isRepeated = false;
                                                        foreach ($failingExample['runs'] as $checkRun => $checkFigures) {
                                                            if ($checkRun != $runNum && isset($checkFigures[$category]) && $checkFigures[$category] === $figure) {
                                                                $isRepeated = true;
                                                                break;
                                                            }
                                                        }
                                                        ?>
                                                        <span class="badge <?= $isRepeated ? 'bg-warning ' : 'bg-primary' ?> me-1 mb-1">
                                                            <?= $category ?>: <?= $figure ?><?= $isRepeated ? ' ⚠' : '' ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                        
                                        <!-- Validation Results for Failing Example -->
                                        <div class="mt-3">
                                            <strong class="text-danger">✗ Validation Results:</strong>
                                            <div class="mt-2">
                                                <?php 
                                                $groupedResults = [];
                                                foreach ($failingResults as $result) {
                                                    $key = ($result['rule']['group_name'] ?? 'General') . '_' . $result['rule']['scope'];
                                                    $groupedResults[$key][] = $result;
                                                }
                                                
                                                foreach ($groupedResults as $results): 
                                                    $firstResult = $results[0];
                                                    $rule = $firstResult['rule'];
                                                    $hasViolations = array_filter($results, function($r) { return !$r['is_passing']; });
                                                    $overallStatus = empty($hasViolations) ? 'success' : 'danger';
                                                ?>
                                                    <div class="mb-2 p-2 bg-white rounded border border-<?= $overallStatus ?>">
                                                        <div class="d-flex align-items-center mb-1">
                                                            <strong class="text-primary me-2"><?= $rule['rule_type'] ?? ($rule['group_name'] ?? 'Figure Rule') ?>:</strong>
                                                            <small class="text-muted">Need <?= $rule['min_distinct'] ?>+ distinct (<?= $rule['scope'] ?> scope)</small>
                                                            <?php if ($rule['is_optional']): ?>
                                                                <span class="badge bg-info ms-1">Optional</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-<?= $overallStatus === 'success' ? 'success' : 'danger' ?> ms-1">
                                                                    <?= $overallStatus === 'success' ? 'PASSED' : 'REQUIRED' ?>
                                                                </span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <?php foreach ($results as $result): ?>
                                                            <div class="d-flex align-items-center mb-1">
                                                                <span class="badge <?= $result['is_passing'] ? 'bg-success' : 'bg-danger' ?> me-2">
                                                                    <i class="fas <?= $result['is_passing'] ? 'fa-check' : 'fa-times' ?> me-1"></i>
                                                                    <?= $result['is_passing'] ? 'PASS' : 'FAIL' ?>
                                                                </span>
                                                                <small>
                                                                    <?= $result['scope_detail'] ?>: Found <strong><?= $result['found_count'] ?></strong> distinct
                                                                    (need <?= $result['required_count'] ?>)
                                                                    <?php if (!$result['is_passing']): ?>
                                                                        <br><strong class="text-danger">⚠ VIOLATION:</strong>
                                                                        <em class="text-muted">
                                                                            <?php if ($result['found_count'] < $result['required_count']): ?>
                                                                                Not enough diversity - need <?= $result['required_count'] - $result['found_count'] ?> more distinct
                                                                            <?php else: ?>
                                                                                Rule not met despite having required count
                                                                            <?php endif; ?>
                                                                        </em>
                                                                    <?php endif; ?>
                                                                    <?php if (!empty($result['values'])): ?>
                                                                        <br><em class="text-muted">Values: <?= implode(', ', array_slice(is_array($result['values']) ? $result['values'] : [$result['values']], 0, 5)) ?><?= count($result['values']) > 5 ? '...' : '' ?></em>
                                                                    <?php endif; ?>
                                                                </small>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php endforeach; ?>
                                                
                                                <?php if (empty($groupedResults)): ?>
                                                    <div class="text-muted">
                                                        <i class="fas fa-info-circle me-1"></i>
                                                        No diversity rules configured for this format.
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Impact Explanation -->
                            <div class="row mt-4">
                                <div class="col-12">
                                    <div class="bg-warning-subtle text-body p-3 rounded">
                                        <h6><i class="fas fa-exclamation-triangle me-1"></i>Impact of Diversity Rule Violations:</h6>
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <strong class="text-success">✓ Valid Attempts:</strong>
                                                <ul class="small mb-0 mt-1">
                                                    <li>Proceed to judge scoring</li>
                                                    <li>Full score potential</li>
                                                    <li>Normal competition flow</li>
                                                </ul>
                                            </div>
                                            <div class="col-md-4">
                                                <strong class="text-danger">✗ Rule Violations:</strong>
                                                <ul class="small mb-0 mt-1">
                                                    <li>Attempt may be rejected</li>
                                                    <li>Score penalty applied</li>
                                                    <li>Required figure correction</li>
                                                </ul>
                                            </div>
                                            <div class="col-md-4">
                                                <strong class="text-info">Optional Rules:</strong>
                                                <ul class="small mb-0 mt-1">
                                                    <li>Violations allowed</li>
                                                    <li>May affect bonus scoring</li>
                                                    <li>Advisory guidelines only</li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Summary -->
                        <div class="bg-primary-subtle text-body p-3 rounded">
                            <h6><i class="fas fa-trophy me-1"></i>Complete Event Formula Summary</h6>
                            <?php if (!empty($diversityRules)): ?>
                                <strong>Pre-Validation:</strong> Check figure diversity rules → Approve/Reject attempt<br>
                            <?php endif; ?>
                            <strong>Individual Run:</strong> <?= $numJudges ?> judges score → Apply "<?= $format['drop_rule'] ?>" rule → Run Score<br>
                            <strong>Final Score:</strong> <?= $numRuns ?> run scores → "<?= $aggregationMethod ?>" aggregation → Final Score<br>
                            <strong>Ranking:</strong> Sort by final score (highest wins) → Apply tiebreak rules → Final Rankings
                            <?php if (!empty($rounds)): ?>
                                <br><strong>Rounds:</strong> 
                                <?php foreach ($rounds as $round): ?>
                                    <?= $round['round_name'] ?> (<?= $round['runs'] ?> runs, <?= $round['aggregation'] ?> method)<?= $round !== end($rounds) ? ', ' : '' ?>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            <?php if (!empty($diversityRules)): ?>
                                <br><strong>Diversity Rules:</strong> <?= count($diversityRules) ?> rules enforcing figure variety across <?= implode(', ', array_unique(array_column($diversityRules, 'scope'))) ?> scope(s)
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Judge Panel Preview -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                    <div class="border-0 shadow-none card-header bg-warning bg-opacity-10 border border-warning rounded-top">
                        <h5 class="mb-0 text-warning">
                            <i class="fas fa-chalkboard-user me-2"></i>Judge Panel Preview
                        </h5>
                        <p class="mb-0 mt-2 small opacity-75">
                            <i class="fas fa-info-circle me-1"></i>
                            Interactive preview of what judges will see during scoring sessions
                        </p>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <p class="mb-2">This panel preview is dynamically generated based on the format's scoring criteria configuration. It shows exactly what judges will interact with during actual scoring sessions.</p>
                            </div>
                            <div class="col-md-4 text-end">
                                <button type="button" class="btn btn-warning btn-sm" onclick="openFullPanelModal()">
                                    <i class="fas fa-expand me-1"></i>Open Full Panel
                                </button>
                            </div>
                        </div>
                        
                        <div class="border rounded bg-light p-3">
                            <div id="judgePanelPreview" class="judge-panel-preview-container">
                                <!-- Panel content will be generated by JavaScript -->
                                <div class="text-center py-4">
                                    <div class="spinner-border text-warning" role="status">
                                        <span class="visually-hidden">Loading panel preview...</span>
                                    </div>
                                    <p class="mt-2 text-muted">Generating judge panel preview...</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-warning-subtle text-body mt-3 p-3 rounded">
                            <h6><i class="fas fa-lightbulb me-2"></i>Panel Features</h6>
                            <div class="row small">
                                <div class="col-md-6">
                                    <ul class="list-unstyled mb-0">
                                        <li><i class="fas fa-check text-success me-1"></i> Real-time score validation</li>
                                        <li><i class="fas fa-check text-success me-1"></i> Format-specific input fields</li>
                                        <li><i class="fas fa-check text-success me-1"></i> Dynamic figure selection</li>
                                    </ul>
                                </div>
                                <div class="col-md-6">
                                    <ul class="list-unstyled mb-0">
                                        <li><i class="fas fa-check text-success me-1"></i> Diversity rule enforcement</li>
                                        <li><i class="fas fa-check text-success me-1"></i> Mobile-responsive interface</li>
                                        <li><i class="fas fa-check text-success me-1"></i> Instant feedback</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                

                <!-- Tiebreak Rules & Competition Management -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover" id="tiebreak-rules">
                    <div class="border-0 shadow-none card-header bg-primary text-white">
                        <h4 class="mb-0">
                            <i class="fas fa-balance-scale me-2"></i>Tiebreak Rules & Competition Management
                        </h4>
                        <p class="mb-0 mt-2 small opacity-75">
                            <i class="fas fa-info-circle me-1"></i>
                            This section defines how tied scores are resolved and manages competition structure including diversity enforcement, round progression, and scoring methods.
                        </p>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <!-- Explanation Section -->
                        <div class="bg-info-subtle text-body mb-4 p-3 rounded">
                            <h6><i class="fas fa-graduation-cap me-2"></i>Understanding Tiebreak Systems</h6>
                            <p class="mb-2">
                                Tiebreak rules ensure fair competition when participants achieve identical scores. The system works in multiple layers:
                            </p>
                            <div class="row">
                                <div class="col-md-6">
                                    <ul class="small mb-0">
                                        <li><strong>Diversity Rules:</strong> Prevent repetitive routines by enforcing variety</li>
                                        <li><strong>Round Structure:</strong> Define progression from qualifiers to finals</li>
                                    </ul>
                                </div>
                                <div class="col-md-6">
                                    <ul class="small mb-0">
                                        <li><strong>Scoring Modes:</strong> Determine how multiple attempts are combined</li>
                                        <li><strong>Tiebreak Order:</strong> Sequential rules to resolve identical final scores</li>
                                    </ul>
                                </div>
                            </div>
                        </div>

                        <!-- Tiebreak Resolution Process -->
                        <?php if (!empty($tiebreakRules)): ?>
                            <div class="mb-4" id="tiebreak-system">
                                <h5 class="text-primary border-bottom pb-2">
                                    <i class="fas fa-equals me-2"></i>Tiebreak Resolution Process
                                </h5>
                                <div class="bg-warning-subtle text-body p-3 rounded mb-3">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    <strong>When Applied:</strong> These rules are triggered automatically when two or more participants have identical final scores.
                                </div>
                                <div class="row g-3">
                                    <?php foreach ($tiebreakRules as $index => $rule): ?>
                                        <div class="col-md-6">
                                            <div class="bg-light p-3 rounded border">
                                                <div class="d-flex align-items-center">
                                                    <span class="badge bg-warning  me-3 fs-6">Step <?= $index + 1 ?></span>
                                                    <div>
                                                        <div class="fw-bold"><?= htmlspecialchars($rule) ?></div>
                                                        <small class="text-muted">
                                                            <?php
                                                            // Add explanations for common tiebreak rules
                                                            $explanations = [
                                                                'countback' => 'Compare highest single scores, then second highest, etc.',
                                                                'head_to_head' => 'Direct comparison between tied participants',
                                                                'latest_score' => 'Most recent attempt breaks the tie',
                                                                'consistency' => 'Lowest score variance wins',
                                                                'best_run' => 'Compare best individual run scores',
                                                                'second_best' => 'Compare second-best run scores',
                                                                'total_attempts' => 'Participant with fewer total attempts wins'
                                                            ];
                                                            
                                                            $ruleKey = strtolower(str_replace(' ', '_', $rule));
                                                            echo isset($explanations[$ruleKey]) ? $explanations[$ruleKey] : 'Standard tiebreak procedure';
                                                            ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <div class="bg-success-subtle text-body mt-3 p-3 rounded">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Final Fallback:</strong> If all tiebreak rules result in identical outcomes, participants receive co-equal rankings (shared position).
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Diversity Rules -->
                        <?php if (!empty($diversityRules)): ?>
                            <div class="mb-4" id="diversity-rules">
                                <h5 class="text-success border-bottom pb-2">
                                    <i class="fas fa-shield-alt me-2"></i>Diversity Rules - Figure Variety Enforcement
                                </h5>
                                <div class="bg-success-subtle text-body p-3 rounded mb-3">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Purpose:</strong> Diversity rules ensure competitive balance by preventing repetitive routines and encouraging variety in figure/trick selection.
                                </div>
                                <div class="row g-3">
                                    <?php foreach ($diversityRules as $rule): ?>
                                        <div class="col-12">
                                            <div class="bg-light p-3 rounded border">
                                                <div class="d-flex justify-content-between align-items-start flex-wrap">
                                                    <div class="flex-grow-1">
                                                        <div class="d-flex align-items-center mb-2">
                                                            <i class="fas fa-gavel text-success me-2"></i>
                                                            <strong class="text-primary"><?= htmlspecialchars($rule['rule_type']) ?></strong>
                                                        </div>
                                                        <?php if ($rule['group_name']): ?>
                                                            <div class="text-muted small">
                                                                <i class="fas fa-layer-group me-1"></i>
                                                                Group: <?= htmlspecialchars($rule['group_name']) ?>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div class="mt-2">
                                                            <small class="text-muted">
                                                                <?php
                                                                // Add explanations based on rule type
                                                                $ruleExplanations = [
                                                                    'no_duplicate' => 'Prevents using the same figure/trick multiple times within the specified scope',
                                                                    'max_per_category' => 'Limits how many figures can be selected from a single category',
                                                                    'min_categories' => 'Requires selection from minimum number of different categories',
                                                                    'balanced_distribution' => 'Ensures even spread across available figure categories'
                                                                ];
                                                                
                                                                $ruleTypeKey = strtolower(str_replace(' ', '_', $rule['rule_type']));
                                                                echo isset($ruleExplanations[$ruleTypeKey]) ? 
                                                                    $ruleExplanations[$ruleTypeKey] : 
                                                                    'Enforces variety in figure selection to maintain competitive integrity';
                                                                ?>
                                                            </small>
                                                        </div>
                                                    </div>
                                                    <div class="d-flex gap-1 flex-wrap">
                                                        <?php if ($rule['scope']): ?>
                                                            <span class="badge bg-secondary">
                                                                <i class="fas fa-crosshairs me-1"></i><?= htmlspecialchars($rule['scope']) ?>
                                                            </span>
                                                        <?php endif; ?>
                                                        <?php if ($rule['min_distinct']): ?>
                                                            <span class="badge bg-warning ">
                                                                <i class="fas fa-hashtag me-1"></i>Min: <?= $rule['min_distinct'] ?>
                                                            </span>
                                                        <?php endif; ?>
                                                        <?php if ($rule['is_optional']): ?>
                                                            <span class="badge bg-info">
                                                                <i class="fas fa-question-circle me-1"></i>Optional
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Rounds Configuration -->
                        <?php if (!empty($rounds)): ?>
                            <div class="mb-4" id="rounds-configuration">
                                <h5 class="text-warning border-bottom pb-2">
                                    <i class="fas fa-layer-group me-2"></i>Rounds Configuration - Tournament Structure
                                </h5>
                                <div class="bg-warning-subtle text-body p-3 rounded mb-3">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Purpose:</strong> Defines the tournament progression from qualifying rounds through finals, including how scores are aggregated at each level.
                                </div>
                                <div class="row g-3">
                                    <?php foreach ($rounds as $index => $round): ?>
                                        <div class="col-md-6">
                                            <div class="bg-light p-3 rounded border">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <h6 class="text-primary mb-0">
                                                        <i class="fas fa-circle-notch me-1"></i><?= htmlspecialchars($round['round_name']) ?>
                                                    </h6>
                                                    <span class="badge bg-primary">
                                                        <i class="fas fa-sort-numeric-up me-1"></i>Round <?= $index + 1 ?>
                                                    </span>
                                                </div>
                                                <div class="mb-2">
                                                    <span class="badge bg-success">
                                                        <i class="fas fa-play me-1"></i><?= $round['runs'] ?> run<?= $round['runs'] != 1 ? 's' : '' ?>
                                                    </span>
                                                </div>
                                                <div class="mb-2">
                                                    <small class="text-muted">
                                                        <i class="fas fa-calculator me-1"></i>
                                                        <strong>Aggregation:</strong> <?= htmlspecialchars($round['aggregation']) ?>
                                                    </small>
                                                </div>
                                                <div class="mt-2">
                                                    <small class="text-muted">
                                                        <?php
                                                        $aggregationExplanations = [
                                                            'sum' => 'All run scores are added together',
                                                            'average' => 'Mean score of all runs',
                                                            'best' => 'Only the highest single run counts',
                                                            'best_2' => 'Top 2 run scores are combined',
                                                            'best_3' => 'Top 3 run scores are combined'
                                                        ];
                                                        
                                                        $aggKey = strtolower(str_replace(' ', '_', $round['aggregation']));
                                                        echo isset($aggregationExplanations[$aggKey]) ? 
                                                            $aggregationExplanations[$aggKey] : 
                                                            'Scores combined using ' . $round['aggregation'] . ' method';
                                                        ?>
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Mode Configuration -->
                        <?php if (!empty($modeConfigs)): ?>
                            <div class="mb-4" id="mode-configuration">
                                <h5 class="text-info border-bottom pb-2">
                                    <i class="fas fa-cogs me-2"></i>Mode Configuration - Sport-Specific Settings
                                </h5>
                                <div class="bg-info-subtle text-body p-3 rounded mb-3">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Purpose:</strong> Sport-specific configurations that define attempt limits, scoring methods, and competition format behavior.
                                </div>
                                <?php foreach ($modeConfigs as $configType => $configs): ?>
                                    <div class="mb-3">
                                        <h6 class="text-primary">
                                            <i class="fas fa-angle-right me-1"></i><?= str_replace('_', ' ', ucwords($configType)) ?>
                                            <small class="text-muted ms-2">
                                                <?php
                                                $typeExplanations = [
                                                    'attempts' => 'Controls how many attempts participants get per round',
                                                    'tricks' => 'Manages trick/figure selection and validation rules',
                                                    'scoring' => 'Defines how individual attempts are scored and combined',
                                                    'timing' => 'Sets time limits and duration constraints'
                                                ];
                                                echo isset($typeExplanations[$configType]) ? 
                                                    '(' . $typeExplanations[$configType] . ')' : '';
                                                ?>
                                            </small>
                                        </h6>
                                        <div class="d-flex flex-wrap gap-2">
                                            <?php foreach ($configs as $key => $value): ?>
                                                <span class="badge bg-light border ">
                                                    <i class="fas fa-cog me-1"></i>
                                                    <strong><?= str_replace('_', ' ', $key) ?>:</strong> <?= $value ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <!-- Summary -->
                        <div class="bg-light text-body border p-3 rounded">
                            <h6><i class="fas fa-clipboard-check me-2"></i>Tiebreak System Summary</h6>
                            <div class="row small">
                                <div class="col-md-3">
                                    <strong>Diversity Rules:</strong> <?= !empty($diversityRules) ? count($diversityRules) . ' active' : 'None configured' ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Round Structure:</strong> <?= !empty($rounds) ? count($rounds) . ' rounds' : 'Not configured' ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Mode Settings:</strong> <?= !empty($modeConfigs) ? count($modeConfigs) . ' categories' : 'Default settings' ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Tiebreak Steps:</strong> <?= !empty($tiebreakRules) ? count($tiebreakRules) . ' rules' : 'Co-equal ranking' ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                

                <!-- Figures Dictionary -->
                <?php if (!empty($figuresBySport)): ?>
                    <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                        <div class="border-0 shadow-none card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-book me-2"></i>Figures Dictionary
                            </h5>
                            <span class="badge bg-light ">
                                <?= count($figuresBySport) ?> categories, 
                                <?= array_sum(array_map('count', $figuresBySport)) ?> items
                            </span>
                        </div>
                        <div class="border-0 shadow-none card-body">
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <span class="text-muted">
                                        Sport: <strong><?= htmlspecialchars($format['sport']) ?></strong>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="accordion" id="figuresAccordion">
                                <?php foreach ($figuresBySport as $categoryName => $items): ?>
                                    <div class="accordion-item">
                                        <h2 class="accordion-header" id="heading-<?= urlencode($categoryName) ?>">
                                            <button class="accordion-button collapsed" type="button" 
                                                    data-bs-toggle="collapse" 
                                                    data-bs-target="#collapse-<?= urlencode($categoryName) ?>" 
                                                    aria-expanded="false" 
                                                    aria-controls="collapse-<?= urlencode($categoryName) ?>">
                                                <i class="fas fa-layer-group me-2"></i>
                                                <strong><?= htmlspecialchars($categoryName) ?></strong>
                                                <span class="badge bg-secondary ms-2"><?= count($items) ?> items</span>
                                            </button>
                                        </h2>
                                        <div id="collapse-<?= urlencode($categoryName) ?>" 
                                             class="accordion-collapse collapse" 
                                             aria-labelledby="heading-<?= urlencode($categoryName) ?>" 
                                             data-bs-parent="#figuresAccordion">
                                            <div class="accordion-body">
                                                <div class="row g-2">
                                                    <?php foreach ($items as $item): ?>
                                                        <div class="col-lg-4 col-md-6 col-sm-12 mb-2">
                                                            <div class="border rounded p-3 bg-light h-100">
                                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                                    <strong class="text-primary"><?= htmlspecialchars($item['item_name']) ?></strong>
                                                                    <?php if (!empty($item['item_code'])): ?>
                                                                        <code class="small bg-white px-1 rounded"><?= htmlspecialchars($item['item_code']) ?></code>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <?php if (!empty($item['item_description'])): ?>
                                                                    <small class="text-muted d-block mb-2">
                                                                        <?= htmlspecialchars($item['item_description']) ?>
                                                                    </small>
                                                                <?php endif; ?>
                                                                <div class="d-flex flex-wrap gap-1">
                                                                    <?php if (!empty($item['difficulty_base'])): ?>
                                                                        <span class="badge bg-warning ">
                                                                            Base: <?= htmlspecialchars($item['difficulty_base']) ?>
                                                                        </span>
                                                                    <?php endif; ?>
                                                                    <?php if (!empty($item['sort_order'])): ?>
                                                                        <span class="badge bg-info">
                                                                            Order: <?= htmlspecialchars($item['sort_order']) ?>
                                                                        </span>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <div class="mt-4">
                                <div class="d-flex flex-wrap gap-2">
                                    <a href="figures_management.php?sport=<?= urlencode($format['sport']) ?>" 
                                       class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-edit me-1"></i>Manage Figures
                                    </a>
                                    <button type="button" class="btn btn-outline-info btn-sm" 
                                            onclick="exportFigures('<?= htmlspecialchars($format['sport']) ?>')">
                                        <i class="fas fa-download me-1"></i>Export JSON
                                    </button>
                                    <button type="button" class="btn btn-outline-success btn-sm" 
                                            onclick="showFigureStats()">
                                        <i class="fas fa-chart-bar me-1"></i>View Stats
                                    </button>
                                </div>
                            </div>
                            
                            <div class="bg-info-subtle text-body mt-3 mb-0 p-3 rounded">
                                <i class="fas fa-lightbulb me-2"></i>
                                <strong>Figures Dictionary Usage:</strong> 
                                These figures can be used for diversity rules, trick identification, and scoring criteria specific to <?= ucfirst($format['sport']) ?> competitions.
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="border-0 shadow-none card border-0 shadow-sm mb-4">
                        <div class="border-0 shadow-none card-header bg-secondary text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-book me-2"></i>Figures Dictionary
                            </h5>
                        </div>
                        <div class="border-0 shadow-none card-body">
                            <div class="bg-warning-subtle text-body p-3 rounded">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                No figure dictionary found for <strong><?= htmlspecialchars($format['sport']) ?></strong>. 
                                <a href="figures_management.php?sport=<?= urlencode($format['sport']) ?>" 
                                   class="text-decoration-none fw-bold">Create one here</a>.
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Results Headers -->
                <?php if (!empty($resultHeaders)): ?>
                    <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                        <div class="border-0 shadow-none card-header bg-info text-white">
                            <h6 class="mb-0">
                                <i class="fas fa-table me-2"></i>Results Table Preview
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <?php foreach ($resultHeaders as $header): ?>
                                                <th class="text-center"><?= htmlspecialchars($header) ?></th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php for ($i = 1; $i <= 3; $i++): ?>
                                            <tr>
                                                <?php foreach ($resultHeaders as $header): ?>
                                                    <td class="text-center text-muted">
                                                        <?= generateSampleDataForHeader($header, $i) ?>
                                                    </td>
                                                <?php endforeach; ?>
                                            </tr>
                                        <?php endfor; ?>
                                    </tbody>
                                </table>
                            </div>
                            <small class="text-muted d-block mt-2">
                                <i class="fas fa-info-circle me-1"></i>
                                This preview shows sample data to demonstrate the results table structure.
                            </small>
                        </div>
                    </div>
                <?php endif; ?>                          
            </div>

            <div class="col-lg-4">
                <!-- Flow Stages -->
                <?php if (!empty($flowStages)): ?>
                    <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                        <div class="border-0 shadow-none card-header bg-dark text-white">
                            <h6 class="mb-0">
                                <i class="fas fa-sitemap me-2"></i>Competition Flow
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body">
                            <?php foreach ($flowStages as $index => $stage): ?>
                                <div class="d-flex align-items-center mb-3 p-2 bg-light rounded">
                                    <span class="badge bg-primary me-3"><?= $index + 1 ?></span>
                                    <span class="flex-grow-1"><?= htmlspecialchars($stage) ?></span>
                                    <?php if ($index < count($flowStages) - 1): ?>
                                        <i class="fas fa-arrow-down text-muted"></i>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Judge Configuration -->
                <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                    <div class="border-0 shadow-none card-header bg-primary text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-gavel me-2"></i>Judge Configuration
                        </h5>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="text-center p-1 bg-light rounded">
                                    <div class="h5 text-primary mb-1">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <strong>Number of Judges</strong>
                                    <div class="mt-2">
                                        <span class="badge bg-secondary fs-6">
                                            <span class="editable-field" data-field="min_judges" data-type="number" data-value="<?= $format['min_judges'] ?>">
                                                <?= $format['min_judges'] ?>
                                            </span><?php if ($format['max_judges'] && $format['max_judges'] != $format['min_judges']): ?>-<span class="editable-field" data-field="max_judges" data-type="number" data-value="<?= $format['max_judges'] ?>"><?= $format['max_judges'] ?></span><?php endif; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center p-1 bg-light rounded">
                                    <div class="h5 text-primary mb-1">
                                        <i class="fas fa-ruler"></i>
                                    </div>
                                    <strong>Scoring Scale</strong>
                                    <div class="mt-2">
                                        <?php if ($format['scale_type'] === 'numeric'): ?>
                                            <span class="badge bg-info fs-6">
                                                <span class="editable-field" data-field="scale_min" data-type="number" data-value="<?= $format['scale_min'] ?>">
                                                    <?= $format['scale_min'] ?>
                                                </span> - 
                                                <span class="editable-field" data-field="scale_max" data-type="number" data-value="<?= $format['scale_max'] ?>">
                                                    <?= $format['scale_max'] ?>
                                                </span>
                                                <?php if ($format['precision_decimal'] > 0): ?>
                                                    (<span class="editable-field" data-field="precision_decimal" data-type="number" data-value="<?= $format['precision_decimal'] ?>"><?= $format['precision_decimal'] ?></span> decimal)
                                                <?php endif; ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-warning fs-6 editable-field" data-field="scale_custom" data-type="text" data-value="<?= htmlspecialchars($format['scale_custom']) ?>">
                                                <?= htmlspecialchars($format['scale_custom']) ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center p-1 bg-light rounded">
                                    <div class="h5 text-primary mb-1">
                                        <i class="fas fa-filter"></i>
                                    </div>
                                    <strong>Drop Rule</strong>
                                    <div class="mt-2">
                                        <span class="badge bg-secondary fs-6 editable-field" 
                                              data-field="drop_rule" data-type="select" data-value="<?= htmlspecialchars($format['drop_rule']) ?>"
                                              data-options='["none","highest","lowest","highest_and_lowest","median"]'>
                                            <?= htmlspecialchars(getDropRuleName($format['drop_rule'])) ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Criteria -->
                <?php if (!empty($criteriaByType)): ?>
                    <div class="border-0 shadow-none card border-0 shadow-sm mb-4 card-hover">
                        <div class="border-0 shadow-none card-header bg-info text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-list-check me-2"></i>Scoring Criteria
                            </h5>
                        </div>
                        <div class="border-0 shadow-none card-body">
                            <?php foreach ($criteriaByType as $type => $criteriaList): ?>
                                <div class="mb-3">
                                    <h6 class="border-bottom pb-2">
                                        <i class="fas fa-tags me-1"></i><?= str_replace('_', ' ', ucwords($type)) ?> Criteria
                                    </h6>
                                    <div class="d-flex flex-wrap gap-2">
                                        <?php foreach ($criteriaList as $criterion): ?>
                                            <span class="bg-primary border btn text-light"><?= htmlspecialchars($criterion) ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
                <!-- JSON Export -->
                <div class="border-0 shadow-none card border-0 shadow-sm card-hover">
                    <div class="border-0 shadow-none card-header bg-success text-white">
                        <h6 class="mb-0">
                            <i class="fas fa-code me-2"></i>JSON Export
                        </h6>
                    </div>
                    <div class="border-0 shadow-none card-body text-center">
                        <div class="mb-3">
                            <i class="fas fa-file-export fa-2x text-success"></i>
                        </div>
                        <p class="text-muted small mb-3">Download this format configuration as a JSON file for backup or import.</p>
                        <button class="btn btn-success w-100" onclick="exportJSON()">
                            <i class="fas fa-download me-2"></i>Export as JSON
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div></div>
    <script>
        // Add fade-in animation on load
        document.addEventListener('DOMContentLoaded', function() {
            const cards = document.querySelectorAll('.card');
            cards.forEach((card, index) => {
                setTimeout(() => {
                    card.classList.add('fade-in');
                }, index * 100);
            });
        });
        function exportJSON() {
            const formatData = {
                id: "<?= $format['format_id'] ?>",
                name: "<?= addslashes($format['name']) ?>",
                sport: "<?= $format['sport'] ?>",
                mode: "<?= $format['mode'] ?>",
                judges: {
                    min: <?= $format['min_judges'] ?>,
                    max: <?= $format['max_judges'] ?? 'null' ?>,
                    scale: <?= $format['scale_type'] === 'numeric' ? '[' . $format['scale_min'] . ', ' . $format['scale_max'] . ']' : '"' . addslashes($format['scale_custom']) . '"' ?>,
                    <?php if ($format['precision_decimal'] > 0): ?>
                    precision: <?= $format['precision_decimal'] ?>,
                    <?php endif; ?>
                    drop: "<?= addslashes($format['drop_rule']) ?>"
                },
                <?php if (!empty($modeConfigs)): ?>
                config: <?= json_encode($modeConfigs) ?>,
                <?php endif; ?>
                <?php if (!empty($rounds)): ?>
                rounds: <?= json_encode(array_reduce($rounds, function($carry, $round) {
                    $carry[$round['round_name']] = [
                        'runs' => (int)$round['runs'],
                        'agg' => $round['aggregation']
                    ];
                    return $carry;
                }, [])) ?>,
                <?php endif; ?>
                <?php if (!empty($criteriaByType)): ?>
                criteria: <?= json_encode($criteriaByType) ?>,
                <?php endif; ?>
                <?php if (!empty($resultHeaders)): ?>
                results: {
                    headers: <?= json_encode($resultHeaders) ?>
                },
                <?php endif; ?>
                <?php if (!empty($flowStages)): ?>
                flow: <?= json_encode($flowStages) ?>,
                <?php endif; ?>
                <?php if (!empty($tiebreakRules)): ?>
                tiebreak: <?= json_encode($tiebreakRules) ?>
                <?php endif; ?>
            };

            const blob = new Blob([JSON.stringify(formatData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '<?= $format['format_id'] ?>.json';
            a.click();
            URL.revokeObjectURL(url);
        }

        // Export figures data for the current sport
        function exportFigures(sport) {
            const figuresData = {
                sport: sport,
                exported_at: new Date().toISOString(),
                figures: <?= json_encode($allFiguresData['by_sport'][$format['sport']] ?? []) ?>,
                stats: {
                    total_categories: <?= count($figuresBySport) ?>,
                    total_items: <?= array_sum(array_map('count', $figuresBySport)) ?>
                }
            };

            const blob = new Blob([JSON.stringify(figuresData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = sport + '_figures.json';
            a.click();
            URL.revokeObjectURL(url);
        }

        // Show figure statistics
        function showFigureStats() {
            const stats = <?= json_encode($allFiguresData['stats'] ?? []) ?>;
            const currentSport = '<?= htmlspecialchars($format['sport']) ?>';
            
            let statsHtml = '<div class="table-responsive"><table class="table table-sm">';
            statsHtml += '<thead><tr><th>Sport</th><th>Categories</th><th>Items</th></tr></thead><tbody>';
            
            stats.forEach(stat => {
                const isCurrentSport = stat.sport_name === currentSport;
                const rowClass = isCurrentSport ? 'table-primary' : '';
                const sportIcon = isCurrentSport ? ' <i class="fas fa-arrow-left"></i>' : '';
                
                statsHtml += `<tr class="${rowClass}">
                    <td><strong>${stat.sport_name}${sportIcon}</strong></td>
                    <td>${stat.category_count}</td>
                    <td>${stat.item_count}</td>
                </tr>`;
            });
            
            statsHtml += '</tbody></table></div>';
            
            // Create modal
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-chart-bar me-2"></i>Figure Dictionary Statistics
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            ${statsHtml}
                            <div class="bg-info-subtle text-body mt-3 p-3 rounded">
                                <i class="fas fa-info-circle me-2"></i>
                                Current sport (${currentSport}) is highlighted.
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }

        // Open Full Panel Modal
        function openFullPanelModal() {
            // Get the current panel content from the judge panel preview container
            const panelPreview = document.getElementById('judgePanelPreview');
            if (!panelPreview) {
                showAlert('Panel preview not loaded yet. Please wait for the panel to generate.', 'warning');
                return;
            }
            
            // Clone the panel content
            const panelContent = panelPreview.cloneNode(true);
            panelContent.id = 'modalJudgePanelPreview'; // Change ID to avoid conflicts
            
            // Create modal
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-xl">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-gavel me-2"></i>Judge Panel Preview - <?= htmlspecialchars($format['name']) ?>
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body" style="max-height: 80vh; overflow-y: auto;">
                            <div class="alert alert-info mb-3">
                                <i class="fas fa-info-circle me-2"></i>
                                This is the full judge panel preview showing exactly what judges will see during scoring sessions.
                            </div>
                            <div id="modalPanelContainer"></div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" onclick="recalculateRunScores()">
                                <i class="fas fa-calculator me-2"></i>Recalculate All Scores
                            </button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // Insert the cloned panel content
            const modalContainer = modal.querySelector('#modalPanelContainer');
            modalContainer.appendChild(panelContent);
            
            // Initialize the modal
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            // Re-attach event listeners for the modal content since it's cloned
            setTimeout(() => {
                addValidationEventListenersToModal(modal);
            }, 300);
            
            // Clean up when modal is hidden
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }
        
        // Add validation event listeners specifically for modal content
        function addValidationEventListenersToModal(modal) {
            // Add event listeners to all score inputs in the modal
            const scoreInputs = modal.querySelectorAll('input[data-run]');
            scoreInputs.forEach(input => {
                input.addEventListener('input', function() {
                    const runIndex = this.dataset.run;
                    if (runIndex) {
                        calculateRunScore(runIndex);
                    }
                });
            });
            
            // Add event listeners to all criterion inputs in the modal
            const criterionInputs = modal.querySelectorAll('input[data-criterion]');
            criterionInputs.forEach(input => {
                input.addEventListener('input', function() {
                    setTimeout(() => {
                        triggerFullValidation();
                    }, 300);
                });
            });
            
            // Add event listeners to all figure selects in the modal
            const figureSelects = modal.querySelectorAll('select[data-run]');
            figureSelects.forEach(select => {
                select.addEventListener('change', function() {
                    const runIndex = this.dataset.run;
                    const categoryId = this.dataset.categoryId;
                    
                    if (categoryId) {
                        validateCategoryDistinctness(runIndex, categoryId);
                    } else {
                        validateRunRequirements(runIndex);
                    }
                    
                    // Also validate competition-level requirements
                    setTimeout(() => {
                        validateCompetitionDiversity();
                    }, 100);
                });
            });
            
            console.log(`Added modal validation listeners to ${scoreInputs.length} score inputs, ${criterionInputs.length} criterion inputs, and ${figureSelects.length} figure selects`);
        }

        // Enhanced search functionality for figures
        function searchFigures() {
            const searchTerm = document.getElementById('figureSearch')?.value.toLowerCase() || '';
            const items = document.querySelectorAll('#figuresAccordion .accordion-body .border');
            
            items.forEach(item => {
                const text = item.textContent.toLowerCase();
                const shouldShow = text.includes(searchTerm);
                item.style.display = shouldShow ? 'block' : 'none';
            });
            
            // Show/hide accordion sections based on whether they have visible items
            document.querySelectorAll('#figuresAccordion .accordion-item').forEach(section => {
                const visibleItems = section.querySelectorAll('.accordion-body .border[style="display: block"], .accordion-body .border:not([style*="display: none"])');
                const hasVisibleItems = visibleItems.length > 0;
                section.style.display = hasVisibleItems ? 'block' : 'none';
            });
        }

        // Inline Editing Functionality
        let editMode = false;
        let originalValues = {};
        let pendingChanges = {};

        function toggleEditMode() {
            editMode = !editMode;
            const editButton = document.getElementById('editButtonText');
            const saveBtn = document.getElementById('saveChangesBtn');
            const cancelBtn = document.getElementById('cancelEditBtn');
            const editAlert = document.getElementById('editModeAlert');
            
            if (editMode) {
                editButton.textContent = 'Disable Editing';
                saveBtn.classList.remove('d-none');
                cancelBtn.classList.remove('d-none');
                editAlert.classList.remove('d-none');
                enableEditableFields();
            } else {
                editButton.textContent = 'Enable Editing';
                saveBtn.classList.add('d-none');
                cancelBtn.classList.add('d-none');
                editAlert.classList.add('d-none');
                disableEditableFields();
            }
        }

        function enableEditableFields() {
            const editableFields = document.querySelectorAll('.editable-field');
            editableFields.forEach(field => {
                // Store original value
                originalValues[field.dataset.field] = field.dataset.value;
                
                // Add click handler and visual feedback
                field.style.cursor = 'pointer';
                field.style.border = '1px dashed rgba(255,255,255,0.5)';
                field.style.padding = '2px 4px';
                field.style.borderRadius = '3px';
                field.title = 'Click to edit';
                
                field.addEventListener('click', handleFieldClick);
            });
        }

        function disableEditableFields() {
            const editableFields = document.querySelectorAll('.editable-field');
            editableFields.forEach(field => {
                field.style.cursor = 'default';
                field.style.border = 'none';
                field.style.padding = '';
                field.title = '';
                field.removeEventListener('click', handleFieldClick);
            });
        }

        function handleFieldClick(event) {
            if (!editMode) return;
            
            const field = event.target;
            const fieldName = field.dataset.field;
            const fieldType = field.dataset.type;
            const currentValue = field.dataset.value;
            
            if (fieldType === 'boolean') {
                toggleBooleanField(field, fieldName);
            } else if (fieldType === 'select') {
                showSelectEditor(field, fieldName, currentValue);
            } else {
                showTextEditor(field, fieldName, currentValue, fieldType);
            }
        }

        function toggleBooleanField(field, fieldName) {
            const currentValue = field.dataset.value === '1';
            const newValue = currentValue ? '0' : '1';
            
            field.dataset.value = newValue;
            pendingChanges[fieldName] = newValue;
            
            // Update visual display
            if (newValue === '1') {
                field.className = field.className.replace('bg-secondary', 'bg-success');
                field.innerHTML = '<i class="fas fa-check-circle me-1"></i>Active';
            } else {
                field.className = field.className.replace('bg-success', 'bg-secondary');
                field.innerHTML = '<i class="fas fa-pause-circle me-1"></i>Inactive';
            }
            
            showUnsavedChangesIndicator();
        }

        // Get human-readable drop rule name
        function getDropRuleDisplayName(dropRuleKey) {
            const dropRuleNames = {
                'none': 'None',
                'highest': 'Drop Highest',
                'lowest': 'Drop Lowest',
                'highest_and_lowest': 'Drop High/Low',
                'median': 'Median Score',
                'drop high/low': 'Drop High/Low',
                'drop high/low per wave': 'Drop High/Low per Wave',
                'drop high/low per trick': 'Drop High/Low per Trick',
                'components': 'Components',
                'n/a': 'N/A'
            };
            
            return dropRuleNames[dropRuleKey] || dropRuleKey.replace('_', ' ');
        }

        function showSelectEditor(field, fieldName, currentValue) {
            const options = JSON.parse(field.dataset.options);
            let selectHtml = `<select class="form-select form-select-sm" onchange="updateFieldValue('${fieldName}', this.value, this)">`;
            
            options.forEach(option => {
                const selected = option === currentValue ? 'selected' : '';
                let displayName;
                
                if (fieldName === 'drop_rule') {
                    displayName = getDropRuleDisplayName(option);
                } else {
                    displayName = option.replace('_', ' ');
                }
                
                selectHtml += `<option value="${option}" ${selected}>${displayName}</option>`;
            });
            selectHtml += '</select>';
            
            const originalHtml = field.innerHTML;
            field.innerHTML = selectHtml;
            
            // Focus and handle blur
            const select = field.querySelector('select');
            select.focus();
            select.addEventListener('blur', () => {
                setTimeout(() => {
                    if (!select.matches(':focus')) {
                        field.innerHTML = originalHtml;
                    }
                }, 100);
            });
        }

        function showTextEditor(field, fieldName, currentValue, fieldType) {
            const inputType = fieldType === 'number' ? 'number' : 'text';
            const originalHtml = field.innerHTML;
            
            field.innerHTML = `<input type="${inputType}" class="form-control form-control-sm" value="${currentValue}" 
                               onblur="updateFieldFromInput('${fieldName}', this)" 
                               onkeypress="if(event.key==='Enter') this.blur()" style="min-width: 100px;">`;
            
            const input = field.querySelector('input');
            input.focus();
            input.select();
            
            // Store original HTML for restoration
            input.dataset.originalHtml = originalHtml;
        }

        function updateFieldValue(fieldName, newValue, selectElement) {
            const field = selectElement.closest('.editable-field');
            field.dataset.value = newValue;
            pendingChanges[fieldName] = newValue;
            
            // Update display
            let displayValue;
            if (fieldName === 'drop_rule') {
                displayValue = getDropRuleDisplayName(newValue);
            } else if (fieldName === 'sport') {
                displayValue = newValue.replace('_', ' ').charAt(0).toUpperCase() + newValue.replace('_', ' ').slice(1);
            } else {
                displayValue = newValue.replace('_', ' ');
            }
            
            setTimeout(() => {
                field.innerHTML = displayValue;
                enableEditableFields(); // Re-enable editing for this field
            }, 100);
            
            showUnsavedChangesIndicator();
        }

        function updateFieldFromInput(fieldName, inputElement) {
            const newValue = inputElement.value;
            const field = inputElement.closest('.editable-field');
            
            if (newValue !== field.dataset.value) {
                field.dataset.value = newValue;
                pendingChanges[fieldName] = newValue;
                showUnsavedChangesIndicator();
            }
            
            // Restore original display
            field.innerHTML = inputElement.dataset.originalHtml.replace(
                field.dataset.value, 
                newValue
            );
            field.dataset.value = newValue;
            
            enableEditableFields(); // Re-enable editing for this field
        }

        function showUnsavedChangesIndicator() {
            const saveBtn = document.getElementById('saveChangesBtn');
            if (Object.keys(pendingChanges).length > 0) {
                saveBtn.classList.add('pulse');
                saveBtn.innerHTML = `<i class="fas fa-save me-2"></i>Save Changes (${Object.keys(pendingChanges).length})`;
            }
        }

        function saveAllChanges() {
            if (Object.keys(pendingChanges).length === 0) {
                showAlert('No changes to save.', 'info');
                return;
            }

            const saveBtn = document.getElementById('saveChangesBtn');
            const originalHtml = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
            saveBtn.disabled = true;

            fetch('scoring_format_update.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    format_id: '<?= $formatId ?>',
                    changes: pendingChanges
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('Changes saved successfully!', 'success');
                    pendingChanges = {};
                    saveBtn.innerHTML = '<i class="fas fa-save me-2"></i>Save Changes';
                    saveBtn.classList.remove('pulse');
                    
                    // Update original values
                    Object.keys(data.updated_values || {}).forEach(key => {
                        originalValues[key] = data.updated_values[key];
                    });
                } else {
                    showAlert('Error saving changes: ' + (data.error || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                showAlert('Network error: ' + error.message, 'danger');
            })
            .finally(() => {
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalHtml;
            });
        }

        function cancelEdit() {
            // Restore original values
            Object.keys(pendingChanges).forEach(fieldName => {
                const field = document.querySelector(`[data-field="${fieldName}"]`);
                if (field) {
                    const originalValue = originalValues[fieldName];
                    field.dataset.value = originalValue;
                    
                    // Restore visual display based on field type
                    if (field.dataset.type === 'boolean') {
                        if (originalValue === '1') {
                            field.className = field.className.replace('bg-secondary', 'bg-success');
                            field.innerHTML = '<i class="fas fa-check-circle me-1"></i>Active';
                        } else {
                            field.className = field.className.replace('bg-success', 'bg-secondary');
                            field.innerHTML = '<i class="fas fa-pause-circle me-1"></i>Inactive';
                        }
                    } else {
                        // For text fields, just update the text content
                        field.textContent = originalValue;
                    }
                }
            });
            
            pendingChanges = {};
            const saveBtn = document.getElementById('saveChangesBtn');
            saveBtn.innerHTML = '<i class="fas fa-save me-2"></i>Save Changes';
            saveBtn.classList.remove('pulse');
            
            showAlert('Changes cancelled.', 'info');
        }

        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `bg-${type}-subtle text-body p-3 rounded position-fixed border`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close float-end" onclick="this.parentElement.remove()"></button>
            `;
            
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }

        // Add pulse animation CSS
        const style = document.createElement('style');
        style.textContent = `
            .pulse {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }
            .editable-field:hover {
                background-color: rgba(255,255,255,0.1) !important;
                transition: background-color 0.2s ease;
            }
        `;
        document.head.appendChild(style);
    </script>

    <script>
        // Judge Panel Preview Generation
        document.addEventListener('DOMContentLoaded', function() {
            // Format criteria data from PHP
            const formatCriteria = <?= json_encode($criteriaByType) ?>;
            const diversityRules = <?= json_encode($diversityRules) ?>;
            const figuresData = <?= json_encode($figuresBySport) ?>;
            const formatConfig = {
                format_id: '<?= htmlspecialchars($formatId) ?>',
                name: '<?= htmlspecialchars($format['name']) ?>',
                sport: '<?= htmlspecialchars($format['sport']) ?>',
                mode: '<?= htmlspecialchars($format['mode']) ?>',
                scale_type: '<?= htmlspecialchars($format['scale_type']) ?>',
                scale_min: <?= $format['scale_min'] ?? 0 ?>,
                scale_max: <?= $format['scale_max'] ?? 10 ?>,
                scale_custom: '<?= htmlspecialchars($format['scale_custom'] ?? '') ?>',
                min_judges: <?= $format['min_judges'] ?? 1 ?>,
                max_judges: <?= $format['max_judges'] ?? 5 ?>,
                drop_rule: '<?= htmlspecialchars($format['drop_rule'] ?? 'none') ?>',
                precision_decimal: <?= $format['precision_decimal'] ?? 1 ?>,
                has_diversity_rules: <?= !empty($diversityRules) ? 'true' : 'false' ?>,
                rounds: <?= json_encode($rounds) ?>,
                total_runs: <?= !empty($rounds) ? max(array_column($rounds, 'runs')) : 3 ?>
            };
            
            // Generate the judge panel preview
            generateJudgePanelPreview(formatCriteria, formatConfig, diversityRules, figuresData);
            
            // Initialize diversity validation after a short delay to ensure elements are rendered
            setTimeout(() => {
                updateFinalScoreValidation();
                
                // Add event listeners to all scoring inputs for real-time validation
                addValidationEventListeners();
            }, 500);
        });
        
        function addValidationEventListeners() {
            // Add event listeners to all score inputs
            const scoreInputs = document.querySelectorAll('input[data-run]');
            scoreInputs.forEach(input => {
                input.addEventListener('input', function() {
                    const runIndex = this.dataset.run;
                    // Debounce the validation to avoid excessive calls
                    clearTimeout(this.validationTimeout);
                    this.validationTimeout = setTimeout(() => {
                        calculateRunScore(runIndex);
                    }, 300);
                });
            });
            
            // Add event listeners to all criterion inputs
            const criterionInputs = document.querySelectorAll('input[data-criterion]');
            criterionInputs.forEach(input => {
                input.addEventListener('input', function() {
                    const runIndex = this.dataset.run;
                    if (runIndex) {
                        // Debounce the calculation to avoid excessive calls
                        clearTimeout(this.criterionTimeout);
                        this.criterionTimeout = setTimeout(() => {
                            // Recalculate run score based on criteria
                            const calculatedScore = calculateRunScore(runIndex);
                            
                            // Update the final run score input in the final score section
                            const finalScoreInput = document.getElementById(`finalRunScore_${runIndex}`);
                            if (finalScoreInput) {
                                finalScoreInput.value = calculatedScore;
                                
                                // Update source indicator
                                const sourceIndicator = document.getElementById(`runScoreSource_${runIndex}`);
                                if (sourceIndicator) {
                                    sourceIndicator.innerHTML = '<i class="fas fa-sync text-success me-1"></i>Updated from criteria';
                                    setTimeout(() => {
                                        sourceIndicator.innerHTML = '<i class="fas fa-calculator me-1"></i>Auto-calculated from criteria';
                                    }, 2000);
                                }
                            }
                            
                            triggerFullValidation();
                        }, 300);
                    }
                });
            });
            
            // Add event listeners to all figure selects
            const figureSelects = document.querySelectorAll('select[data-run]');
            figureSelects.forEach(select => {
                select.addEventListener('change', function() {
                    // Trigger validation after figure selection
                    setTimeout(() => {
                        triggerFullValidation();
                    }, 100);
                });
            });
            
            console.log(`Added validation listeners to ${scoreInputs.length} score inputs, ${criterionInputs.length} criterion inputs, and ${figureSelects.length} figure selects`);
        }
        
        function updateIndividualRunScore(runIndex, newScore) {
            // Update the individual run score manually
            const finalScoreInput = document.getElementById(`finalRunScore_${runIndex}`);
            if (finalScoreInput) {
                finalScoreInput.value = parseFloat(newScore).toFixed(1);
                
                // Update source indicator to show manual entry
                const sourceIndicator = document.getElementById(`runScoreSource_${runIndex}`);
                if (sourceIndicator) {
                    sourceIndicator.innerHTML = '<i class="fas fa-user-edit text-info me-1"></i>Manually entered';
                }
                
                // Update the run score field that other functions rely on
                const runScoreField = document.getElementById(`runScore_${runIndex}`);
                if (runScoreField) {
                    runScoreField.value = parseFloat(newScore).toFixed(1);
                }
                
                // Trigger full validation and final score recalculation
                setTimeout(() => {
                    triggerFullValidation();
                    updateFinalScoreCalculation();
                }, 100);
            }
        }
        
        function generateJudgePanelPreview(criteriaByType, config, diversityRules = [], figuresData = {}) {
            const container = document.getElementById('judgePanelPreview');
            
            if (!criteriaByType || Object.keys(criteriaByType).length === 0) {
                container.innerHTML = `
                    <div class="text-center py-4">
                        <i class="fas fa-exclamation-triangle fa-2x text-muted mb-3"></i>
                        <p class="text-muted">No scoring criteria configured for this format.</p>
                        <a href="scoring_format_edit.php?id=${config.format_id}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-plus me-1"></i>Add Criteria
                        </a>
                    </div>
                `;
                return;
            }
            
            // Check if we have diversity rules and figures
            const hasDiversityRules = diversityRules.length > 0;
            const hasFigures = Object.keys(figuresData).length > 0;
            const totalRuns = config.total_runs || 3; // Default to 3 runs
            
            let panelHTML = `
                <div class="judge-panel-header mb-3">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h6 class="mb-1"><i class="fas fa-user-tie me-1"></i>Judge Panel</h6>
                            <small class="text-muted">${config.name} - ${config.sport}</small>
                        </div>
                        <div class="col-md-6 text-end">
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-secondary">
                                    <i class="fas fa-user me-1"></i>J1
                                </button>
                                <button type="button" class="btn btn-outline-secondary active">
                                    <i class="fas fa-user me-1"></i>J2
                                </button>
                                <button type="button" class="btn btn-outline-secondary">
                                    <i class="fas fa-user me-1"></i>J3
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row g-3">
            `;
            
            // Participant info section (simplified)
            panelHTML += `
                <div class="col-12">
                    <div class="border-0 shadow-none card bg-primary bg-opacity-10 border-primary">
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row align-items-center">
                                <div class="col-md-4">
                                    <label class="form-label small mb-1">Participant</label>
                                    <input type="text" class="form-control form-control-sm" value="Alex Johnson" readonly>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label small mb-1">Bib</label>
                                    <input type="text" class="form-control form-control-sm" value="101" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label small mb-1">Timer</label>
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-text bg-success text-white">
                                            <i class="fas fa-clock"></i>
                                        </span>
                                        <input type="text" class="form-control" value="02:30" readonly>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label small mb-1">&nbsp;</label>
                                    <button class="btn btn-sm btn-warning w-100">
                                        <i class="fas fa-play me-1"></i>Start Timer
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Generate individual run rows
            for (let runIndex = 1; runIndex <= totalRuns; runIndex++) {
                panelHTML += generateRunRow(runIndex, criteriaByType, config, hasDiversityRules, hasFigures, figuresData, diversityRules);
            }
            
            // Add overall final score section
            panelHTML += generateFinalScoreSection(config, totalRuns);
            
            panelHTML += '</div>'; // Close row
            
            container.innerHTML = panelHTML;
        }
        
        function generateSectionsPanel(criteria, config) {
            const scaleInfo = getScaleInfo(config);
            
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-primary">
                        <div class="border-0 shadow-none card-header bg-primary text-white py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-layer-group me-1"></i>Sections Scoring
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
                                ${criteria.map((criterion, index) => `
                                    <div class="col-md-3">
                                        <label class="form-label small mb-1">${criterion}</label>
                                        <input type="number" class="form-control form-control-sm" 
                                               placeholder="${scaleInfo.placeholder}" 
                                               min="${scaleInfo.min}" max="${scaleInfo.max}" 
                                               step="${scaleInfo.step}" 
                                               value="${(Math.random() * (scaleInfo.max - scaleInfo.min) + scaleInfo.min).toFixed(1)}">
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function generateOIPanel(criteria, config) {
            const scaleInfo = getScaleInfo(config);
            
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-info">
                        <div class="border-0 shadow-none card-header bg-info text-white py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-trophy me-1"></i>Overall Impression
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
                                ${criteria.map(criterion => `
                                    <div class="col-md-4">
                                        <label class="form-label small mb-1">${criterion}</label>
                                        <input type="number" class="form-control form-control-sm" 
                                               placeholder="${scaleInfo.placeholder}" 
                                               min="${scaleInfo.min}" max="${scaleInfo.max}" 
                                               step="${scaleInfo.step}" 
                                               value="${(Math.random() * (scaleInfo.max - scaleInfo.min) + scaleInfo.min).toFixed(1)}">
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function generateAttemptsPanel(criteria, config) {
            const scaleInfo = getScaleInfo(config);
            
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-warning">
                        <div class="border-0 shadow-none card-header bg-warning text-dark py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-redo me-1"></i>Attempts/Runs
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
                                ${criteria.map((criterion, index) => `
                                    <div class="col-md-3">
                                        <label class="form-label small mb-1">${criterion}</label>
                                        <div class="input-group input-group-sm">
                                            <input type="number" class="form-control" 
                                                   placeholder="${scaleInfo.placeholder}" 
                                                   min="${scaleInfo.min}" max="${scaleInfo.max}" 
                                                   step="${scaleInfo.step}" 
                                                   value="${(Math.random() * (scaleInfo.max - scaleInfo.min) + scaleInfo.min).toFixed(1)}">
                                            <span class="input-group-text">${index + 1}</span>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function generateTricksPanel(criteria, config) {
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-success">
                        <div class="border-0 shadow-none card-header bg-success text-white py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-magic me-1"></i>Tricks/Elements
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
                                ${criteria.map(criterion => `
                                    <div class="col-md-6">
                                        <label class="form-label small mb-1">${criterion}</label>
                                        <div class="input-group input-group-sm">
                                            <select class="form-select">
                                                <option>Select Figure</option>
                                                <option selected>Double Cork 1440</option>
                                                <option>Triple Cork 1620</option>
                                                <option>Switch Backside 900</option>
                                            </select>
                                            <input type="number" class="form-control" style="max-width: 80px;" 
                                                   placeholder="Score" value="8.5">
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function generateComparativePanel(criteria, config) {
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-secondary">
                        <div class="border-0 shadow-none card-header bg-secondary text-white py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-balance-scale me-1"></i>Comparative Judging
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
                                ${criteria.map(criterion => `
                                    <div class="col-md-4">
                                        <label class="form-label small mb-1">${criterion}</label>
                                        <div class="btn-group w-100" role="group">
                                            <button type="button" class="btn btn-outline-danger btn-sm">A Wins</button>
                                            <button type="button" class="btn btn-outline-success btn-sm active">B Wins</button>
                                            <button type="button" class="btn btn-outline-secondary btn-sm">Tie</button>
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function generateGenericPanel(type, criteria, config) {
            const scaleInfo = getScaleInfo(config);
            const typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
            
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-dark">
                        <div class="border-0 shadow-none card-header bg-dark text-white py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-cogs me-1"></i>${typeLabel}
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
                                ${criteria.map(criterion => `
                                    <div class="col-md-3">
                                        <label class="form-label small mb-1">${criterion}</label>
                                        <input type="number" class="form-control form-control-sm" 
                                               placeholder="${scaleInfo.placeholder}" 
                                               min="${scaleInfo.min}" max="${scaleInfo.max}" 
                                               step="${scaleInfo.step}" 
                                               value="${(Math.random() * (scaleInfo.max - scaleInfo.min) + scaleInfo.min).toFixed(1)}">
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function generateRunRow(runIndex, criteriaByType, config, hasDiversityRules, hasFigures, figuresData, diversityRules = []) {
            const scaleInfo = getScaleInfo(config);
            const runScore = (Math.random() * (scaleInfo.max - scaleInfo.min) + scaleInfo.min).toFixed(1);
            const isCurrentRun = runIndex === 2; // Highlight run 2 as current
            const cardClass = isCurrentRun ? 'border-warning' : 'border-secondary';
            const headerClass = isCurrentRun ? 'bg-warning text-dark' : 'bg-secondary';
            
            let runHTML = `
                <div class="col-12">
                    <div class="border-0 shadow-none card ${cardClass} mb-3">
                        <div class="border-0 shadow-none card-header ${headerClass} py-2">
                            <div class="row align-items-center">
                                <div class="col-md-6">
                                    <h6 class="mb-0">
                                        <i class="fas fa-running me-1"></i>Run ${runIndex}
                                        ${isCurrentRun ? '<span class="badge bg-primary ms-2">CURRENT</span>' : ''}
                                    </h6>
                                </div>
                                <div class="col-md-6 text-end">
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button type="button" class="btn btn-outline-${isCurrentRun ? 'dark' : 'light'} btn-sm">
                                            <i class="fas fa-play me-1"></i>Start
                                        </button>
                                        <button type="button" class="btn btn-outline-${isCurrentRun ? 'dark' : 'light'} btn-sm">
                                            <i class="fas fa-stop me-1"></i>Stop
                                        </button>
                                        <button type="button" class="btn btn-outline-${isCurrentRun ? 'dark' : 'light'} btn-sm">
                                            <i class="fas fa-undo me-1"></i>Reset
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
            `;
            
            // Figure Selection (if diversity rules apply)
            if (hasDiversityRules && hasFigures) {
                runHTML += generateFigureSelectionForRun(runIndex, figuresData, diversityRules);
            }
            
            // Scoring Criteria
            runHTML += `
                <div class="row g-2 mb-3">
                    <div class="col-12">
                        <label class="form-label small mb-1 fw-bold text-primary">
                            <i class="fas fa-star me-1"></i>Scoring Criteria
                        </label>
                    </div>
            `;
            
            // Generate scoring inputs based on criteria types
            const criteriaTypes = Object.keys(criteriaByType);
            let inputCount = 0;
            
            criteriaTypes.forEach(type => {
                const criteria = criteriaByType[type];
                criteria.forEach(criterion => {
                    inputCount++;
                    const sampleScore = (Math.random() * (scaleInfo.max - scaleInfo.min) + scaleInfo.min).toFixed(1);
                    const colSize = inputCount <= 4 ? 'col-md-3' : 'col-md-2';
                    
                    runHTML += `
                        <div class="${colSize}">
                            <label class="form-label small mb-1">${criterion}</label>
                            <input type="number" class="form-control form-control-sm run-criterion-input" 
                                   data-run="${runIndex}" data-criterion="${criterion}"
                                   placeholder="${scaleInfo.placeholder}" 
                                   min="${scaleInfo.min}" max="${scaleInfo.max}" 
                                   step="${scaleInfo.step}" 
                                   value="${sampleScore}"
                                   onchange="calculateRunScore(${runIndex})">
                        </div>
                    `;
                });
            });
            
            runHTML += `
                </div>
                
                <!-- Run Final Score -->
                <div class="row g-2 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label small mb-1 fw-bold text-success">
                            <i class="fas fa-calculator me-1"></i>Run ${runIndex} Final Score
                        </label>
                        <input type="number" class="form-control form-control-sm bg-success text-white fw-bold" 
                               id="runScore_${runIndex}" value="${runScore}" readonly>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small mb-1">Validation</label>
                        <div>
                            <span class="badge bg-success">
                                <i class="fas fa-check-circle me-1"></i>Valid
                            </span>
                            ${hasDiversityRules ? '<span class="badge bg-info ms-1"><i class="fas fa-shapes me-1"></i>Diversity OK</span>' : ''}
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <button type="button" class="btn btn-success btn-sm me-2" onclick="submitRun(${runIndex})">
                            <i class="fas fa-check me-1"></i>Submit Run ${runIndex}
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearRun(${runIndex})">
                            <i class="fas fa-trash me-1"></i>Clear
                        </button>
                    </div>
                </div>
            `;
            
            runHTML += `
                        </div>
                    </div>
                </div>
            `;
            
            return runHTML;
        }
        
        function generateFinalScoreSection(config, totalRuns) {
            // Calculate run scores based on actual judge panel data
            const runScores = [];
            let totalScore = 0;
            
            for (let i = 1; i <= totalRuns; i++) {
                // Get the calculated score from the run's final score input
                const runScoreElement = document.getElementById(`runScore_${i}`);
                let score;
                
                if (runScoreElement && runScoreElement.value) {
                    // Use actual calculated score from the run
                    score = parseFloat(runScoreElement.value);
                } else {
                    // Fallback: simulate realistic scoring based on criteria complexity
                    const scaleInfo = getScaleInfo(config);
                    const baseScore = (scaleInfo.max - scaleInfo.min) * 0.7 + scaleInfo.min; // 70% of scale range
                    
                    // Add run-specific variation (Run 2 typically scores higher)
                    let runMultiplier = 1.0;
                    if (i === 1) runMultiplier = 0.85;      // First run: more conservative
                    else if (i === 2) runMultiplier = 1.15; // Second run: peak performance  
                    else if (i === 3) runMultiplier = 0.95; // Third run: slight fatigue
                    
                    score = parseFloat((baseScore * runMultiplier).toFixed(1));
                }
                
                runScores.push(score);
                totalScore += score;
            }
            
            const averageScore = (totalScore / totalRuns).toFixed(1);
            const bestScore = Math.max(...runScores).toFixed(1);
            
            return `
                <div class="col-12">
                    <div class="border-0 shadow-none card border-success bg-success bg-opacity-10">
                        <div class="border-0 shadow-none card-header bg-success text-white py-2">
                            <h5 class="mb-0">
                                <i class="fas fa-trophy me-2"></i>Final Score Calculation
                            </h5>
                        </div>
                        <div class="border-0 shadow-none card-body py-3">
                            <!-- Run Scores Summary with Figure Selection -->
                            <div class="row g-3 mb-4">
                                <div class="col-12">
                                    <label class="form-label small mb-2 fw-bold">Individual Run Scores & Figure Selection</label>
                                    <div class="row g-3" id="runScoresFiguresDisplay">
                                        ${runScores.map((score, index) => {
                                            const runIndex = index + 1;
                                            const runStatus = index === 0 ? 'Conservative' : 
                                                            index === 1 ? 'Peak Performance' : 'Solid Finish';
                                            
                                            return `
                                                <div class="col-md-4">
                                                    <div class="border-0 shadow-none card border-primary h-100">
                                                        <div class="border-0 shadow-none card-header bg-primary text-white py-2">
                                                            <div class="d-flex justify-content-between align-items-center">
                                                                <span class="fw-bold">Run ${runIndex}</span>
                                                                <div class="text-end">
                                                                    <div class="d-flex align-items-center gap-2">
                                                                        <label class="small mb-0 text-white-50">Final Score:</label>
                                                                        <input type="number" 
                                                                               id="finalRunScore_${runIndex}" 
                                                                               class="form-control form-control-sm bg-transparent text-white fw-bold border-white" 
                                                                               style="width: 70px; text-align: center;" 
                                                                               value="${score}" 
                                                                               step="0.1"
                                                                               onchange="updateIndividualRunScore(${runIndex}, this.value)"
                                                                               onclick="this.select()">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="border-0 shadow-none card-body py-2 small">
                                                            <div class="mb-2">
                                                                <strong>Status:</strong> <span class="text-muted">${runStatus}</span>
                                                                <div class="mt-1">
                                                                    <small class="text-muted">
                                                                        <i class="fas fa-calculator me-1"></i>
                                                                        <span id="runScoreSource_${runIndex}">Auto-calculated from criteria</span>
                                                                    </small>
                                                                </div>
                                                            </div>
                                                            <div class="mb-2">
                                                                <strong>Figures Selected:</strong>
                                                                <div id="runFiguresDisplay_${runIndex}" class="mt-1">
                                                                    <div class="text-muted">
                                                                        <i class="fas fa-spinner fa-spin me-1"></i>Loading figures...
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div>
                                                                <strong>Diversity:</strong>
                                                                <span class="diversity-indicator" data-run="${runIndex}" id="runDiversitySummary_${runIndex}">
                                                                    <i class="fas fa-spinner fa-spin"></i> Checking...
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            `;
                                        }).join('')}
                                    </div>
                                    
                                    <!-- Score Calculation Details -->
                                    <div class="mt-3 row g-2">
                                        <div class="col-md-3">
                                            <div class="small text-muted">
                                                <strong>Total Score:</strong> ${totalScore.toFixed(1)}
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="small text-muted">
                                                <strong>Average:</strong> ${averageScore}
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="small text-success">
                                                <strong>Best Score:</strong> ${bestScore}
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="small text-muted">
                                                <strong>Score Range:</strong> ${(Math.max(...runScores) - Math.min(...runScores)).toFixed(1)}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Competition Diversity Rules Validation -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <div class="border rounded p-3 bg-light">
                                        <h6 class="mb-3">
                                            <i class="fas fa-globe me-2 text-warning"></i>Competition Diversity Rules Validation
                                        </h6>
                                        <div id="competitionDiversityValidation">
                                            <!-- Will be populated by JavaScript -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Final Score Calculation -->
                            <div class="row g-3 align-items-center">
                                <div class="col-md-3">
                                    <label class="form-label small mb-1 fw-bold">Aggregation Method</label>
                                    <select class="form-select form-select-sm bg-info text-white" disabled>
                                        <option selected>Best Score</option>
                                        <option>Average</option>
                                        <option>Sum</option>
                                        <option>Best 2 of 3</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label small mb-1 fw-bold">Calculated Score</label>
                                    <input type="number" class="form-control form-control-sm bg-warning text-dark fw-bold" 
                                           value="${bestScore}" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label small mb-1 fw-bold">Final Score</label>
                                    <input type="number" class="form-control form-control-sm bg-success text-white fw-bold fs-5" 
                                           value="${bestScore}" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label small mb-1">Overall Status</label>
                                    <div>
                                        <span class="badge bg-success fs-6 p-2" id="overallSubmissionStatus">
                                            <i class="fas fa-check-circle me-1"></i>COMPLETE
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Validation Summary -->
                            <div class="row mt-4">
                                <div class="col-12">
                                    <div class="bg-light p-3 rounded">
                                        <h6 class="mb-2"><i class="fas fa-clipboard-check me-1"></i>Validation Summary</h6>
                                        <div class="row small">
                                            <div class="col-md-3">
                                                <i class="fas fa-check text-success me-1"></i>All runs completed: <strong>${totalRuns}/${totalRuns}</strong>
                                            </div>
                                            <div class="col-md-3">
                                                <i class="fas fa-check text-success me-1"></i>Scores within range: <strong>Yes</strong>
                                            </div>
                                            <div class="col-md-3" id="diversityValidationSummary">
                                                <i class="fas fa-spinner fa-spin text-muted me-1"></i>Diversity rules: <strong>Checking...</strong>
                                            </div>
                                            <div class="col-md-3" id="submissionReadiness">
                                                <i class="fas fa-hourglass-half text-warning me-1"></i>Ready to submit: <strong>Pending</strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Action Buttons -->
                            <div class="row mt-4">
                                <div class="col-12 text-center">
                                    <button type="button" class="btn btn-success btn-lg me-3" id="submitFinalScoreBtn">
                                        <i class="fas fa-paper-plane me-2"></i>Submit Final Score
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="recalculateRunScores()">
                                        <i class="fas fa-undo me-2"></i>Recalculate Scores
                                    </button>
                                    <button type="button" class="btn btn-outline-info ms-3">
                                        <i class="fas fa-save me-2"></i>Save Draft
                                    </button>
                                    <button type="button" class="btn btn-outline-warning ms-2" onclick="showDiversityDetails()">
                                        <i class="fas fa-info-circle me-2"></i>Diversity Details
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function getScaleInfo(config) {
            if (config.scale_type === 'numeric') {
                const min = config.scale_min;
                const max = config.scale_max;
                const step = max <= 10 ? 0.1 : 1;
                return {
                    min: min,
                    max: max,
                    step: step,
                    placeholder: `${min}-${max}`
                };
            } else {
                // Custom scale - assume 0-10 for preview
                return {
                    min: 0,
                    max: 10,
                    step: 0.1,
                    placeholder: config.scale_custom || '0-10'
                };
            }
        }
        
        function generateFigureSelectionSection(diversityRules, figuresData, config) {
            let sectionHTML = `
                <div class="col-12">
                    <div class="border-0 shadow-none card bg-info bg-opacity-10 border-info">
                        <div class="border-0 shadow-none card-header bg-info text-white py-2">
                            <h6 class="mb-0">
                                <i class="fas fa-shapes me-1"></i>Figure Selection
                                <span class="badge bg-light text-dark ms-2">
                                    <i class="fas fa-shield-alt me-1"></i>Diversity Rules Active
                                </span>
                            </h6>
                        </div>
                        <div class="border-0 shadow-none card-body py-2">
                            <div class="row g-2">
            `;
            
            // Generate figure selection dropdowns based on diversity rules
            let figureCount = 0;
            const maxFiguresPerRow = 3;
            
            // Process diversity rules to determine figure selection needs
            diversityRules.forEach((rule, ruleIndex) => {
                if (rule.rule_type === 'figure_variety' && rule.scope) {
                    const scopeLabel = rule.scope.charAt(0).toUpperCase() + rule.scope.slice(1);
                    const groupName = rule.group_name || 'General';
                    const minDistinct = rule.min_distinct || 1;
                    
                    // Create figure selection fields based on scope
                    for (let i = 1; i <= minDistinct + 2; i++) {
                        figureCount++;
                        
                        sectionHTML += `
                            <div class="col-md-4">
                                <label class="form-label small mb-1">
                                    ${scopeLabel} Figure ${i}
                                    ${i <= minDistinct ? '<span class="text-danger">*</span>' : ''}
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-select figure-select" 
                                            data-rule-type="${rule.rule_type}" 
                                            data-scope="${rule.scope}" 
                                            data-group="${rule.group_name}"
                                            data-required="${i <= minDistinct ? 'true' : 'false'}"
                                            onchange="validateFigureDiversity(this)">
                                        <option value="">Select Figure...</option>
                                        ${generateFigureOptions(figuresData, rule.scope)}
                                    </select>
                                    <span class="input-group-text figure-validation" id="validation-${figureCount}">
                                        <i class="fas fa-question-circle text-muted"></i>
                                    </span>
                                </div>
                                <small class="text-muted">
                                    ${rule.is_optional ? 'Optional' : 'Required'} - ${groupName}
                                </small>
                            </div>
                        `;
                        
                        // Add new row every 3 figures
                        if (figureCount % maxFiguresPerRow === 0) {
                            sectionHTML += '</div><div class="row g-2">';
                        }
                    }
                }
            });
            
            // If no specific diversity rules found, create generic figure selections
            if (figureCount === 0) {
                for (let i = 1; i <= 6; i++) {
                    sectionHTML += `
                        <div class="col-md-4">
                            <label class="form-label small mb-1">Figure ${i}</label>
                            <div class="input-group input-group-sm">
                                <select class="form-select figure-select" onchange="validateFigureDiversity(this)">
                                    <option value="">Select Figure...</option>
                                    ${generateFigureOptions(figuresData, 'all')}
                                </select>
                                <span class="input-group-text figure-validation">
                                    <i class="fas fa-question-circle text-muted"></i>
                                </span>
                            </div>
                        </div>
                    `;
                    
                    if (i % maxFiguresPerRow === 0 && i < 6) {
                        sectionHTML += '</div><div class="row g-2">';
                    }
                }
            }
            
            sectionHTML += `
                            </div>
                            <div class="mt-3">
                                <div class="bg-light p-2 rounded">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <small class="text-muted">
                                                <i class="fas fa-info-circle me-1"></i>
                                                <strong>Diversity Status:</strong> 
                                                <span id="diversityStatus" class="text-warning">Checking...</span>
                                            </small>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <button type="button" class="btn btn-outline-info btn-sm" onclick="checkAllDiversityRules()">
                                                <i class="fas fa-check-double me-1"></i>Validate All
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            return sectionHTML;
        }
        
        function generateFigureSelectionForRun(runIndex, figuresData, diversityRules) {
            let selectionHTML = `
                <div class="row g-2 mb-3">
                    <div class="col-12">
                        <label class="form-label small mb-1 fw-bold text-info">
                            <i class="fas fa-shapes me-1"></i>Figure Selection - Run ${runIndex}
                        </label>
                    </div>
            `;
            
            // Determine required distinct groups for this run based on diversity rules
            const distinctRequirements = new Map();
            const competitionRequirements = new Map();
            let hasRequireDistinct = false;
            let hasCompetitionRequirements = false;
            
            diversityRules.forEach(rule => {
                if (rule.rule_type === 'figure_variety' && rule.min_distinct > 0) {
                    const groupName = rule.group_name || 'General';
                    const scope = rule.scope || 'run';
                    
                    if (scope === 'run') {
                        distinctRequirements.set(groupName, {
                            min_distinct: rule.min_distinct,
                            is_optional: rule.is_optional === '1' || rule.is_optional === 1,
                            scope: rule.scope,
                            requireDistinct: true
                        });
                        hasRequireDistinct = true;
                    } else if (scope === 'competition') {
                        competitionRequirements.set(groupName, {
                            min_distinct: rule.min_distinct,
                            is_optional: rule.is_optional === '1' || rule.is_optional === 1,
                            scope: rule.scope,
                            requireDistinct: true,
                            isCompetitionLevel: true
                        });
                        hasCompetitionRequirements = true;
                    }
                }
            });
            
            // Generate category-based figure selection columns
            const categories = Object.keys(figuresData);
            const categoriesPerRow = Math.min(categories.length, 4); // Max 4 columns per row
            const colSize = categoriesPerRow <= 2 ? 'col-md-6' : categoriesPerRow === 3 ? 'col-md-4' : 'col-md-3';
            
            if (categories.length > 0) {
                // Generate category columns
                categories.forEach((categoryName, index) => {
                    const figures = figuresData[categoryName] || [];
                    
                    // Check if this category has run-level or competition-level requirements
                    let requirement = {min_distinct: 1, is_optional: true, requireDistinct: false};
                    
                    if (distinctRequirements.has(categoryName)) {
                        requirement = distinctRequirements.get(categoryName);
                    } else if (competitionRequirements.has(categoryName)) {
                        requirement = competitionRequirements.get(categoryName);
                        requirement.isCompetitionLevel = true;
                    }
                    
                    selectionHTML += generateCategoryColumn(runIndex, categoryName, figures, requirement, colSize, index);
                    
                    // Add row break after every 4 categories
                    if ((index + 1) % 4 === 0 && index < categories.length - 1) {
                        selectionHTML += `
                </div>
                <div class="row g-2 mb-2">
                        `;
                    }
                });
            } else {
                // Fallback: no categories available
                selectionHTML += `
                    <div class="col-12">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            No figure categories available for this sport.
                        </div>
                    </div>
                `;
            }
            
            // Add validation summary for this run
            selectionHTML += `
                    <div class="col-12 mt-3">
                        <div class="bg-light p-2 rounded border">
                            <div class="row align-items-center">
                                <div class="col-md-4">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle me-1"></i>
                                        <strong>Run ${runIndex} Status:</strong> 
                                        <span id="runStatus_${runIndex}" class="text-warning">Checking...</span>
                                    </small>
                                </div>
                                <div class="col-md-2">
                                    <small class="text-muted">
                                        <strong>Selected:</strong> 
                                        <span id="selectedCount_${runIndex}" class="text-primary">0</span>
                                    </small>
                                </div>
                                <div class="col-md-3">
                                    <button type="button" class="btn btn-outline-success btn-sm" onclick="validateRunRequirements(${runIndex})">
                                        <i class="fas fa-check me-1"></i>Validate Run
                                    </button>
                                </div>
                                <div class="col-md-3">
                                    ${hasCompetitionRequirements ? `
                                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="validateCompetitionDiversity()">
                                        <i class="fas fa-globe me-1"></i>Check All Runs
                                    </button>
                                    ` : ''}
                                </div>
                            </div>
                            ${hasCompetitionRequirements ? `
                            <div class="row mt-2">
                                <div class="col-12">
                                    <div class="alert alert-info py-2 mb-0">
                                        <small>
                                            <i class="fas fa-exclamation-triangle me-1"></i>
                                            <strong>Competition-Level Diversity:</strong> Some categories require unique figures across all runs.
                                            <span id="competitionDiversityStatus" class="ms-2 badge bg-secondary">Not checked</span>
                                        </small>
                                    </div>
                                </div>
                            </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
            
            return selectionHTML;
        }
        
        function generateCategoryColumn(runIndex, categoryName, figures, requirement, colSize, columnIndex) {
            const requireDistinct = requirement.requireDistinct || false;
            const minDistinct = requirement.min_distinct || 1;
            const isOptional = requirement.is_optional || false;
            const isCompetitionLevel = requirement.isCompetitionLevel || false;
            const maxSelectionsInCategory = requireDistinct ? minDistinct : 1;
            
            // Generate a clean category ID for HTML elements
            const categoryId = categoryName.toLowerCase().replace(/[^a-z0-9]/g, '_');
            
            let columnHTML = `
                <div class="${colSize}">
                    <div class="border-0 shadow-none card border-info h-100 ${isCompetitionLevel ? 'border-warning' : ''}">
                        <div class="border-0 shadow-none card-header ${isCompetitionLevel ? 'bg-warning bg-opacity-10' : 'bg-info bg-opacity-10'} p-2">
                            <div class="d-flex justify-content-between align-items-center">
                                <h6 class="mb-0 ${isCompetitionLevel ? 'text-warning' : 'text-info'}">
                                    <i class="fas fa-${isCompetitionLevel ? 'globe' : 'layer-group'} me-1"></i>
                                    ${categoryName}
                                </h6>
                                <small class="text-muted">
                                    ${figures.length} figures
                                </small>
                            </div>
                            ${requireDistinct ? `
                            <small class="${isCompetitionLevel ? 'text-warning' : 'text-info'}">
                                <i class="fas fa-exclamation-circle me-1"></i>
                                ${isCompetitionLevel ? `Requires ${minDistinct} distinct across ALL runs` : `Requires ${minDistinct} distinct ${minDistinct > 1 ? 'figures' : 'figure'}`}
                            </small>
                            ` : ''}
                            ${isCompetitionLevel ? `
                            <div class="mt-1">
                                <span class="badge bg-warning text-dark">
                                    <i class="fas fa-trophy me-1"></i>Competition Level
                                </span>
                            </div>
                            ` : ''}
                        </div>
                        <div class="border-0 shadow-none card-body p-2">
            `;
            
            // Generate selection fields based on requirements
            if (requireDistinct && minDistinct > 1) {
                // Multiple distinct selections required
                for (let i = 1; i <= minDistinct; i++) {
                    const isRequired = !isOptional || i === 1;
                    const selectId = `figure_${runIndex}_${categoryId}_${i}`;
                    
                    columnHTML += `
                        <div class="mb-2">
                            <label class="form-label small mb-1">
                                Selection ${i} ${isRequired ? '*' : '(optional)'}
                                ${isCompetitionLevel ? '<span class="badge bg-warning text-dark ms-1">ALL RUNS</span>' : ''}
                            </label>
                            <select class="form-select form-select-sm figure-select" 
                                    id="${selectId}"
                                    data-run="${runIndex}" 
                                    data-category="${categoryName}"
                                    data-category-id="${categoryId}"
                                    data-position="${i}"
                                    data-required="${isRequired}"
                                    data-require-distinct="true"
                                    data-competition-level="${isCompetitionLevel}"
                                    onchange="validateCategoryDistinctness('${runIndex}', '${categoryId}')">
                                <option value="">Select Figure...</option>
                                ${generateFigureOptionsForCategory(figures)}
                            </select>
                            <div class="figure-validation mt-1">
                                <small class="text-muted" id="validation_${selectId}">
                                    <i class="fas fa-question-circle me-1"></i>No selection
                                </small>
                            </div>
                        </div>
                    `;
                }
            } else {
                // Single selection (standard)
                const selectId = `figure_${runIndex}_${categoryId}_1`;
                const isRequired = !isOptional;
                
                columnHTML += `
                    <div class="mb-2">
                        <label class="form-label small mb-1">
                            ${categoryName} Figure ${isRequired ? '*' : '(optional)'}
                            ${isCompetitionLevel ? '<span class="badge bg-warning text-dark ms-1">ALL RUNS</span>' : ''}
                        </label>
                        <select class="form-select form-select-sm figure-select" 
                                id="${selectId}"
                                data-run="${runIndex}" 
                                data-category="${categoryName}"
                                data-category-id="${categoryId}"
                                data-position="1"
                                data-required="${isRequired}"
                                data-require-distinct="false"
                                data-competition-level="${isCompetitionLevel}"
                                onchange="validateCategorySelection('${runIndex}', '${categoryId}')">
                            <option value="">Select Figure...</option>
                            ${generateFigureOptionsForCategory(figures)}
                        </select>
                        <div class="figure-validation mt-1">
                            <small class="text-muted" id="validation_${selectId}">
                                <i class="fas fa-question-circle me-1"></i>No selection
                            </small>
                        </div>
                    </div>
                `;
            }
            
            // Add category summary
            columnHTML += `
                            <div class="bg-light p-2 rounded mt-2">
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <strong>Status:</strong>
                                    </small>
                                    <span id="categoryStatus_${runIndex}_${categoryId}" class="badge bg-secondary">
                                        Not started
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            return columnHTML;
        }
        
        function generateFigureOptionsForCategory(figures) {
            let options = '';
            
            if (Array.isArray(figures) && figures.length > 0) {
                figures.forEach(figure => {
                    const figureId = figure.item_id || figure.id || figure.item_name;
                    const figureName = figure.item_name || figure.name || figure.title;
                    const difficulty = figure.difficulty || '';
                    const points = figure.points || '';
                    
                    let displayName = figureName;
                    let additionalInfo = [];
                    
                    if (difficulty) additionalInfo.push(`Diff: ${difficulty}`);
                    if (points) additionalInfo.push(`Pts: ${points}`);
                    
                    if (additionalInfo.length > 0) {
                        displayName += ` (${additionalInfo.join(', ')})`;
                    }
                    
                    options += `<option value="${figureId}" 
                                data-figure-name="${figureName}"
                                data-difficulty="${difficulty}"
                                data-points="${points}">
                        ${displayName}
                    </option>`;
                });
            } else {
                // Sample figures if no real data
                options = `
                    <option value="sample_1" data-figure-name="Basic Move" data-difficulty="1.5">Basic Move (Diff: 1.5)</option>
                    <option value="sample_2" data-figure-name="Intermediate Trick" data-difficulty="2.8">Intermediate Trick (Diff: 2.8)</option>
                    <option value="sample_3" data-figure-name="Advanced Figure" data-difficulty="4.2">Advanced Figure (Diff: 4.2)</option>
                `;
            }
            
            return options;
        }
        
        function generateSingleFigureSelect(runIndex, groupName, figuresData, requirement) {
            return `
                <div class="col-md-6">
                    <label class="form-label small">${groupName} ${requirement.is_optional ? '(Optional)' : ''}</label>
                    <select class="form-select form-select-sm figure-select" 
                            data-run="${runIndex}" 
                            data-group="${groupName}"
                            data-required="${!requirement.is_optional}"
                            onchange="validateRunFigures(${runIndex})">
                        <option value="">Select Figure...</option>
                        ${generateCategoryFigureOptions(figuresData)}
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small">Difficulty</label>
                    <div class="input-group input-group-sm">
                        <input type="number" class="form-control" placeholder="1.0" step="0.1" min="0.1" max="5.0" 
                               data-run="${runIndex}" value="${(Math.random() * 4 + 1).toFixed(1)}">
                        <span class="input-group-text">pts</span>
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label small">Status</label>
                    <div class="d-flex align-items-center pt-1">
                        <span class="figure-validation me-2">
                            <i class="fas fa-question-circle text-muted" title="No selection"></i>
                        </span>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="showFigureDetails(${runIndex}, '${groupName}')">
                            <i class="fas fa-info-circle"></i>
                        </button>
                    </div>
                </div>
            `;
        }
        
        function generateFigureGroupSelect(runIndex, groupName, groupIndex, figuresData, requirement) {
            const minDistinct = requirement.min_distinct || 1;
            const isOptional = requirement.is_optional;
            let groupHTML = '';
            
            // Create multiple selects for min_distinct requirement
            for (let i = 1; i <= minDistinct; i++) {
                const colSize = minDistinct <= 2 ? 'col-md-6' : minDistinct <= 3 ? 'col-md-4' : 'col-md-3';
                const selectId = `figure_${runIndex}_${groupName}_${i}`;
                
                groupHTML += `
                    <div class="${colSize}">
                        <label class="form-label small">
                            ${groupName} #${i} 
                            ${isOptional && i > 1 ? '(Optional)' : ''}
                            ${i === 1 && minDistinct > 1 ? `(${minDistinct} required)` : ''}
                        </label>
                        <select class="form-select form-select-sm figure-select" 
                                id="${selectId}"
                                data-run="${runIndex}" 
                                data-group="${groupName}"
                                data-position="${i}"
                                data-required="${!isOptional || i === 1}"
                                onchange="validateGroupDistinctness('${runIndex}', '${groupName}')">
                            <option value="">Select Figure...</option>
                            ${generateCategoryFigureOptions(figuresData, groupName)}
                        </select>
                        <div class="figure-validation mt-1">
                            <i class="fas fa-question-circle text-muted" title="No selection"></i>
                            <small class="text-muted ms-1" id="validation_${selectId}">No selection</small>
                        </div>
                    </div>
                `;
            }
            
            return groupHTML;
        }
        
        function generateCategoryFigureOptions(figuresData, filterGroup = null) {
            let options = '';
            
            // Generate options organized by category
            Object.keys(figuresData).forEach(categoryName => {
                const categoryFigures = figuresData[categoryName];
                if (Array.isArray(categoryFigures) && categoryFigures.length > 0) {
                    // Filter by group if specified
                    const filteredFigures = filterGroup ? 
                        categoryFigures.filter(figure => 
                            (figure.group_name || 'General') === filterGroup
                        ) : categoryFigures;
                    
                    if (filteredFigures.length > 0) {
                        // Add category header with count
                        options += `<optgroup label="${categoryName} (${filteredFigures.length} figures)">`;
                        
                        filteredFigures.forEach(figure => {
                            const figureId = figure.item_id || figure.id || figure.item_name;
                            const figureName = figure.item_name || figure.name || figure.title;
                            const difficulty = figure.difficulty || '';
                            const points = figure.points || '';
                            
                            let displayName = figureName;
                            if (difficulty && points) {
                                displayName += ` (Diff: ${difficulty}, Pts: ${points})`;
                            } else if (difficulty) {
                                displayName += ` (Difficulty: ${difficulty})`;
                            } else if (points) {
                                displayName += ` (${points} pts)`;
                            }
                            
                            options += `<option value="${figureId}" 
                                        data-category="${categoryName}" 
                                        data-difficulty="${difficulty}"
                                        data-points="${points}"
                                        data-figure-name="${figureName}">
                                ${displayName}
                            </option>`;
                        });
                        
                        options += '</optgroup>';
                    }
                }
            });
            
            // If no figures found, add sample options
            if (!options) {
                options = `
                    <optgroup label="Sample Figures">
                        <option value="sample_1">Basic Move (Difficulty: 1.5)</option>
                        <option value="sample_2">Intermediate Trick (Difficulty: 2.8)</option>
                        <option value="sample_3">Advanced Figure (Difficulty: 4.2)</option>
                    </optgroup>
                `;
            }
            
            return options;
        }
        
        function generateFigureOptions(figuresData, scope) {
            let options = '';
            
            // Generate options based on available figures data
            Object.keys(figuresData).forEach(categoryName => {
                const categoryFigures = figuresData[categoryName];
                if (Array.isArray(categoryFigures)) {
                    // Add category header
                    options += `<optgroup label="${categoryName}">`;
                    
                    categoryFigures.forEach(figure => {
                        const figureId = figure.item_id || figure.id || figure.item_name;
                        const figureName = figure.item_name || figure.name || figure.title;
                        const difficulty = figure.difficulty || '';
                        const displayName = difficulty ? `${figureName} (${difficulty})` : figureName;
                        
                        options += `<option value="${figureId}" data-category="${categoryName}" data-difficulty="${difficulty}">
                            ${displayName}
                        </option>`;
                    });
                    
                    options += '</optgroup>';
                }
            });
            
            // If no figures found, add sample options
            if (!options) {
                options = `
                    <optgroup label="Sample Figures">
                        <option value="fig_1" data-category="Basic">Basic Figure 1</option>
                        <option value="fig_2" data-category="Basic">Basic Figure 2</option>
                        <option value="fig_3" data-category="Advanced">Advanced Figure 1</option>
                        <option value="fig_4" data-category="Advanced">Advanced Figure 2</option>
                        <option value="fig_5" data-category="Expert">Expert Figure 1</option>
                    </optgroup>
                `;
            }
            
            return options;
        }
        
        function validateFigureDiversity(selectElement) {
            const figureSelects = document.querySelectorAll('.figure-select');
            const selectedFigures = Array.from(figureSelects)
                .map(select => select.value)
                .filter(value => value !== '');
            
            // Check for duplicates
            const duplicates = selectedFigures.filter((item, index) => selectedFigures.indexOf(item) !== index);
            const hasDuplicates = duplicates.length > 0;
            
            // Update validation indicators
            figureSelects.forEach((select, index) => {
                const validationIcon = select.parentElement.querySelector('.figure-validation i');
                const value = select.value;
                
                if (!value) {
                    validationIcon.className = 'fas fa-question-circle text-muted';
                } else if (duplicates.includes(value)) {
                    validationIcon.className = 'fas fa-exclamation-triangle text-warning';
                    validationIcon.title = 'Duplicate figure selected';
                } else {
                    validationIcon.className = 'fas fa-check-circle text-success';
                    validationIcon.title = 'Valid selection';
                }
            });
            
            // Update overall diversity status
            const statusElement = document.getElementById('diversityStatus');
            if (selectedFigures.length === 0) {
                statusElement.textContent = 'No figures selected';
                statusElement.className = 'text-muted';
            } else if (hasDuplicates) {
                statusElement.textContent = 'Duplicate figures detected';
                statusElement.className = 'text-warning';
            } else {
                statusElement.textContent = `${selectedFigures.length} unique figures selected`;
                statusElement.className = 'text-success';
            }
        }
        
        function checkAllDiversityRules() {
            // Simulate comprehensive diversity rule checking
            const statusElement = document.getElementById('diversityStatus');
            statusElement.textContent = 'Checking diversity rules...';
            statusElement.className = 'text-primary';
            
            setTimeout(() => {
                validateFigureDiversity(null);
                
                // Additional rule-specific validations could be added here
                const figureSelects = document.querySelectorAll('.figure-select');
                const selectedCount = Array.from(figureSelects).filter(select => select.value).length;
                
                if (selectedCount >= 3) {
                    statusElement.textContent = 'All diversity rules satisfied';
                    statusElement.className = 'text-success';
                } else {
                    statusElement.textContent = 'Need at least 3 figures for diversity';
                    statusElement.className = 'text-warning';
                }
            }, 1000);
        }
        
        // Helper functions for run management
        function calculateRunScore(runIndex) {
            const inputs = document.querySelectorAll(`[data-run="${runIndex}"]`);
            let total = 0;
            let count = 0;
            let sectionTotals = {};
            
            inputs.forEach(input => {
                const value = parseFloat(input.value);
                if (!isNaN(value) && value > 0) {
                    const section = input.dataset.section || 'default';
                    
                    if (!sectionTotals[section]) {
                        sectionTotals[section] = { total: 0, count: 0 };
                    }
                    sectionTotals[section].total += value;
                    sectionTotals[section].count++;
                    total += value;
                    count++;
                }
            });
            
            // Calculate final run score based on aggregation method
            let finalScore = 0;
            if (count > 0) {
                // For sections-based scoring, average within sections then sum
                if (Object.keys(sectionTotals).length > 1) {
                    Object.keys(sectionTotals).forEach(section => {
                        if (section !== 'default') {
                            finalScore += sectionTotals[section].total / sectionTotals[section].count;
                        }
                    });
                } else {
                    // Simple average for single section or default
                    finalScore = total / count;
                }
            }
            
            finalScore = finalScore.toFixed(1);
            
            // Update the run score display
            const scoreField = document.getElementById(`runScore_${runIndex}`);
            if (scoreField) {
                scoreField.value = finalScore;
                // Add visual feedback based on score
                scoreField.style.backgroundColor = finalScore > 7 ? '#d4edda' : finalScore > 5 ? '#fff3cd' : '#f8d7da';
                scoreField.style.transition = 'background-color 0.3s ease';
            }
            
            // Update the final run score input in the final score section
            const finalRunScoreInput = document.getElementById(`finalRunScore_${runIndex}`);
            if (finalRunScoreInput) {
                finalRunScoreInput.value = finalScore;
                
                // Update source indicator to show auto-calculation
                const sourceIndicator = document.getElementById(`runScoreSource_${runIndex}`);
                if (sourceIndicator) {
                    sourceIndicator.innerHTML = '<i class="fas fa-sync text-success me-1"></i>Updated from criteria';
                    setTimeout(() => {
                        sourceIndicator.innerHTML = '<i class="fas fa-calculator me-1"></i>Auto-calculated from criteria';
                    }, 2000);
                }
            }
            
            // Trigger final score recalculation and validation
            setTimeout(() => {
                updateFinalScoreCalculation();
                triggerFullValidation();
            }, 100);
            
            return finalScore;
        }
        
        function recalculateRunScores() {
            // Recalculate all run scores and update final score display
            const totalRuns = document.querySelectorAll('[id^="runScore_"]').length;
            
            for (let runIndex = 1; runIndex <= totalRuns; runIndex++) {
                calculateRunScore(runIndex);
            }
            
            // Update the final score section with new calculations
            setTimeout(() => {
                updateFinalScoreCalculation();
                triggerFullValidation();
                showRunAlert('All run scores recalculated based on judge inputs!', 'info');
            }, 200);
        }
        
        function triggerFullValidation() {
            // Comprehensive validation that runs after any score or figure change
            setTimeout(() => {
                // Update diversity validation
                validateCompetitionDiversity();
                
                // Update run-level validations
                const totalRuns = document.querySelectorAll('[id^="runScore_"]').length;
                for (let runIndex = 1; runIndex <= totalRuns; runIndex++) {
                    validateRunRequirements(runIndex);
                }
                
                // Update final score validation display
                updateFinalScoreValidation();
                
                // Update final score calculation and figures display
                updateFinalScoreCalculation();
                
                // Update overall submission readiness
                updateSubmissionReadiness();
            }, 150);
        }
        
        function updateSubmissionReadiness() {
            // Check all validation criteria to determine if submission is ready
            const diversityViolations = document.querySelectorAll('.text-danger[id*="diversity"], .bg-danger[id*="diversity"]').length;
            
            // Count incomplete runs by checking if run score fields have meaningful values
            const runScoreElements = document.querySelectorAll('[id^="runScore_"]');
            let incompleteRuns = 0;
            runScoreElements.forEach(element => {
                const value = element.value || element.textContent || '0';
                if (!value || value === '0' || value === '0.0') {
                    incompleteRuns++;
                }
            });
            
            const submissionReadiness = document.getElementById('submissionReadiness');
            const submitButton = document.getElementById('submitFinalScoreBtn');
            const overallStatus = document.getElementById('overallSubmissionStatus');
            
            const isReady = diversityViolations === 0 && incompleteRuns === 0;
            
            if (submissionReadiness) {
                if (isReady) {
                    submissionReadiness.innerHTML = `
                        <i class="fas fa-check text-success me-1"></i>Ready to submit: <strong class="text-success">Yes</strong>
                    `;
                } else {
                    const blockers = [];
                    if (diversityViolations > 0) blockers.push('diversity violations');
                    if (incompleteRuns > 0) blockers.push('incomplete runs');
                    
                    submissionReadiness.innerHTML = `
                        <i class="fas fa-ban text-danger me-1"></i>Ready to submit: <strong class="text-danger">Blocked (${blockers.join(', ')})</strong>
                    `;
                }
            }
            
            if (submitButton) {
                if (isReady) {
                    submitButton.disabled = false;
                    submitButton.className = 'btn btn-success btn-lg me-3';
                    submitButton.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Submit Final Score';
                } else {
                    submitButton.disabled = true;
                    submitButton.className = 'btn btn-secondary btn-lg me-3';
                    submitButton.innerHTML = '<i class="fas fa-ban me-2"></i>Cannot Submit (Issues Found)';
                }
            }
            
            if (overallStatus) {
                if (isReady) {
                    overallStatus.className = 'badge bg-success fs-6 p-2';
                    overallStatus.innerHTML = '<i class="fas fa-check-circle me-1"></i>COMPLETE';
                } else {
                    overallStatus.className = 'badge bg-warning fs-6 p-2';
                    overallStatus.innerHTML = '<i class="fas fa-exclamation-triangle me-1"></i>PENDING';
                }
            }
        }
        
        function updateFinalScoreCalculation() {
            // Get current run scores from the final run score inputs
            const finalRunScoreInputs = document.querySelectorAll('[id^="finalRunScore_"]');
            const runScores = [];
            let totalScore = 0;
            
            finalRunScoreInputs.forEach((input, index) => {
                const score = parseFloat(input.value) || 0;
                runScores.push(score);
                totalScore += score;
            });
            
            if (runScores.length === 0) return;
            
            const averageScore = (totalScore / runScores.length).toFixed(1);
            const bestScore = Math.max(...runScores).toFixed(1);
            
            // Update the final score section display
            const finalScoreContainer = document.querySelector('.card.border-success .card-body');
            if (finalScoreContainer) {
                // Skip old badge updates - using new card-based display instead
                
                // Update score calculation details
                const scoreDetails = finalScoreContainer.querySelector('.mt-3.row.g-2');
                if (scoreDetails) {
                    scoreDetails.innerHTML = `
                        <div class="col-md-3">
                            <div class="small text-muted">
                                <strong>Total Score:</strong> ${totalScore.toFixed(1)}
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="small text-muted">
                                <strong>Average:</strong> ${averageScore}
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="small text-success">
                                <strong>Best Score:</strong> ${bestScore}
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="small text-muted">
                                <strong>Score Range:</strong> ${(Math.max(...runScores) - Math.min(...runScores)).toFixed(1)}
                            </div>
                        </div>
                    `;
                }
                
                // Update calculated and final score inputs
                const calculatedScoreInput = finalScoreContainer.querySelector('input.bg-warning');
                const finalScoreInput = finalScoreContainer.querySelector('input.bg-success');
                
                if (calculatedScoreInput) {
                    calculatedScoreInput.value = bestScore;
                }
                if (finalScoreInput) {
                    finalScoreInput.value = bestScore;
                }
                
                // Update run figures display
                updateRunFiguresDisplay();
            }
        }
        
        function updateRunFiguresDisplay() {
            // Update the figure selection display for each run in the final score section
            const runScoreElements = document.querySelectorAll('[id^="runScore_"]');
            
            runScoreElements.forEach((element, index) => {
                const runIndex = index + 1;
                const figuresDisplayElement = document.getElementById(`runFiguresDisplay_${runIndex}`);
                
                if (figuresDisplayElement) {
                    const figuresHtml = generateRunFiguresDisplayHtml(runIndex);
                    figuresDisplayElement.innerHTML = figuresHtml;
                }
            });
        }
        
        function generateRunFiguresDisplayHtml(runIndex) {
            // Get all figure selects for this run
            const runFigureSelects = document.querySelectorAll(`[data-run="${runIndex}"].figure-select, [data-run="${runIndex}"][data-category-id]`);
            
            if (runFigureSelects.length === 0) {
                return '<div class="text-muted small"><i class="fas fa-info-circle me-1"></i>No figures required</div>';
            }
            
            let figuresHtml = '';
            const categoriesFigures = {};
            
            // Group figures by category
            runFigureSelects.forEach(select => {
                const categoryId = select.dataset.categoryId || select.dataset.group || 'General';
                const value = select.value;
                const text = select.options[select.selectedIndex]?.text || 'Not selected';
                
                if (!categoriesFigures[categoryId]) {
                    categoriesFigures[categoryId] = [];
                }
                
                if (value && value !== '') {
                    categoriesFigures[categoryId].push({
                        value: value,
                        text: text,
                        element: select
                    });
                }
            });
            
            // Generate HTML for each category
            Object.keys(categoriesFigures).forEach(categoryId => {
                const figures = categoriesFigures[categoryId];
                
                if (figures.length > 0) {
                    const categoryName = categoryId.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                    
                    figuresHtml += `
                        <div class="mb-1">
                            <span class="badge bg-secondary bg-opacity-25 text-dark small me-1">${categoryName}</span>
                    `;
                    
                    figures.forEach((figure, index) => {
                        const isValid = !figure.element.classList.contains('border-danger');
                        const statusClass = isValid ? 'text-success' : 'text-danger';
                        const statusIcon = isValid ? 'fas fa-check' : 'fas fa-exclamation-triangle';
                        
                        figuresHtml += `
                            <div class="small ${statusClass}">
                                <i class="${statusIcon} me-1"></i>${figure.text}
                            </div>
                        `;
                    });
                    
                    figuresHtml += '</div>';
                }
            });
            
            // If no figures selected
            if (figuresHtml === '') {
                const totalSelects = runFigureSelects.length;
                figuresHtml = `
                    <div class="text-warning small">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        0/${totalSelects} figures selected
                    </div>
                `;
            }
            
            return figuresHtml;
        }
        
        function updateBestScoreIndicators(runScores) {
            // Update the visual indicators for which run has the best score
            const bestScore = Math.max(...runScores);
            
            runScores.forEach((score, index) => {
                const runIndex = index + 1;
                const finalScoreInput = document.getElementById(`finalRunScore_${runIndex}`);
                const cardElement = finalScoreInput?.closest('.card');
                
                if (cardElement) {
                    const header = cardElement.querySelector('.card-header');
                    
                    if (score === bestScore && bestScore > 0) {
                        // This is the best score
                        cardElement.className = cardElement.className.replace(/border-\w+/, 'border-warning');
                        header.className = header.className.replace(/bg-\w+/, 'bg-warning text-dark');
                        
                        // Add best score indicator if not present
                        const scoreDiv = header.querySelector('.text-end');
                        if (!scoreDiv.innerHTML.includes('★ Best Score')) {
                            scoreDiv.innerHTML += '<small class="fw-normal text-dark">★ Best Score</small>';
                        }
                    } else {
                        // Not the best score - remove indicator if present
                        cardElement.className = cardElement.className.replace(/border-\w+/, 'border-primary');
                        header.className = header.className.replace(/bg-\w+ text-\w+/, 'bg-primary text-white');
                        
                        // Remove best score indicator if present
                        const scoreDiv = header.querySelector('.text-end');
                        const bestIndicator = scoreDiv.querySelector('small:contains("★ Best Score")');
                        if (bestIndicator) {
                            bestIndicator.remove();
                        }
                    }
                }
            });
        }
        
        function validateRunFigures(runIndex) {
            // Get all figure selects for this run
            const runSelects = document.querySelectorAll(`[data-run="${runIndex}"].figure-select`);
            
            if (runSelects.length === 0) {
                // Fallback to old single select validation
                const select = document.querySelector(`[data-run="${runIndex}"] .figure-select`);
                const validation = select?.parentElement.querySelector('.figure-validation i');
                
                if (validation) {
                    if (select.value) {
                        validation.className = 'fas fa-check-circle text-success';
                        validation.title = 'Figure selected';
                    } else {
                        validation.className = 'fas fa-question-circle text-muted';
                        validation.title = 'No figure selected';
                    }
                }
            } else {
                // New category-based validation
                const categories = {};
                runSelects.forEach(select => {
                    const categoryId = select.dataset.categoryId || 'default';
                    if (!categories[categoryId]) categories[categoryId] = [];
                    categories[categoryId].push(select);
                });
                
                // Validate each category
                Object.keys(categories).forEach(categoryId => {
                    const categorySelects = categories[categoryId];
                    const requireDistinct = categorySelects[0]?.dataset.requireDistinct === 'true';
                    
                    if (requireDistinct) {
                        validateCategoryDistinctness(runIndex, categoryId);
                    } else {
                        validateCategorySelection(runIndex, categoryId);
                    }
                });
            }
        }
        
        function submitRun(runIndex) {
            // Simulate run submission
            const scoreField = document.getElementById(`runScore_${runIndex}`);
            if (scoreField) {
                // Add visual feedback
                scoreField.classList.add('border-success');
                scoreField.classList.add('border-3');
                
                // Show success message
                showRunAlert(`Run ${runIndex} submitted successfully!`, 'success');
            }
        }
        
        function clearRun(runIndex) {
            // Clear all inputs for this run
            const inputs = document.querySelectorAll(`[data-run="${runIndex}"]`);
            inputs.forEach(input => {
                if (input.type === 'number' || input.type === 'text') {
                    input.value = '';
                } else if (input.tagName === 'SELECT') {
                    input.selectedIndex = 0;
                }
            });
            
            // Clear run score
            const scoreField = document.getElementById(`runScore_${runIndex}`);
            if (scoreField) {
                scoreField.value = '0.0';
                scoreField.classList.remove('border-success', 'border-3');
            }
            
            showRunAlert(`Run ${runIndex} cleared`, 'info');
        }
        
        function showFigureDetails(runIndex, categoryId = null, position = null) {
            let selectSelector;
            
            if (categoryId && position) {
                // New category-based selection
                selectSelector = `#figure_${runIndex}_${categoryId}_${position}`;
            } else if (categoryId) {
                // Category-based but first available
                selectSelector = `[data-run="${runIndex}"][data-category-id="${categoryId}"]`;
            } else {
                // Fallback to old structure
                selectSelector = `[data-run="${runIndex}"].figure-select`;
            }
                
            const select = document.querySelector(selectSelector);
            
            if (select && select.value) {
                const selectedOption = select.options[select.selectedIndex];
                const figureName = selectedOption.dataset.figureName || selectedOption.text;
                const category = select.dataset.category || 'Unknown';
                const difficulty = selectedOption.dataset.difficulty || 'N/A';
                const points = selectedOption.dataset.points || 'N/A';
                
                const detailsMessage = `
                    <div class="figure-details">
                        <h6 class="mb-2"><i class="fas fa-info-circle me-2"></i>Figure Details</h6>
                        <div class="row">
                            <div class="col-6"><strong>Figure:</strong></div>
                            <div class="col-6">${figureName}</div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Category:</strong></div>
                            <div class="col-6">${category}</div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Difficulty:</strong></div>
                            <div class="col-6">${difficulty}</div>
                        </div>
                        <div class="row">
                            <div class="col-6"><strong>Points:</strong></div>
                            <div class="col-6">${points}</div>
                        </div>
                        ${position ? `<div class="row"><div class="col-6"><strong>Position:</strong></div><div class="col-6">${position}</div></div>` : ''}
                    </div>
                `;
                
                // Create a temporary modal or alert with figure details
                showDetailedAlert(detailsMessage, 'info');
            } else {
                const categoryText = categoryId ? ` in ${categoryId.replace(/_/g, ' ')}` : '';
                const positionText = position ? ` (position ${position})` : '';
                showRunAlert(`No figure selected for Run ${runIndex}${categoryText}${positionText}`, 'warning');
            }
        }
        
        function showDetailedAlert(message, type) {
            // Create a more detailed alert with HTML content
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 350px; max-width: 500px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.body.appendChild(alertDiv);
            
            // Auto-remove after 5 seconds (longer for detailed content)
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        function showRunAlert(message, type) {
            // Create a temporary alert
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.body.appendChild(alertDiv);
            
            // Auto-remove after 3 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 3000);
        }
        
        function validateGroupDistinctness(runIndex, groupName) {
            // Get all selects for this group in this run
            const groupSelects = document.querySelectorAll(`[data-run="${runIndex}"][data-group="${groupName}"]`);
            const selectedValues = [];
            const validationResults = [];
            
            groupSelects.forEach((select, index) => {
                const value = select.value;
                const validation = select.parentElement.querySelector('.figure-validation i');
                const statusText = select.parentElement.querySelector('small');
                const isRequired = select.dataset.required === 'true';
                
                if (!value) {
                    if (isRequired) {
                        validation.className = 'fas fa-exclamation-circle text-warning';
                        validation.title = 'Required selection missing';
                        statusText.textContent = 'Required';
                        statusText.className = 'text-warning ms-1';
                        validationResults.push({valid: false, required: true});
                    } else {
                        validation.className = 'fas fa-question-circle text-muted';
                        validation.title = 'Optional selection';
                        statusText.textContent = 'Optional';
                        statusText.className = 'text-muted ms-1';
                        validationResults.push({valid: true, required: false});
                    }
                } else {
                    if (selectedValues.includes(value)) {
                        validation.className = 'fas fa-times-circle text-danger';
                        validation.title = 'Duplicate figure selected';
                        statusText.textContent = 'Duplicate';
                        statusText.className = 'text-danger ms-1';
                        validationResults.push({valid: false, duplicate: true});
                    } else {
                        validation.className = 'fas fa-check-circle text-success';
                        validation.title = 'Valid unique selection';
                        statusText.textContent = 'Valid';
                        statusText.className = 'text-success ms-1';
                        validationResults.push({valid: true});
                        selectedValues.push(value);
                    }
                }
            });
            
            // Update run status
            validateRunRequirements(runIndex);
            
            return validationResults;
        }
        
        function validateRunRequirements(runIndex) {
            const runStatus = document.getElementById(`runStatus_${runIndex}`);
            const selectedCount = document.getElementById(`selectedCount_${runIndex}`);
            if (!runStatus) return;
            
            // Get all figure selects for this run
            const runSelects = document.querySelectorAll(`[data-run="${runIndex}"].figure-select`);
            let totalValid = 0;
            let totalRequired = 0;
            let totalSelected = 0;
            let hasDuplicates = false;
            let hasErrors = false;
            
            // Group by category to check distinctness within categories
            const categories = {};
            runSelects.forEach(select => {
                const categoryId = select.dataset.categoryId || 'default';
                if (!categories[categoryId]) categories[categoryId] = [];
                categories[categoryId].push(select);
            });
            
            // Validate each category
            Object.keys(categories).forEach(categoryId => {
                const categorySelects = categories[categoryId];
                const selectedInCategory = [];
                const requireDistinct = categorySelects[0]?.dataset.requireDistinct === 'true';
                
                categorySelects.forEach(select => {
                    const isRequired = select.dataset.required === 'true';
                    const value = select.value;
                    
                    if (isRequired) totalRequired++;
                    
                    if (value) {
                        totalSelected++;
                        if (requireDistinct && selectedInCategory.includes(value)) {
                            hasDuplicates = true;
                            hasErrors = true;
                        } else {
                            selectedInCategory.push(value);
                            if (isRequired) totalValid++;
                        }
                    } else if (isRequired) {
                        hasErrors = true;
                    }
                });
            });
            
            // Update selected count
            if (selectedCount) {
                selectedCount.textContent = totalSelected;
            }
            
            // Update status display
            if (hasDuplicates) {
                runStatus.textContent = 'Duplicate figures detected';
                runStatus.className = 'text-danger';
            } else if (totalValid < totalRequired) {
                runStatus.textContent = `${totalValid}/${totalRequired} required figures selected`;
                runStatus.className = 'text-warning';
            } else if (totalRequired === 0 && totalSelected === 0) {
                runStatus.textContent = 'No requirements defined';
                runStatus.className = 'text-muted';
            } else if (totalRequired === 0) {
                runStatus.textContent = `${totalSelected} figures selected (optional)`;
                runStatus.className = 'text-info';
            } else {
                runStatus.textContent = 'All requirements satisfied';
                runStatus.className = 'text-success';
            }
        }
        
        function validateAllRunsRequirements() {
            // Find all runs and validate each
            const runStatuses = document.querySelectorAll('[id^="runStatus_"]');
            runStatuses.forEach(status => {
                const runIndex = status.id.replace('runStatus_', '');
                validateRunRequirements(runIndex);
            });
            
            // Show overall summary
            const validRuns = document.querySelectorAll('[id^="runStatus_"] .text-success').length;
            const totalRuns = runStatuses.length;
            
            if (validRuns === totalRuns && totalRuns > 0) {
                showRunAlert(`All ${totalRuns} runs have valid figure selections!`, 'success');
            } else {
                showRunAlert(`${validRuns}/${totalRuns} runs have valid selections`, 'warning');
            }
        }
        
        function validateCategoryDistinctness(runIndex, categoryId) {
            // Get all selects for this category in this run
            const categorySelects = document.querySelectorAll(`[data-run="${runIndex}"][data-category-id="${categoryId}"]`);
            const selectedValues = [];
            const validationResults = [];
            let validSelections = 0;
            let requiredSelections = 0;
            
            categorySelects.forEach((select, index) => {
                const value = select.value;
                const validation = select.parentElement.querySelector('small');
                const isRequired = select.dataset.required === 'true';
                const requireDistinct = select.dataset.requireDistinct === 'true';
                
                if (isRequired) requiredSelections++;
                
                if (!value) {
                    if (isRequired) {
                        validation.innerHTML = '<i class="fas fa-exclamation-circle text-warning me-1"></i>Required';
                        validation.className = 'text-warning';
                        validationResults.push({valid: false, required: true});
                    } else {
                        validation.innerHTML = '<i class="fas fa-question-circle text-muted me-1"></i>Optional';
                        validation.className = 'text-muted';
                        validationResults.push({valid: true, required: false});
                    }
                } else {
                    if (requireDistinct && selectedValues.includes(value)) {
                        validation.innerHTML = '<i class="fas fa-times-circle text-danger me-1"></i>Duplicate';
                        validation.className = 'text-danger';
                        validationResults.push({valid: false, duplicate: true});
                    } else {
                        validation.innerHTML = '<i class="fas fa-check-circle text-success me-1"></i>Valid';
                        validation.className = 'text-success';
                        validationResults.push({valid: true});
                        selectedValues.push(value);
                        validSelections++;
                    }
                }
            });
            
            // Update category status
            const categoryStatus = document.getElementById(`categoryStatus_${runIndex}_${categoryId}`);
            if (categoryStatus) {
                const hasDuplicates = validationResults.some(r => r.duplicate);
                const missingRequired = validSelections < requiredSelections;
                
                if (hasDuplicates) {
                    categoryStatus.textContent = 'Duplicates';
                    categoryStatus.className = 'badge bg-danger';
                } else if (missingRequired) {
                    categoryStatus.textContent = `${validSelections}/${requiredSelections} req`;
                    categoryStatus.className = 'badge bg-warning';
                } else if (requiredSelections === 0 && validSelections === 0) {
                    categoryStatus.textContent = 'Optional';
                    categoryStatus.className = 'badge bg-secondary';
                } else {
                    categoryStatus.textContent = 'Valid';
                    categoryStatus.className = 'badge bg-success';
                }
            }
            
            // Update overall run status
            validateRunRequirements(runIndex);
            
            // Also trigger competition-level validation if this category has competition requirements
            const hasCompetitionLevel = Array.from(categorySelects).some(select => 
                select.dataset.competitionLevel === 'true'
            );
            
            if (hasCompetitionLevel) {
                // Delay to allow UI updates to complete
                setTimeout(() => {
                    triggerFullValidation();
                }, 100);
            }
            
            return validationResults;
        }
        
        function validateCategorySelection(runIndex, categoryId) {
            // For single selection categories (no distinctness requirement)
            const select = document.querySelector(`[data-run="${runIndex}"][data-category-id="${categoryId}"]`);
            if (!select) return;
            
            const validation = select.parentElement.querySelector('small');
            const isRequired = select.dataset.required === 'true';
            const value = select.value;
            
            if (!value) {
                if (isRequired) {
                    validation.innerHTML = '<i class="fas fa-exclamation-circle text-warning me-1"></i>Required';
                    validation.className = 'text-warning';
                } else {
                    validation.innerHTML = '<i class="fas fa-question-circle text-muted me-1"></i>Optional';
                    validation.className = 'text-muted';
                }
            } else {
                validation.innerHTML = '<i class="fas fa-check-circle text-success me-1"></i>Selected';
                validation.className = 'text-success';
            }
            
            // Update category status
            const categoryStatus = document.getElementById(`categoryStatus_${runIndex}_${categoryId}`);
            if (categoryStatus) {
                if (!value && isRequired) {
                    categoryStatus.textContent = 'Required';
                    categoryStatus.className = 'badge bg-warning';
                } else if (!value && !isRequired) {
                    categoryStatus.textContent = 'Optional';
                    categoryStatus.className = 'badge bg-secondary';
                } else {
                    categoryStatus.textContent = 'Selected';
                    categoryStatus.className = 'badge bg-success';
                }
            }
            
            // Update overall run status
            validateRunRequirements(runIndex);
            
            // Also trigger competition-level validation if this category has competition requirements
            if (select.dataset.competitionLevel === 'true') {
                setTimeout(() => {
                    triggerFullValidation();
                }, 100);
            }
        }
        
        function validateCompetitionDiversity() {
            // Get all figure selects across all runs that have competition-level requirements
            const competitionSelects = document.querySelectorAll('[data-competition-level="true"]');
            const competitionStatus = document.getElementById('competitionDiversityStatus');
            
            if (!competitionStatus || competitionSelects.length === 0) {
                return;
            }
            
            // Group by category across all runs
            const categoriesByRuns = {};
            let totalViolations = 0;
            let totalChecked = 0;
            
            competitionSelects.forEach(select => {
                const categoryId = select.dataset.categoryId;
                const runIndex = select.dataset.run;
                const value = select.value;
                
                if (!categoriesByRuns[categoryId]) {
                    categoriesByRuns[categoryId] = {};
                }
                
                if (!categoriesByRuns[categoryId][runIndex]) {
                    categoriesByRuns[categoryId][runIndex] = [];
                }
                
                if (value) {
                    categoriesByRuns[categoryId][runIndex].push({
                        select: select,
                        value: value,
                        runIndex: runIndex
                    });
                }
            });
            
            // Check each category for cross-run duplicates
            Object.keys(categoriesByRuns).forEach(categoryId => {
                const runsData = categoriesByRuns[categoryId];
                const allValues = [];
                const duplicatesByRun = {};
                
                // Collect all values across runs
                Object.keys(runsData).forEach(runIndex => {
                    runsData[runIndex].forEach(item => {
                        allValues.push({
                            value: item.value,
                            runIndex: runIndex,
                            select: item.select
                        });
                    });
                });
                
                // Find duplicates across runs
                allValues.forEach((item, index) => {
                    const duplicates = allValues.filter((other, otherIndex) => 
                        otherIndex !== index && 
                        other.value === item.value
                    );
                    
                    if (duplicates.length > 0) {
                        if (!duplicatesByRun[item.runIndex]) {
                            duplicatesByRun[item.runIndex] = [];
                        }
                        duplicatesByRun[item.runIndex].push(item);
                        totalViolations++;
                    }
                });
                
                // Update validation display for each select
                Object.keys(runsData).forEach(runIndex => {
                    runsData[runIndex].forEach(item => {
                        const validation = item.select.parentElement.querySelector('small');
                        const isDuplicate = duplicatesByRun[runIndex] && 
                            duplicatesByRun[runIndex].some(dup => dup.value === item.value);
                        
                        if (isDuplicate) {
                            validation.innerHTML = '<i class="fas fa-times-circle text-danger me-1"></i>Duplicate across runs';
                            validation.className = 'text-danger';
                        } else {
                            validation.innerHTML = '<i class="fas fa-check-circle text-success me-1"></i>Unique across runs';
                            validation.className = 'text-success';
                        }
                        totalChecked++;
                    });
                });
            });
            
            // Update overall competition status
            if (totalViolations === 0 && totalChecked > 0) {
                competitionStatus.textContent = 'All Valid';
                competitionStatus.className = 'ms-2 badge bg-success';
            } else if (totalViolations > 0) {
                competitionStatus.textContent = `${totalViolations} Violations`;
                competitionStatus.className = 'ms-2 badge bg-danger';
            } else {
                competitionStatus.textContent = 'No figures selected';
                competitionStatus.className = 'ms-2 badge bg-secondary';
            }
            
            // Show summary alert
            if (totalViolations === 0 && totalChecked > 0) {
                showRunAlert('✅ All competition-level diversity requirements satisfied!', 'success');
            } else if (totalViolations > 0) {
                showRunAlert(`❌ Found ${totalViolations} diversity violations across runs. Check highlighted figures.`, 'danger');
            } else {
                showRunAlert('ℹ️ No figures selected for competition-level validation.', 'info');
            }
            
            // Update the final score validation display
            updateFinalScoreValidation();
        }
        
        function updateFinalScoreValidation() {
            // Update diversity validation in final score section
            setTimeout(() => {
                generateCompetitionDiversityValidation();
                updateRunDiversitySummaries();
                updateOverallValidationStatus();
                updateSubmissionReadiness();
            }, 100);
        }
        
        function generateCompetitionDiversityValidation() {
            const container = document.getElementById('competitionDiversityValidation');
            if (!container) return;
            
            // Generate sample validation for the examples provided
            const validationHTML = `
                <div class="row g-3">
                    <!-- Direction Category -->
                    <div class="col-md-6">
                        <div class="border rounded p-3">
                            <h6 class="mb-2">
                                <i class="fas fa-compass me-2"></i>Direction 
                                <span class="badge bg-danger ms-2">❌ Invalid</span>
                            </h6>
                            <div class="small">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 1:</span>
                                    <span class="fw-bold">Frontside</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1 text-danger">
                                    <span>Run 2:</span>
                                    <span class="fw-bold">Frontside ❌</span>
                                </div>
                                <div class="d-flex justify-content-between text-danger">
                                    <span>Run 3:</span>
                                    <span class="fw-bold">Frontside ❌</span>
                                </div>
                                <small class="text-danger mt-2 d-block">
                                    <i class="fas fa-exclamation-triangle me-1"></i>
                                    Direction must be unique across all runs
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Rails Category -->
                    <div class="col-md-6">
                        <div class="border rounded p-3">
                            <h6 class="mb-2">
                                <i class="fas fa-road me-2"></i>Rails 
                                <span class="badge bg-warning ms-2">⚠️ Partial</span>
                            </h6>
                            <div class="small">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 1:</span>
                                    <span class="fw-bold">50-50</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 2:</span>
                                    <span class="fw-bold">Boardslide</span>
                                </div>
                                <div class="d-flex justify-content-between text-warning">
                                    <span>Run 3:</span>
                                    <span class="fw-bold">50-50 ⚠️</span>
                                </div>
                                <small class="text-warning mt-2 d-block">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Rails can repeat if minimum variety met
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Valid Example Toggle -->
                <div class="mt-3">
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="showValidExample()">
                        <i class="fas fa-eye me-1"></i>Show Valid Example
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm ms-2" onclick="showInvalidExample()">
                        <i class="fas fa-eye me-1"></i>Show Invalid Example
                    </button>
                </div>
            `;
            
            container.innerHTML = validationHTML;
        }
        
        function updateRunDiversitySummaries() {
            // Update individual run diversity summaries
            for (let runIndex = 1; runIndex <= 3; runIndex++) {
                const indicator = document.querySelector(`[data-run="${runIndex}"].diversity-indicator`);
                if (indicator) {
                    if (runIndex === 1) {
                        indicator.innerHTML = '<i class="fas fa-check text-success"></i> ✓ Valid';
                        indicator.className = 'diversity-indicator text-success';
                    } else if (runIndex === 2) {
                        indicator.innerHTML = '<i class="fas fa-exclamation-triangle text-warning"></i> ⚠️ Issues';
                        indicator.className = 'diversity-indicator text-warning';
                    } else {
                        indicator.innerHTML = '<i class="fas fa-times text-danger"></i> ❌ Invalid';
                        indicator.className = 'diversity-indicator text-danger';
                    }
                }
            }
        }
        
        function updateOverallValidationStatus() {
            // Update validation summary in final score section
            const diversityValidation = document.getElementById('diversityValidationSummary');
            const submissionReadiness = document.getElementById('submissionReadiness');
            const submitButton = document.getElementById('submitFinalScoreBtn');
            const overallStatus = document.getElementById('overallSubmissionStatus');
            
            if (diversityValidation) {
                diversityValidation.innerHTML = `
                    <i class="fas fa-times text-danger me-1"></i>Diversity rules: <strong class="text-danger">Violations</strong>
                `;
            }
            
            if (submissionReadiness) {
                submissionReadiness.innerHTML = `
                    <i class="fas fa-ban text-danger me-1"></i>Ready to submit: <strong class="text-danger">Blocked</strong>
                `;
            }
            
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.className = 'btn btn-secondary btn-lg me-3';
                submitButton.innerHTML = '<i class="fas fa-ban me-2"></i>Cannot Submit (Diversity Issues)';
            }
            
            if (overallStatus) {
                overallStatus.className = 'badge bg-danger fs-6 p-2';
                overallStatus.innerHTML = '<i class="fas fa-exclamation-triangle me-1"></i>BLOCKED';
            }
        }
        
        function showValidExample() {
            const container = document.getElementById('competitionDiversityValidation');
            if (!container) return;
            
            const validHTML = `
                <div class="row g-3">
                    <!-- Direction Category - Valid -->
                    <div class="col-md-6">
                        <div class="border rounded p-3 border-success">
                            <h6 class="mb-2">
                                <i class="fas fa-compass me-2"></i>Direction 
                                <span class="badge bg-success ms-2">✅ Valid</span>
                            </h6>
                            <div class="small">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 1:</span>
                                    <span class="fw-bold text-success">Frontside</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 2:</span>
                                    <span class="fw-bold text-success">Backside</span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>Run 3:</span>
                                    <span class="fw-bold text-success">Switch</span>
                                </div>
                                <small class="text-success mt-2 d-block">
                                    <i class="fas fa-check-circle me-1"></i>
                                    All directions are unique ✅
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Rails Category - Valid -->
                    <div class="col-md-6">
                        <div class="border rounded p-3 border-success">
                            <h6 class="mb-2">
                                <i class="fas fa-road me-2"></i>Rails 
                                <span class="badge bg-success ms-2">✅ Valid</span>
                            </h6>
                            <div class="small">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 1:</span>
                                    <span class="fw-bold text-success">50-50</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 2:</span>
                                    <span class="fw-bold text-success">Boardslide</span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>Run 3:</span>
                                    <span class="fw-bold text-muted">50-50 ✅</span>
                                </div>
                                <small class="text-success mt-2 d-block">
                                    <i class="fas fa-check-circle me-1"></i>
                                    Minimum variety satisfied (repeat allowed)
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3 alert alert-success">
                    <h6><i class="fas fa-trophy me-2"></i>Valid Case Result:</h6>
                    <p class="mb-0">All competition diversity requirements satisfied. Participant can submit final score.</p>
                </div>
                
                <div class="mt-3">
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="showValidExample()">
                        <i class="fas fa-eye me-1"></i>Show Valid Example
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm ms-2" onclick="showInvalidExample()">
                        <i class="fas fa-eye me-1"></i>Show Invalid Example
                    </button>
                    <button type="button" class="btn btn-success btn-sm ms-3" onclick="applyValidExample()">
                        <i class="fas fa-magic me-1"></i>Apply Valid Settings
                    </button>
                </div>
            `;
            
            container.innerHTML = validHTML;
        }
        
        function showInvalidExample() {
            const container = document.getElementById('competitionDiversityValidation');
            if (!container) return;
            
            const invalidHTML = `
                <div class="row g-3">
                    <!-- Direction Category - Invalid -->
                    <div class="col-md-6">
                        <div class="border rounded p-3 border-danger">
                            <h6 class="mb-2">
                                <i class="fas fa-compass me-2"></i>Direction 
                                <span class="badge bg-danger ms-2">❌ Invalid</span>
                            </h6>
                            <div class="small">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 1:</span>
                                    <span class="fw-bold">Frontside</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1 bg-danger-subtle">
                                    <span>Run 2:</span>
                                    <span class="fw-bold text-danger">Frontside ❌</span>
                                </div>
                                <div class="d-flex justify-content-between bg-danger-subtle">
                                    <span>Run 3:</span>
                                    <span class="fw-bold text-danger">Frontside ❌</span>
                                </div>
                                <small class="text-danger mt-2 d-block">
                                    <i class="fas fa-exclamation-triangle me-1"></i>
                                    Direction duplicated in runs 2 & 3
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Rails Category - Invalid -->
                    <div class="col-md-6">
                        <div class="border rounded p-3 border-danger">
                            <h6 class="mb-2">
                                <i class="fas fa-road me-2"></i>Rails 
                                <span class="badge bg-danger ms-2">❌ Invalid</span>
                            </h6>
                            <div class="small">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 1:</span>
                                    <span class="fw-bold">50-50</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Run 2:</span>
                                    <span class="fw-bold">Boardslide</span>
                                </div>
                                <div class="d-flex justify-content-between bg-danger-subtle">
                                    <span>Run 3:</span>
                                    <span class="fw-bold text-danger">50-50 ❌</span>
                                </div>
                                <small class="text-danger mt-2 d-block">
                                    <i class="fas fa-exclamation-triangle me-1"></i>
                                    Both categories have duplicates
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3 alert alert-danger">
                    <h6><i class="fas fa-ban me-2"></i>Invalid Case Result:</h6>
                    <p class="mb-2">Multiple diversity violations detected:</p>
                    <ul class="mb-0">
                        <li>Direction "Frontside" used in runs 1, 2, and 3 (must be unique)</li>
                        <li>Rails "50-50" used in runs 1 and 3 (creates pattern with Direction duplicates)</li>
                    </ul>
                </div>
                
                <div class="mt-3">
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="showValidExample()">
                        <i class="fas fa-eye me-1"></i>Show Valid Example
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm ms-2" onclick="showInvalidExample()">
                        <i class="fas fa-eye me-1"></i>Show Invalid Example
                    </button>
                    <button type="button" class="btn btn-danger btn-sm ms-3" onclick="applyInvalidExample()">
                        <i class="fas fa-exclamation-triangle me-1"></i>Apply Invalid Settings
                    </button>
                </div>
            `;
            
            container.innerHTML = invalidHTML;
        }
        
        function applyValidExample() {
            // Update individual run summaries to show valid state
            for (let runIndex = 1; runIndex <= 3; runIndex++) {
                const indicator = document.querySelector(`[data-run="${runIndex}"].diversity-indicator`);
                if (indicator) {
                    indicator.innerHTML = '<i class="fas fa-check text-success"></i> ✓ Valid';
                    indicator.className = 'diversity-indicator text-success';
                }
            }
            
            // Update validation status for valid case
            const diversityValidation = document.getElementById('diversityValidationSummary');
            const submissionReadiness = document.getElementById('submissionReadiness');
            const submitButton = document.getElementById('submitFinalScoreBtn');
            const overallStatus = document.getElementById('overallSubmissionStatus');
            
            if (diversityValidation) {
                diversityValidation.innerHTML = `
                    <i class="fas fa-check text-success me-1"></i>Diversity rules: <strong class="text-success">Satisfied</strong>
                `;
            }
            
            if (submissionReadiness) {
                submissionReadiness.innerHTML = `
                    <i class="fas fa-check text-success me-1"></i>Ready to submit: <strong class="text-success">Yes</strong>
                `;
            }
            
            if (submitButton) {
                submitButton.disabled = false;
                submitButton.className = 'btn btn-success btn-lg me-3';
                submitButton.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Submit Final Score';
            }
            
            if (overallStatus) {
                overallStatus.className = 'badge bg-success fs-6 p-2';
                overallStatus.innerHTML = '<i class="fas fa-check-circle me-1"></i>COMPLETE';
            }
            
            showRunAlert('✅ Valid diversity settings applied - ready to submit!', 'success');
        }
        
        function applyInvalidExample() {
            // Apply invalid example (already shown by default)
            updateOverallValidationStatus();
            showInvalidExample();
            showRunAlert('❌ Invalid diversity settings applied - submission blocked!', 'danger');
        }
        
        function showDiversityDetails() {
            // Create detailed modal showing diversity rules and validation
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-globe me-2"></i>Competition Diversity Rules Details
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row g-4">
                                <div class="col-md-6">
                                    <h6 class="text-success">✅ Valid Example</h6>
                                    <div class="border rounded p-3 bg-success-subtle">
                                        <p><strong>Run 1:</strong> Direction = Frontside, Rails = 50-50</p>
                                        <p><strong>Run 2:</strong> Direction = Backside, Rails = Boardslide</p>
                                        <p><strong>Run 3:</strong> Direction = Switch, Rails = 50-50</p>
                                        <small class="text-success">
                                            <i class="fas fa-check me-1"></i>All unique across runs (Rails can repeat if minimum variety met)
                                        </small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <h6 class="text-danger">❌ Invalid Example</h6>
                                    <div class="border rounded p-3 bg-danger-subtle">
                                        <p><strong>Run 1:</strong> Direction = Frontside, Rails = 50-50</p>
                                        <p><strong>Run 2:</strong> Direction = Frontside, Rails = Boardslide ❌</p>
                                        <p><strong>Run 3:</strong> Direction = Frontside, Rails = 50-50 ❌</p>
                                        <small class="text-danger">
                                            <i class="fas fa-times me-1"></i>Direction duplicated across multiple runs
                                        </small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <h6>Competition-Level Diversity Rules:</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Category</th>
                                                <th>Scope</th>
                                                <th>Requirement</th>
                                                <th>Current Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td><i class="fas fa-compass me-1"></i>Direction</td>
                                                <td><span class="badge bg-warning">Competition</span></td>
                                                <td>Must be unique across all runs</td>
                                                <td><span class="badge bg-danger">❌ Violated</span></td>
                                            </tr>
                                            <tr>
                                                <td><i class="fas fa-road me-1"></i>Rails</td>
                                                <td><span class="badge bg-warning">Competition</span></td>
                                                <td>Minimum 2 distinct (repeats allowed)</td>
                                                <td><span class="badge bg-warning">⚠️ Partial</span></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-success" onclick="applyValidExample(); bootstrap.Modal.getInstance(this.closest('.modal')).hide();">
                                Apply Valid Example
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });
        }
    </script>

<style>
    .icon {
    font-size: 48px;
    position: relative;
    opacity: 0;
    will-change: transform, opacity;
  }</style>
<script>
const icon = document.querySelector('.icon');

function animateIcon() {
  let startX = 0;
  let startY = 0;

  // Random movement range ±100px
  let endX = (Math.random() - 0.5) * 100; 
  let endY = (Math.random() - 0.5) * 100;

  // Random curve control point
  let cpX = (Math.random() - 0.5) * 200;
  let cpY = (Math.random() - 0.5) * 200;

  // Randomly decide if rotation happens (50% chance)
  let doRotation = Math.random() > 0.5;
  let startRot = doRotation ? Math.random() * 360 : 0;
  let endRot = doRotation ? startRot + (Math.random() - 0.5) * 720 : 0;

  // Random start and end scale
  let startScale = 0.5 + Math.random() * 0.5; // 0.5 - 1.0
  let endScale = 1 + Math.random(); // 1.0 - 2.0

  let startTime = performance.now();

  function step(now) {
    let progress = (now - startTime) / 10000; // 5s animation
    if (progress > 1) progress = 1;

    // Ease in-out cubic
    let t = progress < 0.5
      ? 4 * progress * progress * progress
      : 1 - Math.pow(-2 * progress + 2, 3) / 2;

    // Quadratic Bézier curve path
    let x = (1 - t) ** 2 * startX + 2 * (1 - t) * t * cpX + t ** 2 * endX;
    let y = (1 - t) ** 2 * startY + 2 * (1 - t) * t * cpY + t ** 2 * endY;

    // Opacity: fade in & out
    let opacity = Math.sin(progress * Math.PI);

    // Rotation & scale interpolation
    let rotation = startRot + (endRot - startRot) * t;
    let scale = startScale + (endScale - startScale) * Math.sin(progress * Math.PI);

    // Apply transform — if no rotation, skip it
    let transform = `translate(${x}px, ${y}px)`;
    if (doRotation) transform += ` rotate(${rotation}deg)`;
    transform += ` scale(${scale})`;

    icon.style.transform = transform;
    icon.style.opacity = opacity.toFixed(2);

    if (progress < 1) {
      requestAnimationFrame(step);
    } else {
      // Restart after short pause
      setTimeout(animateIcon, 500);
    }
  }
  requestAnimationFrame(step);
}

animateIcon();
</script>

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