{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="mb-0">
                    <i class="fas fa-cash-register me-2"></i>Cashier Dashboard
                </h1>
                <small class="text-muted">Welcome, {{ current_user.username }}</small>
            </div>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#printModal">
                    <i class="fas fa-print me-1"></i>Print Matches
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Print Modal -->
<div class="modal fade" id="printModal" tabindex="-1" aria-labelledby="printModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="printModalLabel"><i class="fas fa-print me-2"></i>Print Pending Matches</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Print Options</label>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="printOption" id="printAll" value="all" checked>
                        <label class="form-check-label" for="printAll">
                            Print all pending matches
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="printOption" id="printLastN" value="lastN">
                        <label class="form-check-label" for="printLastN">
                            Print last N matches
                        </label>
                    </div>
                </div>
                <div class="mb-3" id="lastNInput" style="display: none;">
                    <label for="numberOfMatches" class="form-label">Number of matches to print (from the end)</label>
                    <input type="number" class="form-control" id="numberOfMatches" min="1" value="10">
                    <div class="form-text">Enter the number of most recent matches to include in the printout.</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="printPendingMatches()">
                    <i class="fas fa-print me-1"></i>Print
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions for Cashier -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-bolt me-2"></i>Cashier Controls
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <button class="btn btn-primary w-100 fw-bold" id="btn-start-games">
                            <i class="fas fa-gamepad me-2"></i>Start Games
                        </button>
                    </div>
                    <div class="col-md-6 mb-3">
                        <button class="btn btn-success w-100 fw-bold" id="btn-bets">
                            <i class="fas fa-coins me-2"></i>Bets
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Matches from Fixture - Left Side -->
    <div class="col-lg-9 col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-list me-2"></i>Today's Fixture Matches
                        <span class="badge bg-primary ms-2" id="total-matches-count">0</span>
                    </h5>
                    <div class="d-flex gap-2 align-items-center">
                        <label class="form-label mb-0 me-1 small">Date:</label>
                        <input type="date" class="form-control form-control-sm" id="fixture-date-filter" style="width: 150px;">
                    </div>
                </div>
            </div>
            <div class="card-body">
                <!-- Summary Row -->
                <div class="row mb-3">
                    <div class="col-md-2 col-4 text-center">
                        <div class="badge bg-secondary p-2 w-100">
                            <div id="summary-total">0</div>
                            <small>Total</small>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="badge bg-warning p-2 w-100">
                            <div id="summary-pending">0</div>
                            <small>Pending</small>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="badge bg-success p-2 w-100">
                            <div id="summary-bet">0</div>
                            <small>Bet</small>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="badge bg-info p-2 w-100">
                            <div id="summary-ingame">0</div>
                            <small>In Game</small>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="badge bg-dark p-2 w-100">
                            <div id="summary-done">0</div>
                            <small>Done</small>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="badge bg-danger p-2 w-100">
                            <div id="summary-other">0</div>
                            <small>Other</small>
                        </div>
                    </div>
                </div>
                <div id="matches-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading matches...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column -->
    <div class="col-lg-3 col-md-4">
        <!-- Current Display Status - Smaller and Compact -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-desktop me-2"></i>Display Status
                </h6>
            </div>
            <div class="card-body p-3">
                <div class="d-flex flex-column">
                    <!-- Video Status -->
                    <div class="text-center mb-3">
                        <div class="d-flex flex-column align-items-center">
                            <i class="fas fa-video text-primary mb-1" style="font-size: 1.5rem;"></i>
                            <small class="text-primary fw-bold" id="video-status-text">Stopped</small>
                            <small class="text-muted">Video Status</small>
                        </div>
                    </div>

                    <!-- Overlay Status -->
                    <div class="text-center">
                        <div class="d-flex flex-column align-items-center">
                            <i class="fas fa-layer-group text-success mb-1" style="font-size: 1.5rem;"></i>
                            <small class="text-success fw-bold" id="overlay-status-text">Ready</small>
                            <small class="text-muted">Overlay Status</small>
                        </div>
                    </div>
                </div>

                <div class="small">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Video:</span>
                        <small id="current-video-path" class="text-truncate" style="max-width: 120px;">No video loaded</small>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">Template:</span>
                        <small id="current-template-name">default</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Session Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-user me-2"></i>Session Info
                </h6>
            </div>
            <div class="card-body p-3">
                <dl class="mb-0 small">
                    <dt class="text-muted">User</dt>
                    <dd>{{ current_user.username }}</dd>

                    <dt class="text-muted">Role</dt>
                    <dd>
                        <span class="badge bg-info">Cashier</span>
                    </dd>

                    <dt class="text-muted">Login Time</dt>
                    <dd id="login-time">{{ current_user.last_login.strftime('%H:%M') if current_user.last_login else 'Just now' }}</dd>

                    <dt class="text-muted">System Status</dt>
                    <dd>
                        <span class="badge bg-success" id="system-status">Online</span>
                    </dd>
                </dl>
            </div>
        </div>

        <!-- Today's Activity -->
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-chart-bar me-2"></i>Today's Activity
                </h6>
            </div>
            <div class="card-body p-3 text-center">
                <div class="row">
                    <div class="col-6">
                        <h5 class="text-primary mb-1" id="videos-played">0</h5>
                        <small class="text-muted">Videos</small>
                    </div>
                    <div class="col-6">
                        <h5 class="text-success mb-1" id="overlays-updated">0</h5>
                        <small class="text-muted">Overlays</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Overlay Update Modal -->
<div class="modal fade" id="updateOverlayModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Display Overlay</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="update-overlay-form">
                    <div class="mb-3">
                        <label class="form-label">Display Template</label>
                        <select class="form-select" id="overlay-template">
                            <option value="">Loading templates...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Main Message</label>
                        <input type="text" class="form-control" id="overlay-headline"
                               placeholder="Special Offer">
                        <div class="form-text">The main headline or title to display</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Additional Information</label>
                        <textarea class="form-control" id="overlay-text" rows="3"
                                  placeholder="20% off all items today only!"></textarea>
                        <div class="form-text">Additional text or details to show</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="confirm-update-overlay">
                    <i class="fas fa-edit me-1"></i>Update Display
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Send Custom Message Modal -->
<div class="modal fade" id="sendMessageModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Send Custom Message</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="send-message-form">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label class="form-label">Message Title</label>
                                <input type="text" class="form-control" id="message-title"
                                       placeholder="Important Announcement" maxlength="100" required>
                                <div class="form-text">Enter the main title for your message</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">Message Icon</label>
                                <input type="text" class="form-control" id="message-icon"
                                       placeholder="📢" maxlength="5">
                                <div class="form-text">Emoji or short text</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Message Content</label>
                        <textarea class="form-control" id="message-content" rows="3"
                                  placeholder="Enter your custom message here..." maxlength="500" required></textarea>
                        <div class="form-text">Enter the detailed message content</div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Template</label>
                                <select class="form-select" id="message-template" required>
                                    <option value="text" selected>Text Message</option>
                                    <option value="">Loading other templates...</option>
                                </select>
                                <div class="form-text">Choose which overlay template to use</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Display Time</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="message-display-time"
                                           placeholder="10" min="1" max="300" step="1" value="10" required>
                                    <span class="input-group-text">seconds</span>
                                </div>
                                <div class="form-text">How long to show the message (1-300 seconds)</div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" id="confirm-send-message">
                    <i class="fas fa-paper-plane me-1"></i>Send Message
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load available templates on page load
    loadAvailableTemplates();

    // Load fixture matches for cashier dashboard
    loadPendingMatches();

    // Set up date filter with today's date as default
    const dateFilter = document.getElementById('fixture-date-filter');
    if (dateFilter) {
        // Set default to today
        const today = new Date().toISOString().split('T')[0];
        dateFilter.value = today;
        
        // Listen for date changes
        dateFilter.addEventListener('change', function() {
            const selectedDateValue = this.value;
            const today = new Date().toISOString().split('T')[0];
            
            if (selectedDateValue === today) {
                selectedDate = null; // null means today (default behavior)
            } else {
                selectedDate = selectedDateValue;
            }
            
            // Force reload with new date
            isInitialMatchLoad = true;
            cachedMatchesData = null;
            loadPendingMatches();
        });
    }

    // Quick action buttons
    document.getElementById('btn-start-games').addEventListener('click', function() {
        // Show confirmation dialog for starting games
        if (confirm('Are you sure you want to start the games? This will activate all pending matches.')) {
            fetch('/api/cashier/start-games', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'start_games'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Refresh the pending matches list
                    loadPendingMatches();
                    // Show success message
                    showNotification('Games started successfully!', 'success');
                } else {
                    showNotification('Failed to start games: ' + (data.error || 'Unknown error'), 'error');
                }
            })
            .catch(error => {
                showNotification('Error starting games: ' + error.message, 'error');
            });
        }
    });

    document.getElementById('btn-bets').addEventListener('click', function() {
        window.location.href = pageUrl('/cashier/bets');
    });

    document.getElementById('btn-send-message').addEventListener('click', function() {
        new bootstrap.Modal(document.getElementById('sendMessageModal')).show();
    });
    
    document.getElementById('btn-update-overlay').addEventListener('click', function() {
        new bootstrap.Modal(document.getElementById('updateOverlayModal')).show();
    });

    // Confirm actions
    document.getElementById('confirm-update-overlay').addEventListener('click', function() {
        const template = document.getElementById('overlay-template').value;
        const headline = document.getElementById('overlay-headline').value;
        const text = document.getElementById('overlay-text').value;

        fetch('/api/overlay', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                template: template,
                data: {
                    headline: headline,
                    ticker_text: text,
                    title: headline,
                    text: text
                }
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('updateOverlayModal')).hide();
                updateCurrentTemplate(template || 'default');
                // Increment counter
                const overlaysCount = parseInt(document.getElementById('overlays-updated').textContent) + 1;
                document.getElementById('overlays-updated').textContent = overlaysCount;

                // Show success message
                showNotification('Overlay updated successfully!', 'success');
            } else {
                alert('Failed to update overlay: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error: ' + error.message);
        });
    });
    
    document.getElementById('confirm-send-message').addEventListener('click', function() {
        const title = document.getElementById('message-title').value;
        const content = document.getElementById('message-content').value;
        const icon = document.getElementById('message-icon').value || '📢';
        const template = document.getElementById('message-template').value || 'text';
        const displayTime = parseInt(document.getElementById('message-display-time').value) || 10;
        
        if (!title.trim()) {
            alert('Please enter a message title');
            return;
        }
        
        if (!content.trim()) {
            alert('Please enter message content');
            return;
        }
        
        if (displayTime < 1 || displayTime > 300) {
            alert('Display time must be between 1 and 300 seconds');
            return;
        }
        
        fetch('/api/send-custom-message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                title: title.trim(),
                message: content.trim(),
                icon: icon.trim(),
                template: template,
                display_time: displayTime
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('sendMessageModal')).hide();
                // Clear the form
                document.getElementById('send-message-form').reset();
                // Reset template to text and display time to 10
                document.getElementById('message-template').value = 'text';
                document.getElementById('message-display-time').value = '10';
                showNotification('Custom message sent successfully with ' + displayTime + ' second display time!', 'success');
            } else {
                alert('Failed to send message: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error sending message: ' + error.message);
        });
    });

    // Status update functions
    function updateVideoStatus() {
        fetch('/api/video/status')
        .then(response => response.json())
        .then(data => {
            const status = data.player_status || 'stopped';
            document.getElementById('video-status-text').textContent =
                status.charAt(0).toUpperCase() + status.slice(1);
        })
        .catch(error => {
            document.getElementById('video-status-text').textContent = 'Unknown';
        });
    }

    function updateCurrentVideoPath(path) {
        const fileName = path.split('/').pop() || path;
        document.getElementById('current-video-path').textContent = fileName;
    }

    function updateCurrentTemplate(template) {
        document.getElementById('current-template-name').textContent = template;
    }

    function showNotification(message, type = 'info') {
        // Simple notification system - could be enhanced with toast notifications
        const alertClass = type === 'success' ? 'alert-success' : 'alert-info';
        const notification = document.createElement('div');
        notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
        notification.style.top = '20px';
        notification.style.right = '20px';
        notification.style.zIndex = '9999';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(notification);

        // Auto-remove after 3 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }

    // Initial status update
    updateVideoStatus();

    // Periodic status updates
    setInterval(updateVideoStatus, 5000);  // Every 5 seconds
    setInterval(loadPendingMatches, 5000); // Auto-refresh matches every 5 seconds
});

