{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-cash-register me-2"></i>Cashier Dashboard
            <small class="text-muted">Welcome, {{ current_user.username }}</small>
        </h1>
    </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-4 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-4 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 class="col-md-4 mb-3">
                        <button class="btn btn-outline-warning w-100" id="btn-send-message">
                            <i class="fas fa-comment me-2"></i>Send Custom Message
                        </button>
                    </div>
                    <div class="col-md-4 mb-3">
                        <button class="btn btn-outline-success w-100" id="btn-update-overlay">
                            <i class="fas fa-edit me-2"></i>Update Display Overlay
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Pending Matches from First Fixture - Left Side -->
    <div class="col-lg-9 col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-list me-2"></i>Pending Matches - First Fixture
                    <span class="badge bg-warning ms-2" id="pending-matches-count">0</span>
                </h5>
            </div>
            <div class="card-body">
                <div id="pending-matches-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading pending 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 pending matches for cashier dashboard
    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 = '/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;

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

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

    if (!container) {
        console.error('❌ pending-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 pending matches...
            </div>
        `;
    }

    fetch('/api/cashier/pending-matches')
        .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;
                countBadge.className = data.total > 0 ? 'badge bg-warning ms-2' : 'badge bg-success ms-2';

                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 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 pending matches found
            </div>
        `;
        return;
    }

    // Check if table already exists
    let tbody = container.querySelector('tbody');
    
    if (!tbody) {
        // Create new table
        container.innerHTML = `
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th><i class="fas fa-hashtag me-1"></i>Match #</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><i class="fas fa-clock me-1"></i>Start Time</th>
                            <th><i class="fas fa-info-circle me-1"></i>Status</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 matchNumber = row.getAttribute('data-match-number');
        if (matchNumber) {
            existingMatches.set(matchNumber, row);
        }
    });

    const processedMatches = new Set();

    data.matches.forEach(match => {
        const matchNumber = match.match_number.toString();
        processedMatches.add(matchNumber);
        
        const startTime = match.start_time ?
            new Date(match.start_time).toLocaleString() : 'Not scheduled';

        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>Scheduled</span>';
                break;
            case 'bet':
                statusBadge = '<span class="badge bg-success"><i class="fas fa-dollar-sign me-1"></i>Bet</span>';
                break;
            case 'ingame':
                statusBadge = '<span class="badge bg-info"><i class="fas fa-play me-1"></i>In Game</span>';
                break;
            case 'completed':
                statusBadge = '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Completed</span>';
                break;
            case 'cancelled':
                statusBadge = '<span class="badge bg-secondary"><i class="fas fa-times me-1"></i>Cancelled</span>';
                break;
            case 'failed':
                statusBadge = '<span class="badge bg-danger"><i class="fas fa-exclamation-triangle me-1"></i>Failed</span>';
                break;
            case 'paused':
                statusBadge = '<span class="badge bg-warning"><i class="fas fa-pause me-1"></i>Paused</span>';
                break;
            default:
                statusBadge = '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
        }

        const newRowHTML = `
            <td><strong>${match.match_number}</strong></td>
            <td>${match.fighter1_township}</td>
            <td>${match.fighter2_township}</td>
            <td>${match.venue_kampala_township}</td>
            <td>${startTime}</td>
            <td>${statusBadge}</td>
        `;

        const existingRow = existingMatches.get(matchNumber);
        if (existingRow) {
            // Update existing row only if content changed
            if (existingRow.innerHTML !== newRowHTML) {
                existingRow.innerHTML = newRowHTML;
                existingRow.style.backgroundColor = '#fff3cd'; // Highlight briefly
                setTimeout(() => {
                    existingRow.style.backgroundColor = '';
                }, 1000);
            }
        } else {
            // Add new row
            const row = document.createElement('tr');
            row.setAttribute('data-match-number', matchNumber);
            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, matchNumber) => {
        if (!processedMatches.has(matchNumber)) {
            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>';
        });
}
</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 %}
