document.addEventListener('DOMContentLoaded', async (v) => {
    let countries = await fetchCountries();

    // Handlers
    let countrySelector = document.getElementById('userCountry');
    for(country of countries){
        countrySelector.innerHTML += `<option value="${country.text}">${country.text}</option>`;
    }

    let signupForm = document.getElementById('signup');
    signupForm.addEventListener('submit', (e) => {
        e.preventDefault();
        document.getElementById('spinner').classList.add('show');
    
        // Extract form data
        let username = signupForm.querySelector('#username').value;
        let dob = signupForm.querySelector('#u_dob').value;
        let country = signupForm.querySelector('#userCountry').value;
        let gender = signupForm.querySelector('#gender').value;
        let email = signupForm.querySelector('#email').value;
        let password = signupForm.querySelector('#password').value;
        let password2 = signupForm.querySelector('#password2').value;
        let tosInput = signupForm.querySelector('#tos');
        let tos = tosInput.checked;

        // Remove errors
        document.getElementById('usernameError').innerText = null;
        document.getElementById('countryError').innerText = null;
        document.getElementById('emailError').innerText = null;
        document.getElementById('dobError').innerText = null;
        document.getElementById('genderError').innerText = null;
        document.getElementById('passwordError').innerText = null;
        document.getElementById('password2Error').innerText = null;

    
        let userData = {
            username: username,
            country: country,
            gender: gender,
            email: email,
            dob: dob,
            password: password,
            password2: password2,
            acceptTerms: tos
        };
    
        let action = 'signup';
    
        let formData = JSON.stringify({
            action: action,
            userData: userData
        });
    
        // Send request
        fetch('https://api.stellaamor.com/users.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: formData
        })
        .then(response => {
            if(response && response.length){
                return response.json();
            }else{
                return null;
            }
        })
        .then(msg => {
            console.log(msg);
            // If we have a JSON response, process it; otherwise, assume success
            document.getElementById('spinner').classList.remove('show');
            if (msg && msg.status === 'fail') {
                let errorArea = msg.fail_status;
    
                if (errorArea === 'username') {
                    document.getElementById('usernameError').innerText = msg.message;
                }
                if (errorArea === 'country') {
                    document.getElementById('countryError').innerText = msg.message;
                }
                if (errorArea === 'email') {
                    document.getElementById('emailError').innerText = msg.message;
                }
                if (errorArea === 'dob') {
                    document.getElementById('dobError').innerText = msg.message;
                }
                if (errorArea === 'gender') {
                    document.getElementById('genderError').innerText = msg.message;
                }
                if (errorArea === 'password') {
                    document.getElementById('passwordError').innerText = msg.message;
                }
                if (errorArea === 'password2' || errorArea === 'passwords') {
                    document.getElementById('password2Error').innerText = msg.message;
                }
            } else {
                // Success: Redirect to signin page
                setTimeout(() => {
                    window.location.href = '/signin';
                }, 2000);
            }
        })
        .catch(error => {
            console.error('Error during signup:', error);
            document.getElementById('errors').innerText = 'An error occurred. Please try again later.';
        });
    });
    


    // Call init functions
});

async function fetchCountries() {
    try {
        const response = await fetch('https://restcountries.com/v3.1/all?fields=name');
        const data = await response.json();

        const countries = data.map(country => ({
            text: country.name.common,
            val: country.cca2,
        })).sort((a, b) => a.text.localeCompare(b.text));

        return countries;
    } catch (error) {
        console.error('Error fetching countries:', error);
        return [];
    }
}
