const serv = 'https://domconnect.ru';
const host = "rt-internet.ru";
const url = window.location.href;
let hrefCity = url.split(host)[1];

let areasReady = false
let slideReady = false

if (url.endsWith('#/p/tarifsline')) { document.querySelector('.tarifsline-close a').dispatchEvent(new Event("click")) }
if (hrefCity.includes('#/p/regions')) { chooseLocation() }

if (hrefCity.includes('#/')) { hrefCity = hrefCity.slice(0, hrefCity.indexOf('#/')) }
if (hrefCity == "/cities") { hrefCity = '' }
else if (hrefCity.includes("/tarifs/")) { hrefCity = '/tarifs' }
else if (hrefCity.includes("/tarif-")) { hrefCity = '/rostelecom-tarify' }
else if (hrefCity.includes("/addresses")) { hrefCity = '/addresses' }

if (url.endsWith('-ok')) {
	let tel = sessionStorage.getItem('isTel');
	if (tel) {
		document.querySelectorAll('.putPhoneFromForm').forEach((elem) => elem.innerText = tel);
		fetch(`https://apidc.ru/get_phone_info?phone=${tel.replace(/[^0-9]/g, "")}`)
			.then(response => {
				if (response.status === 400 || response.ok) {
					return response.json()
				} else {
					document.querySelector('.mustHide.popupContent div.animated').style.animationDelay = "0.1s";
					sessionStorage.removeItem('isTel');
					throw new Error('Ошибка запроса: ' + response.statusText);
				}
			})
			.then(data => {
				if ('error' in data) {
					const errorBlock = document.querySelector('.mustHide.popupContent div.ansTel');
					console.log('Ошибка определения номера');
					if (errorBlock) {
						errorBlock.innerHTML = `<p style="font-size: 120%; color: #e30613; text-align: center;">Упс!<p><br> Возможно номер ${tel} был введен некорректно, попробуйте еще раз, пожалуйста!`;
					}
				}
				document.querySelector('.mustHide.popupContent div.animated').style.animationDelay = "0.1s";
				sessionStorage.removeItem('isTel');
			})
	} else {
		document.querySelector('.mustHide.popupContent div.animated').style.animationDelay = "0.1s";
	}
}

document.querySelectorAll(`a[href="${window.location.pathname}"]`).forEach(link => {
	if (link.hasAttribute('onclick')) { return; }
	link.style.pointerEvents = 'none'
	link.style.cursor = 'default'
})

window.onload = function () {

	createPhoneMask()
	getYaMetrika()
	createFaqSchema()

	document.querySelectorAll('.formCity input').forEach((elem) => elem.value = domainCity)

	if (document.querySelector('.homeChoose')) {
		let allHomInput = document.querySelectorAll('.homeChoose input')
		allHomInput.forEach(elem => elem.addEventListener('input', homeChoose))
	}

	document.querySelectorAll('div.formStreet input').forEach(item => {
		item.setAttribute('list', 'subdomainStreets')
		item.addEventListener('focus', getStreetsForDatalist)
	})

	let geotime = (hrefCity == "/map") ? 1000 : 4000;
	let geoTimer = setTimeout(() => {
		if (+new Date() >= parseInt(localStorage.getItem('blockTime'))) {
			localStorage.removeItem('isCity');
			console.log('Таймер выбора геолокации закончился и обнулён');
		}
		if (document.querySelector('.chCity')) {
			let geoReady = (localStorage.getItem('isCity') == "yes" || getCookie('chCity') == "yes") ? true : false;
			if (hrefCity == "/map" || !geoReady) {
				getYaMaps(geoReady)
			}
		}
		clearTimeout(geoTimer);
	}, geotime);

	setTimeout(function () {
		let script = document.createElement('script');
		script.src = "https://www.googletagmanager.com/gtag/js?id=G-3PDENZ6CZE";
		script.async = true;
		document.head.appendChild(script);

		script.onload = function () {
			window.dataLayer = window.dataLayer || [];
			function gtag() { dataLayer.push(arguments); }
			gtag('js', new Date());
			gtag('config', 'G-3PDENZ6CZE');
		};
	}, 4000);

	// setTimeout(async () => {
	// 	const data = await fetchJSON(`/cache/chat_info.json`)
	// 	if (!data) { return }
	// 	if (data['chat'] == 1) {
	// 		const callscript = document.createElement('script')
	// 		callscript.src = 'https://crm.domconnect.ru/upload/crm/site_button/loader_5_hqta2z.js' + '?' + (Date.now() / 60000 | 0)
	// 		document.body.append(callscript)
	// 	}
	// }, 6000)
}

