<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cashier Dashboard - {{ app_name }}</title>
    
    <!-- CSS from CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">

    <style>
        .navbar-clock {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            padding: 8px 16px;
            font-family: 'Courier New', monospace;
            font-weight: bold;
            font-size: 1.2rem;
            color: #ffffff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

        .navbar-clock:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        .navbar-clock i {
            color: #ffffff;
            filter: drop-shadow(1px 1px 1px rgba(0, 0, 0, 0.5));
        }

        #clock-time {
            font-size: 1.3rem;
            letter-spacing: 2px;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .navbar-clock {
                font-size: 1rem;
                padding: 6px 12px;
            }

            #clock-time {
                font-size: 1.1rem;
                letter-spacing: 1px;
            }
        }
    </style>
</head>
<body>
    <!-- Simplified Navigation Bar for Cashier -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-cash-register me-2"></i>{{ app_name }} - Cashier
            </a>

            <ul class="navbar-nav ms-auto">
                <!-- Digital Clock -->
                <li class="nav-item d-flex align-items-center me-3">
                    <div id="digital-clock" class="navbar-clock">
                        <i class="fas fa-clock me-2"></i>
                        <span id="clock-time">--:--:--</span>
                    </div>
                </li>
                <!-- Match Timer -->
                <li class="nav-item d-flex align-items-center me-3">
                    <div id="match-timer-navbar" class="navbar-timer">
                        <i class="fas fa-stopwatch me-2"></i>
                        <span id="match-timer-display">--:--</span>
                    </div>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('auth.logout') }}">
                        <i class="fas fa-sign-out-alt me-1"></i>Logout
                    </a>
                </li>
            </ul>
        </div>
    </nav>
    
    <main class="container-fluid mt-4">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'danger' if category == 'error' else category }} alert-dismissible fade show" role="alert">
                        {% if category == 'error' %}
                            <i class="fas fa-exclamation-triangle me-2"></i>
                        {% elif category == 'success' %}
                            <i class="fas fa-check-circle me-2"></i>
                        {% elif category == 'info' %}
                            <i class="fas fa-info-circle me-2"></i>
                        {% endif %}
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}
        
        <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-outline-primary w-100" id="btn-play-video">
                                    <i class="fas fa-play me-2"></i>Start Video Display
                                </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>

                <!-- Betting Mode Configuration - Hidden for Cashier Users -->
                <!-- This feature is only available to admin users -->

                <!-- 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>
    </main>

    <!-- Video Control Modal -->
    <div class="modal fade" id="playVideoModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Start Video Display</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="play-video-form">
                        <div class="mb-3">
                            <label class="form-label">Video File Path</label>
                            <input type="text" class="form-control" id="video-file-path" 
                                   placeholder="/path/to/video.mp4">
                            <div class="form-text">Enter the full path to the video file you want to display</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Display Template</label>
                            <select class="form-select" id="video-template">
                                <option value="">Loading templates...</option>
                            </select>
                            <div class="form-text">Choose the template for displaying information over the video</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-primary" id="confirm-play-video">
                        <i class="fas fa-play me-1"></i>Start Display
                    </button>
                </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>
    
    <!-- System Status Bar -->
    <div id="status-bar" class="fixed-bottom bg-light border-top p-2 d-none d-lg-block">
        <div class="container-fluid">
            <div class="row align-items-center text-small">
                <div class="col-auto">
                    <span class="text-muted">Status:</span>
                    <span id="system-status" class="badge bg-success">Online</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Video:</span>
                    <span id="video-status" class="badge bg-secondary">Stopped</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Last Updated:</span>
                    <span id="last-updated" class="text-muted">--</span>
                </div>
                <div class="col text-end">
                    <small class="text-muted">{{ app_name }} v{{ app_version }}</small>
                </div>
            </div>
        </div>
    </div>
    
    <!-- JavaScript from CDN and local -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="{{ url_for('static', filename='js/dashboard.js') }}"></script>
    
    <script id="dashboard-config" type="application/json">
        {
            "statusUpdateInterval": 30000,
            "apiEndpoint": "/api",
            "user": {
                "id": {{ current_user.id | tojson }},
                "username": {{ current_user.username | tojson }},
                "is_admin": {{ current_user.is_admin | tojson }}
            }
        }
    </script>
    <script>
        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof Dashboard !== 'undefined') {
                var config = JSON.parse(document.getElementById('dashboard-config').textContent);
                Dashboard.init(config);
            }

            // Initialize digital clock
            initializeClock();

            // Load pending matches for cashier dashboard
            loadPendingMatches();
    
            // Betting mode functionality removed for cashier users
        });

        function initializeClock() {
            const clockElement = document.getElementById('clock-time');
            if (!clockElement) return;

            let serverTimeOffset = 0; // Offset between server and client time
            let lastServerTime = null;

            function fetchServerTime() {
                return fetch('/api/server-time')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const serverTimestamp = data.timestamp;
                            const clientTimestamp = Date.now();
                            serverTimeOffset = serverTimestamp - clientTimestamp;
                            lastServerTime = serverTimestamp;
                            return serverTimestamp;
                        } else {
                            throw new Error('Failed to get server time');
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching server time:', error);
                        // Fallback to client time if server time is unavailable
                        return Date.now();
                    });
            }

            function updateClock() {
                const now = Date.now() + serverTimeOffset;
                const date = new Date(now);

                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                const timeString = `${hours}:${minutes}:${seconds}`;

                clockElement.textContent = timeString;
            }

            // Fetch server time initially and set up updates
            fetchServerTime().then(() => {
                // Update immediately with server time
                updateClock();

                // Update display every second (using client time + offset)
                setInterval(updateClock, 1000);

                // Sync with server time every 30 seconds
                setInterval(fetchServerTime, 30000);
            });
        }

        // Function to load and display pending matches
        function loadPendingMatches() {
            fetch('/api/cashier/pending-matches')
                .then(response => response.json())
                .then(data => {
                    const container = document.getElementById('pending-matches-container');
                    const countBadge = document.getElementById('pending-matches-count');

                    if (data.success) {
                        // Update count badge
                        countBadge.textContent = data.total;
                        countBadge.className = data.total > 0 ? 'badge bg-warning ms-2' : 'badge bg-success ms-2';

                        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>
                            `;
                        } else {
                            // Create matches table
                            let tableHtml = `
                                <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>
                            `;

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

                                // Get status from the match object (new status column)
                                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 '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>';
                                }

                                tableHtml += `
                                    <tr>
                                        <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>
                                    </tr>
                                `;
                            });

                            tableHtml += `
                                        </tbody>
                                    </table>
                                </div>
                            `;

                            container.innerHTML = tableHtml;
                        }
                    } else {
                        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 => {
                    const container = document.getElementById('pending-matches-container');
                    container.innerHTML = `
                        <div class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${error.message}
                        </div>
                    `;
                });
        }
    </script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Load available templates on page load
        loadAvailableTemplates();
        
        // 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) {
                        alert('Games started successfully!');
                        // Refresh the pending matches list
                        loadPendingMatches();
                        // Show success message
                        showNotification('Games started successfully!', 'success');
                    } else {
                        alert('Failed to start games: ' + (data.error || 'Unknown error'));
                    }
                })
                .catch(error => {
                    alert('Error starting games: ' + error.message);
                });
            }
        });

        document.getElementById('btn-play-video').addEventListener('click', function() {
            new bootstrap.Modal(document.getElementById('playVideoModal')).show();
        });

        document.getElementById('btn-update-overlay').addEventListener('click', function() {
            new bootstrap.Modal(document.getElementById('updateOverlayModal')).show();
        });
        
        // Confirm actions
        document.getElementById('confirm-play-video').addEventListener('click', function() {
            const filePath = document.getElementById('video-file-path').value;
            const template = document.getElementById('video-template').value;
            
            if (!filePath) {
                alert('Please enter a video file path');
                return;
            }
            
            fetch('/api/video/control', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'play',
                    file_path: filePath,
                    template: template
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    bootstrap.Modal.getInstance(document.getElementById('playVideoModal')).hide();
                    updateVideoStatus();
                    updateCurrentVideoPath(filePath);
                    updateCurrentTemplate(template || 'default');
                    // Increment counter
                    const videosCount = parseInt(document.getElementById('videos-played').textContent) + 1;
                    document.getElementById('videos-played').textContent = videosCount;
                } else {
                    alert('Failed to start video: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
            });
        });
        
        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);
            });
        });
        
        // 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, 10000);  // Every 10 seconds
    });

    function loadAvailableTemplates() {
        fetch('/api/templates')
            .then(response => response.json())
            .then(data => {
                const videoTemplateSelect = document.getElementById('video-template');
                const overlayTemplateSelect = document.getElementById('overlay-template');
                
                // Clear loading options
                videoTemplateSelect.innerHTML = '';
                overlayTemplateSelect.innerHTML = '';
                
                if (data.templates && Array.isArray(data.templates)) {
                    data.templates.forEach(template => {
                        // Add to video template select
                        const videoOption = document.createElement('option');
                        videoOption.value = template.name;
                        videoOption.textContent = template.display_name || template.name;
                        videoTemplateSelect.appendChild(videoOption);
                        
                        // Add to overlay template select
                        const overlayOption = document.createElement('option');
                        overlayOption.value = template.name;
                        overlayOption.textContent = template.display_name || template.name;
                        overlayTemplateSelect.appendChild(overlayOption);
                    });
                    
                    // Select default template if available
                    const defaultVideoOption = videoTemplateSelect.querySelector('option[value="default"]');
                    if (defaultVideoOption) {
                        defaultVideoOption.selected = true;
                    }
                    
                    const defaultOverlayOption = overlayTemplateSelect.querySelector('option[value="default"]');
                    if (defaultOverlayOption) {
                        defaultOverlayOption.selected = true;
                    }
                } else {
                    // Fallback if no templates found
                    const videoOption = document.createElement('option');
                    videoOption.value = 'default';
                    videoOption.textContent = 'Default';
                    videoTemplateSelect.appendChild(videoOption);
                    
                    const overlayOption = document.createElement('option');
                    overlayOption.value = 'default';
                    overlayOption.textContent = 'Default';
                    overlayTemplateSelect.appendChild(overlayOption);
                }
            })
            .catch(error => {
                console.error('Error loading templates:', error);
                // Fallback template options
                const videoTemplateSelect = document.getElementById('video-template');
                const overlayTemplateSelect = document.getElementById('overlay-template');
                
                videoTemplateSelect.innerHTML = '<option value="default">Default</option>';
                overlayTemplateSelect.innerHTML = '<option value="default">Default</option>';
            });
    }

    // Betting mode functions removed - not available for cashier users
    </script>
</body>
</html>