const forms = document.querySelectorAll('.leadform');
const errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];
const languagesByCountry = {
    'AL': 'sq',
    'AD': 'ca',
    'AM': 'hy',
    'AT': 'de',
    'AZ': 'az',
    'BY': 'be',
    'BE': 'nl',
    'BA': 'bs',
    'BG': 'bg',
    'HR': 'hr',
    'CY': 'el',
    'CZ': 'cs',
    'DK': 'da',
    'EE': 'et',
    'FI': 'fi',
    'FR': 'fr',
    'GE': 'ka',
    'DE': 'de',
    'GR': 'el',
    'HU': 'hu',
    'IS': 'is',
    'IE': 'ga',
    'IT': 'it',
    'KZ': 'kk',
    'LV': 'lv',
    'LI': 'de',
    'LT': 'lt',
    'LU': 'lb',
    'MT': 'mt',
    'MD': 'ro',
    'MC': 'fr',
    'ME': 'sr',
    'NL': 'nl',
    'MK': 'mk',
    'NO': 'no',
    'PL': 'pl',
    'PT': 'pt',
    'RO': 'ro',
    'SM': 'it',
    'RS': 'sr',
    'SK': 'sk',
    'SI': 'sl',
    'ES': 'es',
    'SE': 'sv',
    'CH': 'de',
    'TR': 'tr',
    'GB': 'en',
    'VA': 'it',
    'CA': 'en',
    'AU': 'en'
};

function getLanguageByGeo(geo) {
    return languagesByCountry[geo] || 'uk'; // default value
}

async function getCountryByIP() {
    // Локальная функция - возвращаем дефолтную страну
    return 'TR'; // default value для Турции
}

function isOnlyCountries(form, onlyCountries, itiCountry) {
    if (onlyCountries.length > 0) {
        if (!onlyCountries.includes(itiCountry)) {
            showError(form, "This country is not supported");
            return true;
        }
    }

    return false;
}

function showError(form, msg) {
    const phone = form.querySelector('input[name="phone"]');
    const errorMsg = form.querySelector('.error-msg');
    phone.classList.add("error");
    errorMsg.innerHTML = msg;
    errorMsg.classList.remove("hide");
}

function reset(form) {
    const phone = form.querySelector('input[name="phone"]');
    const errorMsg = form.querySelector('.error-msg');
    phone.classList.remove("error");
    errorMsg.innerHTML = "";
    errorMsg.classList.add("hide");
}

function setupFormValidation(form) {
    const phone = form.querySelector('input[name="phone"]');
    const country = form.querySelector('input[name="country"]');
    const language = form.querySelector('input[name="language"]');
    const only_countries = form.querySelector('input[name="only_countries"]');
    const only_countries_value = JSON.parse(only_countries.value);
    const phone_country = form.querySelector('input[name="phone_country"]');

    const iti = window.intlTelInput(phone, {
        utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
        separateDialCode: true,
        initialCountry: 'tr',
        onlyCountries: ['tr']
    });

    phone.addEventListener('blur', function () {
        reset(form);
        if (!phone.value.trim()) {
            showError(form, "Required");
        } else if (!iti.isValidNumber()) {
            const errorCode = iti.getValidationError();
            const msg = errorMap[errorCode] || "Invalid number";
            showError(form, msg);
        }
    });

    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        reset(form);
        if (!iti.isValidNumber()) {
            return;
        }

        if (isOnlyCountries(form, only_countries_value, iti.getSelectedCountryData().iso2)) {
            return;
        }

        // Show loading state
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.textContent = 'Gönderiliyor...';

        phone.value = iti.getNumber();

        switch (country.value) {
            case 'phone':
                country.value = iti.getSelectedCountryData().iso2.toUpperCase();
                break;
            case 'ip':
                try {
                    country.value = await getCountryByIP();
                } catch (error) {
                    console.error('Error fetching country by IP:', error);
                    country.value = 'UA'; // default value
                }
                break;
            case '':
                country.value = 'UA'; // default value
                break;
        }

        if (language.value === 'auto') {
            language.value = getLanguageByGeo(country.value);
        }

        const formData = new FormData(form);
        formData.append('js_token', Math.random().toString(36).substring(2, 15));
        const action = form.action;

        // try {
        const response = await fetch(action, {
            method: 'POST',
            body: formData
        });
        const result = await response.json();

        //     if (result.status === 'success') {
        //         window.location.href = 'thanks.php';
        //     } else {
        //         alert(result.message || 'Bir hata oluştu.');
        //         submitBtn.disabled = false;
        //         submitBtn.textContent = originalText;
        //     }
        // } catch (error) {
        //     console.error('Error:', error);
        //     alert('Bağlantı hatası. Lütfen tekrar deneyin.');
        //     submitBtn.disabled = false;
        //     submitBtn.textContent = originalText;
        // }
    });
}

forms.forEach(form => setupFormValidation(form));