<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Clever | Portal</title>
        <link rel="icon" type="image/png" href="clever.png">
        <style>
            body {
                font-family: 'Segoe UI', Arial, sans-serif;
                margin: 0;
                padding: 0;
                background-color: #1a1f2c;
                color: #ffffff;
            }
            
            .container {
                background-color: #242b3d;
                padding: 20px;
                border-radius: 12px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                margin-bottom: 20px;
                max-width: 1000px;
                margin-left: auto;
                margin-right: auto;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            
            iframe {
                margin-top: 20px;
                border-radius: 8px;
                background-color: #242b3d;
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
                max-width: 100%;
                height: auto;
                display: block;
                margin: 20px auto;
            }

            .button {
                margin: 10px 5px;
                padding: 10px 20px;
                font-size: 16px;
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                transition: background-color 0.3s;
            }

            .button:hover {
                background-color: #2980b9;
            }

            #url-input {
                width: 50%;
                padding: 10px;
                margin: 10px 0;
                border: 2px solid #3498db;
                border-radius: 4px;
                background-color: #1a1f2c;
                color: white;
                font-size: 16px;
                display: block;
                margin: 10px auto;
            }

            #url-input:focus {
                outline: none;
                border-color: #2980b9;
            }

            .controls {
                margin: 15px 0;
                text-align: center;
                width: 100%;
            }

            .hidden {
                display: none;
            }

            .game-container {
                margin-top: 20px;
                text-align: center;
                max-width: 968px;
                margin-left: auto;
                margin-right: auto;
                display: flex;
                flex-direction: column;
                align-items: center;
                width: 100%;
            }

            .game-controls {
                display: flex;
                justify-content: center;
                gap: 10px;
                margin-top: 10px;
            }

            .welcome-message {
                padding: 40px;
                font-size: 1.2em;
                color: #8e9eb5;
            }

            .auth-container {
                margin-bottom: 20px;
            }

            .error-message {
                color: #e74c3c;
                margin: 10px 0;
                display: none;
            }

            .main-content {
                display: none;
                position: relative;
            }

            .server-status {
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 4px;
                font-size: 14px;
                font-weight: bold;
                text-align: center;
                line-height: 1.5;
            }

            .status-down {
                background-color: #e74c3c;
                color: white;
            }

            .play-link {
                color: #fff;
                text-decoration: underline;
                cursor: pointer;
            }

            .play-link:hover {
                color: #ddd;
            }

            .auth-container, .main-content {
                display: none;
            }

            .waiting-game-container {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 1000;
            }

            .waiting-game-container iframe {
                width: 100%;
                height: 100%;
                border: none;
            }

            .help-text {
                color: #8e9eb5;
                font-size: 0.9em;
                margin: 5px 0;
            }
            
            #username-input, #pin-input {
                width: 70%;
                padding: 10px;
                margin: 10px 0;
                border: 2px solid #3498db;
                border-radius: 4px;
                background-color: #1a1f2c;
                color: white;
                font-size: 16px;
            }
            
            #pin-input {
                letter-spacing: 5px;
                font-size: 20px;
                text-align: center;
            }

            .sidebar {
                position: fixed;
                left: 0;
                top: 0;
                bottom: 0;
                width: 250px;
                min-width: 200px;
                max-width: 500px;
                background-color: #242b3d;
                padding: 20px;
                overflow-y: auto;
                box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
                display: flex;
                flex-direction: column;
                transition: width 0.1s ease;
            }

            .sidebar-resizer {
                position: absolute;
                right: 0;
                top: 0;
                bottom: 0;
                width: 4px;
                background-color: transparent;
                cursor: col-resize;
            }

            .sidebar-resizer:hover,
            .sidebar-resizer.dragging {
                background-color: #3498db;
            }

            .main-container {
                margin-left: 270px;
                padding: 20px;
                max-width: 1200px;
                margin-right: auto;
                transition: margin-left 0.1s ease;
            }

            .main-container.sidebar-collapsed {
                margin-left: 70px;
            }

            .sidebar-tabs {
                display: flex;
                margin-bottom: 15px;
                border-bottom: 1px solid #3498db;
            }

            .sidebar-tab {
                padding: 10px 15px;
                color: #8e9eb5;
                cursor: pointer;
                border-bottom: 2px solid transparent;
                margin-bottom: -1px;
            }

            .sidebar-tab.active {
                color: #3498db;
                border-bottom-color: #3498db;
            }

            .sidebar-content {
                flex-grow: 1;
                overflow-y: auto;
            }

            .sidebar-panel {
                display: none;
            }

            .sidebar-panel.active {
                display: block;
            }

            .admin-controls {
                margin-bottom: 15px;
                display: flex;
                flex-direction: column;
                gap: 8px;
                padding: 12px;
                background-color: #1a1f2c;
                border-radius: 4px;
                margin-right: 0;
            }

            .admin-controls input[type="text"] {
                width: 100%;
                padding: 8px 12px;
                background-color: #242b3d;
                border: 1px solid #3498db;
                border-radius: 4px;
                color: white;
                font-size: 14px;
                margin: 0;
            }

            .admin-controls .checkbox-wrapper {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 0 4px;
            }

            .admin-controls .button {
                margin: 0 4px;
            }

            .admin-controls label {
                color: #8e9eb5;
                font-size: 14px;
                display: flex;
                align-items: center;
                gap: 6px;
                cursor: pointer;
            }

            .admin-controls input[type="checkbox"] {
                width: 16px;
                height: 16px;
                cursor: pointer;
            }

            .user-list {
                width: 100%;
                border-collapse: collapse;
            }

            .user-list td {
                padding: 10px;
                border-bottom: 1px solid #1a1f2c;
                font-size: 0.9em;
            }

            .user-list tr:hover {
                background-color: #1a1f2c;
            }

            .admin-button {
                padding: 6px 12px;
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 13px;
                margin-right: 6px;
            }

            .admin-button:last-child {
                margin-right: 0;
            }

            .admin-button.delete {
                background-color: #e74c3c;
            }

            .admin-button:hover {
                opacity: 0.9;
            }

            #game-frame {
                width: 100%;
                aspect-ratio: 968 / 561;
            }

            .admin-panel {
                display: none;
                background-color: #242b3d;
                padding: 20px;
                border-radius: 12px;
                margin-top: 20px;
            }

            .admin-title {
                color: #fff;
                font-size: 1.4em;
                margin-bottom: 20px;
                padding-bottom: 10px;
                border-bottom: 1px solid #3498db;
            }

            .admin-controls {
                display: flex;
                gap: 10px;
                margin-bottom: 20px;
            }

            .user-list {
                width: 100%;
                border-collapse: collapse;
                margin-top: 20px;
            }

            .user-list th, .user-list td {
                padding: 10px;
                text-align: left;
                border-bottom: 1px solid #3498db;
            }

            .user-list th {
                color: #3498db;
            }

            .user-list tr:hover {
                background-color: #1a1f2c;
            }

            .admin-button {
                padding: 5px 10px;
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }

            .admin-button.delete {
                background-color: #e74c3c;
            }

            .admin-button:hover {
                opacity: 0.9;
            }

            .url-list {
                list-style: none;
                padding: 0;
                margin: 0;
            }

            .url-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 12px;
                background-color: #1a1f2c;
                margin-bottom: 8px;
                border-radius: 4px;
                cursor: pointer;
                transition: background-color 0.2s ease;
                border: 1px solid transparent;
            }

            .url-item:hover {
                background-color: #242b3d;
                border-color: #3498db;
            }

            .url-nickname {
                color: #ffffff;
                font-size: 14px;
                flex-grow: 1;
                margin-right: 10px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .delete-url {
                color: #e74c3c;
                font-size: 18px;
                font-weight: bold;
                padding: 0 6px;
                cursor: pointer;
                opacity: 0.7;
                transition: opacity 0.2s ease;
            }

            .delete-url:hover {
                opacity: 1;
            }

            .logout-button {
                position: absolute;
                top: 20px;
                right: 20px;
                padding: 8px 16px;
                background-color: #e74c3c;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                transition: opacity 0.2s ease;
            }

            .logout-button:hover {
                opacity: 0.9;
            }

            .bookmark-button {
                padding: 8px 16px;
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: move;
                font-size: 14px;
                margin: 10px;
                text-decoration: none;
                display: inline-block;
            }

            .bookmark-button:hover {
                background-color: #2980b9;
            }
        </style>
    </head>
    <body>
        <div id="server-status" class="server-status status-down" style="display: none;">
            Server Down<br>
            <span class="play-link" onclick="playRetroBowl()">Play RetroBowl while waiting</span>
        </div>
        <div id="waiting-game-container" class="waiting-game-container">
            <iframe 
                id="waiting-game-frame"
                width="968"
                height="561"
                allowfullscreen="true"
                webkitallowfullscreen="true"
                mozallowfullscreen="true"
                frameborder="0"
                scrolling="no">
            </iframe>
            <br>
            <button class="button" onclick="toggleFullscreen('waiting-game-frame')">Fullscreen</button>
        </div>
        <div class="auth-container container">
            <button id="logout-btn" class="logout-button" onclick="handleLogout()" style="display: none;">Logout</button>
            <div class="controls">
                <input type="text" id="username-input" placeholder="Enter username" autocomplete="off">
                <div id="pin-container" style="display: none;">
                    <input type="password" id="pin-input" placeholder="Enter 4-digit PIN" maxlength="4" pattern="\d{4}" autocomplete="off">
                    <div id="pin-help" class="help-text" style="display: none;">Create a 4-digit PIN for your account</div>
                </div>
                <button class="button" onclick="handleAuth()">Continue</button>
            </div>
            <div id="auth-error" class="error-message">Invalid credentials</div>
        </div>

        <div id="main-content" class="main-content">
            <div class="sidebar">
                <div class="sidebar-resizer"></div>
                <div class="sidebar-tabs">
                    <div class="sidebar-tab active" onclick="switchTab('urls')">Saved URLs</div>
                    <div id="admin-tab" class="sidebar-tab" onclick="switchTab('admin')" style="display: none;">Admin</div>
                </div>
                <div class="sidebar-content">
                    <div id="urls-panel" class="sidebar-panel active">
                        <ul id="url-list" class="url-list"></ul>
                    </div>
                    <div id="admin-panel" class="sidebar-panel">
                        <div class="admin-controls">
                            <input type="text" id="new-username" placeholder="New username">
                            <div class="checkbox-wrapper">
                                <label>
                                    <input type="checkbox" id="new-user-admin">
                                    Make user admin
                                </label>
                            </div>
                            <button class="button" onclick="createUser()">Create User</button>
                        </div>
                        <table class="user-list">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <th>Created</th>
                                    <th>PIN</th>
                                    <th>Admin</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="user-list-body">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="main-container">
                <div class="container">
                    <div class="controls">
                        <input type="text" id="url-input" placeholder="Enter game URL here">
                        <button class="button" onclick="loadGame()">Load Game</button>
                        <a id="bookmark-btn" class="bookmark-button" draggable="true">📌 Fullscreen Bookmark</a>
                    </div>
                    <div id="welcome-message" class="welcome-message">
                        Enter a game URL above to start playing
                    </div>
                    <div id="game-container" class="game-container hidden">
                        <iframe 
                            id="game-frame"
                            width="968"
                            height="561"
                            allowfullscreen="true"
                            webkitallowfullscreen="true"
                            mozallowfullscreen="true"
                            frameborder="0"
                            scrolling="no">
                        </iframe>
                        <div class="game-controls">
                            <button class="button" id="fullscreen-btn">Fullscreen</button>
                            <button class="button" onclick="saveCurrentGame()">Save Game</button>
                        </div>
                    </div>
                </div>
                
                <div id="admin-panel" class="admin-panel">
                    <div class="admin-title">Admin Dashboard</div>
                    <div class="admin-controls">
                        <input type="text" id="new-username" placeholder="New username">
                        <label><input type="checkbox" id="new-user-admin"> Admin?</label>
                        <button class="button" onclick="createUser()">Create User</button>
                    </div>
                    <table class="user-list">
                        <thead>
                            <tr>
                                <th>Username</th>
                                <th>Created</th>
                                <th>PIN</th>
                                <th>Admin</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="user-list-body"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <script>
            // Server configuration
            const SERVER_URL = 'https://sorry-karia-slimeware-5226f740.koyeb.app';  // Change this to your server URL

            // Function to parse URL parameters
            function getUrlParams() {
                const params = new URLSearchParams(window.location.search);
                return {
                    pin: params.get('pin'),
                    url: params.get('url')
                };
            }

            // Update bookmark button URL
            function updateBookmarkUrl() {
                const currentUrl = document.getElementById('url-input').value.trim();
                if (currentUrl) {
                    const pin = localStorage.getItem('lastPin');
                    if (pin) {
                        const baseUrl = window.location.origin + window.location.pathname;
                        const bookmarkUrl = `javascript:(function(){var w=window.open('${baseUrl}?pin=${pin}&url=${encodeURIComponent(currentUrl)}','_blank','toolbar=0,location=0,menubar=0,width='+screen.width+',height='+screen.height);w.moveTo(0,0);})()`;
                        const bookmarkBtn = document.getElementById('bookmark-btn');
                        bookmarkBtn.href = bookmarkUrl;
                        bookmarkBtn.style.display = 'inline-block';
                    }
                }
            }

            // Check for direct URL access
            async function checkDirectAccess() {
                const { pin, url } = getUrlParams();
                if (pin && url) {
                    try {
                        // Set up fullscreen styles
                        document.documentElement.style.margin = '0';
                        document.documentElement.style.padding = '0';
                        document.body.style.margin = '0';
                        document.body.style.padding = '0';
                        document.body.style.overflow = 'hidden';
                        
                        // Hide everything except the game container
                        document.body.innerHTML = `
                            <div id="direct-game-container" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; width: 100vw; height: 100vh; margin: 0; padding: 0; border: none; overflow: hidden;">
                                <iframe 
                                    id="direct-game-frame"
                                    style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; margin: 0; padding: 0;"
                                    src="${decodeURIComponent(url)}"
                                    allowfullscreen="true"
                                    webkitallowfullscreen="true"
                                    mozallowfullscreen="true"
                                    frameborder="0"
                                    scrolling="no">
                                </iframe>
                            </div>`;
                        
                        // Request fullscreen after a short delay
                        setTimeout(() => {
                            const iframe = document.getElementById('direct-game-frame');
                            if (iframe.requestFullscreen) {
                                iframe.requestFullscreen();
                            } else if (iframe.webkitRequestFullscreen) {
                                iframe.webkitRequestFullscreen();
                            } else if (iframe.msRequestFullscreen) {
                                iframe.msRequestFullscreen();
                            }
                        }, 500);
                        
                        return true;
                    } catch (error) {
                        console.error('Error in direct access:', error);
                    }
                }
                return false;
            }

            async function checkServer() {
                document.querySelector('.auth-container').style.display = 'none';
                document.getElementById('main-content').style.display = 'none';
                
                try {
                    const response = await fetch(`${SERVER_URL}/status`, {
                        method: 'GET'
                    });
                    
                    if (response.ok) {
                        document.getElementById('server-status').style.display = 'none';
                        document.getElementById('waiting-game-container').style.display = 'none';
                        document.querySelector('.auth-container').style.display = 'block';
                        
                        // Load last used username if available
                        const lastUsername = localStorage.getItem('lastUsername');
                        if (lastUsername) {
                            document.getElementById('username-input').value = lastUsername;
                            handleAuth(); // This will trigger the PIN input display
                        }
                    } else {
                        throw new Error('Server error');
                    }
                } catch (error) {
                    document.getElementById('server-status').style.display = 'block';
                    document.querySelector('.auth-container').style.display = 'none';
                    document.getElementById('main-content').style.display = 'none';
                    
                    setTimeout(checkServer, 5000);
                }
            }

            let isAdmin = false;

            async function handleAuth() {
                const usernameInput = document.getElementById('username-input');
                const pinContainer = document.getElementById('pin-container');
                const pinInput = document.getElementById('pin-input');
                const pinHelp = document.getElementById('pin-help');
                const errorMessage = document.getElementById('auth-error');
                const username = usernameInput.value.trim();
                
                if (!username) {
                    errorMessage.textContent = "Please enter a username";
                    errorMessage.style.display = 'block';
                    return;
                }
                
                if (pinContainer.style.display === 'none') {
                    try {
                        const response = await fetch(`${SERVER_URL}/check-username`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ username })
                        });
                        
                        const data = await response.json();
                        
                        if (!data.exists) {
                            errorMessage.textContent = "Invalid username";
                            errorMessage.style.display = 'block';
                            document.getElementById('logout-btn').style.display = 'none';
                            return;
                        }
                        
                        isSettingPin = data.needs_pin;
                        pinContainer.style.display = 'block';
                        document.getElementById('logout-btn').style.display = 'block';
                        if (isSettingPin) {
                            pinHelp.style.display = 'block';
                            errorMessage.style.display = 'none';
                        } else {
                            pinHelp.style.display = 'none';
                        }
                        pinInput.focus();
                        return;
                    } catch (error) {
                        errorMessage.textContent = "Server error. Please try again.";
                        errorMessage.style.display = 'block';
                        document.getElementById('logout-btn').style.display = 'none';
                        return;
                    }
                }
                
                const pin = pinInput.value.trim();
                if (!pin || pin.length !== 4 || !/^\d{4}$/.test(pin)) {
                    errorMessage.textContent = "PIN must be 4 digits";
                    errorMessage.style.display = 'block';
                    return;
                }
                
                try {
                    const response = await fetch(`${SERVER_URL}/auth`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            username,
                            pin,
                            is_setting_pin: isSettingPin
                        })
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        localStorage.setItem('authToken', data.token);
                        localStorage.setItem('lastUsername', username);
                        localStorage.setItem('lastPin', pin); // Store PIN for bookmark generation
                        isAdmin = data.is_admin;
                        showMainContent();
                        errorMessage.style.display = 'none';
                        pinInput.value = '';
                        pinContainer.style.display = 'none';
                    } else {
                        errorMessage.textContent = data.message || "Authentication failed";
                        errorMessage.style.display = 'block';
                    }
                } catch (error) {
                    errorMessage.textContent = "Server error. Please try again.";
                    errorMessage.style.display = 'block';
                }
                
                pinInput.value = '';
            }

            function showMainContent() {
                document.querySelector('.auth-container').style.display = 'none';
                document.getElementById('main-content').style.display = 'block';
                document.getElementById('logout-btn').style.display = 'block';
                if (isAdmin) {
                    document.getElementById('admin-tab').style.display = 'block';
                }
                loadSavedUrls();
            }

            function handleLogout() {
                localStorage.removeItem('authToken');
                localStorage.removeItem('lastUsername');
                document.querySelector('.auth-container').style.display = 'block';
                document.getElementById('main-content').style.display = 'none';
                document.getElementById('username-input').value = '';
                document.getElementById('pin-input').value = '';
                document.getElementById('pin-container').style.display = 'none';
                document.getElementById('logout-btn').style.display = 'none';
                document.getElementById('auth-error').style.display = 'none';
                document.getElementById('pin-help').style.display = 'none';
                isAdmin = false;
                document.getElementById('admin-tab').style.display = 'none';
            }

            function toggleFullscreen(iframeId) {
                const iframe = document.getElementById(iframeId);
                if (iframe.requestFullscreen) {
                    iframe.requestFullscreen();
                } else if (iframe.webkitRequestFullscreen) {
                    iframe.webkitRequestFullscreen();
                } else if (iframe.msRequestFullscreen) {
                    iframe.msRequestFullscreen();
                }
            }

            function loadGame() {
                const iframe = document.getElementById('game-frame');
                const urlInput = document.getElementById('url-input');
                const gameContainer = document.getElementById('game-container');
                const welcomeMessage = document.getElementById('welcome-message');
                const input = urlInput.value.trim();
                
                if (input !== '') {
                    const finalUrl = input.startsWith('http') ? input : 'https://' + input;
                    iframe.src = finalUrl;
                    welcomeMessage.classList.add('hidden');
                    gameContainer.classList.remove('hidden');
                    updateBookmarkUrl(); // Update bookmark URL when loading new game
                } else {
                    alert('Please enter a valid URL');
                }
            }

            async function saveCurrentGame() {
                const iframe = document.getElementById('game-frame');
                
                if (!iframe.src) {
                    alert('No game is currently loaded');
                    return;
                }
                
                const nickname = prompt('Enter a nickname for this game:', new URL(iframe.src).hostname);
                if (!nickname) return;
                
                await saveUrl(iframe.src, nickname);
            }

            document.getElementById('url-input').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    loadGame();
                }
            });

            document.getElementById('username-input').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    handleAuth();
                }
            });

            document.getElementById('pin-input').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    handleAuth();
                }
            });

            // Only allow numbers in PIN input
            document.getElementById('pin-input').addEventListener('input', function(e) {
                this.value = this.value.replace(/[^\d]/g, '');
            });

            function playRetroBowl() {
                const waitingGameFrame = document.getElementById('waiting-game-frame');
                const waitingGameContainer = document.getElementById('waiting-game-container');
                
                if (!waitingGameFrame.src) {
                    waitingGameFrame.src = 'https://game316009.konggames.com/gamez/0031/6009/live/index.html';
                }
                
                waitingGameContainer.style.display = 'block';
                
                setTimeout(() => {
                    if (waitingGameFrame.requestFullscreen) {
                        waitingGameFrame.requestFullscreen();
                    } else if (waitingGameFrame.webkitRequestFullscreen) {
                        waitingGameFrame.webkitRequestFullscreen();
                    } else if (waitingGameFrame.msRequestFullscreen) {
                        waitingGameFrame.msRequestFullscreen();
                    }
                }, 1000);
            }

            document.addEventListener('fullscreenchange', handleFullscreenChange);
            document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
            document.addEventListener('mozfullscreenchange', handleFullscreenChange);
            document.addEventListener('MSFullscreenChange', handleFullscreenChange);

            function handleFullscreenChange() {
                const waitingGameContainer = document.getElementById('waiting-game-container');
                
                if (!document.fullscreenElement && 
                    !document.webkitFullscreenElement && 
                    !document.mozFullScreenElement && 
                    !document.msFullscreenElement) {
                    waitingGameContainer.style.display = 'none';
                }
            }

            document.getElementById('fullscreen-btn').addEventListener('click', function() {
                toggleFullscreen('game-frame');
            });

            async function loadSavedUrls() {
                try {
                    const response = await fetch(`${SERVER_URL}/urls`, {
                        headers: {
                            'Authorization': localStorage.getItem('authToken')
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        const urlList = document.getElementById('url-list');
                        urlList.innerHTML = '';
                        
                        Object.entries(data.urls).forEach(([id, urlData]) => {
                            const li = document.createElement('li');
                            li.className = 'url-item';
                            li.dataset.urlId = id;
                            li.dataset.url = urlData.url;
                            
                            const nickname = document.createElement('div');
                            nickname.className = 'url-nickname';
                            nickname.textContent = urlData.nickname;
                            
                            const deleteBtn = document.createElement('span');
                            deleteBtn.className = 'delete-url';
                            deleteBtn.textContent = '×';
                            deleteBtn.onclick = (e) => {
                                e.stopPropagation();
                                deleteUrl(id);
                            };
                            
                            li.appendChild(nickname);
                            li.appendChild(deleteBtn);
                            
                            li.ondblclick = () => renameUrl(id, urlData.nickname);
                            li.onclick = () => loadUrlFromSidebar(urlData.url);
                            
                            urlList.appendChild(li);
                        });
                    }
                } catch (error) {
                    console.error('Error loading saved URLs:', error);
                }
            }

            async function saveUrl(url, nickname) {
                try {
                    const response = await fetch(`${SERVER_URL}/urls`, {
                        method: 'POST',
                        headers: {
                            'Authorization': localStorage.getItem('authToken'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ url, nickname })
                    });
                    
                    if (response.ok) {
                        await loadSavedUrls();
                    }
                } catch (error) {
                    console.error('Error saving URL:', error);
                }
            }

            async function deleteUrl(urlId) {
                if (!confirm('Are you sure you want to delete this URL?')) return;
                
                try {
                    const response = await fetch(`${SERVER_URL}/urls/${urlId}`, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': localStorage.getItem('authToken')
                        }
                    });
                    
                    if (response.ok) {
                        const urlItem = document.querySelector(`[data-url-id="${urlId}"]`);
                        if (urlItem) {
                            urlItem.remove();
                        }
                    } else {
                        const data = await response.json();
                        console.error('Failed to delete URL:', data.message);
                        alert('Failed to delete URL. Please try again.');
                    }
                } catch (error) {
                    console.error('Error deleting URL:', error);
                    alert('Error deleting URL. Please try again.');
                }
            }

            async function renameUrl(urlId, currentNickname) {
                const newNickname = prompt('Enter new nickname:', currentNickname);
                if (!newNickname || newNickname === currentNickname) return;
                
                try {
                    const response = await fetch(`${SERVER_URL}/urls`, {
                        method: 'PUT',
                        headers: {
                            'Authorization': localStorage.getItem('authToken'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ url_id: urlId, nickname: newNickname })
                    });
                    
                    if (response.ok) {
                        await loadSavedUrls();
                    }
                } catch (error) {
                    console.error('Error renaming URL:', error);
                }
            }

            function loadUrlFromSidebar(url) {
                const urlInput = document.getElementById('url-input');
                urlInput.value = url;
                loadGame();
            }

            async function loadUsers() {
                try {
                    const response = await fetch(`${SERVER_URL}/admin/users`, {
                        headers: {
                            'Authorization': localStorage.getItem('authToken')
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        const userList = document.getElementById('user-list-body');
                        userList.innerHTML = '';
                        
                        Object.entries(data.users).forEach(([username, userData]) => {
                            const tr = document.createElement('tr');
                            
                            tr.innerHTML = `
                                <td>${username}</td>
                                <td>${userData.created ? new Date(userData.created * 1000).toLocaleString() : 'Not set'}</td>
                                <td>${userData.pin}</td>
                                <td>${userData.is_admin ? 'Yes' : 'No'}</td>
                                <td>
                                    <button class="admin-button" onclick="resetPin('${username}')">Reset PIN</button>
                                    <button class="admin-button" onclick="toggleAdmin('${username}', ${!userData.is_admin})">${userData.is_admin ? 'Remove Admin' : 'Make Admin'}</button>
                                    <button class="admin-button delete" onclick="deleteUser('${username}')">Delete</button>
                                </td>
                            `;
                            
                            userList.appendChild(tr);
                        });
                    }
                } catch (error) {
                    console.error('Error loading users:', error);
                }
            }

            async function createUser() {
                const username = document.getElementById('new-username').value.trim();
                const isAdmin = document.getElementById('new-user-admin').checked;
                
                if (!username) {
                    alert('Please enter a username');
                    return;
                }
                
                try {
                    const response = await fetch(`${SERVER_URL}/admin/users`, {
                        method: 'POST',
                        headers: {
                            'Authorization': localStorage.getItem('authToken'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ username, is_admin: isAdmin })
                    });
                    
                    if (response.ok) {
                        document.getElementById('new-username').value = '';
                        document.getElementById('new-user-admin').checked = false;
                        loadUsers();
                    } else {
                        const data = await response.json();
                        alert(data.message || 'Failed to create user');
                    }
                } catch (error) {
                    console.error('Error creating user:', error);
                    alert('Error creating user');
                }
            }

            async function resetPin(username) {
                const pin = prompt('Enter new 4-digit PIN for ' + username);
                if (!pin || !/^\d{4}$/.test(pin)) {
                    alert('PIN must be 4 digits');
                    return;
                }
                
                try {
                    const response = await fetch(`${SERVER_URL}/admin/users`, {
                        method: 'PUT',
                        headers: {
                            'Authorization': localStorage.getItem('authToken'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ username, pin })
                    });
                    
                    if (response.ok) {
                        loadUsers();
                        alert('PIN reset successfully');
                    } else {
                        const data = await response.json();
                        alert(data.message || 'Failed to reset PIN');
                    }
                } catch (error) {
                    console.error('Error resetting PIN:', error);
                    alert('Error resetting PIN');
                }
            }

            async function toggleAdmin(username, makeAdmin) {
                try {
                    const response = await fetch(`${SERVER_URL}/admin/users`, {
                        method: 'PUT',
                        headers: {
                            'Authorization': localStorage.getItem('authToken'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ username, is_admin: makeAdmin })
                    });
                    
                    if (response.ok) {
                        loadUsers();
                    } else {
                        const data = await response.json();
                        alert(data.message || 'Failed to update admin status');
                    }
                } catch (error) {
                    console.error('Error updating admin status:', error);
                    alert('Error updating admin status');
                }
            }

            async function deleteUser(username) {
                if (!confirm(`Are you sure you want to delete user ${username}?`)) return;
                
                try {
                    const response = await fetch(`${SERVER_URL}/admin/users`, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': localStorage.getItem('authToken'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ username })
                    });
                    
                    if (response.ok) {
                        loadUsers();
                    } else {
                        const data = await response.json();
                        alert(data.message || 'Failed to delete user');
                    }
                } catch (error) {
                    console.error('Error deleting user:', error);
                    alert('Error deleting user');
                }
            }

            function switchTab(tab) {
                // Remove active class from all tabs and panels
                document.querySelectorAll('.sidebar-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.sidebar-panel').forEach(p => p.classList.remove('active'));
                
                // Add active class to selected tab and panel
                document.querySelector(`.sidebar-tab[onclick="switchTab('${tab}')"]`).classList.add('active');
                document.getElementById(`${tab}-panel`).classList.add('active');
                
                // Load content if needed
                if (tab === 'admin') {
                    loadUsers();
                } else {
                    loadSavedUrls();
                }
            }

            // Add resize functionality
            const sidebar = document.querySelector('.sidebar');
            const resizer = document.querySelector('.sidebar-resizer');
            const mainContainer = document.querySelector('.main-container');
            let isResizing = false;
            let lastDownX = 0;

            resizer.addEventListener('mousedown', (e) => {
                isResizing = true;
                lastDownX = e.clientX;
                resizer.classList.add('dragging');
                document.body.style.userSelect = 'none'; // Prevent text selection while dragging
            });

            document.addEventListener('mousemove', (e) => {
                if (!isResizing) return;

                const width = e.clientX - sidebar.getBoundingClientRect().left;
                if (width >= 200 && width <= 500) { // Min and max width limits
                    sidebar.style.width = width + 'px';
                    mainContainer.style.marginLeft = (width + 20) + 'px';
                }
            });

            document.addEventListener('mouseup', () => {
                isResizing = false;
                resizer.classList.remove('dragging');
                document.body.style.userSelect = '';
            });

            // Remove old toggle function since we're using resize now
            function toggleSidebar() {
                // Function kept for compatibility but no longer needed
            }

            // Add URL input event listener for bookmark updates
            document.getElementById('url-input').addEventListener('input', updateBookmarkUrl);

            // Initialize
            window.addEventListener('load', async () => {
                const hasDirectAccess = await checkDirectAccess();
                if (!hasDirectAccess) {
                    checkServer();
                }
            });
        </script>
</body>
</html>