let cachedMatchesData = null;
let isInitialMatchLoad = true;
let selectedDate = null; // null means today

// Function to load and display fixture matches
function loadPendingMatches() {
    console.log('🔍 loadFixtureMatches() called');

    const container = document.getElementById('matches-container');
    const countBadge = document.getElementById('total-matches-count');

    if (!container) {
        console.error('❌ matches-container not found');
        return;
    }

    console.log('📡 Making API request to /api/cashier/pending-matches');

    // Only show loading state on initial load
    if (isInitialMatchLoad) {
        container.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-spinner fa-spin me-2"></i>Loading matches...
            </div>
        `;
    }

    // Build URL with optional date filter
    let url = '/api/cashier/pending-matches';
    if (selectedDate) {
        url += '?date=' + selectedDate;
    }

    fetch(url)
        .then(response => {
            console.log('📡 API response status:', response.status);
            if (!response.ok) {
                throw new Error('API request failed: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('📦 API response data:', data);

            if (data.success) {
                // Check if data has actually changed
                const currentDataString = JSON.stringify(data);
                if (cachedMatchesData === currentDataString && !isInitialMatchLoad) {
                    console.log('📦 No changes in match data, skipping update');
                    return;
                }
                cachedMatchesData = currentDataString;

                // Update count badge
                countBadge.textContent = data.total;

                // Update summary counts
                updateSummaryCounts(data.matches);

                updateMatchesTable(data, container);
            } else {
                if (isInitialMatchLoad) {
                    container.innerHTML = `
                        <div class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${data.error || 'Unknown error'}
                        </div>
                    `;
                }
            }
        })
        .catch(error => {
            console.error('❌ Error loading matches:', error);
            if (isInitialMatchLoad) {
                container.innerHTML = `
                    <div class="text-center text-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${error.message}
                    </div>
                `;
            }
        })
        .finally(() => {
            isInitialMatchLoad = false;
        });
}

function updateSummaryCounts(matches) {
    const counts = {
        total: matches.length,
        pending: 0,
        bet: 0,
        ingame: 0,
        done: 0,
        other: 0
    };

    matches.forEach(match => {
        const status = match.status || 'pending';
        if (status === 'pending' || status === 'scheduled') {
            counts.pending++;
        } else if (status === 'bet') {
            counts.bet++;
        } else if (status === 'ingame') {
            counts.ingame++;
        } else if (status === 'done') {
            counts.done++;
        } else {
            counts.other++;
        }
    });

    document.getElementById('summary-total').textContent = counts.total;
    document.getElementById('summary-pending').textContent = counts.pending;
    document.getElementById('summary-bet').textContent = counts.bet;
    document.getElementById('summary-ingame').textContent = counts.ingame;
    document.getElementById('summary-done').textContent = counts.done;
    document.getElementById('summary-other').textContent = counts.other;
}

function updateMatchesTable(data, container) {
    if (data.total === 0) {
        container.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-check-circle me-2"></i>No matches found for this fixture
            </div>
        `;
        return;
    }

    // Check if table already exists
    let tbody = container.querySelector('tbody');
    
    if (!tbody) {
        // Create new table with additional columns
        container.innerHTML = `
            <div class="table-responsive">
                <table class="table table-striped table-hover table-sm">
                    <thead class="table-dark">
                        <tr>
                            <th style="width: 40px;"><i class="fas fa-hashtag me-1"></i>#</th>
                            <th><i class="fas fa-user-friends me-1"></i>Fighter 1</th>
                            <th><i class="fas fa-user-friends me-1"></i>Fighter 2</th>
                            <th><i class="fas fa-map-marker-alt me-1"></i>Venue</th>
                            <th style="width: 60px;"><i class="fas fa-info-circle me-1"></i>Status</th>
                            <th style="width: 60px;"><i class="fas fa-trophy me-1"></i>Result</th>
                            <th style="width: 100px;"><i class="fas fa-star me-1"></i>Win Outcomes</th>
                            <th style="width: 55px;"><i class="fas fa-chart-line me-1"></i>U/O</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        `;
        tbody = container.querySelector('tbody');
    }

    // Update table rows intelligently
    const existingRows = Array.from(tbody.children);
    const existingMatches = new Map();
    existingRows.forEach(row => {
        const matchId = row.getAttribute('data-match-id');
        if (matchId) {
            existingMatches.set(matchId, row);
        }
    });

    const processedMatches = new Set();

    data.matches.forEach(match => {
        const matchId = match.id.toString();
        processedMatches.add(matchId);
        
        const startTime = match.start_time ?
            new Date(match.start_time).toLocaleTimeString() : 'N/A';

        const status = match.status || 'pending';
        let statusBadge = '';

        switch (status) {
            case 'scheduled':
                statusBadge = '<span class="badge bg-primary"><i class="fas fa-calendar-check me-1"></i>Sched</span>';
                break;
            case 'bet':
                statusBadge = `<a href="${pageUrl('/bets/new')}" class="badge bg-success text-decoration-none" title="Click to place bet"><i class="fas fa-dollar-sign me-1"></i>Bet</a>`;
                break;
            case 'ingame':
                statusBadge = '<span class="badge bg-info"><i class="fas fa-play me-1"></i>Live</span>';
                break;
            case 'done':
                statusBadge = '<span class="badge bg-dark"><i class="fas fa-check me-1"></i>Done</span>';
                break;
            case 'cancelled':
                statusBadge = '<span class="badge bg-secondary"><i class="fas fa-times me-1"></i>Canc</span>';
                break;
            case 'failed':
                statusBadge = '<span class="badge bg-danger"><i class="fas fa-exclamation-triangle me-1"></i>Fail</span>';
                break;
            case 'paused':
                statusBadge = '<span class="badge bg-warning"><i class="fas fa-pause me-1"></i>Pause</span>';
                break;
            default:
                statusBadge = '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pend</span>';
        }

        // Result display - show actual match result (WIN1, WIN2, DRAW, RET1, RET2, etc.)
        let resultDisplay = '-';
        if (match.result) {
            resultDisplay = `<span class="badge bg-success">${match.result}</span>`;
        }

        // Winning outcomes display - show all winning outcomes from extraction
        let winningOutcomesDisplay = '-';
        if (match.winning_outcomes) {
            try {
                const wo = typeof match.winning_outcomes === 'string' ? JSON.parse(match.winning_outcomes) : match.winning_outcomes;
                if (Array.isArray(wo) && wo.length > 0) {
                    winningOutcomesDisplay = wo.map(o => `<span class="badge bg-primary me-1" style="font-size: 10px;">${o}</span>`).join('');
                }
            } catch (e) {
                winningOutcomesDisplay = `<span class="badge bg-secondary">${match.winning_outcomes}</span>`;
            }
        }

        // Under/Over display
        let underOverDisplay = '-';
        if (match.under_over_result) {
            const uoClass = match.under_over_result === 'UNDER' ? 'bg-info' : 'bg-warning';
            underOverDisplay = `<span class="badge ${uoClass}">${match.under_over_result}</span>`;
        }

        // Row class based on status
        let rowClass = '';
        if (status === 'done') {
            rowClass = 'table-success';
        } else if (status === 'failed' || status === 'cancelled') {
            rowClass = 'table-danger';
        } else if (status === 'ingame') {
            rowClass = 'table-info';
        } else if (status === 'bet') {
            rowClass = 'table-warning';
        }

        const newRowHTML = `
            <td><strong>#${match.match_number}</strong></td>
            <td><strong>${match.fighter1_township}</strong></td>
            <td><strong>${match.fighter2_township}</strong></td>
            <td>${match.venue_kampala_township}</td>
            <td>${statusBadge}</td>
            <td>${resultDisplay}</td>
            <td style="font-size: 10px;">${winningOutcomesDisplay}</td>
            <td>${underOverDisplay}</td>
        `;

        const existingRow = existingMatches.get(matchId);
        if (existingRow) {
            // Update existing row only if content changed
            if (existingRow.innerHTML !== newRowHTML) {
                existingRow.innerHTML = newRowHTML;
                existingRow.className = rowClass;
                existingRow.style.backgroundColor = '#fff3cd'; // Highlight briefly
                setTimeout(() => {
                    existingRow.style.backgroundColor = '';
                }, 1000);
            }
        } else {
            // Add new row
            const row = document.createElement('tr');
            row.setAttribute('data-match-id', matchId);
            row.className = rowClass;
            row.innerHTML = newRowHTML;
            row.style.backgroundColor = '#d4edda'; // Highlight new row
            tbody.appendChild(row);
            setTimeout(() => {
                row.style.backgroundColor = '';
            }, 1000);
        }
    });

    // Remove rows no longer in data
    existingMatches.forEach((row, matchId) => {
        if (!processedMatches.has(matchId)) {
            row.style.backgroundColor = '#f8d7da'; // Highlight removed row
            setTimeout(() => {
                if (row.parentNode) {
                    row.parentNode.removeChild(row);
                }
            }, 500);
        }
    });
}

