<?php
session_start();
include 'includes/db.php';
require_once __DIR__ . '/includes/dompdf/autoload.inc.php';
use Dompdf\Dompdf;

$selected_event  = $_GET['event_id']  ?? 0;
$filter_category = $_GET['category']  ?? 'all';
$filter_gender   = $_GET['gender']    ?? 'all';
$sort_by         = $_GET['sort']      ?? 'none';
$export          = $_GET['export']   ?? 'none';

$events = $pdo
    ->query("SELECT id, name, date FROM events ORDER BY date DESC")
    ->fetchAll(PDO::FETCH_ASSOC);

// Get categories from event_participants table for the selected event
$categories = [];
if ($selected_event) {
    $categories_stmt = $pdo->prepare("SELECT DISTINCT category FROM event_participants WHERE event_id = ? AND category IS NOT NULL AND category != '' ORDER BY category");
    $categories_stmt->execute([$selected_event]);
    $categories = $categories_stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
    $categories = $pdo
        ->query("SELECT DISTINCT category FROM event_participants WHERE category IS NOT NULL AND category != '' ORDER BY category")
        ->fetchAll(PDO::FETCH_COLUMN);
}

// For exports, we still need the original logic (keeping for CSV/PDF export functionality)
if ($export === 'csv' || $export === 'pdf') {
    // Include the original data processing logic here for exports
    // [Keep the original export logic from the previous version]
    // This ensures exports still work without requiring AJAX
}

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>View 3 - Summary Per Participant</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<!-- style skin holder -->
<style>
        .table th, .table td { white-space: nowrap; }
        
.angle-th 
{
 vertical-align: top;
  text-align: center;
}