function openTarifsLine() {
	if (!slideReady) {
		let script = document.createElement('script');
		script.src = "/files/storage/swiper-bundle.min.js";
		document.body.append(script);
		script.onload = () => {
			slideReady = true;
			let b = this.closest('div.tarif-line');
			let a = b.querySelectorAll('.tarifscard');
			let popup = document.querySelector('.swiper-wrapper.popup');
			popup.innerHTML = '';
			a.forEach(tar => {
				let clon = tar.cloneNode(true);
				let slide = document.createElement('div');
				slide.classList.add('swiper-slide');
				slide.append(clon);
				popup.append(slide);
				clon.querySelector('.tarifs-btn').setAttribute('onclick', "setTarifNameDC.apply(this); return false;");
			});
			sliderSwapper();
		}
	} else {

		let b = this.closest('div.tarif-line');
		let a = b.querySelectorAll('.tarifscard');
		let popup = document.querySelector('.swiper-wrapper.popup');
		popup.innerHTML = '';
		a.forEach(tar => {
			let clon = tar.cloneNode(true);
			let slide = document.createElement('div');
			slide.classList.add('swiper-slide');
			slide.append(clon);
			popup.append(slide);
			clon.querySelector('.tarifs-btn').setAttribute('onclick', "setTarifNameDC.apply(this); return false;");
		});
		sliderSwapper();
	}
}

function sliderSwapper() {
	new Swiper('.swiper-container', {
		//стрелки
		//   navigation: {
		//       nextEl: '.swiper-button-next',
		//       prevEl: '.swiper-button-prev'
		//   },
		pagination: {
			el: '.swiper-pagination',
			clickable: true,
			//  modifierClass: 'mybull',
			type: 'progressbar',
		},
		touchEventsTarget: 'wrapper',
		grabCursor: true,
		watchOverFlow: true,
		centerInsufficientSlides: true,
		//  centeredSlides: true,
		//  cpaseBetween: 10,
		breakpoints: {
			320: {
				slidesPerView: 1,
				centeredSlides: true,
			},
			720: {
				slidesPerView: 2,
			},
			1060: {
				slidesPerView: 3,
			},
			1440: {
				slidesPerView: 4,
			},
		},
	});
}

function getPhone() {
	let form = this.querySelector('div.formR');
	sessionStorage.setItem('isTel', form.querySelector('input[type="tel"]').value);
	let formPopup = this.closest('div.clearForm');
	formPopup.classList.add('clearEl');
	let textPreload = 'подбираем грамотного монтажника';
	if (form.classList.contains('proverka')) {
		textPreload = 'ищем наше оборудование в Вашем подъезде';
	} else if (form.classList.contains('zvonok')) {
		textPreload = 'подбираем консультанта с красивым голосом';
	} else if (form.classList.contains('lidul')) {
		textPreload = 'открываем секретные тарифы';
	} else if (form.classList.contains('busns')) {
		textPreload = 'отправляем заявку';
	}
	let div = document.createElement("div");
	div.classList.add('preload');
	div.innerHTML = `<svg style="display:block;" xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 128 128" xml:space="preserve"><g><linearGradient id="linear-grad1"><stop offset="0%" stop-color="#ffffff"/><stop offset="100%" stop-color="rgb(119,0,255)"/></linearGradient><path d="M63.85 0A63.85 63.85 0 1 1 0 63.85 63.85 63.85 0 0 1 63.85 0zm.65 19.5a44 44 0 1 1-44 44 44 44 0 0 1 44-44z" fill="url(#linear-grad1)" fill-rule="evenodd"/><animateTransform attributeName="transform" type="rotate" from="0 64 64" to="360 64 64" dur="1080ms" repeatCount="indefinite"/></g></svg><p>${textPreload}</p>`;
	formPopup.append(div);
}

