document.addEventListener('DOMContentLoaded', async function () {
    await insertUsername();

    const backupButton = document.getElementById('backup');
    const shareButton = document.getElementById('share_dir');
    const changeDepartmentButton = document.getElementById('change_department');
    const changeInfoButton = document.getElementById('change_info');
    const shareFileButton = document.getElementById('share_file');
    const decryptButton = document.getElementById('decrypt');
    const logoutButton = document.getElementById('logout');

    const overlay = document.getElementById('overlay');
    const ceoBackButton = document.getElementById('back_button');
    const ceoSubmitButton = document.getElementById('submit_button');

    let ip = '';
    await window.electronAPI.readFile('ipConfig.json')
        .then(result => {
            const jsonData = JSON.parse(result.content);
            ip = jsonData.ip;
        })

    let triggerSource = '';

    function handleOverlayOpen(buttonId) {
        overlay.style.display = 'block';
        triggerSource = buttonId; // Remember the button that triggered the overlay
        console.log(`${buttonId} button clicked!`);
    }

    ceoBackButton.addEventListener('click', function () {
        overlay.style.display = 'none';
    });

    ceoSubmitButton.addEventListener('click', async function (event) {
        event.preventDefault();
        const password = document.getElementById('ceo_password').value;

        await fetch(`http://${ip}/users/validate_ceo_password`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': 'uc_api',
            },
            body: JSON.stringify({
                password: password
            })
        }).then(async result => {
            const data = await result.json();
            if (!result.ok) {
                throw new Error(data.message);
            }
            if (triggerSource === 'change_department') {
                fadeOut('change_department.html');
            } else if (triggerSource === 'decrypt') {
                console.log('astept decryptarea')
                fadeOut('decrypting_backup.html');
            }
        })

        overlay.style.display = 'none';
        triggerSource = '';
    });

    checkDirBackupFileExists()
        .then(() => console.log('verificare backupDir facuta'));

    checkShareDirFileExists()
        .then(() => console.log('verificare ShareDir facuta'));

    checkDepartmentDirFileExists()
        .then(() => {console.log('verificare departmentDir facuta')})

    backupButton.addEventListener('click', function () {
        console.log('Set backup directory button clicked!');

        window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));
    });

    shareButton.addEventListener('click', function () {
        console.log('Set backup directory button clicked!');

        window.electronAPI.openJsonDirConfigDialog('dirShare.json')
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));
    });

    changeInfoButton.addEventListener('click', function () {
        console.log('Change your info button clicked!');
        fadeOut('profile.html');
    });

    changeDepartmentButton.addEventListener('click', function () {
        handleOverlayOpen('change_department');
    });

    decryptButton.addEventListener('click', function () {
        handleOverlayOpen('decrypt');
    });

    shareFileButton.addEventListener('click', function () {
        console.log('Share a file button clicked!');
        fadeOut('share_file.html');
    });

    logoutButton.addEventListener('click', async function () {
        console.log('Logout button clicked!');
        await window.electronAPI.killBeforeLogout();
        await window.electronAPI.deleteFile('loginData.json');
        fadeOut('login.html');
    });

    async function checkDirBackupFileExists() {
        try {
            // Make an IPC call to check file existence
            const fileExists = await window.electronAPI.checkFileExists('dirBackup.json');

            if (!fileExists) {
                const notificationsDiv = document.getElementById('notifications');
                const button = document.createElement('button');
                button.id = 'backup_alert';
                button.name = 'alert';
                button.textContent = 'Set your backup directory!';
                button.addEventListener('click', handleBackupButtonPressed);
                notificationsDiv.appendChild(button);
            }
        } catch (error) {
            console.error('Error checking file existence:', error);
        }
    }

    async function checkShareDirFileExists() {
        try {
            const fileExists = await window.electronAPI.checkFileExists('dirShare.json');

            if (!fileExists) {
                const notificationsDiv = document.getElementById('notifications');
                const button = document.createElement('button');
                button.id = 'share_file_alert';
                button.name = 'alert';
                button.textContent = 'Set your share directory!';
                button.addEventListener('click', handleShareButtonPressed);
                notificationsDiv.appendChild(button);
            }
        } catch (error) {
            console.error('Error checking file existence:', error);
        }
    }

    async function checkDepartmentDirFileExists() {
        try {
            const fileExists = await window.electronAPI.checkFileExists('dirDepartment.json');

            if (!fileExists) {
                const notificationsDiv = document.getElementById('notifications');
                const button = document.createElement('button');
                button.id = 'department_alert';
                button.name = 'alert';
                button.textContent = 'Set your department directory!';
                button.addEventListener('click', handleDepartmentButtonPressed);
                notificationsDiv.appendChild(button);
            }
        } catch (error) {
            console.error('Error checking file existence:', error);
        }
    }

    async function handleBackupButtonPressed() {
        console.log('Button clicked!');

        await window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));

        const button = document.getElementById('backup_alert');
        button.remove();
    }

    async function handleShareButtonPressed() {
        console.log('Button clicked!');

        await window.electronAPI.openJsonDirConfigDialog('dirShare.json')
            .then(() => console.log('Share directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));

        const button = document.getElementById('backup_alert');
        button.remove();
    }

    async function handleDepartmentButtonPressed() {
        console.log('Button clicked!');

        await window.electronAPI.openJsonDirConfigDialog('dirDepartment.json')
            .then(() => console.log('Department directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));

        const button = document.getElementById('backup_alert');
        button.remove();
    }

    async function insertUsername() {
        try {
            const userData = await window.electronAPI.readFile('loginData.json');
            const userJson = JSON.parse(userData.content);
            const username = userJson.name;

            const usernameField = document.getElementById('username_field');
            if (usernameField) {
                usernameField.textContent = username + '!';
            }
        } catch (error) {
            console.error('Error loading username:', error);
            const usernameField = document.getElementById('username_field');
            usernameField.textContent = 'User!';
        }
    }
});
