{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-tachometer-alt me-2"></i>Dashboard
            <small class="text-muted">Welcome, {{ current_user.username }}</small>
        </h1>
    </div>
</div>


<!-- Quick Actions -->
<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>Quick Actions
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <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 Playback
                        </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 Overlay
                        </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-info w-100" id="btn-create-token">
                            <i class="fas fa-plus me-2"></i>Create API Token
                        </button>
                    </div>
                </div>

                <!-- Match Timer and Interval Configuration -->
                <div class="row mt-3">
                    <div class="col-md-8">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-clock me-2"></i>Match Interval
                            </span>
                            <input type="number" class="form-control" id="match-interval"
                                   placeholder="20" min="1" max="60" step="1" value="20">
                            <span class="input-group-text">minutes</span>
                            <button class="btn btn-outline-primary" id="btn-save-interval">
                                <i class="fas fa-save me-1"></i>Save
                            </button>
                        </div>
                        <small class="text-muted mt-1 d-block">
                            Set the interval between matches in minutes (1-60)
                        </small>
                    </div>
                    <div class="col-md-4">
                        <div class="card bg-light">
                            <div class="card-body text-center p-3">
                                <h5 class="card-title mb-2">
                                    <i class="fas fa-stopwatch me-2"></i>Match Timer
                                </h5>
                                <div class="h3 mb-2" id="admin-match-timer">--:--</div>
                                <div class="mt-2">
                                    <small class="text-muted" id="timer-status">Waiting for games to start...</small>
                                </div>
                                <div class="mt-2">
                                    <small class="text-info">
                                        <i class="fas fa-info-circle me-1"></i>Timer starts automatically when cashier begins games
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card bg-light">
                            <div class="card-body p-3">
                                <h5 class="card-title mb-3">
                                    <i class="fas fa-dice me-2"></i>Betting Mode
                                </h5>
                                <div class="mb-3">
                                    <select class="form-select" id="betting-mode-select">
                                        <option value="all_bets_on_start">All bets on start</option>
                                        <option value="one_bet_at_a_time">One bet at a time</option>
                                    </select>
                                </div>
                                <div class="mt-2">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle me-1"></i>Choose how bets are placed during matches
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {% if current_user.is_admin %}
                <!-- Admin Only Actions -->
                <div class="row mt-3 pt-3 border-top">
                    <div class="col-12">
                        <h6 class="text-muted mb-3">
                            <i class="fas fa-shield-alt me-2"></i>Administrator Actions
                        </h6>
                    </div>
                    <div class="col-md-4 mb-3">
                        <button class="btn btn-outline-primary w-100" id="btn-upload-intro-video">
                            <i class="fas fa-upload me-2"></i>Upload Intro Video
                        </button>
                    </div>
                    <div class="col-md-4 mb-3">
                        <button class="btn btn-outline-danger w-100" id="btn-shutdown-app">
                            <i class="fas fa-power-off me-2"></i>Shutdown Application
                        </button>
                    </div>
                </div>
                {% endif %}

                <!-- Redistribution Balance Management (Admin Only) -->
                {% if current_user.is_admin %}
                <div class="row mt-3 pt-3 border-top">
                    <div class="col-12">
                        <h6 class="text-muted mb-3">
                            <i class="fas fa-balance-scale me-2"></i>Redistribution Balance
                        </h6>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="card bg-light">
                            <div class="card-body text-center p-3">
                                <h5 class="card-title mb-2">
                                    <i class="fas fa-coins me-2"></i>Current Balance
                                </h5>
                                <div class="h4 mb-2 text-primary" id="redistribution-balance">--</div>
                                <div class="mt-2">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle me-1"></i>Balance to compensate over/under redistribution
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="d-grid">
                            <button class="btn btn-outline-danger w-100" id="btn-reset-redistribution-balance">
                                <i class="fas fa-undo me-2"></i>Reset Balance to Zero
                            </button>
                            <small class="text-muted mt-2 d-block">
                                <i class="fas fa-exclamation-triangle me-1"></i>This will reset the redistribution compensation balance
                            </small>
                        </div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- License Configuration -->
<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-file-contract me-2"></i>License Text Configuration
                </h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Overlay License Text</label>
                    <textarea class="form-control" id="license-text" rows="4" maxlength="500"
                              placeholder="Enter license text to display on overlays...">LICENSED BY THE NATIONAL LOTTERIES AND GAMING REGULATORY BOARD - LICENSE NUMBER NLGBR-GB-82-006. Gambling can be addictive and psychologically harmful not allowed for minors</textarea>
                    <div class="form-text">This text will be displayed as a top bar on all overlay templates. Maximum 500 characters.</div>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-primary" id="btn-save-license">
                        <i class="fas fa-save me-1"></i>Save License Text
                    </button>
                    <button class="btn btn-outline-secondary" id="btn-reset-license">
                        <i class="fas fa-undo me-1"></i>Reset to Default
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Activity & System Info -->
<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-clock me-2"></i>Recent Activity
                </h5>
                <small class="text-muted">Last 24 hours</small>
            </div>
            <div class="card-body">
                <div id="activity-list">
                    <div class="d-flex align-items-center mb-3">
                        <div class="flex-shrink-0">
                            <i class="fas fa-info-circle text-info"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="fw-bold">System Started</div>
                            <small class="text-muted">Web dashboard initialized successfully</small>
                        </div>
                        <div class="flex-shrink-0">
                            <small class="text-muted">Just now</small>
                        </div>
                    </div>
                    
                    <div class="d-flex align-items-center mb-3">
                        <div class="flex-shrink-0">
                            <i class="fas fa-user text-success"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="fw-bold">User Login</div>
                            <small class="text-muted">{{ current_user.username }} logged in</small>
                        </div>
                        <div class="flex-shrink-0">
                            <small class="text-muted">Just now</small>
                        </div>
                    </div>
                    
                    <div class="text-center text-muted mt-4">
                        <small>More activity will appear here as you use the system</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-info-circle me-2"></i>System Information
                </h5>
            </div>
            <div class="card-body">
                <dl class="mb-0">
                    <dt class="text-muted">Version</dt>
                    <dd>{{ app_version }}</dd>
                    
                    <dt class="text-muted">Uptime</dt>
                    <dd id="system-uptime">Just started</dd>
                    
                    <dt class="text-muted">User Role</dt>
                    <dd>
                        {% if current_user.is_admin %}
                            <span class="badge bg-danger">Administrator</span>
                        {% else %}
                            <span class="badge bg-primary">User</span>
                        {% endif %}
                    </dd>
                    
                    <dt class="text-muted">Components</dt>
                    <dd>
                        <span class="badge bg-success me-1">Web</span>
                        <span class="badge bg-secondary me-1" id="player-badge">Player</span>
                        <span class="badge bg-secondary" id="api-badge">API Client</span>
                    </dd>
                </dl>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-chart-line me-2"></i>Quick Stats
                </h5>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <h4 class="text-primary" id="videos-played">0</h4>
                        <small class="text-muted">Videos Played</small>
                    </div>
                    <div class="col-6">
                        <h4 class="text-success" id="overlays-updated">0</h4>
                        <small class="text-muted">Overlays Updated</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Quick Action Modals -->
<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 Playback</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>
                    <div class="mb-3">
                        <label class="form-label">Template</label>
                        <select class="form-select" id="video-template">
                            <option value="">Loading templates...</option>
                        </select>
                    </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 Playback
                </button>
            </div>
        </div>
    </div>
</div>

<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 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">Template</label>
                        <select class="form-select" id="overlay-template">
                            <option value="">Loading templates...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Headline/Title</label>
                        <input type="text" class="form-control" id="overlay-headline" 
                               placeholder="Breaking News">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Text Content</label>
                        <textarea class="form-control" id="overlay-text" rows="3" 
                                  placeholder="Additional information..."></textarea>
                    </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 Overlay
                </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>

<!-- Upload Intro Video Modal -->
<div class="modal fade" id="uploadIntroVideoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Upload Default Intro Video</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="upload-intro-video-form" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label">Select Video File</label>
                        <input type="file" class="form-control" id="intro-video-file"
                               accept="video/*" required>
                        <div class="form-text">
                            Supported formats: MP4, AVI, MOV, MKV, WebM (Max 500MB)
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="overwrite-existing">
                            <label class="form-check-label" for="overwrite-existing">
                                Overwrite existing intro video
                            </label>
                        </div>
                    </div>
                    <div id="upload-progress" class="d-none">
                        <div class="progress mb-2">
                            <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                        </div>
                        <small class="text-muted">Uploading...</small>
                    </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-upload-intro-video">
                    <i class="fas fa-upload me-1"></i>Upload Video
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

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

    // Load match interval configuration
    loadMatchInterval();

    // Load betting mode configuration
    loadBettingMode();

    // Load license text configuration
    loadLicenseText();

    // Load redistribution balance (admin only)
    if (document.getElementById('redistribution-balance')) {
        loadRedistributionBalance();
        // Periodic update of redistribution balance
        setInterval(loadRedistributionBalance, 5000); // Update every 5 seconds
    }
    
    // Quick action buttons
    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();
    });
    
    document.getElementById('btn-send-message').addEventListener('click', function() {
        new bootstrap.Modal(document.getElementById('sendMessageModal')).show();
    });
    
    document.getElementById('btn-create-token').addEventListener('click', function() {
        window.location.href = '/tokens';
    });

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

    // Match interval save button
    document.getElementById('btn-save-interval').addEventListener('click', function() {
        saveMatchInterval();
    });

    // Betting mode select
    document.getElementById('betting-mode-select').addEventListener('change', function() {
        saveBettingMode(this.value);
    });

    // License text buttons
    document.getElementById('btn-save-license').addEventListener('click', function() {
        saveLicenseText();
    });

    document.getElementById('btn-reset-license').addEventListener('click', function() {
        resetLicenseText();
    });

    // Redistribution balance reset button (only exists for admin)
    const resetBalanceBtn = document.getElementById('btn-reset-redistribution-balance');
    if (resetBalanceBtn) {
        resetBalanceBtn.addEventListener('click', function() {
            resetRedistributionBalance();
        });
    }
    
    // Admin shutdown button (only exists if user is admin)
    const shutdownBtn = document.getElementById('btn-shutdown-app');
    if (shutdownBtn) {
        shutdownBtn.addEventListener('click', function() {
            if (confirm('Are you sure you want to shutdown the entire application? This will close the Qt player and stop all services.')) {
                fetch('/api/system/shutdown', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Application shutdown initiated. The window will close automatically.');
                        // Redirect to a goodbye page or show shutdown message
                        document.body.innerHTML = '<div class="container mt-5 text-center"><h2>Application Shutting Down...</h2><p>Please wait while the system shuts down gracefully.</p></div>';
                    } else {
                        alert('Failed to shutdown application: ' + (data.error || 'Unknown error'));
                    }
                })
                .catch(error => {
                    alert('Error requesting shutdown: ' + error.message);
                });
            }
        });
    }
    
    // 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();
            } 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();
                document.getElementById('overlays-updated').textContent = 
                    parseInt(document.getElementById('overlays-updated').textContent) + 1;
            } 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';
                alert('Custom message sent successfully with ' + displayTime + ' second display time!');
            } else {
                alert('Failed to send message: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error sending message: ' + error.message);
        });
    });

    document.getElementById('confirm-upload-intro-video').addEventListener('click', function() {
        const fileInput = document.getElementById('intro-video-file');
        const file = fileInput.files[0];
        const overwrite = document.getElementById('overwrite-existing').checked;

        if (!file) {
            alert('Please select a video file to upload');
            return;
        }

        // Validate file size (500MB limit)
        const maxSize = 500 * 1024 * 1024; // 500MB in bytes
        if (file.size > maxSize) {
            alert('File size must be less than 500MB');
            return;
        }

        // Validate file type
        const allowedTypes = ['video/mp4', 'video/avi', 'video/quicktime', 'video/x-matroska', 'video/webm'];
        if (!allowedTypes.includes(file.type) && !file.name.match(/\.(mp4|avi|mov|mkv|webm)$/i)) {
            alert('Please select a valid video file (MP4, AVI, MOV, MKV, or WebM)');
            return;
        }

        const formData = new FormData();
        formData.append('video_file', file);
        formData.append('overwrite', overwrite);

        const uploadBtn = document.getElementById('confirm-upload-intro-video');
        const originalText = uploadBtn.innerHTML;
        const progressDiv = document.getElementById('upload-progress');
        const progressBar = progressDiv.querySelector('.progress-bar');

        // Show progress and disable button
        progressDiv.classList.remove('d-none');
        uploadBtn.disabled = true;
        uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Uploading...';

        fetch('/api/upload-intro-video', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('uploadIntroVideoModal')).hide();
                // Clear the form
                document.getElementById('upload-intro-video-form').reset();
                alert('Intro video uploaded successfully!');
            } else {
                alert('Failed to upload video: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error uploading video: ' + error.message);
        })
        .finally(() => {
            // Hide progress and restore button
            progressDiv.classList.add('d-none');
            progressBar.style.width = '0%';
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = originalText;
        });
    });
    
    // Status update functions
    function updateSystemStatus() {
        fetch('/api/status')
        .then(response => response.json())
        .then(data => {
            if (data.status === 'online') {
                document.getElementById('system-status-text').textContent = 'Online';
                document.getElementById('system-status').className = 'badge bg-success';
            } else {
                document.getElementById('system-status-text').textContent = 'Error';
                document.getElementById('system-status').className = 'badge bg-danger';
            }
        })
        .catch(error => {
            document.getElementById('system-status-text').textContent = 'Offline';
            document.getElementById('system-status').className = 'badge bg-danger';
        });
    }
    
    function updateVideoStatus() {
        fetch('/api/video/status')
        .then(response => response.json())
        .then(data => {
            const status = data.player_status || 'unknown';
            document.getElementById('video-status-text').textContent = 
                status.charAt(0).toUpperCase() + status.slice(1);
            
            const badge = document.getElementById('player-badge');
            if (status === 'playing') {
                badge.className = 'badge bg-success me-1';
            } else if (status === 'paused') {
                badge.className = 'badge bg-warning me-1';
            } else {
                badge.className = 'badge bg-secondary me-1';
            }
        })
        .catch(error => {
            document.getElementById('video-status-text').textContent = 'Unknown';
        });
    }
    
    // Initial status update
    updateSystemStatus();
    updateVideoStatus();

    // Periodic updates
    setInterval(updateSystemStatus, 5000); // 5 seconds
    setInterval(updateVideoStatus, 5000);  // 5 seconds
});

