<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{{ page_title | default("Dashboard") }} - {{ app_name }}{% endblock %}</title>
    
    <!-- CSS with local fallback -->
    <link id="bootstrap-css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link id="fontawesome-css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">

    <script>
        // Check for CSS loading and load local fallbacks if CDN fails
        setTimeout(function() {
            // Check Bootstrap CSS
            var testEl = document.createElement('div');
            testEl.style.display = 'none';
            document.body.appendChild(testEl);
            var bsPrimary = getComputedStyle(testEl).getPropertyValue('--bs-primary');
            document.body.removeChild(testEl);

            if (!bsPrimary || bsPrimary.trim() === '') {
                console.log('Bootstrap CDN failed, loading local version');
                var bootstrapLink = document.createElement('link');
                bootstrapLink.rel = 'stylesheet';
                bootstrapLink.href = '{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}';
                document.head.appendChild(bootstrapLink);
            }

            // Check Font Awesome CSS
            var faTestEl = document.createElement('i');
            faTestEl.className = 'fa fa-test';
            faTestEl.style.display = 'none';
            document.body.appendChild(faTestEl);
            var faFontFamily = getComputedStyle(faTestEl).getPropertyValue('font-family');
            document.body.removeChild(faTestEl);

            if (!faFontFamily || !faFontFamily.includes('Font Awesome')) {
                console.log('Font Awesome CDN failed, loading local version');
                var faLink = document.createElement('link');
                faLink.rel = 'stylesheet';
                faLink.href = '{{ url_for('static', filename='vendor/fontawesome/all.min.css') }}';
                document.head.appendChild(faLink);
            }
        }, 2000); // Wait 2 seconds for CDN to load
    </script>
    
    <style>
        .navbar-clock {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            padding: 8px 16px;
            font-family: 'Courier New', monospace;
            font-weight: bold;
            font-size: 1.2rem;
            color: #ffffff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

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

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

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

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

            #clock-time {
                font-size: 1.1rem;
                letter-spacing: 1px;
            }
        }
    </style>

    {% block head %}{% endblock %}
