<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Match Detail - Fixture Manager</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
        }
        .nav {
            display: flex;
            gap: 1rem;
        }
        .nav a {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        .nav a:hover {
            background-color: rgba(255,255,255,0.1);
        }
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .content {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .btn {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            display: inline-block;
            margin: 0.5rem 0;
            border: none;
            cursor: pointer;
            font-size: 0.9rem;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-danger {
            background-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background-color: #e0a800;
        }
        .btn-success {
            background-color: #28a745;
        }
        .btn-success:hover {
            background-color: #218838;
        }
        .btn-secondary {
            background-color: #6c757d;
        }
        .btn-secondary:hover {
            background-color: #545b62;
        }
        .btn-sm {
            padding: 4px 8px;
            font-size: 0.8rem;
            margin: 0 2px;
        }
        .alert {
            padding: 12px;
            margin-bottom: 1rem;
            border-radius: 4px;
        }
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .actions-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 1rem;
        }
        .match-info {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            background-color: white;
            border-radius: 6px;
            border-left: 4px solid #007bff;
        }
        .info-label {
            font-size: 1rem;
            color: #666;
            font-weight: 500;
            margin: 0;
            min-width: 120px;
        }
        .info-value {
            font-size: 1.1rem;
            font-weight: bold;
            color: #333;
            text-align: right;
            word-break: break-all;
            max-width: 70%;
        }
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .status-active {
            background-color: #d4edda;
            color: #155724;
        }
        .status-inactive {
            background-color: #f8d7da;
            color: #721c24;
        }
        .section {
            margin-bottom: 2rem;
        }
        .section h2 {
            color: #333;
            border-bottom: 2px solid #007bff;
            padding-bottom: 0.5rem;
            margin-bottom: 1rem;
        }
        .outcomes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        .outcome-card {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            transition: all 0.3s ease;
        }
        .outcome-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        .outcome-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }
        .outcome-name {
            font-weight: 600;
            color: #495057;
            font-size: 0.95rem;
        }
        .outcome-input {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }
        .outcome-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
        }
        .no-outcomes {
            text-align: center;
            padding: 3rem;
            color: #6c757d;
        }
        .no-outcomes-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
        .add-outcome-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1.5rem;
        }
        .add-outcome-form {
            display: grid;
            grid-template-columns: 1fr 1fr auto;
            gap: 1rem;
            align-items: end;
        }
        .form-group {
            display: flex;
            flex-direction: column;
        }
        .form-label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
        }
        .form-input {
            padding: 0.5rem;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 1rem;
        }
        .form-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
        }
        .loading {
            display: none;
            text-align: center;
            padding: 1rem;
        }
        .spinner {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #007bff;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-right: 0.5rem;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .zip-section {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
        }
        .zip-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
        }
        .upload-form {
            display: inline-block;
        }
        .upload-form input[type="file"] {
            display: none;
        }
        .upload-label {
            padding: 8px 16px;
            font-size: 0.9rem;
            background-color: #28a745;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            display: inline-block;
            margin: 0;
        }
        .upload-label:hover {
            background-color: #218838;
        }
        .progress-container {
            width: 300px;
            margin: 1rem 0;
            display: none;
        }
        .progress-bar {
            width: 100%;
            height: 25px;
            background-color: #f0f0f0;
            border-radius: 12px;
            overflow: hidden;
            border: 1px solid #ddd;
        }
        .progress-fill {
            height: 100%;
            background-color: #28a745;
            width: 0%;
            transition: width 0.3s ease;
            border-radius: 12px;
        }
        .progress-text {
            font-size: 0.8rem;
            text-align: center;
            line-height: 25px;
            color: white;
            font-weight: bold;
            text-shadow: 1px 1px 1px rgba(0,0,0,0.5);
        }
        .upload-status {
            font-size: 0.9rem;
            margin: 0.5rem 0;
            padding: 0.5rem;
            border-radius: 4px;
            display: none;
        }
        .upload-status.uploading {
            background-color: #ffc107;
            color: #212529;
        }
        .upload-status.success {
            background-color: #28a745;
            color: white;
        }
        .upload-status.error {
            background-color: #dc3545;
            color: white;
        }
        @media (max-width: 768px) {
            .outcomes-grid {
                grid-template-columns: 1fr;
            }
            .add-outcome-form {
                grid-template-columns: 1fr;
            }
            .zip-actions {
                flex-direction: column;
                align-items: stretch;
            }
            .progress-container {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">🥊 Fixture Manager</div>
        <div class="nav">
            <a href="{{ url_for('main.dashboard') }}">Dashboard</a>
            <a href="{{ url_for('main.fixtures') }}">Fixtures</a>
            <a href="{{ url_for('main.uploads') }}">Uploads</a>
            <a href="{{ url_for('main.statistics') }}">Statistics</a>
            {% if current_user.is_admin %}
                <a href="{{ url_for('main.admin_panel') }}">Admin</a>
            {% endif %}
            <a href="{{ url_for('auth.logout') }}">Logout</a>
        </div>
    </div>

    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'error' if category == 'error' else 'success' }}">{{ message }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <div class="content">
            {% if match %}
            <div class="actions-bar">
                <div>
                    <h1>Match #{{ match.match_number }}</h1>
                    <p style="margin: 0; color: #666;">{{ match.fighter1_township }} vs {{ match.fighter2_township }}</p>
                </div>
                <div>
                    <a href="{{ url_for('main.fixture_detail', fixture_id=match.fixture_id) }}" class="btn btn-secondary">← Back to Fixture</a>
                    <a href="{{ url_for('main.fixtures') }}" class="btn">View All Fixtures</a>
                </div>
            </div>

            <!-- Match Information -->
            <div class="match-info">
                <div class="info-item">
                    <div class="info-label">Match Number</div>
                    <div class="info-value">#{{ match.match_number }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Fighter 1</div>
                    <div class="info-value">{{ match.fighter1_township }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Fighter 2</div>
                    <div class="info-value">{{ match.fighter2_township }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Venue</div>
                    <div class="info-value">{{ match.venue_kampala_township }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Status</div>
                    <div class="info-value">
                        <span class="status-badge {{ 'status-active' if match.active_status else 'status-inactive' }}">
                            {{ 'Active' if match.active_status else 'Inactive' }}
                        </span>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label">Created</div>
                    <div class="info-value">{{ match.created_at.strftime('%Y-%m-%d %H:%M') if match.created_at else 'N/A' }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Fixture ID</div>
                    <div class="info-value" style="font-family: monospace; font-size: 0.9rem;">{{ match.fixture_id[:8] }}...</div>
                </div>
            </div>

            <!-- ZIP File Management Section -->
            <div class="section">
                <h2>ZIP File Management</h2>
                <div class="zip-section">
                    <div class="zip-actions" id="zip_actions_{{ match.id }}">
                        {% if match.zip_upload_status == 'completed' %}
                            <div style="display: flex; align-items: center; gap: 1rem;">
                                <span class="status-badge status-active">ZIP File Uploaded</span>
                                <span style="font-size: 0.9rem; color: #666;">{{ match.zip_filename or 'Unknown filename' }}</span>
                            </div>
                            <!-- Replace ZIP option -->
                            <form class="upload-form" id="upload_form_{{ match.id }}" method="POST" action="{{ url_for('upload.upload_zip') }}" enctype="multipart/form-data">
                                <input type="hidden" name="match_id" value="{{ match.id }}">
                                <input type="file" id="zip_file_{{ match.id }}" name="zip_file" accept=".zip" data-match-id="{{ match.id }}">
                                <label for="zip_file_{{ match.id }}" class="upload-label btn-warning" title="Replace existing ZIP file">Replace ZIP</label>
                            </form>
                            <!-- Delete ZIP option -->
                            <form class="upload-form" method="POST" action="{{ url_for('upload.delete_zip', match_id=match.id) }}" style="display: inline;">
                                <button type="submit" class="btn btn-danger" title="Delete ZIP file" onclick="return confirm('Are you sure you want to delete the ZIP file for Match #{{ match.match_number }}?')">Delete ZIP</button>
                            </form>
                        {% else %}
                            <div style="display: flex; align-items: center; gap: 1rem;">
                                <span class="status-badge status-inactive">No ZIP File</span>
                                {% if match.zip_upload_status == 'failed' %}
                                    <span style="font-size: 0.9rem; color: #dc3545;">Upload failed</span>
                                {% elif match.zip_upload_status == 'pending' %}
                                    <span style="font-size: 0.9rem; color: #ffc107;">Upload pending</span>
                                {% endif %}
                            </div>
                            <!-- Upload ZIP option -->
                            <form class="upload-form" id="upload_form_{{ match.id }}" method="POST" action="{{ url_for('upload.upload_zip') }}" enctype="multipart/form-data">
                                <input type="hidden" name="match_id" value="{{ match.id }}">
                                <input type="file" id="zip_file_{{ match.id }}" name="zip_file" accept=".zip" data-match-id="{{ match.id }}">
                                <label for="zip_file_{{ match.id }}" class="upload-label" title="Upload ZIP file for this match">Upload ZIP</label>
                            </form>
                        {% endif %}
                    </div>
                    
                    <!-- Progress bar (hidden by default) -->
                    <div class="progress-container" id="progress_{{ match.id }}">
                        <div class="progress-bar">
                            <div class="progress-fill" id="progress_fill_{{ match.id }}">
                                <div class="progress-text" id="progress_text_{{ match.id }}">0%</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Upload status (hidden by default) -->
                    <div class="upload-status" id="status_{{ match.id }}"></div>
                </div>
            </div>

            <!-- Outcomes Section -->
            <div class="section">
                <h2>Match Outcomes</h2>
                
                <!-- Alert Messages -->
                <div id="alert-container"></div>
                
                <!-- Loading Indicator -->
                <div id="loading" class="loading">
                    <div class="spinner"></div>
                    Updating outcomes...
                </div>
                
                {% if outcomes %}
                <div class="outcomes-grid" id="outcomes-grid">
                    {% for outcome in outcomes %}
                    <div class="outcome-card" data-outcome-id="{{ outcome.id }}">
                        <div class="outcome-header">
                            <div class="outcome-name">{{ outcome.column_name }}</div>
                            <div class="outcome-actions">
                                <button class="btn btn-danger btn-sm delete-outcome-btn" 
                                        data-outcome-id="{{ outcome.id }}" 
                                        data-column-name="{{ outcome.column_name }}">
                                    Delete
                                </button>
                            </div>
                        </div>
                        <input type="number" 
                               class="outcome-input" 
                               value="{{ outcome.float_value }}" 
                               data-column-name="{{ outcome.column_name }}"
                               data-original-value="{{ outcome.float_value }}"
                               step="0.01"
                               onchange="markOutcomeChanged(this)"
                               placeholder="Enter numeric value">
                    </div>
                    {% endfor %}
                </div>
                
                <div style="text-align: center; margin-top: 1.5rem;">
                    <button class="btn btn-success" onclick="saveAllChanges()" id="save-button" style="display: none;">
                        Save All Changes
                    </button>
                </div>
                {% else %}
                <div class="no-outcomes">
                    <div class="no-outcomes-icon">📊</div>
                    <h4>No Outcomes Available</h4>
                    <p>This match doesn't have any outcomes recorded yet. Add some outcomes below to get started.</p>
                </div>
                {% endif %}
                
                <!-- Add New Outcome -->
                <div class="add-outcome-section">
                    <h4 style="margin-top: 0; color: #333;">Add New Outcome</h4>
                    <div class="add-outcome-form">
                        <div class="form-group">
                            <label class="form-label">Outcome Name</label>
                            <input type="text" class="form-input" id="new-outcome-name" placeholder="e.g., Score, Rating, Points">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Value</label>
                            <input type="number" class="form-input" id="new-outcome-value" step="0.01" placeholder="0.00">
                        </div>
                        <button class="btn btn-success" onclick="addNewOutcome()">Add Outcome</button>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
    </div>

    <script>
        let changedOutcomes = new Set();
        let activeUploads = new Map();
        
        function markOutcomeChanged(input) {
            const originalValue = parseFloat(input.dataset.originalValue);
            const currentValue = parseFloat(input.value);
            const columnName = input.dataset.columnName;
            
            if (originalValue !== currentValue) {
                changedOutcomes.add(columnName);
                input.style.borderColor = '#ffc107';
                input.style.backgroundColor = '#fff3cd';
            } else {
                changedOutcomes.delete(columnName);
                input.style.borderColor = '#ced4da';
                input.style.backgroundColor = 'white';
            }
            
            // Show/hide save button
            const saveButton = document.getElementById('save-button');
            if (changedOutcomes.size > 0) {
                saveButton.style.display = 'inline-block';
            } else {
                saveButton.style.display = 'none';
            }
        }
        
        function saveAllChanges() {
            const outcomes = {};
            const inputs = document.querySelectorAll('.outcome-input');
            
            inputs.forEach(input => {
                const columnName = input.dataset.columnName;
                const value = input.value;
                if (changedOutcomes.has(columnName)) {
                    outcomes[columnName] = value;
                }
            });
            
            if (Object.keys(outcomes).length === 0) {
                showAlert('No changes to save.', 'info');
                return;
            }
            
            showLoading(true);
            
            fetch(`/match/{{ match.id }}/outcomes`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ outcomes: outcomes })
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                if (data.error) {
                    showAlert(data.error, 'danger');
                } else {
                    showAlert(data.message, 'success');
                    // Update original values and clear changes
                    inputs.forEach(input => {
                        const columnName = input.dataset.columnName;
                        if (changedOutcomes.has(columnName)) {
                            input.dataset.originalValue = input.value;
                            input.style.borderColor = '#ced4da';
                            input.style.backgroundColor = 'white';
                        }
                    });
                    changedOutcomes.clear();
                    document.getElementById('save-button').style.display = 'none';
                }
            })
            .catch(error => {
                showLoading(false);
                showAlert('Failed to save changes: ' + error.message, 'danger');
            });
        }
        
        function deleteOutcome(outcomeId, columnName) {
            if (!confirm(`Are you sure you want to delete the outcome "${columnName}"?`)) {
                return;
            }
            
            showLoading(true);
            
            fetch(`/match/{{ match.id }}/outcomes/${outcomeId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                if (data.error) {
                    showAlert(data.error, 'danger');
                } else {
                    showAlert(data.message, 'success');
                    // Remove the outcome card from the DOM
                    const outcomeCard = document.querySelector(`[data-outcome-id="${outcomeId}"]`);
                    if (outcomeCard) {
                        outcomeCard.remove();
                    }
                    
                    // Check if no outcomes left
                    const remainingOutcomes = document.querySelectorAll('.outcome-card');
                    if (remainingOutcomes.length === 0) {
                        location.reload(); // Reload to show "no outcomes" message
                    }
                }
            })
            .catch(error => {
                showLoading(false);
                showAlert('Failed to delete outcome: ' + error.message, 'danger');
            });
        }
        
        function addNewOutcome() {
            const nameInput = document.getElementById('new-outcome-name');
            const valueInput = document.getElementById('new-outcome-value');
            
            const name = nameInput.value.trim();
            const value = valueInput.value.trim();
            
            if (!name || !value) {
                showAlert('Please enter both outcome name and value.', 'danger');
                return;
            }
            
            if (isNaN(parseFloat(value))) {
                showAlert('Please enter a valid numeric value.', 'danger');
                return;
            }
            
            const outcomes = {};
            outcomes[name] = value;
            
            showLoading(true);
            
            fetch(`/match/{{ match.id }}/outcomes`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ outcomes: outcomes })
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                if (data.error) {
                    showAlert(data.error, 'danger');
                } else {
                    showAlert(data.message, 'success');
                    // Clear the form
                    nameInput.value = '';
                    valueInput.value = '';
                    // Reload the page to show the new outcome
                    setTimeout(() => location.reload(), 1000);
                }
            })
            .catch(error => {
                showLoading(false);
                showAlert('Failed to add outcome: ' + error.message, 'danger');
            });
        }
        
        function showAlert(message, type) {
            const alertContainer = document.getElementById('alert-container');
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type}`;
            alertDiv.textContent = message;
            
            alertContainer.innerHTML = '';
            alertContainer.appendChild(alertDiv);
            
            // Auto-hide success messages
            if (type === 'success') {
                setTimeout(() => {
                    alertDiv.remove();
                }, 3000);
            }
        }
        
        function showLoading(show) {
            const loading = document.getElementById('loading');
            loading.style.display = show ? 'block' : 'none';
        }

        // ZIP Upload Functions
        function startUpload(matchId) {
            const fileInput = document.getElementById(`zip_file_${matchId}`);
            const file = fileInput.files[0];
            
            if (!file) {
                return;
            }

            // Show progress bar and hide upload form
            const uploadForm = document.getElementById(`upload_form_${matchId}`);
            const progressContainer = document.getElementById(`progress_${matchId}`);
            const statusDiv = document.getElementById(`status_${matchId}`);
            
            uploadForm.style.display = 'none';
            progressContainer.style.display = 'block';
            statusDiv.style.display = 'block';
            statusDiv.className = 'upload-status uploading';
            statusDiv.textContent = 'Uploading...';

            // Create FormData
            const formData = new FormData();
            formData.append('zip_file', file);
            formData.append('match_id', matchId);

            // Create XMLHttpRequest for progress tracking
            const xhr = new XMLHttpRequest();
            activeUploads.set(matchId, xhr);

            // Progress event handler
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    updateProgress(matchId, percentComplete);
                }
            });

            // Load event handler (upload complete)
            xhr.addEventListener('load', function() {
                if (xhr.status === 200) {
                    // Success
                    updateProgress(matchId, 100);
                    statusDiv.className = 'upload-status success';
                    statusDiv.textContent = 'Upload successful!';
                    
                    // Reload page after a short delay to show updated status
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    // Error
                    handleUploadError(matchId, 'Upload failed');
                }
                activeUploads.delete(matchId);
            });

            // Error event handler
            xhr.addEventListener('error', function() {
                handleUploadError(matchId, 'Network error');
                activeUploads.delete(matchId);
            });

            // Abort event handler
            xhr.addEventListener('abort', function() {
                handleUploadError(matchId, 'Upload cancelled');
                activeUploads.delete(matchId);
            });

            // Start upload
            xhr.open('POST', '{{ url_for("upload.upload_zip") }}', true);
            xhr.send(formData);
        }

        function updateProgress(matchId, percent) {
            const progressFill = document.getElementById(`progress_fill_${matchId}`);
            const progressText = document.getElementById(`progress_text_${matchId}`);
            
            progressFill.style.width = percent + '%';
            progressText.textContent = percent + '%';
            
            // Change color based on progress
            if (percent < 50) {
                progressFill.style.backgroundColor = '#ffc107'; // Yellow
            } else if (percent < 100) {
                progressFill.style.backgroundColor = '#17a2b8'; // Blue
            } else {
                progressFill.style.backgroundColor = '#28a745'; // Green
            }
        }

        function handleUploadError(matchId, errorMessage) {
            const uploadForm = document.getElementById(`upload_form_${matchId}`);
            const progressContainer = document.getElementById(`progress_${matchId}`);
            const statusDiv = document.getElementById(`status_${matchId}`);
            
            // Show error status
            statusDiv.className = 'upload-status error';
            statusDiv.textContent = errorMessage;
            
            // Hide progress bar and show upload form again after delay
            setTimeout(() => {
                progressContainer.style.display = 'none';
                statusDiv.style.display = 'none';
                uploadForm.style.display = 'inline-block';
                
                // Reset file input
                const fileInput = document.getElementById(`zip_file_${matchId}`);
                fileInput.value = '';
            }, 3000);
        }

        // Event listeners
        document.addEventListener('DOMContentLoaded', function() {
            // Delete outcome buttons
            document.querySelectorAll('.delete-outcome-btn').forEach(button => {
                button.addEventListener('click', function() {
                    const outcomeId = this.dataset.outcomeId;
                    const columnName = this.dataset.columnName;
                    deleteOutcome(outcomeId, columnName);
                });
            });

            // File input change handlers
            document.querySelectorAll('input[type="file"][data-match-id]').forEach(input => {
                input.addEventListener('change', function() {
                    const matchId = this.dataset.matchId;
                    startUpload(matchId);
                });
            });

            // Prevent form submission on file change (we handle it with AJAX)
            const uploadForms = document.querySelectorAll('.upload-form');
            uploadForms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    return false;
                });
            });
        });

        // Handle Enter key in add outcome form
        document.getElementById('new-outcome-name').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('new-outcome-value').focus();
            }
        });
        
        document.getElementById('new-outcome-value').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                addNewOutcome();
            }
        });
    </script>
</body>
</html>