document.addEventListener('DOMContentLoaded', async function() {
    try {
        // Make API call to fetch department data
        const response = await fetch('http://localhost:5000/departments', {
            method: 'GET',
            headers: {
                'x-api-key': 'uc_api'
            }
        });
        const res = await response.json();
        const data = res['data'];

        const formContent = document.querySelector('.signup-form-content');
        data.forEach(department => {
            const label = document.createElement('label');
            label.innerHTML = `<input type="radio" name="dept" value="${department.id}">${department.name}`;
            formContent.appendChild(label);
        });
    } catch (error) {
        await window.electronAPI.showAlert(error.message)
            .then(() => console.log('Alert window opened'))
            .catch(error => console.error('Error changing content:', error));
    }

    document.getElementById('back').addEventListener('click', async function() {
        try {
            await window.electronAPI.changeContent('sign_up_profile.html');
            console.log('Content changed successfully');
        } catch (error) {
            console.error('Error changing content:', error);
        }
    });

    // Handler for the continue button
    document.getElementById('submit').addEventListener('click', async function(e) {
        e.preventDefault();

        const selectedDept = document.querySelector('input[name="dept"]:checked').value;

        try {
            if (!selectedDept) {
                throw new Error('No department had been selected!.');
            }

            let result = await window.electronAPI.readFile('signupData.json');
            if (!result.success) {
                throw new Error('Error reading the file. Please try again later.');
            }

            const data = JSON.parse(result.content);

            const email = data.email;
            const name = data.name;
            const password = data.password;

            result = await window.electronAPI.deleteFile('signupData.json');
            if (!result.success) {
                throw new Error('Error deleting the file. Please try again later.');
            }

            await fetch('http://localhost:5000/users/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'uc_api'
                },
                body: JSON.stringify({
                    name: name,
                    email: email,
                    password: password,
                    department: selectedDept,
                })
            }).then(async response => {
                if(!response.ok){
                    await window.electronAPI.showAlert("Internal server error. Try again later!")
                        .then(() => console.log('Alert window opened'))
                        .catch(error => console.error('Error changing content:', error));
                }

                window.electronAPI.changeContent('sign_up_confirmation.html')
                    .then(() => console.log('Content changed successfully'))
                    .catch(error => console.error('Error changing content:', error));
            }).catch(error => {
               console.error(error);
            });

        } catch (error) {
            await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error changing content:', error));
        }
    });
});
