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

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

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

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

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

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

    {% 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">
                <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 == 'main.video_control_page' %}active{% endif %}"
                           href="{{ url_for('main.video_control_page') }}">
                            <i class="fas fa-video me-1"></i>Video Control
                        </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.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>

                <!-- Digital Clock -->
                <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>
    </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 from CDN and local -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="{{ url_for('static', filename='js/dashboard.js') }}"></script>
    
    {% 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 serverTimeOffset = 0; // Offset between server and client time
            let lastServerTime = null;

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

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

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

                clockElement.textContent = timeString;
            }

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

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

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

        function 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;
                    default:
                        console.log('Unknown notification type:', type);
                }

                // Show notification to user
                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 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';
                }

                // 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)}`;
                }

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

            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>