document.addEventListener('DOMContentLoaded', function() {
    function getCookie(name) {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.startsWith(name + '=')) {
                return cookie.substring(name.length + 1, cookie.length);
            }
        }
        return null;
    }

    const username = getCookie('name'); // Using 'name' to match your cookie structure
    const usernameField = document.getElementById('username_field');
    if (usernameField && username) {
        usernameField.textContent = username;
    }else{
        usernameField.textContent = 'Admin';
    }

    // Define handler function
    function handleButtonClick(event) {
        console.log(`${event.target.id} button was clicked`);
        // Implement specific logic for each button here
    }

    // Attach event handlers to specific buttons
    const startUcButton = document.getElementById('start_uc');
    const stopUcButton = document.getElementById('stop_uc');
    const ceoInfoButton = document.getElementById('ceo_info');
    const usersInfoButton = document.getElementById('users_info');
    const resetUcButton = document.getElementById('reset_uc');
    const logoutButton = document.getElementById('logout');

    startUcButton.addEventListener('click', () => {
        console.log('Start UC Button pressed');
        fetch('/server', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ action: 'start' }),
        })
            .then(response => response.json())
            .then(data => alert(data.message))
            .catch(error => console.error('Error:', error));
    });

    stopUcButton.addEventListener('click', () => {
        console.log('Stop UC Button pressed');
        fetch('/server', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ action: 'stop' }),
        })
            .then(response => response.json())
            .then(data => alert(data.message))
            .catch(error => console.error('Error:', error));
    });

    ceoInfoButton.addEventListener('click', () => {
        console.log('Ceo Info Button pressed');

        const domain = window.location.hostname;
        const endpoint = 'http://' + domain + ':5000/admin/ceo';
        const id = getCookie('id');

        fetch(endpoint, {
            method: 'GET',
            headers: {
                'Authorization': id,
                'x-api-key': "uc_api"
            },
        })
            .then(async response => {
                if (!response.ok) {
                    const responseData = await response.json();
                    throw new Error(responseData.message);
                }

                return await response.json()
            })
            .then(data => {
                alert(data.message);

                // Assuming 'data' is the property you want to download
                const toDownload = data.data;
                const jsonStr = JSON.stringify(toDownload, null, 2);
                const blob = new Blob([jsonStr], { type: 'application/json' });
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = 'ceo.json';
                document.body.appendChild(a);
                a.click();

                // Cleanup: remove the link and revoke the URL
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            })
            .catch(error => {
                alert(error)
                console.error('Error: '+ error)
            });
    })

    usersInfoButton.addEventListener('click', () => {
        console.log('Users Info Button pressed');

        const domain = window.location.hostname;
        const endpoint = 'http://' + domain + ':5000/admin/users';
        const id = getCookie('id');

        fetch(endpoint, {
            method: 'GET',
            headers: {
                'Authorization': id,
                'x-api-key': "uc_api"
            },
        })
            .then(async response => {
                if (!response.ok) {
                    const responseData = await response.json();
                    throw new Error(responseData.message);
                }

                return await response.json()
            })
            .then(data => {
                alert(data.message);

                const toDownload = data.data;
                const jsonStr = JSON.stringify(toDownload, null, 2);
                const blob = new Blob([jsonStr], { type: 'application/json' });
                const url = URL.createObjectURL(blob);

                // Create a temporary link to trigger the download
                const a = document.createElement('a');
                a.href = url;
                a.download = 'users.json';
                document.body.appendChild(a);
                a.click();

                // Cleanup: remove the link and revoke the URL
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            })
            .catch(error => {
                alert(error)
                console.error('Error: '+ error)
            });
    })

    resetUcButton.addEventListener('click', () => {
        console.log('Reset UC Button pressed');

        const domain = window.location.hostname;
        const endpoint = 'http://' + domain + ':5000/admin/reset_server';
        const id = getCookie('id');

        fetch(endpoint, {
            method: 'GET',
            headers: {
                'Authorization': id,
                'x-api-key': "uc_api"
            },
        })
            .then(async response => {
                if (!response.ok) {
                    const responseData = await response.json();
                    throw new Error(responseData.message);
                }

                return await response.json()
            })
            .then(data => alert(data.message))
            .catch(error => {
                alert(error)
                console.error('Error: '+ error)
            });
    })

    logoutButton.addEventListener('click', () => {
        console.log('Logout button was clicked');

        const deleteCookie = (name) => {
            document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure`;
        }

        deleteCookie('email');
        deleteCookie('name');
        deleteCookie('id');

        fadeOut('/login');
    });
});