function loadAvailableTemplates() {
    fetch('/api/templates')
        .then(response => response.json())
        .then(data => {
            const overlayTemplateSelect = document.getElementById('overlay-template');
            const messageTemplateSelect = document.getElementById('message-template');

            // Clear loading options
            overlayTemplateSelect.innerHTML = '';
            
            // Keep text as default and clear loading options for message template
            messageTemplateSelect.innerHTML = '<option value="text" selected>Text Message</option>';

            if (data.templates && Array.isArray(data.templates)) {
                data.templates.forEach(template => {
                    // Add to overlay template select
                    const overlayOption = document.createElement('option');
                    overlayOption.value = template.name;
                    overlayOption.textContent = template.display_name || template.name;
                    overlayTemplateSelect.appendChild(overlayOption);

                    // Add to message template select (only if it's not "text" since we already have it)
                    if (template.name !== 'text') {
                        const messageOption = document.createElement('option');
                        messageOption.value = template.name;
                        messageOption.textContent = template.display_name || template.name;
                        messageTemplateSelect.appendChild(messageOption);
                    }
                });

                // Select default template if available for overlay
                const defaultOverlayOption = overlayTemplateSelect.querySelector('option[value="default"]');
                if (defaultOverlayOption) {
                    defaultOverlayOption.selected = true;
                }
                
                // Text template should remain selected for messages
                messageTemplateSelect.value = 'text';
            } else {
                // Fallback if no templates found
                const overlayOption = document.createElement('option');
                overlayOption.value = 'default';
                overlayOption.textContent = 'Default';
                overlayTemplateSelect.appendChild(overlayOption);

                // Message template fallback is already set above
            }
        })
        .catch(error => {
            console.error('Error loading templates:', error);
            // Fallback template options
            const overlayTemplateSelect = document.getElementById('overlay-template');
            const messageTemplateSelect = document.getElementById('message-template');

            overlayTemplateSelect.innerHTML = '<option value="default">Default</option>';
            // Message template fallback is already set
            messageTemplateSelect.innerHTML = '<option value="text" selected>Text Message</option>';
        });
}