function loadMatchInterval() {
    fetch('/api/config/match-interval')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.match_interval) {
                document.getElementById('match-interval').value = data.match_interval;
            }
        })
        .catch(error => {
            console.error('Error loading match interval:', error);
            // Keep default value if loading fails
        });
}

function saveMatchInterval() {
    const intervalInput = document.getElementById('match-interval');
    const intervalValue = parseInt(intervalInput.value);

    if (!intervalValue || intervalValue < 1 || intervalValue > 60) {
        alert('Please enter a valid interval between 1 and 60 minutes');
        return;
    }

    const saveBtn = document.getElementById('btn-save-interval');
    const originalText = saveBtn.innerHTML;

    // Show loading state
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

    fetch('/api/config/match-interval', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            match_interval: intervalValue
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload the match interval to confirm the saved value
            loadMatchInterval();
            alert('Match interval saved successfully!');
        } else {
            alert('Failed to save match interval: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Error saving match interval: ' + error.message);
    })
    .finally(() => {
        // Restore button state
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalText;
    });
}

function loadBettingMode() {
    fetch('/api/betting-mode')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const select = document.getElementById('betting-mode-select');
            if (select) {
                select.value = data.betting_mode;
            }
        } else {
            console.error('Failed to load betting mode:', data.error);
        }
    })
    .catch(error => {
        console.error('Error loading betting mode:', error);
    });
}

