const cityInput = document.getElementById('cityInput');
const cityList = document.getElementById('cityList');
const btnViewLanding = document.getElementById('btn-view-landing');
btnViewLanding.classList.add("hidden");

function searchCity() {
    const input = cityInput.value.trim().toLowerCase();
    const isEmpty = input.length < 2;

    cityList.classList.toggle("hidden", isEmpty);
    cityList.innerHTML = '';

    if (isEmpty) return;

    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            const comuniJSON = JSON.parse(this.responseText);
            const emiliaRomagnaCities = comuniJSON.filter(city => city.regione.nome === 'Emilia-Romagna' && city.nome.toLowerCase().includes(input));

            if (emiliaRomagnaCities.length === 0) {
                const li = document.createElement('li');
                li.textContent = "Non siamo reperibili in questo luogo.";
                cityList.appendChild(li);
            } else {
                emiliaRomagnaCities.forEach(city => {
                    const li = document.createElement('li');
                    li.textContent = city.nome;
                    li.addEventListener('click', function () {
                        cityInput.value = city.nome;
                        btnViewLanding.classList.remove("hidden");
                        nomeCitta = city.nome.toString();
                        nomeCitta = city.nome.replace(/\s/g, "-");
                        nomeCitta = nomeCitta.replace(/\'/g, "-");
                        btnViewLanding.href = `${window.location.origin}/lp/riparazione-porte-garage/${encodeURIComponent(nomeCitta.toLowerCase())}/`;
                        cityList.classList.add("hidden");
                        initMap(city.nome);
                        document.cookie = `cityInput=${encodeURIComponent(city.nome)}; path=/`;
                        document.cookie = `btnViewLandingHidden=false; path=/`;
                    });
                    cityList.appendChild(li);
                });
            }
        }
    };
    xhr.open("GET", "../comuni.json", true);
    xhr.send();
}

document.addEventListener('click', function (event) {
    if (event.target !== cityInput) {
        cityList.classList.add("hidden");
    }
});

window.addEventListener('load', function () {
    const savedCityInput = getCookie('cityInput');
    const savedBtnViewLandingHidden = getCookie('btnViewLandingHidden');
    if (savedCityInput) {
        cityInput.value = decodeURIComponent(savedCityInput);
        nomeCitta = savedCityInput.toString();
        nomeCitta = savedCityInput.replace(/\s/g, "-");
        nomeCitta = nomeCitta.replace(/\'/g, "-");
        btnViewLanding.href = `${window.location.origin}/lp/elettricista-vicino-a-me/${encodeURIComponent(nomeCitta.toLowerCase())}/`;
        initMap(savedCityInput);
    }
    if (savedBtnViewLandingHidden === 'false') {
        btnViewLanding.classList.remove("hidden");
    }
});

function getCookie(name) {
    const cookieValue = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
    return cookieValue ? cookieValue.pop() : null;
}