// Print functionality
document.addEventListener('DOMContentLoaded', function() {
    // Toggle last N input visibility
    document.querySelectorAll('input[name="printOption"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const lastNInput = document.getElementById('lastNInput');
            if (this.value === 'lastN') {
                lastNInput.style.display = 'block';
            } else {
                lastNInput.style.display = 'none';
            }
        });
    });
});

function printPendingMatches() {
    if (!cachedMatchesData) {
        alert('No match data available. Please wait for matches to load.');
        return;
    }
    
    const printOption = document.querySelector('input[name="printOption"]:checked').value;
    const data = JSON.parse(cachedMatchesData);
    let matchesToPrint = [...data.matches];
    
    // Apply last N filter
    if (printOption === 'lastN') {
        const n = parseInt(document.getElementById('numberOfMatches').value) || 10;
        matchesToPrint = matchesToPrint.slice(-n);
    }
    
    // Generate print content
    const printContent = generateCashierPrintContent(matchesToPrint, data.fixture_id);
    
    // Create print window
    const printWindow = window.open('', '_blank');
    printWindow.document.write(printContent);
    printWindow.document.close();
    printWindow.focus();
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('printModal'));
    if (modal) {
        modal.hide();
    }
    
    // Trigger print after a short delay
    setTimeout(() => {
        printWindow.print();
    }, 500);
}

