let t = {}, pos = null, lastMsg = null; const $ = (id) => document.getElementById(id); const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k]); const ruDate = (iso) => iso.split("-").reverse().join("."); const dist = (m) => (m < 1000 ? m + " " + t.m : (m / 1000).toFixed(1) + " " + t.km); const LANGS = ["ru", "kk", "en"]; const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } }; const dname = (d) => t["district_" + d.id] || d.name; const ptext = (s) => (t.promoTexts && t.promoTexts[s]) || s; const covered = () => districts.filter((d) => d.count > 0); const coveredText = () => covered().map(dname).join(", "); function fillCoverage() { const txt = covered().length ? fmt(t.coverage, { districts: coveredText() }) : ""; $("coverage").textContent = txt; $("coverage2").textContent = txt; const none = !covered().length; $("geo").disabled = none; $("only").disabled = none; $("maxPrice").disabled = none; if (none) { $("manual").hidden = true; $("out").innerHTML = `
${t.listPreparing}
`; } else if (!pos && (!$("out").children.length || $("start"))) $("out").innerHTML = `
${t.startHint}
`; } function fillDistricts() { const sel = $("district"), cur = sel.value; sel.innerHTML = "" + covered().map((d) => ``).join(""); sel.value = cur; } async function setLang(l) { try { localStorage.setItem("lang", l); } catch {} t = await (await fetch(`i18n/${l}.json`)).json(); document.documentElement.lang = l; document.querySelectorAll("[data-i]").forEach((e) => (e.textContent = t[e.dataset.i])); document.querySelectorAll("[data-ph]").forEach((e) => (e.placeholder = t[e.dataset.ph])); document.querySelectorAll("[data-al]").forEach((e) => e.setAttribute("aria-label", t[e.dataset.al])); document.querySelectorAll("[data-ti]").forEach((e) => (e.title = t[e.dataset.ti])); fillDistricts(); fillCoverage(); syncFilters(); document.title = t.title; document.querySelectorAll("[data-l]").forEach((b) => { b.classList.toggle("on", b.dataset.l === l); b.setAttribute("aria-pressed", String(b.dataset.l === l)); }); if (pos) load(); else if (lastMsg && covered().length) msg(lastMsg); // сообщение на экране — тоже на новом языке } const filterQuery = () => `&maxKm=${$("maxKm").value}&maxPrice=${$("maxPrice").value}`; const filtersOn = () => $("only").checked || $("maxKm").value || $("maxPrice").value; // фильтр расстояния доступен только когда известно место пользователя function syncFilters() { $("maxKm").disabled = !pos; $("distNote").hidden = Boolean(pos); } function resetFilters() { $("only").checked = false; $("maxKm").value = ""; $("maxPrice").value = ""; load(); } function noMatch(key) { $("out").innerHTML = `
${t[key]}
`; const b = document.createElement("button"); b.className = "btn alt"; b.id = "reset"; b.textContent = t.resetFilters; b.onclick = resetFilters; $("out").append(b); } function msg(key) { lastMsg = key; $("out").innerHTML = `
${t[key]}
`; } async function load() { try { await show(); } catch { msg("error"); } } async function show() { msg("searching"); syncFilters(); const r = await fetch(`/api/venues?lat=${pos.lat}&lng=${pos.lng}&only=${$("only").checked ? 1 : 0}${filterQuery()}`); if (!r.ok) return msg("error"); const list = await r.json(); if (!list.length) { // с фильтром пусто: далеко от заведений или просто нет предложений? let far = !filtersOn(); if (!far) far = !(await (await fetch(`/api/venues?lat=${pos.lat}&lng=${pos.lng}&only=0&maxKm=&maxPrice=`)).json()).length; if (far) showManual(); if (far) { $("out").innerHTML = `
${fmt(t.noneNearby, { districts: coveredText() })}
`; return; } return noMatch($("only").checked && !$("maxKm").value && !$("maxPrice").value ? "noOffers" : "noMatch"); } const out = $("out"); out.textContent = ""; const sum = document.createElement("div"); sum.className = "msg note"; sum.id = "summary"; sum.textContent = fmt($("only").checked ? t.resultsOffers : t.resultsAll, { n: list.length }); out.append(sum); for (const v of list) { const c = document.createElement("div"); c.className = "card"; const body = document.createElement("div"); body.className = "body"; const top = document.createElement("div"); top.className = "top"; const h = document.createElement("h2"); h.textContent = v.name; const d = document.createElement("span"); d.className = "dist"; d.textContent = dist(v.distance); top.append(h, d); const m = document.createElement("div"); m.className = "meta"; m.textContent = v.address; const desc = document.createElement("p"); desc.className = "desc" + (v.description ? "" : " empty"); desc.textContent = v.description || t.noDescription; body.append(top, m, desc); c.append(photo(v), body); if (v.lunch) body.append(tag(fmt(t.lunch, { price: v.lunch.price, from: v.lunch.from, to: v.lunch.to }), "lunch")); if (v.promo) body.append(tag(fmt(v.promo.until ? t.promo : t.promoOpen, { text: ptext(v.promo.text), until: v.promo.until && ruDate(v.promo.until) }), "promo")); if ((v.lunch || v.promo) && v.checked) { const n = document.createElement("div"); n.className = "meta"; n.textContent = fmt(t.checkedOn, { date: ruDate(v.checked) }); body.append(n); } else if (v.unconfirmed) { const n = document.createElement("div"); n.className = "meta"; n.textContent = t.notConfirmed; body.append(n); } out.append(c); } } // Фото или заглушка: пустого места на карточке не бывает, в том числе если картинка не загрузилась. function photo(v) { const box = document.createElement("div"); box.className = "photo"; const stub = () => { box.className = "photo stub"; box.textContent = "🍽"; box.setAttribute("role", "img"); box.setAttribute("aria-label", t.noPhoto); }; if (!v.photo) { stub(); return box; } const img = document.createElement("img"); img.src = v.photo; img.alt = fmt(t.photoAlt, { name: v.name }); img.loading = "lazy"; img.onerror = () => { img.remove(); stub(); }; box.append(img); return box; } function tag(s, cls) { const d = document.createElement("span"); d.className = "badge " + cls; d.textContent = s; return d; } function showManual() { $("manual").hidden = false; } $("geo").onclick = () => { if (!navigator.geolocation) { showManual(); return msg("geoFailed"); } msg("searching"); navigator.geolocation.getCurrentPosition( (p) => { pos = { lat: p.coords.latitude, lng: p.coords.longitude }; load(); }, (e) => { showManual(); msg(e.code === 1 ? "geoDenied" : e.code === 3 ? "geoSlow" : "geoFailed"); }, { timeout: 10000 }); }; $("district").onchange = (e) => { const d = districts.find((x) => x.id === e.target.value); if (d) { pos = d; load(); } }; $("addrBtn").onclick = async () => { msg("searching"); try { const r = await fetch("/api/locate?q=" + encodeURIComponent($("addr").value)); if (!r.ok) return msg("addrNotFound"); pos = await r.json(); } catch { return msg("error"); } load(); }; $("addr").onkeydown = (e) => { if (e.key === "Enter") $("addrBtn").click(); }; const onFilter = () => { if (pos) load(); else if (!$("geo").disabled) msg("filterNeedPlace"); }; $("only").onchange = onFilter; $("maxKm").onchange = onFilter; $("maxPrice").onchange = onFilter; const menu = $("menu"), veil = $("veil"); const toggle = (open) => { menu.classList.toggle("open", open); veil.hidden = !open; $("burger").setAttribute("aria-expanded", String(open)); }; $("burger").onclick = () => toggle(!menu.classList.contains("open")); veil.onclick = () => toggle(false); document.addEventListener("keydown", (e) => { if (e.key === "Escape") toggle(false); }); function route() { const id = location.hash === "#about" ? "about" : "nearby"; document.querySelectorAll("section").forEach((e) => e.classList.toggle("on", e.id === id)); toggle(false); } window.onhashchange = route; document.querySelectorAll("[data-l]").forEach((b) => (b.onclick = () => { setLang(b.dataset.l); toggle(false); })); const districts = await (await fetch("/api/districts")).json(); await setLang(LANGS.includes(saved()) ? saved() : "ru"); route();