</head>
<body>
    {% if current_user.is_authenticated %}
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="{{ url_for('main.index') }}">
                <i class="fas fa-play-circle me-2"></i>{{ app_name }}
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                {% if request.endpoint not in ['main.cashier_dashboard', 'main.cashier_bets', 'main.cashier_new_bet', 'main.cashier_bet_details', 'main.cashier_verify_bet_page', 'main.cashier_reports'] %}
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.index' %}active{% endif %}"
                           href="{{ url_for('main.index') }}">
                            <i class="fas fa-tachometer-alt me-1"></i>Home
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint in ['main.bets', 'main.new_bet', 'main.bet_details'] %}active{% endif %}"
                           href="{{ url_for('main.bets') }}">
                            <i class="fas fa-coins me-1"></i>Bets
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.templates' %}active{% endif %}"
                           href="{{ url_for('main.templates') }}">
                            <i class="fas fa-layer-group me-1"></i>Templates
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.fixtures' %}active{% endif %}"
                           href="{{ url_for('main.fixtures') }}">
                            <i class="fas fa-list-ul me-1"></i>Fixtures
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.extraction' %}active{% endif %}"
                           href="{{ url_for('main.extraction') }}">
                            <i class="fas fa-cogs me-1"></i>Extraction
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.api_tokens' %}active{% endif %}"
                           href="{{ url_for('main.api_tokens') }}">
                            <i class="fas fa-key me-1"></i>API Tokens
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.statistics' %}active{% endif %}"
                           href="{{ url_for('main.statistics') }}">
                            <i class="fas fa-chart-bar me-1"></i>Statistics
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.reports' %}active{% endif %}"
                           href="{{ url_for('main.reports') }}">
                            <i class="fas fa-file-alt me-1"></i>Reports
                        </a>
                    </li>
                    {% if current_user.is_admin %}
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-cog me-1"></i>Admin
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="{{ url_for('main.configuration') }}">
                                <i class="fas fa-sliders-h me-1"></i>Configuration
                            </a></li>
                            <li><a class="dropdown-item" href="{{ url_for('main.users') }}">
                                <i class="fas fa-users me-1"></i>User Management
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ url_for('main.oauth_providers') }}">
                                <i class="fas fa-key me-1"></i>OAuth Providers
                            </a></li>
                            <li><a class="dropdown-item" href="{{ url_for('main.billing') }}">
                                <i class="fas fa-credit-card me-1"></i>Billing Management
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ url_for('main.logs') }}">
                                <i class="fas fa-file-alt me-1"></i>Logs
                            </a></li>
                            <li><a class="dropdown-item" href="{{ url_for('screen_cast.screen_cast_dashboard') }}">
                                <i class="fas fa-cast me-1"></i>Screen Cast
                            </a></li>
                        </ul>
                    </li>
                    {% endif %}
                </ul>
                {% else %}
                <!-- Cashier Navigation -->
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.cashier_dashboard' %}active{% endif %}"
                           href="{{ url_for('main.cashier_dashboard') }}">
                            <i class="fas fa-tachometer-alt me-1"></i>Cashier Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint in ['main.cashier_bets', 'main.cashier_new_bet', 'main.cashier_bet_details'] %}active{% endif %}"
                           href="{{ url_for('main.cashier_bets') }}">
                            <i class="fas fa-coins me-1"></i>Bets
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.cashier_verify_bet' %}active{% endif %}"
                           href="{{ url_for('main.cashier_verify_bet_page') }}">
                            <i class="fas fa-qrcode me-1"></i>Verify Bet
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.cashier_reports' %}active{% endif %}"
                           href="{{ url_for('main.cashier_reports') }}">
                            <i class="fas fa-file-alt me-1"></i>Reports
                        </a>
                    </li>
                </ul>
                {% endif %}

                <!-- Digital Clock and User Menu positioned on the right -->
                <div class="ms-auto d-flex align-items-center">
                    <div class="d-flex align-items-center me-3">
                        <div id="digital-clock" class="navbar-clock">
                            <i class="fas fa-clock me-2"></i>
                            <span id="clock-time">--:--:--</span>
                        </div>
                    </div>
                    <ul class="navbar-nav">
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-user me-1"></i>{{ current_user.username }}
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="{{ url_for('auth.change_password') }}">
                                    <i class="fas fa-lock me-1"></i>Change Password
                                </a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="{{ url_for('auth.logout') }}">
                                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                                </a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>
    {% endif %}
    
    <main class="{% if current_user.is_authenticated %}container-fluid mt-4{% else %}container{% endif %}">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'danger' if category == 'error' else category }} alert-dismissible fade show" role="alert">
                        {% if category == 'error' %}
                            <i class="fas fa-exclamation-triangle me-2"></i>
                        {% elif category == 'success' %}
                            <i class="fas fa-check-circle me-2"></i>
                        {% elif category == 'info' %}
                            <i class="fas fa-info-circle me-2"></i>
                        {% endif %}
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}
        
        {% block content %}{% endblock %}
    </main>
    
    {% if current_user.is_authenticated %}
    <!-- System Status Bar -->
    <div id="status-bar" class="fixed-bottom bg-light border-top p-2 d-none d-lg-block">
        <div class="container-fluid">
            <!-- Download Progress Bar (hidden by default) -->
            <div id="download-progress-container" class="row mb-2 d-none">
                <div class="col-12">
                    <div class="d-flex align-items-center">
                        <span class="text-muted me-2">
                            <i class="fas fa-download me-1"></i>Downloading Fixtures:
                        </span>
                        <div class="progress flex-grow-1 me-2" style="height: 8px;">
                            <div id="download-progress-bar" class="progress-bar progress-bar-striped progress-bar-animated"
                                 role="progressbar" style="width: 0%"></div>
                        </div>
                        <small id="download-progress-text" class="text-muted">0%</small>
                    </div>
                </div>
            </div>
            <!-- Status Information -->
            <div class="row align-items-center text-small">
                <div class="col-auto">
                    <span class="text-muted">Status:</span>
                    <span id="system-status" class="badge bg-success">Online</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Video:</span>
                    <span id="video-status" class="badge bg-secondary">Stopped</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Match Timer:</span>
                    <span id="match-timer" class="badge bg-warning text-dark">--:--</span>
                </div>
                <div class="col-auto">
                    <span class="text-muted">Last Updated:</span>
                    <span id="last-updated" class="text-muted">--</span>
                </div>
                <div class="col text-end">
                    <small class="text-muted">{{ app_name }} v{{ app_version }}</small>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    
    <!-- JavaScript with local fallback -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Load local fallback if CDN fails
        if (typeof bootstrap === 'undefined') {
            document.write('<script src="{{ url_for("static", filename="vendor/bootstrap/js/bootstrap.bundle.min.js") }}"><\/script>');
        }
    </script>
    <script src="{{ url_for('static', filename='js/dashboard.js') }}"></script>
    
    {% if current_user.is_authenticated %}
    <script>
        // Global API base URL - respects proxy prefix
        window.API_BASE_URL = "{{ url_for('api.system_status') | replace('/api/status', '/api') }}";
        
        // Global base URL for page navigation - respects proxy prefix
        // Extract the base path from a known URL
        window.BASE_PATH = "{{ url_for('main.index') | replace('/', '') }}";
        if (window.BASE_PATH) {
            window.BASE_PATH = '/' + window.BASE_PATH;
        }
        
        // Helper function to build API URLs that respects proxy prefix
        window.apiUrl = function(endpoint) {
            // Remove leading slash if present
            var path = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
            // Ensure API_BASE_URL doesn't end with slash and path doesn't start with slash
            var baseUrl = window.API_BASE_URL.replace(/\/$/, '');
            return baseUrl + '/' + path;
        };
        
        // Helper function to build page URLs that respects proxy prefix
        // Use this for hardcoded page links like /fixtures/123, /matches/456, etc.
        window.pageUrl = function(path) {
            // If path already starts with the base path, return as-is
            if (window.BASE_PATH && path.startsWith(window.BASE_PATH)) {
                return path;
            }
            // Remove leading slash if present
            if (path.startsWith('/')) {
                path = path.substring(1);
            }
            // Prepend base path
            return window.BASE_PATH + '/' + path;
        };
        
        // Intercept fetch to automatically prepend proxy prefix to /api/ URLs
        // Only modify URLs that start with /api/ (hardcoded URLs)
        // Do NOT modify URLs generated by url_for() which already have the correct prefix
        (function() {
            var originalFetch = window.fetch;
            window.fetch = function(url, options) {
                // Only modify URLs that start EXACTLY with /api/ (hardcoded URLs)
                // Do NOT modify URLs like /mbetter/api/... which are already correct
                if (typeof url === 'string' && url.startsWith('/api/')) {
                    var path = url.replace('/api/', ''); // Remove '/api/' prefix
                    url = window.API_BASE_URL.replace(/\/$/, '') + '/' + path;
                }
                return originalFetch.call(this, url, options);
            };
        })();
    </script>
    <script id="dashboard-config" type="application/json">
        {
            "statusUpdateInterval": 30000,
            "apiEndpoint": {{ url_for('api.system_status') | replace('/api/status', '/api') | tojson }},
            "user": {
                "id": {{ current_user.id | tojson }},
                "username": {{ current_user.username | tojson }},
                "is_admin": {{ current_user.is_admin | tojson }}
            }
        }
    </script>
    <script>
        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof Dashboard !== 'undefined') {
                var config = JSON.parse(document.getElementById('dashboard-config').textContent);
                Dashboard.init(config);
            }

            // Initialize digital clock
            initializeClock();
        });

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

            let serverTimeBase = null;
            let serverTimeStartLocal = null;

            function fetchServerTime() {
                return fetch('{{ url_for("api.system_status") | replace("/api/status", "/api/server-time") }}')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.formatted_time) {
                            // Use the server's pre-formatted time string
                            serverTimeBase = data.formatted_time;
                            serverTimeStartLocal = Date.now();
                            return true;
                        } else {
                            throw new Error('Failed to get server time');
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching server time:', error);
                        // Use local time as fallback
                        serverTimeBase = null;
                        return false;
                    });
            }

            function updateClock() {
                if (serverTimeBase && serverTimeStartLocal) {
                    // Calculate elapsed seconds since server time fetch
                    const elapsedMs = Date.now() - serverTimeStartLocal;
                    const elapsedSeconds = Math.floor(elapsedMs / 1000);
                    
                    // Parse server time and add elapsed seconds
                    const [hours, minutes, seconds] = serverTimeBase.split(':').map(num => parseInt(num, 10));
                    const serverDateTime = new Date();
                    serverDateTime.setHours(hours, minutes, seconds + elapsedSeconds, 0);
                    
                    const displayHours = String(serverDateTime.getHours()).padStart(2, '0');
                    const displayMinutes = String(serverDateTime.getMinutes()).padStart(2, '0');
                    const displaySeconds = String(serverDateTime.getSeconds()).padStart(2, '0');
                    const timeString = `${displayHours}:${displayMinutes}:${displaySeconds}`;
                    
                    clockElement.textContent = timeString;
                } else {
                    // Fallback to local time
                    const now = new Date();
                    const hours = String(now.getHours()).padStart(2, '0');
                    const minutes = String(now.getMinutes()).padStart(2, '0');
                    const seconds = String(now.getSeconds()).padStart(2, '0');
                    const timeString = `${hours}:${minutes}:${seconds}`;
                    clockElement.textContent = timeString;
                }
            }

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

                // Update display every second
                setInterval(updateClock, 1000);

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

    </script>
    {% endif %}
    
    {% block scripts %}{% endblock %}
</body>
</html>