{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1>Configuration</h1>
            <p>Manage application settings and preferences.</p>
            
            <!-- General Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>General Settings</h5>
                </div>
                <div class="card-body">
                    <form id="general-config-form">
                        <div class="mb-3">
                            <label for="app-name" class="form-label">Application Name</label>
                            <input type="text" class="form-control" id="app-name" value="{{ config.app_name or 'MbetterClient' }}">
                        </div>
                        <div class="mb-3">
                            <label for="log-level" class="form-label">Log Level</label>
                            <select class="form-select" id="log-level">
                                <option value="DEBUG" {% if config.log_level == 'DEBUG' %}selected{% endif %}>DEBUG</option>
                                <option value="INFO" {% if config.log_level == 'INFO' %}selected{% endif %}>INFO</option>
                                <option value="WARNING" {% if config.log_level == 'WARNING' %}selected{% endif %}>WARNING</option>
                                <option value="ERROR" {% if config.log_level == 'ERROR' %}selected{% endif %}>ERROR</option>
                            </select>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="enable-qt" {% if config.enable_qt %}checked{% endif %}>
                            <label class="form-check-label" for="enable-qt">
                                Enable Qt Video Player
                            </label>
                        </div>
                        <button type="submit" class="btn btn-primary">Save General Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- Video Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Video Settings</h5>
                </div>
                <div class="card-body">
                    <form id="video-config-form">
                        <div class="mb-3">
                            <label for="video-width" class="form-label">Video Width</label>
                            <input type="number" class="form-control" id="video-width" value="{{ config.video_width or 1920 }}">
                        </div>
                        <div class="mb-3">
                            <label for="video-height" class="form-label">Video Height</label>
                            <input type="number" class="form-control" id="video-height" value="{{ config.video_height or 1080 }}">
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="fullscreen" {% if config.fullscreen %}checked{% endif %}>
                            <label class="form-check-label" for="fullscreen">
                                Fullscreen Mode
                            </label>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Video Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- API Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>API Settings</h5>
                </div>
                <div class="card-body">
                    <form id="api-config-form">
                        <div class="mb-3">
                            <label for="fastapi-url" class="form-label">FastAPI Server URL</label>
                            <input type="url" class="form-control" id="fastapi-url"
                                   value="{{ config.fastapi_url or 'https://mbetter.nexlab.net/api/updates' }}"
                                   placeholder="https://mbetter.nexlab.net/api/updates">
                            <div class="form-text">Base URL for FastAPI server requests (include https:// or http://)</div>
                        </div>
                        <div class="mb-3">
                            <label for="api-token" class="form-label">API Access Token</label>
                            <input type="password" class="form-control" id="api-token"
                                   value="{{ config.api_token or '' }}"
                                   placeholder="Enter your API access token">
                            <div class="form-text">Authentication token for FastAPI server access</div>
                        </div>
                        <div class="mb-3">
                            <label for="api-interval" class="form-label">Request Interval (seconds)</label>
                            <input type="number" class="form-control" id="api-interval"
                                   value="{{ config.api_interval or 1800 }}" min="30" max="86400">
                            <div class="form-text">Time between automatic API requests (30 seconds to 24 hours)</div>
                        </div>
                        <div class="mb-3">
                            <label for="api-timeout" class="form-label">Request Timeout (seconds)</label>
                            <input type="number" class="form-control" id="api-timeout"
                                   value="{{ config.api_timeout or 30 }}" min="5" max="300">
                            <div class="form-text">Timeout for API requests (5-300 seconds)</div>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="api-enabled"
                                   {% if config.api_enabled != false %}checked{% endif %}>
                            <label class="form-check-label" for="api-enabled">
                                Enable API Client
                            </label>
                            <div class="form-text">Enable/disable automatic API requests</div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save API Settings</button>
                        <button type="button" class="btn btn-outline-secondary ms-2" id="test-api-connection">
                            Test Connection
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Screen Cast Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Screen Cast Settings</h5>
                </div>
                <div class="card-body">
                    <form id="screen-cast-config-form">
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="screen-cast-enabled"
                                   {% if config.screen_cast_enabled != false %}checked{% endif %}>
                            <label class="form-check-label" for="screen-cast-enabled">
                                Enable Screen Cast & Chromecast Streaming
                            </label>
                            <div class="form-text">Enable screen capture and Chromecast streaming functionality</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="screen-cast-port" class="form-label">Stream Port</label>
                            <input type="number" class="form-control" id="screen-cast-port"
                                   value="{{ config.screen_cast_port or 8000 }}" min="1024" max="65535">
                            <div class="form-text">Port for the HTTP streaming server (1024-65535)</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="chromecast-name" class="form-label">Preferred Chromecast Device</label>
                            <input type="text" class="form-control" id="chromecast-name"
                                   value="{{ config.chromecast_name or '' }}"
                                   placeholder="Leave empty for auto-discovery">
                            <div class="form-text">Name of preferred Chromecast device (optional)</div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="screen-cast-resolution" class="form-label">Capture Resolution</label>
                                    <select class="form-select" id="screen-cast-resolution">
                                        <option value="1920x1080" {% if config.screen_cast_resolution == '1920x1080' %}selected{% endif %}>1920x1080 (Full HD)</option>
                                        <option value="1280x720" {% if config.screen_cast_resolution == '1280x720' or not config.screen_cast_resolution %}selected{% endif %}>1280x720 (HD)</option>
                                        <option value="854x480" {% if config.screen_cast_resolution == '854x480' %}selected{% endif %}>854x480 (SD)</option>
                                        <option value="640x360" {% if config.screen_cast_resolution == '640x360' %}selected{% endif %}>640x360 (Low)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="screen-cast-framerate" class="form-label">Frame Rate (FPS)</label>
                                    <select class="form-select" id="screen-cast-framerate">
                                        <option value="30" {% if config.screen_cast_framerate == 30 %}selected{% endif %}>30 FPS</option>
                                        <option value="24" {% if config.screen_cast_framerate == 24 %}selected{% endif %}>24 FPS</option>
                                        <option value="15" {% if config.screen_cast_framerate == 15 or not config.screen_cast_framerate %}selected{% endif %}>15 FPS</option>
                                        <option value="10" {% if config.screen_cast_framerate == 10 %}selected{% endif %}>10 FPS</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="screen-cast-auto-start-capture"
                                           {% if config.screen_cast_auto_start_capture %}checked{% endif %}>
                                    <label class="form-check-label" for="screen-cast-auto-start-capture">
                                        Auto-start Screen Capture
                                    </label>
                                    <div class="form-text">Automatically start capturing when application starts</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="screen-cast-auto-start-streaming"
                                           {% if config.screen_cast_auto_start_streaming %}checked{% endif %}>
                                    <label class="form-check-label" for="screen-cast-auto-start-streaming">
                                        Auto-start Chromecast Streaming
                                    </label>
                                    <div class="form-text">Automatically start streaming when capture begins</div>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Save Screen Cast Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- Database Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Database Settings</h5>
                </div>
                <div class="card-body">
                    <form id="database-config-form">
                        <div class="mb-3">
                            <label for="db-path" class="form-label">Database Path</label>
                            <input type="text" class="form-control" id="db-path" value="{{ config.db_path or 'data/mbetterclient.db' }}">
                        </div>
                        <button type="submit" class="btn btn-primary">Save Database Settings</button>
                    </form>
                </div>
            </div>
            
            <!-- Global Betting Mode Settings (Admin Only) -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-cog"></i> Global Betting Mode Settings</h5>
                    <small class="text-muted">Admin Only - System-wide Configuration</small>
                </div>
                <div class="card-body">
                    <form id="betting-mode-config-form">
                        <div class="mb-3">
                            <label for="betting-mode" class="form-label">Global Betting Mode</label>
                            <select class="form-select" id="betting-mode">
                                <option value="all_bets_on_start">All Bets on Start - All matches become 'bet' status when START_GAME is triggered</option>
                                <option value="one_bet_at_a_time">One Bet at a Time - Only first match becomes 'bet', others remain 'scheduled'</option>
                            </select>
                            <div class="form-text">
                                <strong>Global System Setting:</strong> Determines how START_GAME messages affect match status across all fixtures.
                                <br><small class="text-muted">This affects all users and all game sessions.</small>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Global Betting Mode</button>
                    </form>
                    <div id="betting-mode-status" class="mt-3"></div>
                </div>
            </div>
            
            <!-- Currency Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-money-bill-wave"></i> Currency Settings</h5>
                    <small class="text-muted">Configure currency symbol for betting pages and thermal receipts</small>
                </div>
                <div class="card-body">
                    <form id="currency-config-form">
                        <div class="mb-3">
                            <label for="currency-symbol" class="form-label">Currency Symbol</label>
                            <select class="form-select" id="currency-symbol">
                                <option value="USh">USh - Ugandan Shilling</option>
                                <option value="$">$ - US Dollar</option>
                                <option value="€">€ - Euro</option>
                                <option value="£">£ - British Pound</option>
                                <option value="¥">¥ - Japanese Yen</option>
                                <option value="₹">₹ - Indian Rupee</option>
                                <option value="R">R - South African Rand</option>
                                <option value="KSh">KSh - Kenyan Shilling</option>
                                <option value="TSh">TSh - Tanzanian Shilling</option>
                                <option value="₦">₦ - Nigerian Naira</option>
                                <option value="₵">₵ - Ghanaian Cedi</option>
                                <option value="Custom" id="custom-option">Custom Symbol</option>
                            </select>
                            <div class="form-text">Choose the currency symbol to display in betting pages and thermal receipts</div>
                        </div>
                        
                        <div class="mb-3" id="custom-symbol-input" style="display: none;">
                            <label for="custom-currency-symbol" class="form-label">Custom Currency Symbol</label>
                            <input type="text" class="form-control" id="custom-currency-symbol"
                                   placeholder="Enter custom symbol (e.g., Br, ₡, ₸)" maxlength="5">
                            <div class="form-text">Enter a custom currency symbol (maximum 5 characters)</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="currency-position" class="form-label">Currency Position</label>
                            <select class="form-select" id="currency-position">
                                <option value="before">Before Amount (USh 100.00)</option>
                                <option value="after">After Amount (100.00 USh)</option>
                            </select>
                            <div class="form-text">Choose where to display the currency symbol relative to the amount</div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Preview</label>
                            <div class="form-control-plaintext">
                                <span class="badge bg-light text-dark fs-6" id="currency-preview">USh 150.50</span>
                            </div>
                            <div class="form-text">This is how amounts will appear in the application</div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Save Currency Settings</button>
                    </form>
                    <div id="currency-status" class="mt-3"></div>
                </div>
            </div>
            
            <!-- Barcode Settings -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5><i class="fas fa-barcode"></i> Barcode Settings</h5>
                    <small class="text-muted">Configure barcode generation for bet verification and thermal printing</small>
                </div>
                <div class="card-body">
                    <form id="barcode-config-form">
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="barcode-enabled"
                                   {% if config.barcode_enabled %}checked{% endif %}>
                            <label class="form-check-label" for="barcode-enabled">
                                Enable Barcode Generation
                            </label>
                            <div class="form-text">Generate barcodes alongside QR codes for bet verification</div>
                        </div>
                        
                        <div class="mb-3" id="barcode-standard-group">
                            <label for="barcode-standard" class="form-label">Barcode Standard</label>
                            <select class="form-select" id="barcode-standard">
                                <option value="none" {% if config.barcode_standard == 'none' or not config.barcode_standard %}selected{% endif %}>No Barcode</option>
                                <option value="code128" {% if config.barcode_standard == 'code128' %}selected{% endif %}>Code 128 (Most common)</option>
                                <option value="code39" {% if config.barcode_standard == 'code39' %}selected{% endif %}>Code 39 (Legacy systems)</option>
                                <option value="ean13" {% if config.barcode_standard == 'ean13' %}selected{% endif %}>EAN-13 (European retail)</option>
                                <option value="ean8" {% if config.barcode_standard == 'ean8' %}selected{% endif %}>EAN-8 (Short retail)</option>
                                <option value="upca" {% if config.barcode_standard == 'upca' %}selected{% endif %}>UPC-A (US retail)</option>
                                <option value="upce" {% if config.barcode_standard == 'upce' %}selected{% endif %}>UPC-E (US compact)</option>
                                <option value="codabar" {% if config.barcode_standard == 'codabar' %}selected{% endif %}>Codabar (Libraries)</option>
                                <option value="itf" {% if config.barcode_standard == 'itf' %}selected{% endif %}>ITF (Industrial)</option>
                            </select>
                            <div class="form-text">Choose barcode standard compatible with your scanners</div>
                        </div>
                        
                        <div class="row" id="barcode-size-group">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="barcode-width" class="form-label">Barcode Width (px)</label>
                                    <input type="number" class="form-control" id="barcode-width"
                                           value="{{ config.barcode_width or 200 }}" min="100" max="800">
                                    <div class="form-text">Image width in pixels (100-800)</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="barcode-height" class="form-label">Barcode Height (px)</label>
                                    <input type="number" class="form-control" id="barcode-height"
                                           value="{{ config.barcode_height or 100 }}" min="50" max="300">
                                    <div class="form-text">Image height in pixels (50-300)</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row" id="barcode-options-group">
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="barcode-show-thermal"
                                           {% if config.barcode_show_on_thermal %}checked{% endif %}>
                                    <label class="form-check-label" for="barcode-show-thermal">
                                        Show on Thermal Receipts
                                    </label>
                                    <div class="form-text">Include barcode on printed betting receipts</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="barcode-show-verification"
                                           {% if config.barcode_show_on_verification %}checked{% endif %}>
                                    <label class="form-check-label" for="barcode-show-verification">
                                        Show on Verification Page
                                    </label>
                                    <div class="form-text">Display barcode on bet verification page</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3" id="barcode-preview-group" style="display: none;">
                            <label class="form-label">Barcode Preview</label>
                            <div class="border rounded p-3 bg-light text-center">
                                <div id="barcode-preview-container">
                                    <small class="text-muted">Preview will appear here when barcode is enabled</small>
                                </div>
                                <small class="text-muted d-block mt-2">Sample barcode with bet ID format</small>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Save Barcode Settings</button>
                    </form>
                    <div id="barcode-status" class="mt-3"></div>
                </div>
            </div>
            
            <!-- API Client Debug Section -->
            <div class="card mb-5">
                <div class="card-header">
                    <h5><i class="fas fa-bug me-2"></i>API Client Debug</h5>
                    <small class="text-muted">Test and monitor API client functionality</small>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <button type="button" class="btn btn-info" id="check-api-status">
                            <i class="fas fa-search me-1"></i>Check API Client Status
                        </button>
                        <button type="button" class="btn btn-warning ms-2" id="trigger-api-request">
                            <i class="fas fa-play me-1"></i>Trigger Manual Request
                        </button>
                    </div>
                    <div id="api-status-result" class="mt-3" style="max-height: 400px; overflow-y: auto;"></div>
                </div>
            </div>
            
            <!-- Add bottom padding for better visibility -->
            <div style="height: 100px;"></div>
        </div>
    </div>
</div>

<script>
    // Save general configuration
    document.getElementById('general-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            app_name: document.getElementById('app-name').value,
            log_level: document.getElementById('log-level').value,
            enable_qt: document.getElementById('enable-qt').checked
        };
        
        saveConfig('general', config);
    });
    
    // Save video configuration
    document.getElementById('video-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            video_width: parseInt(document.getElementById('video-width').value),
            video_height: parseInt(document.getElementById('video-height').value),
            fullscreen: document.getElementById('fullscreen').checked
        };
        
        saveConfig('video', config);
    });
    
    // Save database configuration
    document.getElementById('database-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            db_path: document.getElementById('db-path').value
        };
        
        saveConfig('database', config);
    });
    
    // Save API configuration
    document.getElementById('api-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            fastapi_url: document.getElementById('fastapi-url').value,
            api_token: document.getElementById('api-token').value,
            api_interval: parseInt(document.getElementById('api-interval').value),
            api_timeout: parseInt(document.getElementById('api-timeout').value),
            api_enabled: document.getElementById('api-enabled').checked
        };
        
        saveConfig('api', config);
    });
    
    // Save screen cast configuration
    document.getElementById('screen-cast-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const config = {
            enabled: document.getElementById('screen-cast-enabled').checked,
            stream_port: parseInt(document.getElementById('screen-cast-port').value),
            chromecast_name: document.getElementById('chromecast-name').value,
            resolution: document.getElementById('screen-cast-resolution').value,
            framerate: parseInt(document.getElementById('screen-cast-framerate').value),
            auto_start_capture: document.getElementById('screen-cast-auto-start-capture').checked,
            auto_start_streaming: document.getElementById('screen-cast-auto-start-streaming').checked
        };
        
        saveConfig('screen_cast', config);
    });
    
    // Test API connection
    document.getElementById('test-api-connection').addEventListener('click', function() {
        const url = document.getElementById('fastapi-url').value;
        const token = document.getElementById('api-token').value;
        
        if (!url) {
            alert('Please enter a FastAPI URL first');
            return;
        }
        
        this.disabled = true;
        this.textContent = 'Testing...';
        
        fetch('/api/config/test-connection', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                url: url,
                token: token
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Connection successful! Response: ' + (data.message || 'OK'));
            } else {
                alert('Connection failed: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Connection test failed: ' + error.message);
        })
        .finally(() => {
            this.disabled = false;
            this.textContent = 'Test Connection';
        });
    });
    
    // Generic config save function
    function saveConfig(section, config) {
        fetch('/api/config/' + section, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(config)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(section.charAt(0).toUpperCase() + section.slice(1) + ' configuration saved successfully');
            } else {
                alert('Failed to save ' + section + ' configuration: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to save ' + section + ' configuration');
        });
    }
    
    // Check API client status
    document.getElementById('check-api-status').addEventListener('click', function() {
        this.disabled = true;
        this.textContent = 'Checking...';
        
        fetch('/api/api-client/status')
        .then(response => response.json())
        .then(data => {
            const resultDiv = document.getElementById('api-status-result');
            
            if (data.success) {
                const status = data.status;
                let html = '<div class="alert alert-info"><strong>API Client Status:</strong><br>';
                html += '<strong>Message Bus:</strong> ' + (status.message_bus_available ? 'Available' : 'Not Available') + '<br>';
                html += '<strong>Config Manager:</strong> ' + (status.config_manager_available ? 'Available' : 'Not Available') + '<br>';
                
                if (status.api_config) {
                    html += '<strong>API Configuration:</strong><br>';
                    html += '&nbsp;&nbsp;URL: ' + (status.api_config.fastapi_url || 'Not set') + '<br>';
                    html += '&nbsp;&nbsp;Token: ' + (status.api_config.api_token_set ? 'Set' : 'Not set') + '<br>';
                    html += '&nbsp;&nbsp;Interval: ' + status.api_config.api_interval + ' seconds<br>';
                    html += '&nbsp;&nbsp;Enabled: ' + status.api_config.api_enabled + '<br>';
                }
                
                if (status.fastapi_endpoint && Object.keys(status.fastapi_endpoint).length > 0) {
                    const ep = status.fastapi_endpoint;
                    html += '<strong>FastAPI Endpoint:</strong><br>';
                    html += '&nbsp;&nbsp;URL: ' + (ep.url || 'Not set') + '<br>';
                    html += '&nbsp;&nbsp;Enabled: ' + ep.enabled + '<br>';
                    html += '&nbsp;&nbsp;Interval: ' + ep.interval + ' seconds<br>';
                    html += '&nbsp;&nbsp;Auth Configured: ' + ep.auth_configured + '<br>';
                    html += '&nbsp;&nbsp;Total Requests: ' + ep.total_requests + '<br>';
                    html += '&nbsp;&nbsp;Consecutive Failures: ' + ep.consecutive_failures + '<br>';
                    html += '&nbsp;&nbsp;Last Request: ' + (ep.last_request || 'Never') + '<br>';
                    html += '&nbsp;&nbsp;Last Success: ' + (ep.last_success || 'Never') + '<br>';
                } else {
                    html += '<strong>FastAPI Endpoint:</strong> Not configured<br>';
                }
                
                html += '</div>';
                resultDiv.innerHTML = html;
            } else {
                resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            document.getElementById('api-status-result').innerHTML =
                '<div class="alert alert-danger">Error checking status: ' + error.message + '</div>';
        })
        .finally(() => {
            this.disabled = false;
            this.textContent = 'Check API Client Status';
        });
    });
    
    // Trigger manual API request
    document.getElementById('trigger-api-request').addEventListener('click', function() {
        this.disabled = true;
        this.textContent = 'Triggering...';
        
        fetch('/api/api-client/trigger', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({endpoint: 'fastapi_main'})
        })
        .then(response => response.json())
        .then(data => {
            const resultDiv = document.getElementById('api-status-result');
            
            if (data.success) {
                resultDiv.innerHTML = '<div class="alert alert-success">' + data.message + '</div>';
            } else {
                resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            document.getElementById('api-status-result').innerHTML =
                '<div class="alert alert-danger">Error triggering request: ' + error.message + '</div>';
        })
        .finally(() => {
            this.disabled = false;
            this.textContent = 'Trigger Manual Request';
        });
    });
    
    // Load current global betting mode and currency settings on page load
    document.addEventListener('DOMContentLoaded', function() {
        loadBettingMode();
        loadCurrencySettings();
        setupCurrencyHandlers();
        loadBarcodeSettings();
        setupBarcodeHandlers();
    });
    
    // Load global betting mode configuration
    function loadBettingMode() {
        fetch('/api/betting-mode')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('betting-mode').value = data.betting_mode || 'all_bets_on_start';
                // Don't show any status on page load - only after user saves
            } else {
                console.error('Failed to load betting mode:', data.error);
                document.getElementById('betting-mode-status').innerHTML =
                    '<div class="alert alert-warning"><small><i class="fas fa-exclamation-triangle"></i> Could not load current betting mode</small></div>';
            }
        })
        .catch(error => {
            console.error('Error loading betting mode:', error);
            document.getElementById('betting-mode-status').innerHTML =
                '<div class="alert alert-warning"><small><i class="fas fa-exclamation-triangle"></i> Error loading betting mode</small></div>';
        });
    }
    
    // Save global betting mode configuration
    document.getElementById('betting-mode-config-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const bettingMode = document.getElementById('betting-mode').value;
        const statusDiv = document.getElementById('betting-mode-status');
        
        // Clear previous status
        statusDiv.innerHTML = '';
        
        // Save global betting mode
        fetch('/api/betting-mode', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                betting_mode: bettingMode
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                statusDiv.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' + data.message + '<br><small>This setting affects all users and game sessions.</small></div>';
                
                // Auto-hide success message after 5 seconds
                setTimeout(() => {
                    statusDiv.innerHTML = '<div class="alert alert-success"><small><i class="fas fa-check-circle"></i> Global betting mode configured</small></div>';
                }, 5000);
            } else {
                statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Failed to save global betting mode: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            console.error('Error saving betting mode:', error);
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Error saving global betting mode: ' + error.message + '</div>';
        });
    });
    
    // Currency settings handlers
    function setupCurrencyHandlers() {
        const symbolSelect = document.getElementById('currency-symbol');
        const customInput = document.getElementById('custom-symbol-input');
        const customSymbol = document.getElementById('custom-currency-symbol');
        const positionSelect = document.getElementById('currency-position');
        const preview = document.getElementById('currency-preview');
        
        // Handle currency symbol change
        symbolSelect.addEventListener('change', function() {
            if (this.value === 'Custom') {
                customInput.style.display = 'block';
                customSymbol.required = true;
            } else {
                customInput.style.display = 'none';
                customSymbol.required = false;
            }
            updateCurrencyPreview();
        });
        
        // Handle custom symbol input
        customSymbol.addEventListener('input', updateCurrencyPreview);
        
        // Handle position change
        positionSelect.addEventListener('change', updateCurrencyPreview);
        
        // Handle form submission
        document.getElementById('currency-config-form').addEventListener('submit', function(e) {
            e.preventDefault();
            saveCurrencySettings();
        });
    }
    
    function updateCurrencyPreview() {
        const symbolSelect = document.getElementById('currency-symbol');
        const customSymbol = document.getElementById('custom-currency-symbol');
        const positionSelect = document.getElementById('currency-position');
        const preview = document.getElementById('currency-preview');
        
        let symbol = symbolSelect.value;
        if (symbol === 'Custom') {
            symbol = customSymbol.value || 'SYM';
        }
        
        const amount = '150.50';
        const position = positionSelect.value;
        
        if (position === 'before') {
            preview.textContent = `${symbol} ${amount}`;
        } else {
            preview.textContent = `${amount} ${symbol}`;
        }
    }
    
    function loadCurrencySettings() {
        fetch('/api/currency-settings')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const settings = data.settings;
                const symbolSelect = document.getElementById('currency-symbol');
                const customInput = document.getElementById('custom-symbol-input');
                const customSymbol = document.getElementById('custom-currency-symbol');
                const positionSelect = document.getElementById('currency-position');
                
                // Set currency symbol
                if (settings.symbol && !Array.from(symbolSelect.options).some(opt => opt.value === settings.symbol)) {
                    // Custom symbol
                    symbolSelect.value = 'Custom';
                    customSymbol.value = settings.symbol;
                    customInput.style.display = 'block';
                } else {
                    symbolSelect.value = settings.symbol || 'USh';
                }
                
                // Set position
                positionSelect.value = settings.position || 'before';
                
                // Update preview
                updateCurrencyPreview();
                
                // Only show status if non-default settings are loaded
                if (settings.symbol && settings.symbol !== 'USh') {
                    document.getElementById('currency-status').innerHTML =
                        '<div class="alert alert-success"><small><i class="fas fa-check-circle"></i> Custom currency settings loaded</small></div>';
                }
            } else {
                // Use defaults
                document.getElementById('currency-symbol').value = 'USh';
                document.getElementById('currency-position').value = 'before';
                updateCurrencyPreview();
                
                document.getElementById('currency-status').innerHTML =
                    '<div class="alert alert-info"><small><i class="fas fa-info-circle"></i> Using default currency settings (Ugandan Shilling)</small></div>';
            }
        })
        .catch(error => {
            console.error('Error loading currency settings:', error);
            // Use defaults
            document.getElementById('currency-symbol').value = 'USh';
            document.getElementById('currency-position').value = 'before';
            updateCurrencyPreview();
            
            document.getElementById('currency-status').innerHTML =
                '<div class="alert alert-warning"><small><i class="fas fa-exclamation-triangle"></i> Error loading currency settings, using defaults</small></div>';
        });
    }
    
    function saveCurrencySettings() {
        const symbolSelect = document.getElementById('currency-symbol');
        const customSymbol = document.getElementById('custom-currency-symbol');
        const positionSelect = document.getElementById('currency-position');
        const statusDiv = document.getElementById('currency-status');
        
        let symbol = symbolSelect.value;
        if (symbol === 'Custom') {
            symbol = customSymbol.value.trim();
            if (!symbol) {
                statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Please enter a custom currency symbol</div>';
                return;
            }
        }
        
        const settings = {
            symbol: symbol,
            position: positionSelect.value
        };
        
        statusDiv.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin"></i> Saving currency settings...</div>';
        
        fetch('/api/currency-settings', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(settings)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                statusDiv.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' + data.message + '</div>';
                
                // Auto-hide success message after 3 seconds
                setTimeout(() => {
                    statusDiv.innerHTML = '<div class="alert alert-success"><small><i class="fas fa-check-circle"></i> Currency settings saved</small></div>';
                }, 3000);
            } else {
                statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Failed to save currency settings: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            console.error('Error saving currency settings:', error);
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Error saving currency settings: ' + error.message + '</div>';
        });
    }
    
    // Barcode settings handlers
    function setupBarcodeHandlers() {
        const enabledCheckbox = document.getElementById('barcode-enabled');
        const standardSelect = document.getElementById('barcode-standard');
        const widthInput = document.getElementById('barcode-width');
        const heightInput = document.getElementById('barcode-height');
        const thermalCheckbox = document.getElementById('barcode-show-thermal');
        const verificationCheckbox = document.getElementById('barcode-show-verification');
        const previewGroup = document.getElementById('barcode-preview-group');
        
        // Handle barcode enabled/disabled state
        function updateBarcodeControls() {
            const enabled = enabledCheckbox.checked;
            const isNoneSelected = standardSelect.value === 'none';
            const shouldShow = enabled && !isNoneSelected;
            
            // Show/hide preview
            previewGroup.style.display = shouldShow ? 'block' : 'none';
            
            // Enable/disable controls
            standardSelect.disabled = !enabled;
            widthInput.disabled = !shouldShow;
            heightInput.disabled = !shouldShow;
            thermalCheckbox.disabled = !shouldShow;
            verificationCheckbox.disabled = !shouldShow;
            
            if (shouldShow) {
                updateBarcodePreview();
            }
        }
        
        // Update barcode preview
        function updateBarcodePreview() {
            const container = document.getElementById('barcode-preview-container');
            const standard = standardSelect.value;
            const width = widthInput.value;
            const height = heightInput.value;
            
            if (standard === 'none' || !enabledCheckbox.checked) {
                container.innerHTML = '<small class="text-muted">Preview will appear here when barcode is enabled</small>';
                return;
            }
            
            // Create sample barcode preview using actual barcode generation
            const sampleId = '12345678-ABCD-EF12-3456-7890ABCDEF12';
            container.innerHTML = `
                <div style="border: 1px solid #ddd; padding: 10px; background: white; display: inline-block; text-align: center;">
                    <div id="barcode-preview-img" style="width: ${Math.min(width, 300)}px; height: ${Math.min(height, 80)}px; display: flex; align-items: center; justify-content: center; background: #f8f9fa;">
                        <small style="color: #666;">Generating ${standard.toUpperCase()} barcode...</small>
                    </div>
                    <small class="d-block mt-1" style="word-break: break-all; font-family: monospace;">${sampleId.substring(0, 8)}...</small>
                </div>
            `;
            
            // Generate actual barcode preview
            generateBarcodePreview(sampleId, standard, width, height);
        }
        
        // Event listeners
        enabledCheckbox.addEventListener('change', updateBarcodeControls);
        standardSelect.addEventListener('change', updateBarcodeControls);
        widthInput.addEventListener('input', updateBarcodePreview);
        heightInput.addEventListener('input', updateBarcodePreview);
        
        // Handle form submission
        document.getElementById('barcode-config-form').addEventListener('submit', function(e) {
            e.preventDefault();
            saveBarcodeSettings();
        });
        
        // Initial setup
        updateBarcodeControls();
    }
    
    // Generate actual barcode preview
    function generateBarcodePreview(betUuid, standard, width, height) {
        // Format the UUID for the specific barcode standard
        let barcodeData = betUuid.replace(/-/g, '').substring(0, 16);
        
        // For numeric standards, create a numeric representation
        if (['ean13', 'ean8', 'upca', 'upce', 'itf', 'codabar'].includes(standard)) {
            // Create a hash-based numeric representation
            const numericHash = Math.abs(hashCode(betUuid)).toString();
            if (standard === 'ean13') {
                barcodeData = numericHash.substring(0, 12).padStart(12, '0');
            } else if (standard === 'ean8') {
                barcodeData = numericHash.substring(0, 7).padStart(7, '0');
            } else if (standard === 'upca') {
                barcodeData = numericHash.substring(0, 11).padStart(11, '0');
            } else if (standard === 'upce') {
                barcodeData = numericHash.substring(0, 7).padStart(7, '0');
            } else if (standard === 'itf') {
                // ITF needs even number of digits
                const evenDigits = numericHash.substring(0, 16).padStart(16, '0');
                barcodeData = evenDigits;
            } else if (standard === 'codabar') {
                barcodeData = 'A' + numericHash.substring(0, 14) + 'A';
            }
        }
        
        // Create a simple visual representation of what the barcode would look like
        const previewContainer = document.getElementById('barcode-preview-img');
        if (previewContainer) {
            // Create barcode-like visual using CSS
            const barCount = Math.min(30, barcodeData.length * 2);
            let barcodeHtml = '<div style="display: flex; height: 100%; align-items: center; justify-content: center;">';
            barcodeHtml += '<div style="display: flex; height: 70%; align-items: center;">';
            
            for (let i = 0; i < barCount; i++) {
                // Alternate bar widths to simulate barcode pattern
                const barWidth = 1 + (i % 4);
                const isBlack = i % 2 === 0;
                barcodeHtml += `<div style="width: ${barWidth}px; height: 100%; background: ${isBlack ? '#000' : '#fff'}; margin: 0 0.5px;"></div>`;
            }
            
            barcodeHtml += '</div></div>';
            previewContainer.innerHTML = barcodeHtml;
        }
    }
    
    // Simple hash function for creating numeric representations
    function hashCode(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32-bit integer
        }
        return hash;
    }
    
    function loadBarcodeSettings() {
        fetch('/api/barcode-settings')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const settings = data.settings;
                
                document.getElementById('barcode-enabled').checked = settings.enabled || false;
                document.getElementById('barcode-standard').value = settings.standard || 'none';
                document.getElementById('barcode-width').value = settings.width || 200;
                document.getElementById('barcode-height').value = settings.height || 100;
                document.getElementById('barcode-show-thermal').checked = settings.show_on_thermal !== false;
                document.getElementById('barcode-show-verification').checked = settings.show_on_verification !== false;
                
                // Force update controls after loading settings
                setTimeout(() => {
                    const event = new Event('change');
                    document.getElementById('barcode-enabled').dispatchEvent(event);
                }, 100);
                
                // Don't show any status on page load - only after user saves settings
            } else {
                // Use defaults
                document.getElementById('barcode-enabled').checked = false;
                document.getElementById('barcode-standard').value = 'none';
                document.getElementById('barcode-width').value = 200;
                document.getElementById('barcode-height').value = 100;
                document.getElementById('barcode-show-thermal').checked = true;
                document.getElementById('barcode-show-verification').checked = true;
                
                document.getElementById('barcode-status').innerHTML =
                    '<div class="alert alert-info"><small><i class="fas fa-info-circle"></i> Using default barcode settings</small></div>';
            }
        })
        .catch(error => {
            console.error('Error loading barcode settings:', error);
            // Use defaults
            document.getElementById('barcode-enabled').checked = false;
            document.getElementById('barcode-standard').value = 'none';
            document.getElementById('barcode-width').value = 200;
            document.getElementById('barcode-height').value = 100;
            document.getElementById('barcode-show-thermal').checked = true;
            document.getElementById('barcode-show-verification').checked = true;
            
            document.getElementById('barcode-status').innerHTML =
                '<div class="alert alert-warning"><small><i class="fas fa-exclamation-triangle"></i> Error loading barcode settings, using defaults</small></div>';
        });
    }
    
    function saveBarcodeSettings() {
        const statusDiv = document.getElementById('barcode-status');
        
        const settings = {
            enabled: document.getElementById('barcode-enabled').checked,
            standard: document.getElementById('barcode-standard').value,
            width: parseInt(document.getElementById('barcode-width').value),
            height: parseInt(document.getElementById('barcode-height').value),
            show_on_thermal: document.getElementById('barcode-show-thermal').checked,
            show_on_verification: document.getElementById('barcode-show-verification').checked
        };
        
        // Validation
        if (settings.enabled && settings.standard === 'none') {
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Please select a barcode standard when barcode is enabled</div>';
            return;
        }
        
        if (settings.width < 100 || settings.width > 800) {
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Barcode width must be between 100 and 800 pixels</div>';
            return;
        }
        
        if (settings.height < 50 || settings.height > 300) {
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Barcode height must be between 50 and 300 pixels</div>';
            return;
        }
        
        statusDiv.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin"></i> Saving barcode settings...</div>';
        
        fetch('/api/barcode-settings', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(settings)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                statusDiv.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' + data.message + '</div>';
                
                // Auto-hide success message after 3 seconds
                setTimeout(() => {
                    statusDiv.innerHTML = '<div class="alert alert-success"><small><i class="fas fa-check-circle"></i> Barcode settings saved</small></div>';
                }, 3000);
            } else {
                statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Failed to save barcode settings: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            console.error('Error saving barcode settings:', error);
            statusDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> Error saving barcode settings: ' + error.message + '</div>';
        });
    }
</script>
{% endblock %}