function saveBettingMode(mode) {
    fetch('/api/betting-mode', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            betting_mode: mode
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Betting mode saved successfully:', mode);
        } else {
            console.error('Failed to save betting mode:', data.error);
            // Revert the select if save failed
            loadBettingMode();
        }
    })
    .catch(error => {
        console.error('Error saving betting mode:', error);
        // Revert the select if save failed
        loadBettingMode();
    });
}

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

            // Clear loading options
            videoTemplateSelect.innerHTML = '';
            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 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);

                    // 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 video and overlay
                const defaultVideoOption = videoTemplateSelect.querySelector('option[value="default"]');
                if (defaultVideoOption) {
                    defaultVideoOption.selected = true;
                }

                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 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);

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

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

function loadLicenseText() {
    fetch('/api/config/license-text')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.license_text) {
                document.getElementById('license-text').value = data.license_text;
            }
        })
        .catch(error => {
            console.error('Error loading license text:', error);
            // Keep default value if loading fails
        });
}

function saveLicenseText() {
    const licenseText = document.getElementById('license-text').value.trim();

    if (licenseText.length > 500) {
        alert('License text must be 500 characters or less');
        return;
    }

    const saveBtn = document.getElementById('btn-save-license');
    const originalText = saveBtn.innerHTML;

    // Show loading state
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

    fetch('/api/config/license-text', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            license_text: licenseText
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('License text saved successfully!');
        } else {
            alert('Failed to save license text: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Error saving license text: ' + error.message);
    })
    .finally(() => {
        // Restore button state
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalText;
    });
}

