document.addEventListener('DOMContentLoaded', async function () {
    const cancelButton = document.getElementById('login');
    const continueButton = document.getElementById('continue');

    const signupDataExists = await window.electronAPI.checkFileExists('signupData.json');
    if (signupDataExists) {
        await window.electronAPI.readFile('signupData.json')
            .then(result => {
                const signupData = JSON.parse(result.content);

                // Assign the values to the form inputs
                if (signupData.email) document.querySelector('input[name="email"]').value = signupData.email;
                if (signupData.name) document.querySelector('input[name="name"]').value = signupData.name;
                if (signupData.password) document.querySelector('input[name="password"]').value = signupData.password;
            })
            .catch(error => {
                console.error('Error reading signup data:', error.message);
            });
    }

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

    cancelButton.addEventListener('click', function () {
        console.log(`'Login' button clicked!`);
        fadeOut('login.html');
    });

    continueButton.addEventListener('click', async function (e) {
        e.preventDefault();
        console.log('Continue button clicked');

        const form = document.getElementById('signupForm');
        const formData = new FormData(form);

        const email = formData.get('email');

        await fetch(`http://${ip}/users/validate_email`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': 'uc_api'
            },
            body: JSON.stringify({
                email: email
            })
        }).then(async response => {
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.message);
            }

        }).then(async () => {
            const formDataJSON = {};
            formData.forEach((value, key) => {
                formDataJSON[key] = value;
            });

            await window.electronAPI.writeFile('signupData.json', JSON.stringify(formDataJSON));
            fadeOut('sign_up_departments.html');
        }).catch(async error => {
            await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error changing content:', error));
        })
    });
});