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

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

    const signupForm = document.getElementById('signupForm');
    signupForm.addEventListener('submit', (e) => {
        e.preventDefault();
        document.getElementById('errors').innerText = '';
        document.getElementById('errors').classList.add('d-none');
    
        // Extract form data
        const username = signupForm.querySelector('#username').value;
        const dob = signupForm.querySelector('#u_dob').value;
        const country = signupForm.querySelector('#userCountry').value;
        const gender = signupForm.querySelector('#gender').value;
        const email = signupForm.querySelector('#email').value;
        const password = signupForm.querySelector('#password').value;
        const password2 = signupForm.querySelector('#password2').value;
        const tosInput = signupForm.querySelector('#tos');
        const tos = tosInput.checked;

        // Remove errors
        document.getElementById('errors').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);
            // document.getElementById('spinner').classList.remove('show');
            if (msg && msg.status === 'fail') {
                document.getElementById('errors').innerText = msg.message;
                document.getElementById('errors').classList.remove('d-none');
            } else {
                setTimeout(() => {
                    window.location.href = '/login/';
                }, 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 [];
    }
}
