document.addEventListener('DOMContentLoaded', async function () {
    const signinButton = document.getElementById('signin');
    const submitButton = document.getElementById('submit');

    await window.electronAPI.readFile('loginData.json')
        .then(async result => {
            const loginData = JSON.parse(result.content);
            const { email, password } = loginData;

            const response = await fetch('http://localhost:5000/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'uc_api'
                },
                body: JSON.stringify({
                    email: email,
                    password: password
                })
            });

            if(response.ok) {
                window.electronAPI.changeContent('main_menu.html')
                    .then(() => console.log('Navigated to dashboard'))
                    .catch(error => console.error('Error navigating:', error));
            }
        }).catch(async error => {
            console.error('Can\'t read loginData');
            await window.electronAPI.deleteFile('loginData.json')
        });

    signinButton.addEventListener('click', function (e) {
        window.electronAPI.changeContent('sign_up_profile.html')
            .then(() => console.log('Content changed successfully'))
            .catch(error => console.error('Error changing content:', error));
    });

    submitButton.addEventListener('click', async function (e) {
        try {
            e.preventDefault();
            console.log('Submit button clicked');

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

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

            if (!email || !password) {
                throw new Error('Both email and password are required.');
            }

            const response = await fetch('http://localhost:5000/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'uc_api'
                },
                body: JSON.stringify({
                    email: email,
                    password: password
                })
            });

            switch (response.status) {
                case 401:
                    throw new Error('Invalid credentials!');
                case 500:
                    throw new Error('Internal server error. Try again later!');
            }

            const responseBody = await response.json();

            const result = await window.electronAPI.writeFile('loginData.json', JSON.stringify(responseBody.message, null, 2));
            if (!result.success) {
                throw new Error('Error writing to file. Please try again later.');
            }

            window.electronAPI.changeContent('main_menu.html')
                .then(() => console.log('Navigated to dashboard'))
                .catch(error => console.error('Error navigating:', error));

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