function resetLicenseText() {
    const defaultText = 'LICENSED BY THE NATIONAL LOTTERIES AND GAMING REGULATORY BOARD - LICENSE NUMBER NLGBR-GB-82-006. Gambling can be addictive and psychologically harmful not allowed for minors';
    document.getElementById('license-text').value = defaultText;
}

function loadRedistributionBalance() {
    fetch('/api/redistribution-balance')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const balanceElement = document.getElementById('redistribution-balance');
                const balance = data.redistribution_balance;
                balanceElement.textContent = balance.toFixed(2);
                // Color coding: green for positive, red for negative, neutral for zero
                if (balance > 0) {
                    balanceElement.className = 'h4 mb-2 text-success';
                } else if (balance < 0) {
                    balanceElement.className = 'h4 mb-2 text-danger';
                } else {
                    balanceElement.className = 'h4 mb-2 text-primary';
                }
            } else {
                document.getElementById('redistribution-balance').textContent = 'Error';
                console.error('Failed to load redistribution balance:', data.error);
            }
        })
        .catch(error => {
            document.getElementById('redistribution-balance').textContent = 'Error';
            console.error('Error loading redistribution balance:', error);
        });
}

function resetRedistributionBalance() {
    if (!confirm('Are you sure you want to reset the redistribution balance to zero? This action cannot be undone.')) {
        return;
    }

    const resetBtn = document.getElementById('btn-reset-redistribution-balance');
    const originalText = resetBtn.innerHTML;

    // Show loading state
    resetBtn.disabled = true;
    resetBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Resetting...';

    fetch('/api/redistribution-balance/reset', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            // Reload the balance
            loadRedistributionBalance();
        } else {
            alert('Failed to reset redistribution balance: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Error resetting redistribution balance: ' + error.message);
    })
    .finally(() => {
        // Restore button state
        resetBtn.disabled = false;
        resetBtn.innerHTML = originalText;
    });
}

</script>
{% endblock %}
