<!--
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}AISBF Dashboard{% endblock %}</title>
    <link rel="icon" type="image/png" href="/favicon.ico">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; background: #1a1a2e; color: #e0e0e0; }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        .header { background: #16213e; color: white; padding: 20px 0; margin-bottom: 30px; border-bottom: 2px solid #0f3460; }
        .header h1 { font-size: 24px; font-weight: 600; display: inline-block; }
        .header-actions { float: right; }
        .nav { background: #16213e; padding: 15px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.3); display: flex; flex-wrap: wrap; gap: 10px; }
        .nav a { color: #a0a0a0; text-decoration: none; padding: 8px 12px; border-radius: 4px; flex-shrink: 0; }
        .nav a:hover { background: #0f3460; color: #e0e0e0; }
        .nav a.active { background: #e94560; color: white; }
        .content { background: #16213e; padding: 30px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: 500; color: #e0e0e0; }
        .form-group input, .form-group textarea, .form-group select { width: 100%; padding: 10px; border: 1px solid #0f3460; border-radius: 4px; font-size: 14px; background: #1a1a2e; color: #e0e0e0; }
        .form-group textarea { min-height: 200px; font-family: 'Courier New', monospace; }
        .btn { padding: 10px 20px; background: #e94560; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; text-decoration: none; display: inline-block; margin-left: 10px; }
        .btn:hover { background: #c73e54; }
        .btn-secondary { background: #0f3460; }
        .btn-secondary:hover { background: #1a4a7a; }
        .btn-danger { background: #e74c3c; }
        .btn-danger:hover { background: #c0392b; }
        .btn-warning { background: #f39c12; }
        .btn-warning:hover { background: #e67e22; }
        .alert { padding: 15px; border-radius: 4px; margin-bottom: 20px; }
        .alert-success { background: #1a3a2e; color: #4ade80; border: 1px solid #22c55e; }
        .alert-error { background: #3a1a1a; color: #f87171; border: 1px solid #ef4444; }
        .alert-info { background: #1a2a3a; color: #60a5fa; border: 1px solid #3b82f6; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #0f3460; color: #e0e0e0; }
        th { background: #0f3460; font-weight: 600; color: #e0e0e0; }
        .code { background: #0f3460; padding: 15px; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 13px; overflow-x: auto; color: #e0e0e0; }
    </style>
    <script>
        /*
         * Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
         *
         * This program is free software: you can redistribute it and/or modify
         * it under the terms of the GNU General Public License as published by
         * the Free Software Foundation, either version 3 of the License, or
         * (at your option) any later version.
         *
         * This program is distributed in the hope that it will be useful,
         * but WITHOUT ANY WARRANTY; without even the implied warranty of
         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
         * GNU General Public License for more details.
         *
         * You should have received a copy of the GNU General Public License
         * along with this program.  If not, see <https://www.gnu.org/licenses/>.
         */
        function restartServer() {
            if (confirm('Are you sure you want to restart the server? This will disconnect all active connections.')) {
                fetch('{{ url_for(request, "/dashboard/restart") }}', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'}
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message + ' The page will reload in 5 seconds.');
                    setTimeout(() => window.location.reload(), 5000);
                })
                .catch(error => {
                    alert('Error restarting server: ' + error);
                });
            }
        }
        
        // Snake Game Easter Egg
        (function() {
            var keyHistory = [];
            var lastKeyTime = 0;
            var timeout = 10000; // 10 seconds window
            var sequence = ['ArrowUp', 'ArrowDown', 'ArrowUp'];
            var currentIndex = 0;
            
            document.addEventListener('keydown', function(e) {
                // Don't activate easter egg when typing in input fields
                var activeElement = document.activeElement;
                if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' || activeElement.tagName === 'SELECT')) {
                    return;
                }
                
                var now = Date.now();
                
                // Reset if too much time passed
                if (now - lastKeyTime > timeout) {
                    keyHistory = [];
                    currentIndex = 0;
                }
                lastKeyTime = now;
                
                // Only track ArrowUp and ArrowDown
                if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
                    keyHistory.push(e.key);
                    
                    // Check if current sequence matches target
                    if (keyHistory[currentIndex] === sequence[currentIndex]) {
                        currentIndex++;
                        if (currentIndex === sequence.length) {
                            // Sequence complete! Open the game
                            openSnakeGame();
                            keyHistory = [];
                            currentIndex = 0;
                        }
                    } else {
                        // Wrong key, reset
                        keyHistory = [];
                        currentIndex = 0;
                    }
                }
            });
            
            function openSnakeGame() {
                var gameHtml = `
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Snake Game - AISBF Easter Egg</title>
                    <style>
                        @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
                        * { box-sizing: border-box; margin: 0; padding: 0; }
                        html, body {
                            width: 100%; height: 100%;
                            background: #09080a;
                            font-family: 'Press Start 2P', cursive;
                            overflow: hidden;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                        }
                        #game-container {
                            position: relative;
                            display: flex;
                            flex-direction: column;
                            align-items: center;
                        }
                        #start-screen {
                            position: absolute;
                            background: #120d18;
                            padding: 30px;
                            border: 5px solid #0d0a12;
                            box-shadow: 0 50px 50px -30px rgba(0,0,0,0.3);
                            text-align: center;
                            z-index: 10;
                            border-radius: 10px;
                        }
                        #start-screen h1 {
                            color: #ff76ff;
                            font-size: 24px;
                            margin-bottom: 20px;
                            text-shadow: 0 0 10px #ff76ff;
                        }
                        #start-screen .difficulty {
                            margin: 20px 0;
                        }
                        #start-screen .difficulty button {
                            background: #0d0a12;
                            border: 2px solid #3e3f43;
                            color: #e9eaee;
                            padding: 10px 15px;
                            margin: 5px;
                            cursor: pointer;
                            font-family: 'Press Start 2P', cursive;
                            font-size: 10px;
                        }
                        #start-screen .difficulty button:hover,
                        #start-screen .difficulty button.active {
                            border-color: #ff76ff;
                            color: #ff76ff;
                        }
                        #start-screen .play-btn {
                            background: #ff76ff;
                            border: none;
                            color: #0d0a12;
                            padding: 15px 30px;
                            font-family: 'Press Start 2P', cursive;
                            font-size: 14px;
                            cursor: pointer;
                            margin-top: 20px;
                        }
                        #start-screen .play-btn:hover {
                            background: #ff5acc;
                        }
                        canvas {
                            background: #09080a;
                            border: 2px solid #0d0a12;
                        }
                        #score {
                            position: fixed;
                            top: 20px;
                            right: 20px;
                            color: #ff76ff;
                            font-size: 30px;
                            display: none;
                        }
                        .hidden { display: none !important; }
                    </style>
                </head>
                <body>
                    <div id="score">0</div>
                    <div id="game-container">
                        <div id="start-screen">
                            <h1>🐍 AISBF Snake 🐍</h1>
                            <div class="difficulty">
                                <button data-speed="150" class="active">Easy</button>
                                <button data-speed="100">Medium</button>
                                <button data-speed="50">Hard</button>
                            </div>
                            <button class="play-btn" onclick="startGame()">Play</button>
                        </div>
                        <canvas id="game-canvas"></canvas>
                    </div>
                    <script>
                        const canvas = document.getElementById('game-canvas');
                        const ctx = canvas.getContext('2d');
                        const startScreen = document.getElementById('start-screen');
                        const scoreDisplay = document.getElementById('score');
                        
                        // Set canvas size
                        canvas.width = 600;
                        canvas.height = 400;
                        
                        let snake = [];
                        let food = {};
                        let direction = 'right';
                        let nextDirection = 'right';
                        let gameLoop = null;
                        let score = 0;
                        let speed = 150;
                        
                        // Difficulty buttons
                        document.querySelectorAll('.difficulty button').forEach(btn => {
                            btn.addEventListener('click', function() {
                                document.querySelectorAll('.difficulty button').forEach(b => b.classList.remove('active'));
                                this.classList.add('active');
                                speed = parseInt(this.dataset.speed);
                            });
                        });
                        
                        function initGame() {
                            snake = [
                                {x: 300, y: 200},
                                {x: 280, y: 200},
                                {x: 260, y: 200}
                            ];
                            direction = 'right';
                            nextDirection = 'right';
                            score = 0;
                            scoreDisplay.textContent = score;
                            placeFood();
                        }
                        
                        function placeFood() {
                            food = {
                                x: Math.floor(Math.random() * (canvas.width - 20)) + 10,
                                y: Math.floor(Math.random() * (canvas.height - 20)) + 10
                            };
                            // Align to grid
                            food.x = Math.floor(food.x / 20) * 20 + 10;
                            food.y = Math.floor(food.y / 20) * 20 + 10;
                        }
                        
                        function startGame() {
                            startScreen.classList.add('hidden');
                            scoreDisplay.style.display = 'block';
                            initGame();
                            if (gameLoop) clearInterval(gameLoop);
                            gameLoop = setInterval(update, speed);
                        }
                        
                        function update() {
                            direction = nextDirection;
                            
                            const head = {x: snake[0].x, y: snake[0].y};
                            
                            switch(direction) {
                                case 'up': head.y -= 20; break;
                                case 'down': head.y += 20; break;
                                case 'left': head.x -= 20; break;
                                case 'right': head.x += 20; break;
                            }
                            
                            // Check wall collision
                            if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
                                gameOver();
                                return;
                            }
                            
                            // Check self collision
                            for (let i = 0; i < snake.length; i++) {
                                if (head.x === snake[i].x && head.y === snake[i].y) {
                                    gameOver();
                                    return;
                                }
                            }
                            
                            snake.unshift(head);
                            
                            // Check food collision
                            if (head.x === food.x && head.y === food.y) {
                                score += 10;
                                scoreDisplay.textContent = score;
                                placeFood();
                            } else {
                                snake.pop();
                            }
                            
                            draw();
                        }
                        
                        function draw() {
                            // Clear canvas
                            ctx.fillStyle = '#09080a';
                            ctx.fillRect(0, 0, canvas.width, canvas.height);
                            
                            // Draw snake
                            ctx.fillStyle = '#fac020';
                            snake.forEach((segment, i) => {
                                ctx.fillStyle = i === 0 ? '#ffd700' : '#fac020';
                                ctx.fillRect(segment.x - 9, segment.y - 9, 18, 18);
                            });
                            
                            // Draw food
                            ctx.fillStyle = '#ee6b71';
                            ctx.beginPath();
                            ctx.arc(food.x, food.y, 8, 0, Math.PI * 2);
                            ctx.fill();
                        }
                        
                        function gameOver() {
                            clearInterval(gameLoop);
                            alert('Game Over! Score: ' + score + '\nPress OK to play again.');
                            startScreen.classList.remove('hidden');
                            scoreDisplay.style.display = 'none';
                        }
                        
                        // Keyboard controls
                        document.addEventListener('keydown', function(e) {
                            switch(e.key) {
                                case 'ArrowUp':
                                    if (direction !== 'down') nextDirection = 'up';
                                    e.preventDefault();
                                    break;
                                case 'ArrowDown':
                                    if (direction !== 'up') nextDirection = 'down';
                                    e.preventDefault();
                                    break;
                                case 'ArrowLeft':
                                    if (direction !== 'right') nextDirection = 'left';
                                    e.preventDefault();
                                    break;
                                case 'ArrowRight':
                                    if (direction !== 'left') nextDirection = 'right';
                                    e.preventDefault();
                                    break;
                            }
                        });
                        
                        // Initial draw
                        draw();
                    <\/script>
                </body>
                </html>
                `;
                
                var gameWindow = window.open('', 'SnakeGame', 'width=650,height=500');
                gameWindow.document.write(gameHtml);
                gameWindow.document.close();
            }
        })();
    </script>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>AISBF Dashboard</h1>
            {% if request.session.logged_in %}
            <div class="header-actions">
                <a href="{{ url_for(request, '/dashboard/license') }}" class="btn btn-secondary">License</a>
                <button onclick="restartServer()" class="btn btn-warning">Restart Server</button>
                <a href="{{ url_for(request, '/dashboard/logout') }}" class="btn btn-secondary">Logout</a>
            </div>
            {% endif %}
        </div>
    </div>
    
    {% if request.session.logged_in %}
    <div class="container">
        <div class="nav">
            <a href="{{ url_for(request, '/dashboard') }}" {% if request.path == '/dashboard' %}class="active"{% endif %}>Overview</a>
            <a href="{{ url_for(request, '/dashboard/providers') }}" {% if '/providers' in request.path %}class="active"{% endif %}>Providers</a>
            <a href="{{ url_for(request, '/dashboard/rotations') }}" {% if '/rotations' in request.path %}class="active"{% endif %}>Rotations</a>
            <a href="{{ url_for(request, '/dashboard/autoselect') }}" {% if '/autoselect' in request.path %}class="active"{% endif %}>Autoselect</a>
            <a href="{{ url_for(request, '/dashboard/prompts') }}" {% if '/prompts' in request.path %}class="active"{% endif %}>Prompts</a>
            <a href="{{ url_for(request, '/dashboard/analytics') }}" {% if '/analytics' in request.path %}class="active"{% endif %}>Analytics</a>
            {% if request.session.role == 'admin' %}
            <a href="{{ url_for(request, '/dashboard/users') }}" {% if '/users' in request.path %}class="active"{% endif %}>Users</a>
            {% endif %}
            <a href="{{ url_for(request, '/dashboard/settings') }}" {% if '/settings' in request.path %}class="active"{% endif %}>Settings</a>
            <a href="{{ url_for(request, '/dashboard/docs') }}" {% if '/docs' in request.path %}class="active"{% endif %}>Docs</a>
            <a href="{{ url_for(request, '/dashboard/about') }}" {% if '/about' in request.path %}class="active"{% endif %}>About</a>
        </div>
    </div>
    {% endif %}
    
    <div class="container">
        <div class="content">
            {% block content %}{% endblock %}
        </div>
    </div>
</body>
</html>
