<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Console</title>
    <style>
        body {
            background-color: black;
            color: white;
            font-family: "Courier New", Courier, monospace;
            padding: 10px;
            margin: 0;
        }

        #console {
            flex-grow: 1;
            padding: 10px;
            background: #111;
            color: #eee;
            overflow-y: auto;
            white-space: pre-wrap;
            font-family: monospace;
        }
        #input-container {
            display: flex;
            background: rgba(34, 34, 34, 0);
            padding: 10px;
            position: fixed;
            bottom: 30px;
            left: 0;
            right: 0;
            margin: 0;
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 5px;
        }
        #input-text {
            flex-grow: 1;
            background: transparent;
            color: #fff;
            border: none;
            outline: none;
            padding: 5px;
            font-family: monospace;
            resize: none;
            height: 40px;
        }
        #cursor {
            width: 2px;
            background: #fff;
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            opacity: 0;
        }

        @keyframes blink {
            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0;
            }
        }
    </style>
</head>

<body>
    <div id="input-container">
        <textarea id="input-text" placeholder="Type your command here..."></textarea>
    </div>
    <div id="console"></div>

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/toxicity"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js"></script>
    <script>
        const consoleDiv = document.getElementById('console');
        const inputText = document.getElementById('input-text');
        const apiKey = '861bb1d5059c4cb3aba595e7a6253fbe';
        const loadTime = new Date();
        const cursor = document.getElementById('cursor');
        console.log('Page loaded at:', loadTime);

        function showInitialMessage() {
            printToConsole("Type 'help' for help.");
        }

        window.onload = function () {
            showInitialMessage();
        };

        // Login thing

        let loggedInAsAdmin = false;
        const adminCredentials = {
            password: 'admin123', // Don't fear to use this to your advantage, its just for shits and giggles
        };

        function login(password) {
            console.log('Login attempt with password:', password);
            if (password === adminCredentials.password) {
                loggedInAsAdmin = true;
                console.log('Login successful');
                return `Login successful! Welcome, admin.`;
            } else {
                console.log(`Invalid password: ${password}`)
                return `Error: Invalid password.`;
            }
        }

        // Weather things

        function getLocation() {
            console.log('Getting user location...');
            return new Promise((resolve, reject) => {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(
                        (position) => {
                            console.log('Location retrieved:', position);
                            resolve(position);
                        },
                        (error) => {
                            console.error('Geolocation error:', error);
                            reject(error);
                        }
                    );
                } else {
                    console.log('Geolocation error, browser incompability.')
                    reject('Geolocation is not supported by this browser.');
                }
            });
        }

        function getWeatherFromAPI(lat, lon) {
            console.log(`Fetching weather for lat:${lat}, lon:${lon}`);
            const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;
            return fetch(url)
                .then(response => response.json())
                .then(data => {
                    console.log('Weather API response:', data);
                    if (data.cod === 200) {
                        const weather = {
                            city: data.name,
                            temp: data.main.temp,
                            description: data.weather[0].description,
                            windSpeed: data.wind.speed
                        };
                        console.log('Processed weather data:', weather);
                        return `Weather in ${weather.city}:
        Temperature: ${weather.temp}°C
        Condition: ${weather.description}
        Wind: ${weather.windSpeed} m/s`;
                    } else {
                        console.error('Weather API error:', data);
                        return 'Could not fetch weather data.';
                    }
                })
                .catch((error) => {
                    console.error('Weather fetch error:', error);
                    return `Error fetching weather data: ${error.message}`;
                });
        }

        function getWeather(command) {
            console.log('Weather command received:', command);
            return getLocation()
                .then(position => {
                    const lat = position.coords.latitude;
                    const lon = position.coords.longitude;
                    console.log(`Got coordinates: lat=${lat}, lon=${lon}`);
                    return getWeatherFromAPI(lat, lon);
                })
                .catch(error => {
                    console.error('Weather error:', error);
                    return `Error: ${error}`;
                });
        }

        // Ping

        function pingHost(host) {
            console.log('Pinging host:', host);
            const startTime = new Date().getTime();
            const url = `https://${host}`;
            return fetch(url, { method: 'HEAD' })
                .then(response => {
                    const endTime = new Date().getTime();
                    const latency = endTime - startTime;
                    console.log(`Ping successful - latency: ${latency}ms`);
                    return `Pinging ${host}...\nReply from ${host}: bytes=32 time=${latency}ms TTL=54`;
                })
                .catch((error) => {
                    console.error('Ping error:', error);
                    return `Error: Could not ping ${host}. Check the host or your connection.`;
                });
        }

        function getRandomNumber(min, max) {
            console.log(`Generating random number between ${min} and ${max}`);
            const result = Math.floor(Math.random() * (max - min + 1)) + min;
            console.log('Generated number:', result);
            return result;
        }

        // Directory system

        let currentDirectory = '/';
        let directoryStructure = {
            '/': ['src', 'cache', 'cookies'],
            '/src': ['index.html', 'script.js', 'style.css'],
            '/cache': ['session_uptime'],
            '/cookies': ['isadmin'],
        };
        console.log('Directory structure initialized:', directoryStructure);

        function directorySystem() {
            console.log('Listing directory:', currentDirectory);
            const currentDirContents = directoryStructure[currentDirectory];
            if (currentDirContents && currentDirContents.length > 0) {
                console.log('Directory contents:', currentDirContents);
                return currentDirContents.join('\n');
            } else {
                console.log('Empty directory');
                return 'No files or directories in this directory.';
            }
        }

        function changeDirectory(path) {
            console.log('Changing directory to:', path);
            if (directoryStructure[path]) {
                currentDirectory = path;
                console.log(`Changed directory to ${path}`)
                return `Changed directory to ${path}`;
            } else {
                console.error('Directory not found:', path);
                return `Error: Directory ${path} not found.`;
            }
        }

        let fileContents = {
            '/src/index.html': 'too large to handle',
            '/src/script.js': 'too large to handle',
            '/src/style.css': 'too large to handle',
            '/cache/session_uptime': '<FILE READ ERROR>',
            '/cookies/isadmin': 'false',
        };
        console.log('File contents initialized:', fileContents);

        function typeFile(file) {
            const filePath = currentDirectory + '/' + file;
            console.log('Attempting to read file:', filePath);
            if (fileContents[filePath]) {
                console.log('File found, returning contents');
                return fileContents[filePath];
            } else {
                console.error('File not found:', filePath);
                return `Error: File ${file} not found.`;
            }
        }

        // Variable function

        let userConfig = {};
        console.log('User config initialized:', userConfig);
        function handleSet(command) {
            console.log('Set command received:', command);
            const args = command.slice(4).trim().split(' ');
            if (args.length < 2) {
                console.error('Invalid set command - insufficient arguments');
                return 'Error: Provide a key and a value. Example: set myKey myValue';
            }
            const key = args[0];
            const value = args.slice(1).join(' ');
            userConfig[key] = value;
            console.log(`Config updated - key: ${key}, value: ${value}`);
            return `Config set: ${key} = ${value}`;
        }

        function handleGet(command) {
            console.log('Get command received:', command);
            const key = command.slice(4).trim();
            if (userConfig.hasOwnProperty(key)) {
                console.log(`Retrieved value for key ${key}:`, userConfig[key]);
                return `${userConfig[key]}`;
            }
            console.error('Key not found:', key);
            return `Error: Key "${key}" not found.`;
        }

        function handleConfig() {
            console.log('Listing all config entries');
            if (Object.keys(userConfig).length === 0) {
                console.log('No configurations found');
                return 'No custom configurations found.';
            }
            const config = Object.entries(userConfig)
                .map(([key, value]) => `${key}: ${value}`)
                .join('\n');
            console.log('Current config:', config);
            return config;
        }

        function handleDelete(command) {
            console.log('Delete command received:', command);
            const key = command.slice(7).trim();
            if (userConfig.hasOwnProperty(key)) {
                delete userConfig[key];
                console.log('Deleted key:', key);
                return `Key "${key}" deleted.`;
            }
            console.error('Key not found for deletion:', key);
            return `Error: Key "${key}" not found.`;
        }

        // AI

        function handleAPI(command) {
            console.log('API command received:', command);
            const apiKey = command.slice(4).trim();
            if (!apiKey) {
                console.error('No API key provided');
                return 'Error: Please provide an API key. Example: api your-api-key-here';
            }
            localStorage.setItem('userAPIKey', apiKey);
            console.log('API key stored');
            return 'API key has been set successfully.';
        }

        let currentModel = 'gpt-3.5-turbo';
        async function handleAI(command) {
            console.log('AI command received:', command);
            const parts = command.slice(3).trim().split(' ');
            const model = parts[0];
            if (model === 'gpt') {
                const selectedModel = parts[1];
                if (selectedModel === '3.5' || selectedModel === '4') {
                    const newModel = selectedModel === '4' ? 'gpt-4' : `gpt-${selectedModel}-turbo`;
                    if (newModel === currentModel) {
                        return `Nothing changed. Model: ${currentModel}`;
                    }
                    console.log(`Switching to GPT-${selectedModel}`);
                    currentModel = newModel;
                    return `Model switched to GPT-${selectedModel}`;
                } else {
                    return 'Error: Invalid model specified. Use "3.5" or "4".';
                }
            }
            const message = command.slice(3).trim();
            if (!message) {
                console.error('No message provided for AI');
                return 'Error: You need to provide a message. Example: ai Hello!';
            }
            const userAPIKey = localStorage.getItem('userAPIKey');
            if (!userAPIKey) {
                console.error('No API key found');
                return 'Error: No OpenAI API key found. Please set your API key using the command "api <your-api-key>".';
            }
            const data = { messages: [{ role: "user", content: message }] };
            console.log('Sending request to OpenAI:', data);
            try {
                const response = await fetch("https://api.openai.com/v1/chat/completions", {
                    headers: {
                        Authorization: `Bearer ${userAPIKey}`,
                        "Content-Type": "application/json",
                    },
                    method: "POST",
                    body: JSON.stringify({
                        model: `${currentModel}`,
                        messages: data.messages,
                        max_tokens: 150,
                    }),
                });
                console.log('OpenAI response status:', response.status);
                if (response.ok) {
                    const result = await response.json();
                    console.log('OpenAI response:', result);
                    if (result.choices && result.choices.length > 0) {
                        return `AI: ${result.choices[0].message.content}`;
                    }
                    console.error('Unexpected response format:', result);
                    return 'Error: Unexpected response format';
                } else if (response.status === 401) {
                    console.error('Invalid API key');
                    return 'Error: Invalid or missing API key';
                } else {
                    console.error('API request failed:', response.status);
                    return `Error: API request failed with status ${response.status}`;
                }
            } catch (error) {
                console.error('AI Error:', error);
                return `Error: ${error.message}`;
            }
        }

        // Install

        async function handleInstall(command) {
            console.log('Install command received:', command);
            const parts = command.trim().split(/\s+/);
            if (!parts[1]) {
                console.error('No package name provided');
                return 'Error: Please provide a package name. Example: install package-name';
            }
            const packageName = parts[1].toLowerCase();
            const downloadUrl = `https://community.chocolatey.org/api/v2/package/${packageName}`;
            console.log('Opening download URL:', downloadUrl);
            window.open(downloadUrl, '_blank');
            return `Opening download for "${packageName}"...`;
        }

        // Theme

        async function handleTheme(command) {
            console.log('Theme command received:', command);
            const parts = command.trim().split(/\s+/);
            if (!parts[1]) {
                console.error('No theme specified');
                return 'Error: Please specify a theme. Example: theme light';
            }
            const theme = parts[1].toLowerCase();
            if (theme === 'light') {
                document.body.style.backgroundColor = 'white';
                document.body.style.color = 'black';
                return 'Switched to light theme.';
            } else if (theme === 'dark') {
                document.body.style.backgroundColor = 'black';
                document.body.style.color = 'white';
                return 'Switched to dark theme.';
            } else {
                console.error('Invalid theme specified');
                return `Error: "${theme}" is not a valid theme. Available themes: light, dark.`;
            }
        }

        // Font

        async function handleFont(command) {
            console.log('Font command received:', command);
            const parts = command.trim().split(/\s+/);
            if (!parts[1]) {
                console.error('No font size specified');
                return 'Error: Please specify a font size. Example: font small';
            }
            const fontSize = parts[1].toLowerCase();
            if (fontSize === 'tiny') {
                document.body.style.fontSize = '8px';
                return 'Font size set to tiny.';
            } else if (fontSize === 'small') {
                document.body.style.fontSize = '12px';
                return 'Font size set to small.';
            } else if (fontSize === 'medium') {
                document.body.style.fontSize = '16px';
                return 'Font size set to medium.';
            } else if (fontSize === 'large') {
                document.body.style.fontSize = '20px';
                return 'Font size set to large.';
            } else if (fontSize === 'huge') {
                document.body.style.fontSize = '24px';
                return 'Font size set to huge.';
            } else if (fontSize === 'zero' || fontSize === 'secret' || fontSize === 'none') {
                document.body.style.fontSize = '0px';
            } else {
                console.error('Invalid font size specified');
                return `Error: "${fontSize}" is not a valid font size. Available sizes: tiny, small, medium, large.`;
            }
        }

        // Color

        async function handleColor(command) {
            console.log('Color command received:', command);
            const color = command.slice(6).trim();
            if (!color) {
                console.error('No color specified');
                return 'Error: Please specify a color. Example: color red or color #ff0000';
            }
            document.body.style.color = color;
            return `Text color changed to "${color}".`;
        }

        // Uptime

        function formatUptime(ms) {
            console.log('Formatting uptime for ms:', ms);
            const seconds = Math.floor(ms / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            const days = Math.floor(hours / 24);
            const formattedUptime = `${days}d ${hours % 24}h ${minutes % 60}m ${seconds % 60}s`;
            console.log('Formatted uptime:', formattedUptime);
            return formattedUptime;
        }

        // Flipping text

        function flipText(text) {
            console.log('Flipping text:', text);
            const flip = {
                'a': 'ɒ', 'b': 'q', 'c': 'ɔ', 'd': 'p', 'e': 'ǝ', 'f': 'ɟ', 'g': 'ƃ', 'h': 'ɥ',
                'i': 'ı', 'j': 'ɾ', 'k': 'ʞ', 'l': 'ʃ', 'm': 'ɯ', 'n': 'u', 'o': 'o', 'p': 'd',
                'q': 'b', 'r': 'ɹ', 's': 's', 't': 'ʇ', 'u': 'n', 'v': 'ʌ', 'w': 'ʍ', 'x': 'x',
                'y': 'ʎ', 'z': 'z', ' ': ' '
            };
            const result = text.split('').map(char => flip[char] || char).reverse().join('');
            console.log('Flipped result:', result);
            return result;
        }

        // Calculator

        function calculate(expression) {
            console.log('Calculating expression:', expression);
            try {
                const result = math.evaluate(expression);
                console.log('Calculation result:', result);
                return result;
            } catch (e) {
                console.error('Calculation error:', e);
                return 'Error: Invalid calculation';
            }
        }

        // Print

        function handlePrint(command) {
            console.log('Print command received:', command);
            const text = command.slice(5).trim();
            const regex = /[^\s"']+|"([^"]*)"|'([^']*)'|\((.*?)\)/g;
            const matches = [...text.matchAll(regex)];
            const words = matches.map(match => match[0]);

            let output = '';
            for (let i = 0; i < words.length; i++) {
                const word = words[i];
                let value;
                    if (word.startsWith('(') && word.endsWith(')')) {
                const expression = word.slice(1, -1);
                try {
                    value = calculate(expression);
                } catch (e) {
                    value = word;
                }
            } else {
                value = userConfig.hasOwnProperty(word) ? userConfig[word] : word;
            }
            if (i < words.length - 1 && ['+', '-', '*', '/', '%'].includes(words[i + 1])) {
                if (!isNaN(value) && i + 2 < words.length && !isNaN(words[i + 2])) {
                    try {
                        output += calculate(`${value}${words[i + 1]}${words[i + 2]}`);
                        i += 2;
                    } catch (e) {
                        output += value;
                    }
                } else {
                    output += value;
                }
                i++;
            } else {
                const nextIsPlus = i < words.length - 1 && words[i + 1] === '+';
                output += value + (nextIsPlus ? '' : ' ');
            }
        }

            return output.trim() || 'Error: Please provide text or variable to print';
        }

        // Credits

        function getCredits() {
            console.log('Getting credits');
            return `Matthew "Dumbass" Orginald III.`;
        }

        // About

        function getAbout() {
            console.log('Getting about info');
            return 'Terminal based website. What more did u expect.';
        }

        // Help

        function handleHelp(command) {
            console.log('Help command requested, admin status:', loggedInAsAdmin);
            const args = command.split(' ').slice(1);
            if (args.length === 0) {
                if (loggedInAsAdmin) {
                    return `Admin Commands:
    - help: Show this admin help menu
    - whoami: Displays current user
    - users: Displays a list of users
    - restart: Restarts the console
    - logout: Log out of the admin account`;
                }
                return `General Commands:
    - help: Show this help menu
    - cls: Clear the console
    - time: Show the current time
    - ver: Shows the console version
    - whoami: Shows current user
    - weather: Shows the weather, may ask for permissions
    - random [min] [max]: Generate a random number between min and max
    - credits: Shows the creator of this site
    - about: Shows the info about this website
    - title [title]: Changes the title
    - prnt [text or var]: Prints that text or variable

    Variables:
    - set [var]: Sets a variable (by creating or overriding)
    - get [var]: Get variable value
    - config: Lists all variables
    - delete [var]: Delete a variable

    Directory:
    - dir: Shows the current directory
    - cd [directory]: Change current directory
    - type [file]: Display the content of a file

    Customization:
    - theme [light or dark]: Switches to the desired theme | FLASHBANG WARNING
    - font [tiny, small, medium, large, huge]: Switches to the desired font size
    - color [color]: Changes the text color to the desired color

    Fun:
    - coinflip: Simulates a coin flip
    - calc [expression]: Math, example: calc 1+1
    - flip [text]: Flips the text to unicode characters
    - ping [host]: Simulate a ping to a host
    - ai [message]: Chats with AI, no follow up questions
    - ai gpt [3.5 or 4]: Changes the gpt version of chatgpt
    - api [api]: Sets an API for the AI, AI doesnt otherwise work
    - install [package name]: Downloads a package from chocolatey or github (if it doesnt exist on chocolatey)
    - encode [text]: Encode text in base64
    - decode [text]: Decode text in base64

    Admin:
    - login [password]: Log in as an admin`;
            } else {
                const commandHelp = {
                    help: 'I wonder what?',
                    cls: 'Clears the console output.',
                    time: 'Shows the current time.',
                    ver: 'Displays the version of the console.',
                    whoami: 'Shows the current user.',
                    weather: 'Fetches the current weather based on your location.',
                    random: 'Generates a random number between the specified min and max values.',
                    credits: 'Displays the creator of this site.',
                    about: 'Shows information about this website.',
                    title: 'Changes the title of the console. Usage: title [new title]',
                    prnt: 'Prints the specified text or variable. Usage: prnt [text or var]',
                    set: 'Sets a variable. Usage: set [var] [value]',
                    get: 'Retrieves the value of a variable. Usage: get [var]',
                    config: 'Lists all variables.',
                    delete: 'Deletes a variable. Usage: delete [var]',
                    dir: 'Displays the current directory contents.',
                    cd: 'Changes the current directory. Usage: cd [directory]',
                    type: 'Displays the content of a specified file. Usage: type [file]',
                    theme: 'Changes the theme of the console. Usage: theme [light or dark]',
                    font: 'Changes the font size. Usage: font [tiny, small, medium, large, huge]',
                    color: 'Changes the text color. Accepts only normal color names (red, green, blue, etc...) Usage: color [color]',
                    coinflip: 'Simulates a coin flip.',
                    calc: 'Performs a calculation. Usage: calc [expression]',
                    flip: 'Flips the specified text to unicode characters. Usage: flip [text]',
                    ping: 'Pings a specified host. Usage: ping [host]',
                    ai: 'Chats with AI. Usage: ai [message] | Changes the GPT model. usage: ai gpt [3.5 or 4]',
                    install: 'Downloads a package. Usage: install [package name]',
                    api: 'Sets an API key for the AI. Usage: api [api key]',
                    encode: 'Encodes text in base64. Usage: encode [text]',
                    decode: 'Decodes base64 text. Usage: decode [text]',
                    login: 'Logs in as an admin. Usage: login [password]',
                    logout: 'Logs out of the admin account.',
                    admin: 'Executes an admin-only command.',
                    users: 'Displays a list of users.',
                    restart: 'Restarts the console.',
                    };

                    const specificCommand = args[0].toLowerCase();
                    if (commandHelp[specificCommand]) {
                        return commandHelp[specificCommand];
                    } else {
                        return `Error: No help available for command "${args[0]}".`;
                    }
                }
            }

            // Clear

            function handleClear() {
                console.log('Clearing console');
                consoleDiv.textContent = '';
                return '';
            }

            // Time

            function handleTime() {
                console.log('Getting current time');
                return new Date().toLocaleTimeString();
            }

            // Version

            function handleVersion() {
                console.log('Getting version info');
                return 'HTTPS Console\nV.1.0.0';
            }

            // Coin Flip

            function handleCoinflip() {
                console.log('Performing coinflip');
                const result = Math.random() < 0.5 ? "Heads" : "Tails";
                console.log('Coinflip result:', result);
                return result;
            }

            // WhoAmI

            function handleWhoami() {
                console.log('Whoami requested, admin status:', loggedInAsAdmin);
                return loggedInAsAdmin ? 'https://localhost/u/admin' : 'https://localhost/u/guest';
            }

            // Encode

            function handleEncode(command) {
                const text = command.slice(7).trim();
                return btoa(text);
            }

            // Decode

            function handleDecode(command) {
                const text = command.slice(7).trim();
                return atob(text);
            }

            // Title

            function handleTitle(command) {
                console.log('Title change requested:', command);
                const newTitle = command.slice(6).trim();
                if (newTitle) {
                    const oldTitle = document.title;
                    document.title = newTitle;
                    console.log(`Title changed from ${oldTitle} to ${newTitle}`);
                    return `Title changed to "${newTitle}"`;
                }
                console.error('No title provided');
                return 'Error: You need to provide a new title after "title". Example: title My New Title';
            }

            // Ping

            function handlePing(command) {
                console.log('Ping command received:', command);
                const host = command.slice(5).trim();
                if (host) {
                    pingHost(host).then(result => {
                        consoleDiv.textContent += result + '\n';
                    });
                    return '';
                }
                console.error('No host provided for ping');
                return 'Error: You need to provide a host after "ping". Example: ping google.com';
            }

            // ADMIN

            // Login

            function handleLogout() {
                console.log('Logout requested, current admin status:', loggedInAsAdmin);
                if (loggedInAsAdmin) {
                    loggedInAsAdmin = false;
                    console.log('Logout successful');
                    return 'You have logged out successfully.';
                }
                console.log('Logout failed - not logged in');
                return 'You are not logged in.';
            }

            // Admin

            function handleAdmin() {
                console.log('Admin command requested, admin status:', loggedInAsAdmin);
                if (loggedInAsAdmin) {
                    return 'Admin-only command executed!';
                }
                return 'Error: You must be logged in as admin to execute this command.';
            }

            // Users

            function handleUsers() {
                console.log('Users list requested, admin status:', loggedInAsAdmin);
                if (loggedInAsAdmin) {
                    return 'Users:\n- admin [CURRENT]\n- guest';
                }
                return 'Error: You must be logged in as admin to execute this command.';
            }

            // Restart

            function handleRestart() {
                console.log('Restart requested, admin status:', loggedInAsAdmin);
                if (loggedInAsAdmin) {
                    console.log('Initiating restart...');
                    setTimeout(() => {
                        location.reload(true);
                    }, 500);
                    return 'Restarting...';
                }
                return 'Error: You must be logged in as admin to execute this command.';
            }

            // Command Execution

            async function executeCommand(command) {
                console.log('Executing command:', command);
                const commands = command.split('&&').map(cmd => cmd.trim());
                if (commands.length > 1) {
                    let output = '';
                    for (const cmd of commands) {
                        const result = await executeCommand(cmd);
                        if (result) {
                            output += result + '\n';
                        }
                    }
                    return output.trim();
                }
                
                const [mainCommand, ...args] = command.toLowerCase().split(' ');

                switch (mainCommand) {
                    // General commands
                    case 'help':
                        return handleHelp(command);
                    case 'cls':
                        return handleClear();
                    case 'time':
                        return handleTime();
                    case 'ver':
                        return handleVersion();
                    case 'whoami':
                        return handleWhoami();
                    case 'weather':
                        return getWeather(command);
                    case 'random':
                        return getRandomNumber(parseInt(args[0], 10), parseInt(args[1], 10));
                    case 'credits':
                        return getCredits();
                    case 'about':
                        return getAbout();
                    case 'title':
                        return handleTitle(command);
                    case 'prnt':
                        return handlePrint(command);

                    // Variables
                    case 'set':
                        return handleSet(command);
                    case 'get':
                        return handleGet(command);
                    case 'config':
                        return handleConfig();
                    case 'delete':
                        return handleDelete(command);
                    
                    // Directory
                    case 'dir':
                        return directorySystem();
                    case 'cd':
                        return changeDirectory(args[0]);
                    case 'type':
                        return typeFile(args[0]);

                    // Customization
                    case 'font':
                        return handleFont(command);
                    case 'theme':
                        return handleTheme(command);
                    case 'color':
                        return await handleColor(command);

                    // Fun
                    case 'coinflip':
                        return handleCoinflip();
                    case 'calc':
                        return calculate(args.join(' '));
                    case 'flip':
                        return flipText(args.join(' '));
                    case 'ping':
                        return handlePing(command);
                    case 'ai':
                        return await handleAI(command);
                    case 'install':
                        return handleInstall(command);
                    case 'api':
                        return handleAPI(command);
                    case 'encode':
                        return handleEncode(command);
                    case 'decode':
                        return handleDecode(command);

                    // Admin
                    case 'login':
                        return login(args[0]);
                    case 'logout':
                        return handleLogout();
                    case 'admin':
                        return handleAdmin();
                    case 'restart':
                        return handleRestart();
                    case 'users':
                        return handleUsers();

                    // For someone dumb
                    case 'admin123':
                        return 'No, use it like this: login admin123 : not like certain someone did...';

                    // Error Handling
                    default:
                        console.error('Unknown command:', command);
                        return `'${command}' is not recognized as a command. Type 'help' for available commands.`;
                }
            }

        let history = [];
        let currentHistoryIndex = -1;

        function printToConsole(text) {
            const consoleDiv = document.getElementById("console");
            consoleDiv.textContent += `${text}\n`;
            consoleDiv.scrollTop = consoleDiv.scrollHeight;
        }

        document.addEventListener('keydown', async (e) => {
            const inputTextElement = document.getElementById('input-text');
            if (e.key === 'Enter') {
                e.preventDefault();
                const command = inputTextElement.value.trim();
                if (command) {
                    printToConsole(`> ${command}`);
                    const output = await executeCommand(command);
                    if (output) printToConsole(output);
                    history.push(command);
                    currentHistoryIndex = history.length;
                }
                inputTextElement.value = '';
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                if (currentHistoryIndex > 0) {
                    currentHistoryIndex--;
                    inputTextElement.value = history[currentHistoryIndex];
                }
            } else if (e.key === 'ArrowDown') {
                e.preventDefault();
                if (currentHistoryIndex < history.length - 1) {
                    currentHistoryIndex++;
                    inputTextElement.value = history[currentHistoryIndex];
                } else if (currentHistoryIndex === history.length - 1) {
                    inputTextElement.value = '';
                }
            }
        });
    </script>
</body>

</html>