function generateCashierPrintContent(matches, fixtureId) {
    const now = new Date().toLocaleString();
    
    let matchesHTML = '';
    matches.forEach(match => {
        const startTime = match.start_time ? new Date(match.start_time).toLocaleString() : 'Not scheduled';
        const status = match.status || 'pending';
        const statusText = status.toUpperCase();
        
        // Result display
        const result = match.result || '-';
        
        // Winning outcomes display
        let winningOutcomes = '-';
        if (match.winning_outcomes) {
            try {
                const wo = typeof match.winning_outcomes === 'string' ? JSON.parse(match.winning_outcomes) : match.winning_outcomes;
                if (Array.isArray(wo) && wo.length > 0) {
                    winningOutcomes = wo.join(', ');
                }
            } catch (e) {
                winningOutcomes = match.winning_outcomes;
            }
        }
        
        // Under/Over display
        const underOver = match.under_over_result || '-';
        
        matchesHTML += `
            <tr>
                <td style="text-align: center; font-weight: bold;">#${match.match_number}</td>
                <td style="font-weight: bold;">${match.fighter1_township}</td>
                <td style="font-weight: bold;">${match.fighter2_township}</td>
                <td>${match.venue_kampala_township}</td>
                <td style="text-align: center;">${statusText}</td>
                <td style="text-align: center; font-weight: bold;">${result}</td>
                <td style="text-align: center; font-size: 10px;">${winningOutcomes}</td>
                <td style="text-align: center;">${underOver}</td>
            </tr>
        `;
    });
    
    // Calculate summary stats
    const doneMatches = matches.filter(m => m.status === 'done');
    const winCount = doneMatches.filter(m => m.result && (m.result.startsWith('WIN') || m.result === 'W1' || m.result === 'W2')).length;
    const drawCount = doneMatches.filter(m => m.result === 'DRAW' || m.result === 'X').length;
    const underCount = doneMatches.filter(m => m.under_over_result === 'UNDER').length;
    const overCount = doneMatches.filter(m => m.under_over_result === 'OVER').length;
    
    return `
<!DOCTYPE html>
<html>
<head>
    <title>Fixture Matches Report - Cashier Dashboard</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #333;
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #333;
            padding-bottom: 15px;
        }
        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }
        .header .subtitle {
            font-size: 14px;
            color: #666;
        }
        .info {
            margin-bottom: 20px;
            padding: 10px;
            background: #f5f5f5;
            border-radius: 5px;
        }
        .info table {
            width: 100%;
        }
        .info td {
            padding: 3px 10px;
        }
        .info td:first-child {
            font-weight: bold;
            width: 150px;
        }
        .summary {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 10px;
        }
        .summary-box {
            text-align: center;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            min-width: 80px;
        }
        .summary-box .number {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }
        .summary-box .label {
            font-size: 10px;
            color: #666;
        }
        table.matches {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table.matches th {
            background: #333;
            color: white;
            padding: 8px 5px;
            text-align: center;
            font-size: 10px;
        }
        table.matches td {
            border: 1px solid #ddd;
            padding: 6px 5px;
            vertical-align: middle;
            font-size: 11px;
        }
        .footer {
            text-align: center;
            font-size: 10px;
            color: #666;
            margin-top: 20px;
            border-top: 1px solid #ddd;
            padding-top: 10px;
        }
        @media print {
            body {
                padding: 0;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Fixture Matches Report</h1>
        <div class="subtitle">Cashier Dashboard - Generated on ${now}</div>
    </div>
    
    <div class="info">
        <table>
            <tr>
                <td>Fixture ID:</td>
                <td>${fixtureId || 'N/A'}</td>
            </tr>
            <tr>
                <td>Total Matches:</td>
                <td>${matches.length}</td>
            </tr>
            <tr>
                <td>Completed:</td>
                <td>${doneMatches.length}</td>
            </tr>
            <tr>
                <td>Printed By:</td>
                <td>{{ current_user.username }} (Cashier)</td>
            </tr>
        </table>
    </div>
    
    <div class="summary">
        <div class="summary-box">
            <div class="number">${matches.length}</div>
            <div class="label">Total</div>
        </div>
        <div class="summary-box">
            <div class="number">${matches.filter(m => m.status === 'bet').length}</div>
            <div class="label">Betting</div>
        </div>
        <div class="summary-box">
            <div class="number">${doneMatches.length}</div>
            <div class="label">Done</div>
        </div>
        <div class="summary-box">
            <div class="number">${winCount}</div>
            <div class="label">Wins</div>
        </div>
        <div class="summary-box">
            <div class="number">${drawCount}</div>
            <div class="label">Draws</div>
        </div>
        <div class="summary-box">
            <div class="number">${underCount}</div>
            <div class="label">Under</div>
        </div>
        <div class="summary-box">
            <div class="number">${overCount}</div>
            <div class="label">Over</div>
        </div>
    </div>
    
    <table class="matches">
        <thead>
            <tr>
                <th style="width: 40px;">#</th>
                <th style="width: 100px;">Fighter 1</th>
                <th style="width: 100px;">Fighter 2</th>
                <th style="width: 80px;">Venue</th>
                <th style="width: 50px;">Status</th>
                <th style="width: 50px;">Result</th>
                <th style="width: 80px;">Win Outcomes</th>
                <th style="width: 50px;">U/O</th>
            </tr>
        </thead>
        <tbody>
            ${matchesHTML}
        </tbody>
    </table>
    
    <div class="footer">
        <p>This report was generated by MbetterClient Cashier Dashboard</p>
        <p>Fixture ID: ${fixtureId || 'N/A'} | Printed: ${now}</p>
    </div>
</body>
</html>
    `;
}
</script>
<script>
// Initialize dashboard with timer functionality
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Dashboard with timer support
    if (typeof Dashboard !== 'undefined') {
        Dashboard.init({
            user: {
                username: '{{ current_user.username }}',
                role: 'cashier'
            }
        });
    }
    
    // Hook into the start games button to trigger timer notifications
    const startGamesBtn = document.getElementById('btn-start-games');
    if (startGamesBtn) {
        startGamesBtn.addEventListener('click', function() {
            // The existing START_GAME logic will trigger the timer
            // Dashboard.js will automatically sync with the server timer
        });
    }
});
</script>
{% endblock %}
