<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="favicon.ico">
    <title>NINEHACK</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
    <style>
        html, body {
            overflow: hidden;
            height: 100%;
        }
        .container {
            display: flex;
            height: 100vh;
        }
        .list-container {
            width: 50%;
            padding: 20px;
            background-color: #f9f9f9;
            border-right: 2px solid #ccc;
            overflow-y: auto;
        }
        .control-container {
            width: 50%;
            padding: 20px;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
        }

        #debug {
            display: block;
            width: 100%; /* Ensure debug takes full width */
            margin-top: 20px; /* Add space between the control and debug section */
        }


        .textarea {
            width: 100%; /* Make the textarea take full width */
        }

        .input {
            width: 100%; /* Ensure input takes full width */
            margin-right: 10px;
        }

        .button {
            width: 100%; /* Buttons inside #debug should take full width */
        }

        .radio-buttons {
            margin: 15px 0;
        }
        #device-dropdown {
            margin-top: 20px;
            display: none;
            width: 100%; /* Full width */
        }

        .select {
            width: 100%; /* Full width for the select element */
        }

        /* Ensuring the select element inside the dropdown takes full width */
        #device-select {
            width: 100%; /* Full width for the device select */
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="list-container">
            <h3 class="title is-4 has-text-centered">Devices</h3>
            <p id="no-items-text">No devices scanned yet.</p>
            <!-- Список устройств будет отображаться здесь -->
            <ul id="item-list" class="list is-hoverable"></ul>
        </div>

        <div class="control-container">
            <button id="scan-button" class="button" style="width: 100%; height: 40%;" onclick="scanAction()">Scan</button>
            <div class="radio-buttons">
                <label class="radio">
                    <input type="radio" name="mode" value="Bluetooth" checked>
                    Bluetooth
                </label>
                <label class="radio">
                    <input type="radio" name="mode" value="Serial" disabled>
                    Serial
                </label>
            </div>

            <!-- Выпадающий список для выбора устройства -->
            <div id="device-dropdown">
                <label class="label" id="devicedrop">Select</label>
                <div class="control" id="devicedrop">
                    <div class="select" style="margin-bottom: 10px;">
                        <select id="device-select">
                            <option value="" disabled selected>Select a device</option>
                        </select>
                    </div>
                </div>
                <button id="select-button" class="button is-fullwidth" onclick="selectDevice()">Select Device</button>
            </div>
            <div style="display: none; width: 100%;" id="debug">
                <textarea class="textarea" id="debug_text" style="height: 160px; margin-bottom: 10px;" disabled></textarea>
                <div style="margin-bottom: 10px; display:flex; flex-direction: row;">
                    <input class="input" style="margin-right: 10px;" placeholder="Command" disabled value="CMD (disabled)"></input>
                    <button class="button" disabled>Send</button>
                </div>
                <button id="lock" class="button is-fullwidth" style="margin-bottom: 5px;" disabled>Lock</button>
                <button id="unlock" class="button is-fullwidth" style="margin-bottom: 5px;" disabled>Unlock</button>
            </div>
        </div>
    </div>

    <script>
        // Declare variables in global scope
        let itemCount = 0;
        let deviceSelect, deviceDropdown, deviceDrop, debug, debug_text;

        document.addEventListener('DOMContentLoaded', () => {
            // Initialize global variables after DOM is loaded
            deviceSelect = document.getElementById('device-select');
            deviceDropdown = document.getElementById('device-dropdown'); // Correct unique ID
            deviceDrop = document.getElementById('devicedrop');
            debug = document.getElementById('debug');
            debug_text = document.getElementById('debug_text');
        });

        async function scanAction() {
            deviceDrop.style = "";
            debug_text.value = "";
            debug.style = "display: none;";

            const mode = document.querySelector('input[name="mode"]:checked').value;
            itemCount++;

            // Change the button's class to "loading"
            const scanButton = document.getElementById('scan-button');
            scanButton.classList.toggle('is-loading'); // Add or remove loading class

            try {
                // Send request to server to start scanning
                const response = await fetch(`/scan?mode=${mode}`);
                const data = await response.json();

                // Update the item list
                const list = document.getElementById('item-list');
                list.innerHTML = ''; // Clear current list
                deviceSelect.innerHTML = '<option value="" disabled selected>Select a device</option>'; // Reset dropdown

                if (data.length > 0) {
                    // Show the dropdown
                    deviceDropdown.style.display = 'block';
                    data.forEach((device) => {
                        // Add device to the list
                        const listItem = document.createElement('li');
                        listItem.className = 'list-group-item';
                        listItem.style = "cursor: pointer;";
                        listItem.textContent = `${device.name} (${device.macAddress})`;
                        listItem.onclick = () => {
                            deviceSelect.value = device.macAddress; // Set selected device
                        };
                        list.appendChild(listItem);

                        // Add device to the dropdown
                        const option = document.createElement('option');
                        option.value = device.macAddress;
                        option.textContent = `${device.name} (${device.macAddress})`;
                        deviceSelect.appendChild(option);
                    });
                    document.getElementById('no-items-text').style.display = 'none';
                } else {
                    document.getElementById('no-items-text').style.display = 'block';
                }
            } catch (error) {
                console.error('Error during scan:', error);
            } finally {
                // Remove loading class from button
                scanButton.classList.remove('is-loading');
            }
        }

        async function selectDevice() {
            const selectedDevice = deviceSelect.value;

            // Hide the device dropdown and show the debug area
            deviceDropdown.style.display = "none";
            debug.style.display = "block";
            debug_text.value = `Connecting to ${selectedDevice}...\n`;

            try {
                // Fetch data from /connect
                const step1Response = await fetch('/connect');
                if (!step1Response.ok) throw new Error(`ERR: ${step1Response.status}`);
                const step1Data = await step1Response.text();
                debug_text.value += `${step1Data}\n`;

                // Fetch data from /step2
                const step2Response = await fetch('/command');
                if (!step2Response.ok) throw new Error(`ERR: ${step2Response.status}`);
                const step2Data = await step2Response.text();
                debug_text.value += `${step2Data}\n`;

                const step3Response = await fetch('/key');
                if (!step3Response.ok) throw new Error(`ERR: ${step3Response.status}`);
                const step3dt = await step3Response.text();
                debug_text.value += `${step3dt}\n`;

                const step4Response = await fetch('/key_check');
                if (!step4Response.ok) throw new Error(`ERR: ${step4Response.status}`);
                const step4dt = await step4Response.text();
                debug_text.value += `${step4dt}\n`;

            } catch (error) {
                debug_text.value += `Error: ${error.message}\n`;
            }
        }

        async function selectDevice() {
            const selectedDevice = deviceSelect.value;

            // Hide the device dropdown and show the debug area
            deviceDropdown.style.display = "none";
            debug.style.display = "block";
            debug_text.value = `Connecting to ${selectedDevice}...\n`;

            try {
                // Fetch data from /connect
                const step1Response = await fetch('/connect');
                if (!step1Response.ok) throw new Error(`ERR: ${step1Response.status}`);
                const step1Data = await step1Response.text();
                debug_text.value += `${step1Data}\n`;

                // Fetch data from /step2
                const step2Response = await fetch('/command');
                if (!step2Response.ok) throw new Error(`ERR: ${step2Response.status}`);
                const step2Data = await step2Response.text();
                debug_text.value += `${step2Data}\n`;

                const step3Response = await fetch('/key');
                if (!step3Response.ok) throw new Error(`ERR: ${step3Response.status}`);
                const step3dt = await step3Response.text();
                debug_text.value += `${step3dt}\n`;

                const step4Response = await fetch('/key_check');
                if (!step4Response.ok) throw new Error(`ERR: ${step4Response.status}`);
                const step4dt = await step4Response.text();
                debug_text.value += `${step4dt}\n`;

            } catch (error) {
                
            }
        }
    </script>

</body>
</html>
