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

    submitButton.addEventListener('click', async function (e) {
        e.preventDefault();
        try {
            const ipAddress = ipInput.value.trim();
            if (!ipAddress) {
                throw new Error('Please enter an IP address.');
            }

            fetch(`http://${ipAddress}/heartbeat`)
                .then(async response => {
                    if (!response.ok) {
                        throw new Error('Test failed. Check ip and server.');
                    }

                    await window.electronAPI.writeFile('ipConfig.json', JSON.stringify({ip: ipAddress}));
                    fadeOut('login.html');
                })
                .catch(async error => {
                    await window.electronAPI.showAlert('Can\'t reach server.')
                        .then(() => console.log('Alert window opened'))
                        .catch(error => console.error('Error showing alert:', error));
                });
        } catch (error) {
            console.error('Error:', error.message);
            await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
        }
    });
});
