make the ui draggable

// ==UserScript==
// @name         FurryChat Enhanced
// @namespace    http://tampermonkey.net/
// @version      1.4
// @description  Even Better FC with Add Friends Feature and Duplicate Prevention
// @author       You
// @match        https://furrychat.net/chat/
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // ========================
    // Define Variables
    // ========================

    // Initialize reload speed from localStorage or set default
    let speed = parseInt(localStorage.getItem('fcReloadSpeed')) || 1000; // Default to 1000ms

    // Variable to hold the interval ID for chat reloading
    let chatLog;

    // Flag to determine if the chat is paused
    let isPaused = false;

    // Key for storing added friends in localStorage
    const addedFriendsKey = 'fcAddedFriends';

    // Initialize the set of added friends from localStorage or create a new Set
    let addedFriends = new Set(JSON.parse(localStorage.getItem(addedFriendsKey)) || []);

    // ========================
    // Define fetchAndAddFriends
    // ========================

    /**
     * Fetches the user list and adds each user as a friend if not already added.
     */
    async function fetchAndAddFriends() {
        try {
            // Send the POST request
            const response = await fetch("https://furrychat.net/chat/system/panel/user_list.php", {
                method: "POST",
                headers: {
                    "Accept": "*/*",
                    "Accept-Language": "en-US,en;q=0.9,ru;q=0.8",
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "Origin": "https://furrychat.net",
                    "Referer": "https://furrychat.net/chat/",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
                    "X-Requested-With": "XMLHttpRequest"
                },
                body: new URLSearchParams({
                    "token": "b40f4fb84a60ab3a58b6d700f38eeb65" // Ensure this token is valid or dynamically fetched
                })
            });

            // Check if the response is OK
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }

            // Get the HTML response as text
            const html = await response.text();

            // Create a temporary DOM parser
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');

            // Select all elements containing the `dropUser` function call
            const userElements = doc.querySelectorAll("[onclick^='dropUser']");

            // Counter for added friends
            let addedCount = 0;
            let skippedCount = 0;

            // Extract IDs and call addFriend(ID) for each
            userElements.forEach(element => {
                const onclickAttr = element.getAttribute("onclick");
                const idMatch = onclickAttr.match(/dropUser\(this,(\d+),/);
                if (idMatch) {
                    const userID = idMatch[1];
                    if (!addedFriends.has(userID)) {
                        console.log(`Adding friend: ID ${userID}`);
                        addFriend(userID);  // Ensure `addFriend` is defined in the page context
                        addedFriends.add(userID);
                        addedCount++;
                    } else {
                        console.log(`Already added friend: ID ${userID} - Skipping`);
                        skippedCount++;
                    }
                }
            });

            // Save the updated set of added friends to localStorage
            localStorage.setItem(addedFriendsKey, JSON.stringify(Array.from(addedFriends)));

            // Provide feedback to the user
            alert(`Add Friends process completed!\nAdded: ${addedCount}\nSkipped (already friends): ${skippedCount}`);

        } catch (error) {
            console.error("Error fetching or adding friends:", error);
            alert("An error occurred while adding friends. Check the console for details.");
        }
    }

    // ========================
    // Create Settings Panel
    // ========================

    // Define the HTML for the settings panel, including the new "Add Friends" button and "Reset Added Friends" button
    const settingsPanel = `
        <div id="reload-settings" style="
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 9999;
            font-family: Arial, sans-serif;
            font-size: 14px;
        ">
            <h3 style="margin-top: 0;">Chat Settings</h3>
            <label for="reload-slider">Reload Speed:</label>
            <input type="range" id="reload-slider" min="100" max="5000" value="${speed}" step="100" style="width: 100%;">
            <span id="reload-value">${speed}</span> ms<br><br>
            <button id="pause-button" style="
                background-color: ${isPaused ? 'green' : 'blue'};
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                cursor: pointer;
                margin-bottom: 10px;
            ">
                ${isPaused ? 'Resume' : 'Pause'}
            </button><br>
            <button id="add-friends-button" style="
                background-color: green;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                cursor: pointer;
                width: 100%;
                margin-bottom: 10px;
            ">
                Add Friends
            </button>
            <button id="reset-friends-button" style="
                background-color: red;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                cursor: pointer;
                width: 100%;
            ">
                Reset Added Friends
            </button>
        </div>
    `;

    // Append the settings panel to the body
    $('body').append(settingsPanel);

    // ========================
    // Event Listeners
    // ========================

    /**
     * Toggle Pause/Resume of Chat Reloading
     */
    $('#pause-button').on('click', function() {
        isPaused = !isPaused;  // Toggle pause state
        $(this).text(isPaused ? 'Resume' : 'Pause');
        $(this).css('background-color', isPaused ? 'green' : 'blue');

        if (isPaused) {
            clearInterval(chatLog); // Stop the interval
            console.log("Chat reloading paused.");
        } else {
            chatLog = setInterval(chatReload, speed); // Restart the interval
            chatReload(); // Force an immediate reload
            console.log("Chat reloading resumed.");
        }
    });

    /**
     * Update Reload Speed based on Slider Input
     */
    $('#reload-slider').on('input', function() {
        speed = parseInt($(this).val());
        $('#reload-value').text(speed);
        localStorage.setItem('fcReloadSpeed', speed); // Save to localStorage

        if (!isPaused) { // Only restart if not paused
            clearInterval(chatLog);
            chatLog = setInterval(chatReload, speed);
            console.log(`Chat reload speed set to: ${speed} ms`);
        }
    });

    /**
     * Trigger fetchAndAddFriends when "Add Friends" button is clicked
     */
    $('#add-friends-button').on('click', function() {
        // Optional: Confirm action with the user
        if (confirm("Are you sure you want to add all users as friends who aren't already friends?")) {
            fetchAndAddFriends();
        }
    });

    /**
     * Reset the list of added friends when "Reset Added Friends" button is clicked
     */
    $('#reset-friends-button').on('click', function() {
        if (confirm("Are you sure you want to reset the list of added friends? This will allow adding the same friends again.")) {
            addedFriends.clear();
            localStorage.removeItem(addedFriendsKey);
            alert("Added friends list has been reset.");
            console.log("Added friends list has been reset.");
        }
    });

    // ========================
    // Initialize Chat Reloading
    // ========================

    /**
     * Function to reload chat - replace with actual implementation
     */


    // Start the chat reloading interval if not paused
    if (!isPaused) {
        chatLog = setInterval(chatReload, speed);
    }

    // ========================
    // Observe 'reload-value' for Changes
    // ========================

    /**
     * Observe changes to the reload speed display and update localStorage accordingly
     */
    const speedObserver = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type === 'childList') {
                localStorage.setItem('fcReloadSpeed', mutation.target.textContent);
            }
        });
    });

    const speedElement = document.getElementById('reload-value');
    if (speedElement) {
        speedObserver.observe(speedElement, { childList: true });
    }

    // ========================
    // Optional: Automatically Add Friends on Load
    // ========================
    // Uncomment the line below to automatically run fetchAndAddFriends when the script loads
    // fetchAndAddFriends();

})();