
let allFixtures = [];

// Load fixtures on page load
document.addEventListener('DOMContentLoaded', function() {
    loadFixtures();
    
    // Event listeners
    document.getElementById('refresh-btn').addEventListener('click', loadFixtures);
    document.getElementById('status-filter').addEventListener('change', filterFixtures);
    document.getElementById('upload-filter').addEventListener('change', filterFixtures);
    document.getElementById('search-input').addEventListener('input', filterFixtures);
    
    // Reset fixtures button (admin only)
    const resetBtn = document.getElementById('reset-fixtures-btn');
    if (resetBtn) {
        resetBtn.addEventListener('click', resetFixtures);
    }
});

function loadFixtures() {
    const loading = document.getElementById('loading');
    const refreshBtn = document.getElementById('refresh-btn');
    
    loading.style.display = 'block';
    refreshBtn.disabled = true;
    
    fetch('/api/fixtures')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                allFixtures = data.fixtures;
                updateSummaryCards();
                filterFixtures(); // This will also render the table
            } else {
                alert('Error loading fixtures: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to load fixtures: ' + error.message);
        })
        .finally(() => {
            loading.style.display = 'none';
            refreshBtn.disabled = false;
        });
}

function updateSummaryCards() {
    const totalCount = allFixtures.length;
    const pendingCount = allFixtures.filter(f => f.fixture_status === 'pending').length;
    const runningCount = allFixtures.filter(f => f.fixture_status === 'running').length;
    const scheduledCount = allFixtures.filter(f => f.fixture_status === 'scheduled').length;
    const betCount = allFixtures.filter(f => f.fixture_status === 'bet').length;
    const ingameCount = allFixtures.filter(f => f.fixture_status === 'ingame').length;
    const endCount = allFixtures.filter(f => f.fixture_status === 'end').length;

    document.getElementById('total-count').textContent = totalCount;
    document.getElementById('pending-count').textContent = pendingCount;
    document.getElementById('running-count').textContent = runningCount;

    // Update the summary cards to show more status types
    const summaryCards = document.getElementById('summary-cards');
    const betInGameCount = betCount + ingameCount;
    summaryCards.innerHTML = `
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-primary">
                        <i class="fas fa-list me-2"></i>Total Fixtures
                    </h5>
                    <h3 id="total-count" class="text-primary">` + totalCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-warning">
                        <i class="fas fa-clock me-2"></i>Pending
                    </h5>
                    <h3 id="pending-count" class="text-warning">` + pendingCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-info">
                        <i class="fas fa-play me-2"></i>Running
                    </h5>
                    <h3 id="running-count" class="text-info">` + runningCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-secondary">
                        <i class="fas fa-calendar me-2"></i>Scheduled
                    </h5>
                    <h3 class="text-secondary">` + scheduledCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-success">
                        <i class="fas fa-gamepad me-2"></i>Bet/In Game
                    </h5>
                    <h3 class="text-success">` + betInGameCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-dark">
                        <i class="fas fa-stop me-2"></i>End
                    </h5>
                    <h3 class="text-dark">` + endCount + `</h3>
                </div>
            </div>
        </div>
    `;
}

function filterFixtures() {
    const statusFilter = document.getElementById('status-filter').value;
    const uploadFilter = document.getElementById('upload-filter').value;
    const searchTerm = document.getElementById('search-input').value.toLowerCase();

    let filteredFixtures = allFixtures.filter(fixture => {
        // Status filter
        if (statusFilter && fixture.fixture_status !== statusFilter) {
            return false;
        }

        // Upload filter - check the first match's upload status
        if (uploadFilter && fixture.matches && fixture.matches.length > 0) {
            if (fixture.matches[0].zip_upload_status !== uploadFilter) {
                return false;
            }
        }

        // Search filter
        if (searchTerm) {
            const searchText = (fixture.fighter1_township + ' ' + fixture.fighter2_township + ' ' + fixture.venue_kampala_township).toLowerCase();
            if (!searchText.includes(searchTerm)) return false;
        }

        return true;
    });

    renderFixturesTable(filteredFixtures);
    document.getElementById('filtered-count').textContent = filteredFixtures.length + ' fixtures';

    // Show/hide empty state
    const emptyState = document.getElementById('empty-state');
    const fixturesTable = document.querySelector('.card .table-responsive').parentElement;

    if (filteredFixtures.length === 0 && allFixtures.length === 0) {
        emptyState.style.display = 'block';
        fixturesTable.style.display = 'none';
    } else {
        emptyState.style.display = 'none';
        fixturesTable.style.display = 'block';
    }
}

function renderFixturesTable(fixtures) {
    const tbody = document.getElementById('fixtures-tbody');
    tbody.innerHTML = '';

    fixtures.forEach(fixture => {
        const row = document.createElement('tr');
        const startTimeInfo = fixture.start_time ? '<br><small class="text-info">Start: ' + new Date(fixture.start_time).toLocaleString() + '</small>' : '';
        row.innerHTML = `
            <td>
                <strong>#` + fixture.match_number + `</strong>
                <br>
                <small class="text-muted">` + fixture.match_count + ` matches</small>
            </td>
            <td>
                <div class="fw-bold">` + fixture.fighter1_township + `</div>
                <small class="text-muted">vs</small>
                <div class="fw-bold">` + fixture.fighter2_township + `</div>
            </td>
            <td>` + fixture.venue_kampala_township + `</td>
            <td>` + getFixtureStatusBadge(fixture) + `</td>
            <td>` + getUploadStatusBadge(fixture) + `</td>
            <td>
                <small class="text-muted">
                    ` + new Date(fixture.created_at).toLocaleString() + `
                </small>
                ` + startTimeInfo + `
            </td>
            <td>
                <a href="/fixtures/` + fixture.id + `" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-eye me-1"></i>Details
                </a>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function getFixtureStatusBadge(fixture) {
    const status = fixture.fixture_status;

    switch (status) {
        case 'pending':
            return '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
        case 'running':
            return '<span class="badge bg-info"><i class="fas fa-play me-1"></i>Running</span>';
        case 'scheduled':
            return '<span class="badge bg-secondary"><i class="fas fa-calendar me-1"></i>Scheduled</span>';
        case 'bet':
            return '<span class="badge bg-primary"><i class="fas fa-money-bill me-1"></i>Bet</span>';
        case 'ingame':
            return '<span class="badge bg-success"><i class="fas fa-gamepad me-1"></i>In Game</span>';
        case 'end':
            return '<span class="badge bg-dark"><i class="fas fa-stop me-1"></i>End</span>';
        default:
            return '<span class="badge bg-secondary"><i class="fas fa-question me-1"></i>Unknown</span>';
    }
}

function getUploadStatusBadge(fixture) {
    // Get upload status from the first match in the fixture
    if (!fixture.matches || fixture.matches.length === 0) {
        return '<span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Pending</span>';
    }

    const firstMatch = fixture.matches[0];
    const status = firstMatch.zip_upload_status || 'pending';
    const progress = firstMatch.zip_upload_progress || 0;

    switch (status) {
        case 'completed':
            return '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Completed</span>';
        case 'uploading':
            return `<span class="badge bg-info"><i class="fas fa-spinner fa-spin me-1"></i>Uploading (${progress.toFixed(1)}%)</span>`;
        case 'failed':
            return '<span class="badge bg-danger"><i class="fas fa-times me-1"></i>Failed</span>';
        default:
            return '<span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Pending</span>';
    }
}

function resetFixtures() {
    const confirmMessage = 'WARNING: This will permanently delete ALL fixture data including:\n\n' +
                          '• All synchronized matches and outcomes\n' +
                          '• All downloaded ZIP files\n' +
                          '• This action cannot be undone!\n\n' +
                          'Are you sure you want to reset all fixtures data?';
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    const resetBtn = document.getElementById('reset-fixtures-btn');
    const originalText = resetBtn.innerHTML;
    
    resetBtn.disabled = true;
    resetBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Resetting...';
    
    fetch('/api/fixtures/reset', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`Fixtures reset successfully!\n\nRemoved:\n• ${data.removed.matches} matches\n• ${data.removed.outcomes} outcomes\n• ${data.removed.zip_files} ZIP files`);
            // Reload fixtures to show empty state
            loadFixtures();
        } else {
            alert('Error resetting fixtures: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to reset fixtures: ' + error.message);
    })
    .finally(() => {
        resetBtn.disabled = false;
        resetBtn.innerHTML = originalText;
    });
}
