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 setConfButton = document.getElementById('set_conf');
    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');
    })

    setConfButton.addEventListener('click', () => {
        console.log('Set Conf Button pressed');
    })

    logoutButton.addEventListener('click', function() {
        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');

        window.location.href = '/login';
    });
});