function getCookie(name) {
	let matches = document.cookie.match(new RegExp(
		"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	));
	return matches ? decodeURIComponent(matches[1]) : undefined;
}

function createPhoneMask() {
	[].forEach.call(document.querySelectorAll('input[type="tel"]'), function (input) {
		var keyCode;
		function mask(event) {
			event.keyCode && (keyCode = event.keyCode);
			var pos = this.selectionStart;
			if (pos < 3) event.preventDefault();
			var matrix = "+7 (___) ___ ____",
				i = 0,
				def = matrix.replace(/\D/g, ""),
				val = this.value.replace(/\D/g, ""),
				new_value = matrix.replace(/[_\d]/g, function (a) {
					return i < val.length ? val.charAt(i++) || def.charAt(i) : a
				});
			i = new_value.indexOf("_");
			if (i != -1) {
				i < 5 && (i = 3);
				new_value = new_value.slice(0, i)
			}
			var reg = matrix.substr(0, this.value.length).replace(/_+/g,
				function (a) {
					return "\\d{1," + a.length + "}"
				}).replace(/[+()]/g, "\\$&");
			reg = new RegExp("^" + reg + "$");
			if (!reg.test(this.value) || this.value.length < 5 || keyCode > 47 && keyCode < 58) this.value = new_value;
			if (event.type == "blur" && this.value.length < 5) this.value = ""
			if (new_value.includes('+7 (89')) {
				new_value = new_value.replace('+7 (89', '+7 (9');
				this.value = new_value;
			}
		}

		input.addEventListener("input", mask, false);
		input.addEventListener("focus", mask, false);
		input.addEventListener("blur", mask, false);
		input.addEventListener("keydown", mask, false)

	});
}

async function chooseLocation() {
	if (areasReady) { return }
	areasReady = await fetchJSON(`/cache/thv/areas_cities.json`)
	if (!areasReady) { return }
	document.querySelector('.areas_list').insertAdjacentHTML('beforeend', '<ul id="areas-list"></ul>')
	const areasList = document.querySelector('#areas-list')
	areasReady.forEach(area => {
		areasList.insertAdjacentHTML('beforeend', `<li class="areas-item" onclick="createCityList.apply(this)" data-id="${area.id}">${area.name}</li>`)
	})
}

function createCityList() {
	const isMobile = window.getComputedStyle(document.querySelector('.cities_list')).display == 'none' ? true : false
	let areaId = this.dataset.id

	if (!isMobile) {
		if (this.classList.contains('checked')) { return }
		const myUl = document.getElementById('cities-list')
		const another = document.querySelector('.areas-item.checked')
		if (another) {
			another.classList.remove('checked')
			clearUl(myUl)
		}
		this.classList.add('checked')
		getCitiesList(areaId, myUl)
	} else {
		if (this.classList.contains('checked')) {
			moreCitiesList.remove()
			return this.classList.remove('checked')
		}

		let another = document.querySelector('.areas-item.checked')
		if (another) {
			moreCitiesList.remove()
			another.classList.remove('checked')
		}
		this.classList.add('checked')
		this.insertAdjacentHTML('afterend', '<li id="moreCitiesList"><ul class="city-list__item"></ul</li>')
		getCitiesList(areaId, moreCitiesList.querySelector('.city-list__item'))
	}
}

function getCitiesList(areaId, myUl) {
	const area = areasReady.find(({ id }) => id == areaId)
	area['cities'].forEach(city => {
		myUl.append(ctreateCityLink(city))
	})
}

function ctreateCityLink(city, fromsearch = false) {
	let li = document.createElement('li')
	let a = document.createElement('a')
	a.href = `https://${city.domain}.${host}${hrefCity}`
	a.classList.add('cities-item')
	a.setAttribute("onclick", "setSubdomain()");
	let text = city.name
	if (city.okrug.trim() != '') { text += '<br><span>' + city.okrug.replace('муниципальный округ', 'м.о.') + '</span>' }
	if (fromsearch) { text += ` (${city.obl})` }
	a.innerHTML = text
	li.append(a)
	return li
}

const searchLocalityDebounced = debounce(searchDC, 200)
function searchDC() {
	if (!areasReady) { return toggleSearchDC('none', 'none', 'block') }
	const value = myInputCity.value.toLowerCase().replaceAll('ё', 'е')

	if (!value) { return toggleSearchDC('none', 'inline-block', 'none') }

	if (value.length < 3) {
		searchList.innerHTML = '<li>Введите не менее 3-х символов</li>';
		return toggleSearchDC('block', 'none', 'none');
	}
	
searchList.textContent = ''
const foundLocalities = []

areasReady.every(area => {
  if (foundLocalities.length >= 9) return false
  
  const sortedCities = [...area.cities].sort((a, b) => b.type === 99 ? 1 : a.type === 99 ? -1 : 0)
  
  sortedCities.forEach(city => {
    if (foundLocalities.length >= 9) return
    
    if (isRealCity(city.name) && city.name.toLowerCase().replaceAll('ё', 'е').includes(value)) {
        console.log(city);
      foundLocalities.push(city)
    }
  })
 
  return true 
})

areasReady.every(area => {
  if (foundLocalities.length >= 9) return false
  
  area.cities.forEach(city => {
    if (foundLocalities.length >= 9) return

    if (!isRealCity(city.name) && city.name.toLowerCase().replaceAll('ё', 'е').includes(value)) {
      foundLocalities.push(city)
    }
  })
  
  return true;
})

	if (!foundLocalities.length) {
		return toggleSearchDC('none', 'none', 'block')
	}
	foundLocalities.forEach(city => {
		searchList.append(ctreateCityLink(city, true))
	})
	toggleSearchDC('block', 'none', 'none')
}

function isRealCity(name) {
  const invalidSubstrings = [
    "рабочий поселок", "село", "поселок", "поселок городского типа", "деревня", 
    "хутор", "коттеджный поселок", "слобода", "садовое товарищество", "аул", 
    "станица", "сельский округ"
  ];
  const normalizedName = name.toLowerCase().replaceAll('ё', 'е');

  for (const substring of invalidSubstrings) {
    if (normalizedName.includes(substring)) {
      return false;
    }
  }
  return true;
}

function toggleSearchDC(search, list, nocity) {
	searchList.style.display = search;
	document.querySelector('.listFromDC').style.display = list;
	document.querySelector('.noCityFromDC').style.display = nocity;
}
function clearInputCity() {
	myInputCity.value = ''
	clearUl(searchList)
	toggleSearchDC('none', 'inline-block', 'none')
}

function clearUl(ul) {
	let liList = ul.querySelectorAll('li');
	if (liList.length > 0) {
		liList.forEach((li) => li.remove());
	}
}

function homeChoose() {
	form1 = this.closest('.formR');
	form2 = this.closest('.clearForm').querySelector('.form2').style;
	if (this.value == 0 || this.value == 2) {
		if (form1.classList.contains('notHome')) {
			form1.classList.remove('notHome');
		}
		form2.display = 'none';
	} else if (this.value == 1) {
		if (!form1.classList.contains('notHome')) {
			form1.classList.add('notHome');
		}
		form2.display = 'block';
	}
}

function createFaqSchema() {
	let allQ = document.querySelectorAll('.faq-block>div');
	if (allQ.length > 0) {
		let qs = [];
		allQ.forEach(elem => {
			let q = elem.querySelector('summary').textContent;
			let a = elem.querySelector('details>div').textContent;
			let ob = { "@type": "Question", name: q, acceptedAnswer: { "@type": "Answer", text: a } };
			qs.push(ob);
		});
		let txt = {
			"@context": "https://schema.org",
			"@type": "FAQPage",
			mainEntity: qs
		};
		const script = document.createElement('script');
		script.setAttribute('type', 'application/ld+json');
		script.textContent = JSON.stringify(txt);
		document.head.append(script);
	}
}

function getYaMetrika() {
	const metricaId = 55966849
	let loadedMetrica = false
	let timerId

	if (isPageSpeedTest()) {
		return timerId = setTimeout(loadMetrica, 10000);
	}

	if (navigator.userAgent.indexOf('YandexMetrika') > -1 || isInIframe()) {
		loadMetrica();
	} else {
		toggleEventListeners('add')
	}

	function loadFallback() {
		timerId = setTimeout(loadMetrica, 1000);
	}

	function loadMetrica() {
		if (loadedMetrica) { return; }

		(function (m, e, t, r, i, k, a) {
			m[i] = m[i] || function () { (m[i].a = m[i].a || []).push(arguments) };
			m[i].l = 1 * new Date(); k = e.createElement(t), a = e.getElementsByTagName(t)[0], k.async = 1, k.src = r, a.parentNode.insertBefore(k, a)
		})(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

		ym(metricaId, "init", {
			clickmap: true,
			trackLinks: true,
			accurateTrackBounce: true,
			webvisor: true,
			ecommerce: "dataLayer"
		});

		loadedMetrica = true;
		clearTimeout(timerId);
		toggleEventListeners('remove')
	}

	function toggleEventListeners(action) {
		const method = action + 'EventListener'
		window[method]('scroll', loadMetrica)
		window[method]('touchstart', loadMetrica)
		document[method]('mouseenter', loadMetrica)
		document[method]('click', loadMetrica)
		document[method]('DOMContentLoaded', loadFallback)
	}

	function isInIframe() {
		try {
			return window.self !== window.top || window.frameElement;
		} catch (e) {
			return true;
		}
	}

	function isPageSpeedTest() {
		const userAgent = navigator.userAgent || '';
		return userAgent.includes('moto g power') && userAgent.includes('Mobile');
	}
}

async function getStreetsForDatalist() {
	document.querySelectorAll('div.formStreet input').forEach(item => {
		item.removeEventListener('focus', getStreetsForDatalist)
	})
	let data = await fetchJSON(`/cache/thv/streets/${openedSubdomain}.json`)
	if (!data) { return }
	setStreetsToDatalist(data)
}

function setStreetsToDatalist(streets = {}) {
	const datalist = document.createElement('datalist')
	datalist.id = 'subdomainStreets'
	Object.keys(streets).forEach(street => {
		const option = document.createElement('option')
		option.value = street
		option.dataset.id = streets[street]
		datalist.append(option)
	})
	document.body.append(datalist)
}

function setSpeed() {
	if (this.classList.contains('active')) return;
	let card = this.closest('div.tarifscard');
	let prev = card.querySelector('.flex-speed.active');
	if (prev) { prev.classList.remove('active'); }
	this.classList.add('active');
	card.querySelector('.attr-int span').textContent = this.dataset.value;
	card.querySelector('.tarif-ap').textContent = this.dataset.price;
	if (card.querySelector('.tarif-apnext')) {
		card.querySelector('.tarif-apnext').innerText = this.dataset.nextprice + ' руб/мес';
	}
}

let tooltipElem;
function tooltip(txt) {
	if (tooltipElem) {
		removeTooltip();
	}
	let target = event.currentTarget;
	if (!txt) return;

	tooltipElem = document.createElement('div');
	tooltipElem.className = 'tooltip';
	tooltipElem.innerHTML = txt;
	document.body.append(tooltipElem);

	let coords = target.getBoundingClientRect();
	let left = coords.left + (target.offsetWidth - tooltipElem.offsetWidth) / 2;
	if (left < 0) left = 0;

	let top = coords.top - tooltipElem.offsetHeight - 5;
	if (top < 0) {
		top = coords.top + target.offsetHeight + 5;
	}

	tooltipElem.style.left = left + 'px';
	tooltipElem.style.top = top + 'px';
	tooltipElem.style.zIndex = '1000';
}

function removeTooltip() {
	if (tooltipElem) {
		tooltipElem.remove();
		tooltipElem = null;
	}
}

/* GEOLOCATION*/

function getYaMaps(geoReady) {
	let script = document.createElement('script');
	script.src = "https://api-maps.yandex.ru/2.1/?lang=ru_RU&apikey=556681e8-ce9f-43a9-afa4-78111f5a62b7";
	document.head.append(script);
	script.onload = function () {
		if (!geoReady) {
			ymaps.ready(init);
		}
		if (hrefCity == "/map") {
			let scriptMap = document.createElement('script');
			scriptMap.src = "/Heatmap.min.js";
			document.head.append(scriptMap);
			scriptMap.onload = function () { ymaps.ready(init_bigmap) }
		}
	}
}
function init() {
	console.log('Поиск геолокации...');
	let geolocation = ymaps.geolocation;
	geolocation.get({
		provider: 'auto',
		mapStateAutoApply: true
	})
		.then(function (result) {
			const res = result.geoObjects.get(0)
			const yaCity = res.properties.get('metaDataProperty.GeocoderMetaData.Address.Components')

			const city = yaCity.find(item => item.kind === "locality")?.name || null
			const province = yaCity.filter(item => item.kind === "province").map(item => item.name)
			if (!province || !city) { return console.log("Геолокация не определена") }

			console.log("Геолокация определена как " + city, province)
			searchLocalityInCache(province, city.toLowerCase().replaceAll('ё', 'е'))
		})
}

async function searchLocalityInCache(province, value) {
	const areas = await fetchJSON('/cache/thv/areas_cities.json')
	if (!areas) { return console.log('Кэш не найден') }

	const findProvince = areas.find(({ name }) => province.includes(name))
	if (!findProvince) { return }

	const findLocality = findProvince.cities.find(city => city.name.toLowerCase().replaceAll('ё', 'е').includes(value))

	if (findLocality) {
		showGeoCheck(findLocality)
	} else {
		closeBlock()
		console.log('Геолокация определена без ТхВ от провайдера и заблокирована')
	}
}

function showGeoCheck(findcity) {
	if (url.includes(findcity.domain)) {
		console.log('Геолокация совпадает  с выбранным доменом')
		return closeBlock()
	} else {
		document.getElementById('subdomain').innerText = findcity.name2
		document.querySelector('.header__btn a').href = `https://${findcity.domain}.${host}${hrefCity}`
		document.querySelector('.chCity').style.display = "block"
		document.querySelector('.chCity > div').style.animationDelay = "1s"
	}
}
function setSubdomain() {
	document.cookie = `chCity=yes; domain=${host}; path=/; max-age=86400`
	localStorage.setItem('isCity', 'yes')
	localStorage.setItem('blockTime', +new Date() + (24 * 3600 * 1000))
}
function closeBlock() {
	setSubdomain()
	document.querySelector('.chCity').style.display = "none"
}

async function fetchJSON(url, settings = {}) {
	try {
		const res = await fetch(url, settings);
		if (res.status < 200 || res.status >= 300) {
			let error = new Error(`status: ${res.status};${res.statusText}`);
			error.response = res;
			throw error
		}
		//	if (res.headers.get('content-type') !== 'application/json') {
		//		let error = new Error(`Некорректный ответ от сервера content-type: ${res.headers.get('content-type')}`);
		//		error.response = res;
		//		throw error
		//	}
		return await res.json();
	} catch (err) {
		console.error(err.message, err.response);
		return false;
	}
}

function debounce(func, wait) {
	let timeout
	return function (...args) {
		clearTimeout(timeout)
		timeout = setTimeout(() => func.apply(this, args), wait)
	}
}

function checkThv() {
	document.querySelectorAll(`.formStreet input`).forEach(elem => elem.value = streetInput.value)
	document.querySelectorAll(`.formHouse input`).forEach(elem => elem.value = houseInput.value)

	const street = document.querySelector(`#subdomainStreets option[value*="${streetInput.value}"]`)
	const house = document.querySelector(`#subdomainHouses option[value="${houseInput.value}"]`)

	if (street && house && street.dataset.id == house.dataset.road) {
		document.querySelector('.emptyThV').style.display = 'none'
		addressReady.textContent = `, ${street.value}, ${house.value}`
		if (document.querySelector('#DCadr')) {
			checkTarifsForAddress(street.value, house.value)
		}
		if (hrefCity == "/map") {
			centerMap(house.dataset.c1, house.dataset.c0)
		}
		return document.querySelector('.readyThV').style.display = 'block'
	}

	document.querySelector('.readyThV').style.display = 'none'
	document.querySelector('.emptyThV').style.display = 'block'
}

function checkTarifsForAddress(street, house) {
	DCadr.textContent = `${domainCity}, ${street}, ${house}`
	addr2 = `${street.split(',').reverse().join(' ')} ${house}`.toLowerCase()
	checkAddrThV()
}

async function getCustomHouses() {
	const street = streetInput.value
	if (!street) { return }

	const option = document.querySelector(`#subdomainStreets option[value*="${street}"]`)
	const streetId = option ? option.dataset.id : 0

	if (!streetId) { return }
	const currentRoad = document.querySelector(`#subdomainHouses option`)
	if (currentRoad && currentRoad.dataset.road == streetId) { return }

	const data = await fetchJSON(`/cache/thv/address/${openedSubdomain}.json`)
	if (!data) { return }
	const roadsHouses = Object.values(data).filter(({ road }) => road == streetId)
	setHousesToDatalist(roadsHouses)
}

function setHousesToDatalist(houses = []) {
	const prevList = document.querySelector(`#subdomainHouses`)
	if (prevList) { prevList.remove() }

	const datalist = document.createElement('datalist')
	datalist.id = 'subdomainHouses'
	houses.forEach(home => {
		const option = document.createElement('option')
		option.value = home.name
		option.dataset.id = home.id
		option.dataset.c0 = home.coord0
		option.dataset.c1 = home.coord1
		option.dataset.road = home.road
		datalist.append(option)
	})
	document.body.append(datalist)
}