<!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.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();
        });

        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);
            });
        }
    </script>
    {% endif %}
    
    {% block scripts %}{% endblock %}
</body>
</html>