.angle-th span 
{
  -ms-writing-mode: vertical-rl;
  -webkit-writing-mode: vertical-rl;
  writing-mode: vertical-rl;
  transform: rotate(180deg);
  white-space: nowrap;
}
        .angle-th { transform: rotate(180deg); }
        
        .col-best, .col-average, .col-overall-best, .col-highest-average {
            text-align: center;
        }
        
        .col-best { background-color: #d1ecf1; }
        .col-average { background-color: #f8d7da; }
        .col-overall-best { background-color: #c3e6cb; }
        .col-highest-average { background-color: #bee5eb; }

.col-control-points {
    background-color: #fff3cd;
    font-size: 0.7em;
    padding: 2px !important;
    min-width: 150px;
    max-width: 180px;
}

.control-point-breakdown {
    display: flex;
    flex-direction: column;
    gap: 3px;
    max-width: 180px;
}

.control-point-group {
    border: 1px solid #dee2e6;
    border-radius: 4px;
    background: rgba(255, 255, 255, 0.9);
    margin-bottom: 2px;
}

.control-point-header {
    background: #f8f9fa;
    padding: 2px 4px;
    border-bottom: 1px solid #dee2e6;
    font-weight: 600;
    font-size: 0.75em;
    color: #495057;
    text-align: center;
}

.control-point-name {
    font-weight: 600;
    color: #495057;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}

.judges-in-control-point {
    padding: 2px;
    display: flex;
    flex-direction: column;
    gap: 1px;
}

.judge-score-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1px 3px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 2px;
    font-size: 0.75em;
    white-space: nowrap;
}

.judge-name {
    font-weight: 500;
    color: #495057;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 45px;
    font-size: 0.8em;
}

.judge-score {
    font-weight: 600;
    color: #212529;
    min-width: 30px;
    text-align: right;
    font-size: 0.85em;
}

.judge-score-item:hover {
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.control-point-group:hover {
    border-color: #adb5bd;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Color coding for different control points */
.control-point-group:nth-child(1) .control-point-header {
    background: #e3f2fd;
    border-bottom-color: #90caf9;
}

.control-point-group:nth-child(2) .control-point-header {
    background: #f3e5f5;
    border-bottom-color: #ce93d8;
}

.control-point-group:nth-child(3) .control-point-header {
    background: #e8f5e8;
    border-bottom-color: #a5d6a7;
}

.control-point-group:nth-child(4) .control-point-header {
    background: #fff3e0;
    border-bottom-color: #ffcc80;
}

/* Update angle headers for control point columns */
.angle-th.col-control-points span {
    font-size: 0.65em;
}

/* Loading states */
.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.table-container {
    position: relative;
}

.loading-spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
}
.heat-container {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 12px;
    background: #f8f9fa;
}

.heat-header {
    font-weight: 600;
    color: #495057;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.heat-toggle {
    font-size: 0.8em;
}

.run-selection {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.run-checkbox {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.9em;
}

.run-checkbox input[type="checkbox"] {
    margin: 0;
}

.heat-controls {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
}

.heat-controls .btn {
    font-size: 0.75em;
    padding: 2px 8px;
}

.heat-disabled {
    opacity: 0.6;
    pointer-events: auto !important;
}
div#heatRunContainer {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
    column-gap: 1em;
}
.heat-inactive {
    opacity: 0.5;
    background-color: #f8f9fa;
    border-color: #dee2e6;
}

.heat-inactive .heat-header label {
    color: #6c757d;
    text-decoration: line-through;
}

.heat-inactive .heat-header label::after {
    content: " (inactive)";
    font-size: 0.7em;
    color: #dc3545;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.alert alert-api {
    margin-top: 1rem;
}
</style>
</head>
<body class="body-bg-aurora-bright">
   
<div class="p-4">
    <h2>View 3: Summary Table</h2>

    <!-- Export Buttons -->
    <?php $base = $_SERVER['PHP_SELF'].'?'.http_build_query([
        'event_id'=>$selected_event,
        'category'=>$filter_category,
        'gender'=>$filter_gender,
        'sort'=>$sort_by
    ]); ?>

    <div class="col-md-12 mb-4">
        <div class="btn-group me-3">
            <button class="btn btn-outline-info" id="refreshTableBtn">
                <i class="fas fa-sync-alt me-1"></i>Refresh
            </button>
            <button class="btn btn-outline-secondary" id="autoRefreshToggle">
                <i class="fas fa-clock me-1"></i>Auto: OFF
            </button>
        </div>
        <div class="btn-group">
            <a href="<?= $base.'&export=csv' ?>" class="btn btn-outline-primary">Export CSV</a>
            <a href="<?= $base.'&export=pdf' ?>" class="btn btn-outline-primary">Export PDF</a>
        </div>
    </div>

    <!-- Filters & Sorting -->
    <form method="get" class="row g-3 mb-4" id="filterForm">
        <div class="col-md-3">
            <label>Select Event</label>
            <select name="event_id" class="form-select" id="eventSelect">
                <option value="">-- Choose Event --</option>
                <?php foreach ($events as $ev): ?>
                <option value="<?= $ev['id'] ?>" <?= $selected_event == $ev['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($ev['name']) ?> (<?= htmlspecialchars($ev['date']) ?>)
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label>Category</label>
            <select name="category" class="form-select" id="categorySelect">
                <option value="all">All Categories</option>
                <?php foreach ($categories as $cat): ?>
                <option value="<?= $cat ?>" <?= $filter_category == $cat ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label>Gender</label>
            <select name="gender" class="form-select" id="genderSelect">
                <option value="all" <?= $filter_gender=='all'?'selected':'' ?>>All</option>
                <option value="M"   <?= $filter_gender=='M'  ?'selected':'' ?>>Male</option>
                <option value="F"   <?= $filter_gender=='F'  ?'selected':'' ?>>Female</option>
                <option value="OPEN"<?= $filter_gender=='OPEN'?'selected':'' ?>>Open</option>
            </select>
        </div>
        <div class="col-md-3">
            <label>Sort by</label>
            <select name="sort" class="form-select" id="sortSelect">
                <option value="none"           <?= $sort_by==='none'           ?'selected':'' ?>>None</option>
                <option value="OverallAverage"    <?= $sort_by==='OverallAverage'    ?'selected':'' ?>>Overall Average</option>
                <option value="HighestAverage" <?= $sort_by==='HighestAverage' ?'selected':'' ?>>Highest Average</option>
            </select>
        </div>
    </form>

    <!-- Column Filters -->
    <div class="border-0 shadow-none card mb-4">
        <div class="border-0 shadow-none card-header">
            <h6 class="mb-0">
                <i class="fas fa-filter me-2"></i>Column Filters
                <button class="btn btn-sm btn-outline-secondary float-end" type="button" data-bs-toggle="collapse" data-bs-target="#columnFiltersContent">
                    Toggle
                </button>
            </h6>
        </div>
        <div class="border-0 shadow-none card-body collapse show" id="columnFiltersContent">
            <!-- Heat and Run Selection -->
            <div class="row mb-3">
                <div class="col-12">
                    <label class="form-label">Heat & Run Selection</label>
                    <div id="heatRunContainer">
                        <!-- Heat/Run options will be populated dynamically -->
                    </div>
                </div>
            </div>
            
            <!-- Column Type Toggles -->
            <div class="row mb-3">
                <div class="col-12">
                    <label class="form-label">Show Column Types</label>
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showRuns" checked>
                                <label class="form-check-label" for="showRuns">Run Scores</label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showJudges">
                                <label class="form-check-label" for="showJudges">Judge Breakdown</label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showFigures">
                                <label class="form-check-label" for="showFigures">Figures</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showControlPoints" checked>
                                <label class="form-check-label" for="showControlPoints">Control Points</label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showHeatBest" checked>
                                <label class="form-check-label" for="showHeatBest">Heat Best</label>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showHeatAverage" checked>
                                <label class="form-check-label" for="showHeatAverage">Heat Average</label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showOverallBest" checked>
                                <label class="form-check-label" for="showOverallBest">Overall Best</label>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="showHighestAverage" checked>
                                <label class="form-check-label" for="showHighestAverage">Highest Average</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Preset Buttons -->
            <div class="row">
                <div class="col-12">
                    <label class="form-label">Quick Presets</label>
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-outline-primary" id="presetAll">Show All</button>
                        <button type="button" class="btn btn-outline-secondary" id="presetBasic">Basic View</button>
                        <button type="button" class="btn btn-outline-secondary" id="presetJudges">Judge Focus</button>
                        <button type="button" class="btn btn-outline-secondary" id="presetHeat1">Heat 1 Only</button>
                        <button type="button" class="btn btn-outline-secondary" id="presetHeat2">Heat 2 Only</button>
                        <button type="button" class="btn btn-outline-secondary" id="presetSummary">Summary Only</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- API Status Messages -->
    <div id="apiMessages"></div>

    <!-- Summary Table Container -->
    <div class="table-container">
        <div class="loading-overlay" id="loadingOverlay" style="display: none;">
            <div class="loading-spinner"></div>
        </div>
        
        <h4 class="mt-4" id="categoryTitle"><?= htmlspecialchars($filter_category) ?></h4>
        <div class="table-responsive">
            <table id="summaryTable" class="table table-bordered table-hover table-striped table-sm" style="font-size: .8em;">
                <thead id="tableHead">
                    <!-- Table header will be populated via AJAX -->
                </thead>
                <tbody id="tableBody">
                    <!-- Table body will be populated via AJAX -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- Initial State Message -->
    <div id="initialMessage" class="alert alert-info">
        <h5>Welcome to the Summary Table</h5>
        <p>Select an event and category to view the detailed scoreboard.</p>
        <p>The table will automatically refresh to show the latest scores.</p>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>


<script>
// Summary Table API Management with Enhanced Heat/Run Selection
class SummaryTableAPI {
    constructor() {
        this.autoRefreshInterval = null;
        this.autoRefreshEnabled = false;
        this.currentParams = this.getCurrentParams();
        this.availableColumns = null;
        this.heatRunSelections = {}; // Store heat/run selections
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadInitialData();
    }
 showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }

    showMessage(message, type = 'info') {
        const messagesDiv = document.getElementById('apiMessages');
        messagesDiv.innerHTML = `
            <div class="alert alert-${type} alert alert-api">
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                ${message}
            </div>
        `;
    }

    async updateCategories() {
        const eventId = document.getElementById('eventSelect').value;
        if (!eventId) {
            document.getElementById('categorySelect').innerHTML = '<option value="all">All Categories</option>';
            return;
        }

        try {
            const response = await fetch(`api/get_categories.php?event_id=${eventId}`);
            const data = await response.json();
            
            let options = '<option value="all">All Categories</option>';
            if (data.success && data.categories) {
                data.categories.forEach(cat => {
                    options += `<option value="${cat}">${cat}</option>`;
                });
            }
            document.getElementById('categorySelect').innerHTML = options;
        } catch (error) {
            console.error('Error updating categories:', error);
        }
    }

    applyPreset(presetName) {
        // Ensure heatRunSelections is initialized
        if (!this.heatRunSelections) {
            this.heatRunSelections = {};
        }

        switch (presetName) {
            case 'all':
                Object.keys(this.heatRunSelections).forEach(heat => {
                    if (this.heatRunSelections[heat]) {
                        this.heatRunSelections[heat].enabled = true;
                        if (this.heatRunSelections[heat].runs) {
                            this.heatRunSelections[heat].runs.forEach(run => run.selected = true);
                        }
                    }
                });
                
                this.setCheckboxValue('showRuns', true);
                this.setCheckboxValue('showJudges', false);
                this.setCheckboxValue('showControlPoints', true);
                this.setCheckboxValue('showFigures', false);
                this.setCheckboxValue('showHeatBest', true);
                this.setCheckboxValue('showHeatAverage', true);
                this.setCheckboxValue('showOverallBest', true);
                this.setCheckboxValue('showHighestAverage', true);
                break;

            case 'basic':
                Object.keys(this.heatRunSelections).forEach(heat => {
                    if (this.heatRunSelections[heat]) {
                        this.heatRunSelections[heat].enabled = true;
                        if (this.heatRunSelections[heat].runs) {
                            this.heatRunSelections[heat].runs.forEach(run => run.selected = true);
                        }
                    }
                });
                
                this.setCheckboxValue('showRuns', true);
                this.setCheckboxValue('showJudges', false);
                this.setCheckboxValue('showControlPoints', false);
                this.setCheckboxValue('showFigures', false);
                this.setCheckboxValue('showHeatBest', true);
                this.setCheckboxValue('showHeatAverage', false);
                this.setCheckboxValue('showOverallBest', true);
                this.setCheckboxValue('showHighestAverage', false);
                break;

            case 'judges':
                Object.keys(this.heatRunSelections).forEach(heat => {
                    if (this.heatRunSelections[heat]) {
                        this.heatRunSelections[heat].enabled = true;
                        if (this.heatRunSelections[heat].runs) {
                            this.heatRunSelections[heat].runs.forEach(run => run.selected = true);
                        }
                    }
                });
                
                this.setCheckboxValue('showRuns', true);
                this.setCheckboxValue('showJudges', true);
                this.setCheckboxValue('showControlPoints', true);
                this.setCheckboxValue('showFigures', true);
                this.setCheckboxValue('showHeatBest', false);
                this.setCheckboxValue('showHeatAverage', false);
                this.setCheckboxValue('showOverallBest', false);
                this.setCheckboxValue('showHighestAverage', false);
                break;

            case 'heat1':
                Object.keys(this.heatRunSelections).forEach(heat => {
                    if (this.heatRunSelections[heat]) {
                        this.heatRunSelections[heat].enabled = (heat === '1');
                        if (this.heatRunSelections[heat].runs) {
                            this.heatRunSelections[heat].runs.forEach(run => run.selected = true);
                        }
                    }
                });
                
                this.setCheckboxValue('showRuns', true);
                this.setCheckboxValue('showJudges', false);
                this.setCheckboxValue('showControlPoints', true);
                this.setCheckboxValue('showFigures', false);
                this.setCheckboxValue('showHeatBest', true);
                this.setCheckboxValue('showHeatAverage', true);
                this.setCheckboxValue('showOverallBest', false);
                this.setCheckboxValue('showHighestAverage', false);
                break;

            case 'heat2':
                Object.keys(this.heatRunSelections).forEach(heat => {
                    if (this.heatRunSelections[heat]) {
                        this.heatRunSelections[heat].enabled = (heat === '2');
                        if (this.heatRunSelections[heat].runs) {
                            this.heatRunSelections[heat].runs.forEach(run => run.selected = true);
                        }
                    }
                });
                
                this.setCheckboxValue('showRuns', true);
                this.setCheckboxValue('showJudges', false);
                this.setCheckboxValue('showControlPoints', true);
                this.setCheckboxValue('showFigures', false);
                this.setCheckboxValue('showHeatBest', true);
                this.setCheckboxValue('showHeatAverage', true);
                this.setCheckboxValue('showOverallBest', false);
                this.setCheckboxValue('showHighestAverage', false);
                break;

            case 'summary':
                Object.keys(this.heatRunSelections).forEach(heat => {
                    if (this.heatRunSelections[heat]) {
                        this.heatRunSelections[heat].enabled = false;
                        if (this.heatRunSelections[heat].runs) {
                            this.heatRunSelections[heat].runs.forEach(run => run.selected = false);
                        }
                    }
                });
                
                this.setCheckboxValue('showRuns', false);
                this.setCheckboxValue('showJudges', false);
                this.setCheckboxValue('showControlPoints', false);
                this.setCheckboxValue('showFigures', false);
                this.setCheckboxValue('showHeatBest', true);
                this.setCheckboxValue('showHeatAverage', true);
                this.setCheckboxValue('showOverallBest', true);
                this.setCheckboxValue('showHighestAverage', true);
                break;
        }

        // Update UI to reflect changes
        this.updateHeatRunInterface();
        this.loadTableData();
    }

    // Helper method to safely set checkbox values
    setCheckboxValue(id, value) {
        const element = document.getElementById(id);
        if (element) {
            element.checked = value;
        }
    }
    getCurrentParams() {
        const baseParams = {
            event_id: document.getElementById('eventSelect').value,
            category: document.getElementById('categorySelect').value,
            gender: document.getElementById('genderSelect').value,
            sort: document.getElementById('sortSelect').value
        };

        // Add column filter parameters
        const columnParams = this.getColumnFilterParams();
        return { ...baseParams, ...columnParams };
    }

    buildHeatRunFilter() {
        const filter = {};
        
        // Check if heatRunSelections is properly initialized
        if (!this.heatRunSelections || Object.keys(this.heatRunSelections).length === 0) {
            return filter; // Return empty filter if not initialized
        }
        
        Object.keys(this.heatRunSelections).forEach(heat => {
            const heatNum = parseInt(heat);
            const heatData = this.heatRunSelections[heat];
            
            if (heatData && heatData.enabled && heatData.runs) {
                const selectedRuns = heatData.runs.filter(run => run && run.selected).map(run => run.number);
                if (selectedRuns.length > 0) {
                    filter[heatNum] = selectedRuns;
                }
            }
        });
        
        return filter;
    }

    getColumnFilterParams() {
        // Build heat/run filter from selections
        const heatRunFilter = this.buildHeatRunFilter();
        
        // Check if elements exist before accessing them
        const getCheckboxValue = (id) => {
            const element = document.getElementById(id);
            return element ? (element.checked ? 'true' : 'false') : 'true';
        };
        
        return {
            heat_run_filter: JSON.stringify(heatRunFilter),
            show_runs: getCheckboxValue('showRuns'),
            show_judges: getCheckboxValue('showJudges'),
            show_control_points: getCheckboxValue('showControlPoints'),
            show_figures: getCheckboxValue('showFigures'),
            show_heat_best: getCheckboxValue('showHeatBest'),
            show_heat_average: getCheckboxValue('showHeatAverage'),
            show_overall_best: getCheckboxValue('showOverallBest'),
            show_highest_average: getCheckboxValue('showHighestAverage')
        };
    }

    bindEvents() {
        // Form change events
        document.getElementById('eventSelect').addEventListener('change', () => {
            this.updateCategories();
            this.loadTableData();
        });

        document.getElementById('categorySelect').addEventListener('change', () => {
            this.loadTableData();
        });

        document.getElementById('genderSelect').addEventListener('change', () => {
            this.loadTableData();
        });

        document.getElementById('sortSelect').addEventListener('change', () => {
            this.loadTableData();
        });

        // Column type toggles
        ['showRuns', 'showJudges', 'showControlPoints', 'showFigures', 'showHeatBest', 
         'showHeatAverage', 'showOverallBest', 'showHighestAverage'].forEach(id => {
            document.getElementById(id).addEventListener('change', () => {
                this.loadTableData();
            });
        });

        // Refresh button
        document.getElementById('refreshTableBtn').addEventListener('click', () => {
            this.loadTableData();
        });

        // Auto refresh toggle
        document.getElementById('autoRefreshToggle').addEventListener('click', () => {
            this.toggleAutoRefresh();
        });

        // Preset buttons
        document.getElementById('presetAll').addEventListener('click', () => {
            this.applyPreset('all');
        });

        document.getElementById('presetBasic').addEventListener('click', () => {
            this.applyPreset('basic');
        });

        document.getElementById('presetJudges').addEventListener('click', () => {
            this.applyPreset('judges');
        });

        document.getElementById('presetHeat1').addEventListener('click', () => {
            this.applyPreset('heat1');
        });

        document.getElementById('presetHeat2').addEventListener('click', () => {
            this.applyPreset('heat2');
        });

        document.getElementById('presetSummary').addEventListener('click', () => {
            this.applyPreset('summary');
        });
    }

    createHeatRunInterface(availableColumns) {
        if (!availableColumns || !availableColumns.heats) return;

        const container = document.getElementById('heatRunContainer');
        if (!container) return;
        
        // Only create interface if it doesn't exist or if the structure changed
        const shouldRecreate = this.shouldRecreateInterface(availableColumns);
        
        if (shouldRecreate) {
            container.innerHTML = '';
            this.initializeHeatRunSelections(availableColumns);
            this.createHeatRunUI(availableColumns);
        } else {
            // Just update the existing interface state
            this.updateExistingInterface();
        }
    }

    shouldRecreateInterface(availableColumns) {
        // Check if we need to recreate the interface
        if (!this.heatRunSelections || Object.keys(this.heatRunSelections).length === 0) {
            return true;
        }
        
        // Check if heats have changed
        const currentHeats = Object.keys(this.heatRunSelections).map(h => parseInt(h)).sort();
        const newHeats = availableColumns.heats.slice().sort();
        
        if (currentHeats.length !== newHeats.length || 
            !currentHeats.every((heat, index) => heat === newHeats[index])) {
            return true;
        }
        
        // Check if runs have changed for any heat
        for (const heat of availableColumns.heats) {
            const currentRuns = this.heatRunSelections[heat]?.runs?.map(r => r.number).sort() || [];
            const newRuns = [];
            
            for (let r = 1; r <= 10; r++) {
                if (availableColumns.runs && availableColumns.runs.some(run => run.includes(`H${heat}R${r}`))) {
                    newRuns.push(r);
                }
            }
            
            if (currentRuns.length !== newRuns.length || 
                !currentRuns.every((run, index) => run === newRuns[index])) {
                return true;
            }
        }
        
        return false;
    }

    initializeHeatRunSelections(availableColumns) {
        // Initialize or reinitialize heat/run selections
        this.heatRunSelections = {};
        
        availableColumns.heats.forEach(heat => {
            this.heatRunSelections[heat] = {
                enabled: true,
                runs: []
            };
            
            // Determine runs for this heat
            for (let r = 1; r <= 10; r++) {
                if (availableColumns.runs && availableColumns.runs.some(run => run.includes(`H${heat}R${r}`))) {
                    this.heatRunSelections[heat].runs.push({
                        number: r,
                        selected: true
                    });
                }
            }
        });
    }

    createHeatRunUI(availableColumns) {
        const container = document.getElementById('heatRunContainer');
        
        // Create UI for each heat
        availableColumns.heats.forEach(heat => {
            const heatDiv = document.createElement('div');
            heatDiv.className = 'heat-container';
            heatDiv.id = `heat-${heat}-container`;

            const heatData = this.heatRunSelections[heat];
            if (!heatData || !heatData.runs) return;
            
            // Get heat name from heat_info if available
            const heatInfo = availableColumns.heat_info && availableColumns.heat_info[heat];
            const heatName = heatInfo ? heatInfo.name : `Heat ${heat}`;
            const scoringMethod = heatInfo ? heatInfo.runs_scoring_method : 'average';
            const isActive = heatInfo ? heatInfo.is_active : 1;
            
            heatDiv.innerHTML = `
                <div class="heat-header">
                    <div>
                        <input type="checkbox" id="heat-${heat}-toggle" ${heatData.enabled ? 'checked' : ''} >
                        <label for="heat-${heat}-toggle" class="ms-2">
                            ${heatName}
                            <small class="text-muted">(${scoringMethod})</small>
                        </label>
                    </div>
                    <div class="heat-controls">
                        <button type="button" class="btn btn-outline-success heat-all-btn" data-heat="${heat}" >All</button>
                        <button type="button" class="btn btn-outline-danger heat-none-btn" data-heat="${heat}" >None</button>
                    </div>
                </div>
                <div class="run-selection" id="heat-${heat}-runs">
                    ${heatData.runs.map(run => `
                        <div class="run-checkbox">
                            <input type="checkbox" id="heat-${heat}-run-${run.number}" 
                                   data-heat="${heat}" data-run="${run.number}" 
                                   ${run.selected ? 'checked' : ''}>
                            <label for="heat-${heat}-run-${run.number}">R${run.number}</label>
                        </div>
                    `).join('')}
                </div>
            `;

            container.appendChild(heatDiv);
            
            // Add inactive styling if heat is not active
            if (!isActive) {
                heatDiv.classList.add('heat-inactive');
            }
        });

        // Bind events for all heats at once
        this.bindAllHeatEvents(availableColumns.heats);
    }

    updateExistingInterface() {
        // Update the existing interface without recreating it
        if (!this.heatRunSelections) return;
        
        Object.keys(this.heatRunSelections).forEach(heat => {
            const heatToggle = document.getElementById(`heat-${heat}-toggle`);
            const container = document.getElementById(`heat-${heat}-container`);
            
            if (heatToggle && this.heatRunSelections[heat]) {
                heatToggle.checked = this.heatRunSelections[heat].enabled;
                if (container) {
                    if (this.heatRunSelections[heat].enabled) {
                        container.classList.remove('heat-disabled');
                    } else {
                        container.classList.add('heat-disabled');
                    }
                }
            }

            if (this.heatRunSelections[heat] && this.heatRunSelections[heat].runs) {
                this.heatRunSelections[heat].runs.forEach(run => {
                    const runCheckbox = document.getElementById(`heat-${heat}-run-${run.number}`);
                    if (runCheckbox) {
                        runCheckbox.checked = run.selected;
                    }
                });
            }
        });
    }

    bindAllHeatEvents(heats) {
        // Remove any existing event listeners to prevent duplicates
        this.removeAllHeatEvents(heats);
        
        // Bind events for all heats
        heats.forEach(heat => {
            this.bindHeatEvents(heat);
        });
    }

    removeAllHeatEvents(heats) {
        // Remove existing event listeners to prevent duplicates
        heats.forEach(heat => {
            const heatToggle = document.getElementById(`heat-${heat}-toggle`);
            if (heatToggle) {
                heatToggle.replaceWith(heatToggle.cloneNode(true));
            }

            if (this.heatRunSelections[heat] && this.heatRunSelections[heat].runs) {
                this.heatRunSelections[heat].runs.forEach(run => {
                    const runCheckbox = document.getElementById(`heat-${heat}-run-${run.number}`);
                    if (runCheckbox) {
                        runCheckbox.replaceWith(runCheckbox.cloneNode(true));
                    }
                });
            }

            const allBtn = document.querySelector(`[data-heat="${heat}"].heat-all-btn`);
            if (allBtn) {
                allBtn.replaceWith(allBtn.cloneNode(true));
            }

            const noneBtn = document.querySelector(`[data-heat="${heat}"].heat-none-btn`);
            if (noneBtn) {
                noneBtn.replaceWith(noneBtn.cloneNode(true));
            }
        });
    }

    bindHeatEvents(heat) {
        // Heat toggle
        const heatToggle = document.getElementById(`heat-${heat}-toggle`);
        if (heatToggle) {
            heatToggle.addEventListener('change', (e) => {
                console.log(`Heat ${heat} toggle changed to:`, e.target.checked);
                if (this.heatRunSelections[heat]) {
                    this.heatRunSelections[heat].enabled = e.target.checked;
                    const container = document.getElementById(`heat-${heat}-container`);
                    if (container) {
                        if (e.target.checked) {
                            container.classList.remove('heat-disabled');
                        } else {
                            container.classList.add('heat-disabled');
                        }
                    }
                    this.loadTableData();
                }
            });
        }

        // Run checkboxes
        if (this.heatRunSelections[heat] && this.heatRunSelections[heat].runs) {
            this.heatRunSelections[heat].runs.forEach(run => {
                const runCheckbox = document.getElementById(`heat-${heat}-run-${run.number}`);
                if (runCheckbox) {
                    runCheckbox.addEventListener('change', (e) => {
                        console.log(`Heat ${heat} Run ${run.number} changed to:`, e.target.checked);
                        const runIndex = this.heatRunSelections[heat].runs.findIndex(r => r.number === run.number);
                        if (runIndex !== -1) {
                            this.heatRunSelections[heat].runs[runIndex].selected = e.target.checked;
                        }
                        this.loadTableData();
                    });
                }
            });
        }

        // All button
        const allBtn = document.querySelector(`[data-heat="${heat}"].heat-all-btn`);
        if (allBtn) {
            allBtn.addEventListener('click', (e) => {
                console.log(`Heat ${heat} All button clicked`);
                e.preventDefault();
                if (this.heatRunSelections[heat] && this.heatRunSelections[heat].runs) {
                    this.heatRunSelections[heat].runs.forEach(run => run.selected = true);
                    this.heatRunSelections[heat].runs.forEach(run => {
                        const checkbox = document.getElementById(`heat-${heat}-run-${run.number}`);
                        if (checkbox) checkbox.checked = true;
                    });
                    this.loadTableData();
                }
            });
        }

        // None button
        const noneBtn = document.querySelector(`[data-heat="${heat}"].heat-none-btn`);
        if (noneBtn) {
            noneBtn.addEventListener('click', (e) => {
                console.log(`Heat ${heat} None button clicked`);
                e.preventDefault();
                if (this.heatRunSelections[heat] && this.heatRunSelections[heat].runs) {
                    this.heatRunSelections[heat].runs.forEach(run => run.selected = false);
                    this.heatRunSelections[heat].runs.forEach(run => {
                        const checkbox = document.getElementById(`heat-${heat}-run-${run.number}`);
                        if (checkbox) checkbox.checked = false;
                    });
                    this.loadTableData();
                }
            });
        }

        // Apply initial disabled state
        if (this.heatRunSelections[heat] && !this.heatRunSelections[heat].enabled) {
            const container = document.getElementById(`heat-${heat}-container`);
            if (container) {
                container.classList.add('heat-disabled');
            }
        }
    }

    // Update the updateHeatRunInterface method to use the new approach
    updateHeatRunInterface() {
        this.updateExistingInterface();
    }

    // Update the loadTableData method to avoid recreating the interface unnecessarily
    async loadTableData() {
        this.currentParams = this.getCurrentParams();
        
        if (!this.currentParams.event_id) {
            document.getElementById('initialMessage').style.display = 'block';
            document.getElementById('summaryTable').style.display = 'none';
            document.getElementById('categoryTitle').style.display = 'none';
            return;
        }

        

        this.showLoading();
        document.getElementById('initialMessage').style.display = 'none';

        try {
            const params = new URLSearchParams(this.currentParams);
            const response = await fetch(`api/summary_table_api.php?${params}`);
            const data = await response.json();
            console.log('Table data response:', data);
            if (data.success) {
                document.getElementById('tableHead').innerHTML = data.table_head;
                document.getElementById('tableBody').innerHTML = data.table_body;
                
                // Add badge styles if available
                let existingStyles = document.getElementById('tableBadgeStyles');
                if (existingStyles) {
                    existingStyles.remove();
                }
                if (data.table_badge_colors) {
                    const styleElement = document.createElement('style');
                    styleElement.id = 'tableBadgeStyles';
                    styleElement.textContent = data.table_badge_colors;
                    document.head.appendChild(styleElement);
                }
                
                document.getElementById('categoryTitle').textContent = data.category;
                document.getElementById('categoryTitle').style.display = 'block';
                document.getElementById('summaryTable').style.display = 'table';
                
                // Update available columns for filters (only create interface if needed)
                if (data.available_columns) {
                    this.availableColumns = data.available_columns;
                    this.createHeatRunInterface(data.available_columns);
                }
                
                const columnCount = data.headers ? data.headers.length + 6 : 'N/A'; // +6 for basic columns
                let message = `Loaded ${data.participant_count} participants with ${columnCount} columns for category "${data.category}"`;
                
                // Add filter information
                if (data.using_filtered_calculations) {
                    message += `<br><small class="text-info"><i class="fas fa-filter me-1"></i>OverallBest and HighestAverage calculated from selected runs only</small>`;
                }
                if (data.filter_summary) {
                    message += `<br><small class="text-muted">${data.filter_summary}</small>`;
                }
                
                this.showMessage(message, 'success');
            }
        } catch (error) {
            console.error('Error loading table data:', error);
            this.showMessage('Error connecting to server. Please try again.', 'danger');
        } finally {
            this.hideLoading();
        }
    }

    loadInitialData() {
        if (this.currentParams.event_id) {
            this.loadTableData();
        }
    }

    toggleAutoRefresh() {
        this.autoRefreshEnabled = !this.autoRefreshEnabled;
        const button = document.getElementById('autoRefreshToggle');
        
        if (this.autoRefreshEnabled) {
            button.innerHTML = '<i class="fas fa-clock me-1"></i>Auto: ON';
            button.classList.remove('btn-outline-secondary');
            button.classList.add('btn-success');
            
            this.autoRefreshInterval = setInterval(() => {
                this.loadTableData();
            }, 10000); // Refresh every 10 seconds
            
            this.showMessage('Auto-refresh enabled (every 10 seconds)', 'info');
        } else {
            button.innerHTML = '<i class="fas fa-clock me-1"></i>Auto: OFF';
            button.classList.remove('btn-success');
            button.classList.add('btn-outline-secondary');
            
            if (this.autoRefreshInterval) {
                clearInterval(this.autoRefreshInterval);
                this.autoRefreshInterval = null;
            }
        }
    }
}

// Initialize the Summary Table API
document.addEventListener('DOMContentLoaded', function() {
    window.summaryTableAPI = new SummaryTableAPI();
});

// Add this to your table generation or after the table is loaded
function makeTableSortable() {
    document.querySelectorAll('th[data-sortable]').forEach(header => {
        header.style.cursor = 'pointer';
        header.addEventListener('click', function() {
            const column = this.dataset.sort;
            const currentDirection = this.dataset.direction || 'desc';
            const newDirection = currentDirection === 'desc' ? 'asc' : 'desc';
            
            // Update visual indicators
            document.querySelectorAll('th').forEach(h => {
                h.classList.remove('sort-asc', 'sort-desc');
            });
            this.classList.add('sort-' + newDirection);
            this.dataset.direction = newDirection;
            
            // Reload table with new sort
            loadTableWithSort(column, newDirection);
        });
    });
}

function loadTableWithSort(column, direction) {
    // Add sort parameters to your existing loadTableData function
    const params = new URLSearchParams(window.location.search);
    params.set('sort', column);
    params.set('sort_direction', direction);
    
    // Update your AJAX call to include these parameters
    const url = 'api/summary_table_api.php?' + params.toString();
    // ... your existing AJAX logic
}
</script>
</body>
</html>