<!DOCTYPE html>
<html lang="en">
<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 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <noscript>
        <link rel="stylesheet" href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}">
    </noscript>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <noscript>
        <link rel="stylesheet" href="{{ url_for('static', filename='vendor/fontawesome/all.min.css') }}">
    </noscript>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/dashboard.css') }}">
    
    <style>
        .navbar-clock {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            padding: 8px 16px;
            font-family: 'Courier New', monospace;
            font-weight: bold;
            font-size: 1.2rem;
            color: #ffffff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

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

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

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

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

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

    {% 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'] %}
                <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>Dashboard
                        </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.video_test' %}active{% endif %}"
                           href="{{ url_for('main.video_test') }}">
                            <i class="fas fa-upload me-1"></i>Video Test
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'screen_cast.screen_cast_dashboard' %}active{% endif %}"
                           href="{{ url_for('screen_cast.screen_cast_dashboard') }}">
                            <i class="fas fa-cast me-1"></i>Screen Cast
                        </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>
                    {% 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><a class="dropdown-item" href="{{ url_for('main.logs') }}">
                                <i class="fas fa-file-alt me-1"></i>Logs
                            </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>
                </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">
            <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 id="dashboard-config" type="application/json">
        {
            "statusUpdateInterval": 30000,
            "apiEndpoint": "/api",
            "user": {
                "id": {{ current_user.id | tojson }},
                "username": {{ current_user.username | tojson }},
                "is_admin": {{ current_user.is_admin | tojson }}
            }
        }
    </script>
    <script>
        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof Dashboard !== 'undefined') {
                var config = JSON.parse(document.getElementById('dashboard-config').textContent);
                Dashboard.init(config);
            }

            // Initialize digital clock
            initializeClock();

            // Initialize long polling for notifications
            initializeNotifications();
        });

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

            let serverTimeBase = null;
            let serverTimeStartLocal = null;

            function fetchServerTime() {
                return fetch('/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);
            });
        }

        function initializeNotifications() {
            let pollingActive = true;
            let reconnectDelay = 1000; // Start with 1 second delay
            const maxReconnectDelay = 30000; // Max 30 seconds

            function pollNotifications() {
                if (!pollingActive) return;

                fetch('/api/notifications?timeout=30', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'same-origin'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success && data.notification) {
                        handleNotification(data.notification);
                    }
                    // Reset reconnect delay on successful response
                    reconnectDelay = 1000;
                    // Continue polling
                    setTimeout(pollNotifications, 100);
                })
                .catch(error => {
                    console.error('Notification polling error:', error);
                    // Exponential backoff for reconnection
                    reconnectDelay = Math.min(reconnectDelay * 2, maxReconnectDelay);
                    console.log(`Reconnecting in ${reconnectDelay}ms...`);
                    setTimeout(pollNotifications, reconnectDelay);
                });
            }

            function handleNotification(notification) {
                console.log('Received notification:', notification);

                const { type, data, timestamp } = notification;

                // Handle different notification types
                switch (type) {
                    case 'START_GAME':
                        handleStartGame(data, timestamp);
                        break;
                    case 'MATCH_START':
                        handleMatchStart(data, timestamp);
                        break;
                    case 'GAME_STATUS':
                        handleGameStatus(data, timestamp);
                        break;
                    case 'TIMER_UPDATE':
                        handleTimerUpdate(data, timestamp);
                        break;
                    case 'FIXTURE_STATUS_UPDATE':
                        handleFixtureStatusUpdate(data, timestamp);
                        break;
                    default:
                        console.log('Unknown notification type:', type);
                }

                // Show notification to user (except for timer and fixture status updates)
                if (type !== 'TIMER_UPDATE' && type !== 'FIXTURE_STATUS_UPDATE') {
                    showNotificationToast(type, data);
                }
            }

            function handleStartGame(data, timestamp) {
                console.log('Handling START_GAME notification:', data);

                // Update match timer display
                const matchTimerElement = document.getElementById('match-timer');
                if (matchTimerElement) {
                    matchTimerElement.textContent = 'Starting...';
                    matchTimerElement.className = 'badge bg-success';
                }

                // Trigger timer initialization in Dashboard.js if available
                if (typeof Dashboard !== 'undefined' && Dashboard.onStartGameMessage) {
                    Dashboard.onStartGameMessage();
                }

                // Trigger custom event for page-specific handling
                const event = new CustomEvent('startGame', {
                    detail: { data, timestamp }
                });
                document.dispatchEvent(event);
            }

            function handleMatchStart(data, timestamp) {
                console.log('Handling MATCH_START notification:', data);

                // Reset and restart timer
                const matchTimerElement = document.getElementById('match-timer');
                if (matchTimerElement) {
                    matchTimerElement.textContent = '00:00';
                    matchTimerElement.className = 'badge bg-primary';
                }

                // Force sync with match timer component
                if (typeof Dashboard !== 'undefined' && Dashboard.syncWithServerTimer) {
                    Dashboard.syncWithServerTimer();
                }

                // Trigger custom event for page-specific handling
                const event = new CustomEvent('matchStart', {
                    detail: { data, timestamp }
                });
                document.dispatchEvent(event);
            }

            function handleGameStatus(data, timestamp) {
                console.log('Handling GAME_STATUS notification:', data);

                // Update status displays
                const status = data.status;
                const fixtureId = data.fixture_id;

                // Update status bar if present
                const systemStatusElement = document.getElementById('system-status');
                if (systemStatusElement) {
                    systemStatusElement.textContent = status;
                    systemStatusElement.className = `badge bg-${getStatusColor(status)}`;
                }

                // If this is a timer-related status, sync with timer
                if (status === 'started' && data.action === 'refresh') {
                    if (typeof Dashboard !== 'undefined' && Dashboard.syncWithServerTimer) {
                        Dashboard.syncWithServerTimer();
                    }
                }

                // Trigger custom event for page-specific handling
                const event = new CustomEvent('gameStatus', {
                    detail: { data, timestamp }
                });
                document.dispatchEvent(event);
            }

            function handleTimerUpdate(data, timestamp) {
                console.log('Handling TIMER_UPDATE notification:', data);

                // Update timer displays directly from server data ONLY
                if (data.running !== undefined && data.remaining_seconds !== undefined) {
                    // Clear any existing client-side timers
                    if (window.clientTimerInterval) {
                        clearInterval(window.clientTimerInterval);
                        window.clientTimerInterval = null;
                    }
                    
                    // Update all timer elements with server data
                    updateTimerElements(data.remaining_seconds, data.running);
                    
                    // Store server data for potential interpolation
                    window.lastServerUpdate = {
                        remaining_seconds: data.remaining_seconds,
                        timestamp: Date.now(),
                        running: data.running
                    };
                    
                    // Update timer status text
                    const timerStatus = document.getElementById('timer-status');
                    if (timerStatus) {
                        if (data.running) {
                            timerStatus.textContent = 'Timer running';
                            timerStatus.className = 'text-success';
                        } else {
                            timerStatus.textContent = 'Waiting for games to start...';
                            timerStatus.className = 'text-muted';
                        }
                    }

                    // Trigger custom event for page-specific handling
                    const event = new CustomEvent('timerUpdate', {
                        detail: { data, timestamp }
                    });
                    document.dispatchEvent(event);
                }
            }

            function handleFixtureStatusUpdate(data, timestamp) {
                console.log('Handling FIXTURE_STATUS_UPDATE notification:', data);

                // Trigger automatic refresh if on fixtures page
                const currentPage = window.location.pathname;
                if (currentPage === '/fixtures' || currentPage.startsWith('/fixtures/')) {
                    // Check if loadFixtures function exists (fixtures page)
                    if (typeof loadFixtures === 'function') {
                        console.log('Auto-refreshing fixtures due to status update');
                        loadFixtures();
                    }
                    
                    // Check if loadFixtureDetails function exists (fixture details page)
                    if (typeof loadFixtureDetails === 'function') {
                        console.log('Auto-refreshing fixture details due to status update');
                        loadFixtureDetails();
                    }
                }

                // Trigger custom event for page-specific handling
                const event = new CustomEvent('fixtureStatusUpdate', {
                    detail: { data, timestamp }
                });
                document.dispatchEvent(event);
            }

            function updateTimerElements(seconds, isRunning) {
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;
                const timeString = minutes.toString().padStart(2, '0') + ':' + remainingSeconds.toString().padStart(2, '0');

                console.log(`Updating timer elements: ${timeString} (${seconds}s, running: ${isRunning})`);

                // Update status bar timer
                const statusTimer = document.getElementById('match-timer');
                if (statusTimer) {
                    statusTimer.textContent = timeString;

                    if (!isRunning) {
                        statusTimer.className = 'badge bg-warning text-dark';
                        statusTimer.style.animation = '';
                    } else if (seconds <= 60) { // Last minute
                        statusTimer.className = 'badge bg-danger text-white';
                        statusTimer.style.animation = 'timerPulse 0.5s infinite';
                    } else if (seconds <= 300) { // Last 5 minutes
                        statusTimer.className = 'badge bg-warning text-dark';
                        statusTimer.style.animation = '';
                    } else {
                        statusTimer.className = 'badge bg-success text-white';
                        statusTimer.style.animation = '';
                    }
                }

                // Update admin dashboard timer if present
                const adminTimer = document.getElementById('admin-match-timer');
                if (adminTimer) {
                    adminTimer.textContent = timeString;
                    if (isRunning) {
                        adminTimer.className = seconds <= 60 ? 'h3 mb-2 text-danger fw-bold' : 'h3 mb-2 text-success fw-bold';
                    } else {
                        adminTimer.className = 'h3 mb-2 text-muted';
                    }
                }
            }

            function showNotificationToast(type, data) {
                // Create and show a toast notification
                const toastHtml = `
                    <div class="toast align-items-center text-white bg-primary border-0" role="alert">
                        <div class="d-flex">
                            <div class="toast-body">
                                <i class="fas fa-bell me-2"></i>
                                <strong>${type.replace('_', ' ')}</strong>
                                ${data.fixture_id ? ` - Fixture ${data.fixture_id}` : ''}
                            </div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                        </div>
                    </div>
                `;

                // Add toast to container or create one
                let toastContainer = document.querySelector('.toast-container');
                if (!toastContainer) {
                    toastContainer = document.createElement('div');
                    toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
                    toastContainer.style.zIndex = '9999';
                    document.body.appendChild(toastContainer);
                }

                toastContainer.insertAdjacentHTML('beforeend', toastHtml);

                // Initialize and show the toast
                const toastElement = toastContainer.lastElementChild;
                const toast = new bootstrap.Toast(toastElement, {
                    autohide: true,
                    delay: 5000
                });
                toast.show();

                // Remove from DOM after hiding
                toastElement.addEventListener('hidden.bs.toast', () => {
                    toastElement.remove();
                });
            }

            function getStatusColor(status) {
                switch (status) {
                    case 'running': return 'success';
                    case 'scheduled': return 'warning';
                    case 'pending': return 'secondary';
                    case 'completed': return 'info';
                    case 'error': return 'danger';
                    default: return 'secondary';
                }
            }

            // Start polling
            console.log('Starting notification polling...');
            pollNotifications();

            // Stop polling when page unloads
            window.addEventListener('beforeunload', () => {
                pollingActive = false;
            });
        }
    </script>
    {% endif %}
    
    {% block scripts %}{% endblock %}
</body>
</html>