sozday-dlya-menya-prilozheni/app.js

249 lines
20 KiB
JavaScript

/* Ауада: состояние, экраны и взаимодействия. */
const state = {weather:null,recommendations:[],evening:null,liveEvents:[],eventsLive:false,page:"today",recFilter:"all",seasonFilter:seasonForMonth(new Date().getMonth()),settings:loadSettings()};
const pageMeta = {
today:["navToday","todaySubtitle"],weather:["navWeather","weatherSubtitle"],recommendations:["navRecommendations","recSubtitle"],music:["navMusic","musicSubtitle"],events:["navEvents","eventsSubtitle"]
};
function loadSettings() {
try { return {workStart:"09:00",workEnd:"18:00",musicAdvice:true,...JSON.parse(SafeStore.getItem("auada_settings")||"{}")}; }
catch (_) { return {workStart:"09:00",workEnd:"18:00",musicAdvice:true}; }
}
function esc(value) { return String(value ?? "").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c])); }
function icon(name, cls="kt-icon") { return `<svg class="${cls}" aria-hidden="true"><use href="#${name}"></use></svg>`; }
function externalLink(url,text) { return `<a class="kt-ai-link card-link" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(text)}${icon("external")}</a>`; }
function actionLink(url,text,primary=false) { return `<a class="kt-ai-btn card-link" ${primary ? 'data-variant="primary"' : ""} href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(text)}${icon("external")}</a>`; }
function applyTranslations() {
document.documentElement.lang = currentLang;
document.querySelectorAll("[data-lang]").forEach(button => { const active = button.dataset.lang === currentLang; button.dataset.active = String(active); button.setAttribute("aria-pressed",String(active)); });
document.getElementById("languageSwitch").setAttribute("aria-label",t("interfaceLanguage"));
document.title = t("appTitle");
document.getElementById("menuButton").setAttribute("aria-label",t("menu"));
document.getElementById("notificationButton").setAttribute("aria-label",t("notifications"));
["closeNotifications","closeSettings"].forEach(id=>document.getElementById(id).setAttribute("aria-label",t("close")));
document.querySelectorAll("[data-i18n]").forEach(el => { el.textContent = t(el.dataset.i18n); });
const meta = pageMeta[state.page];
document.getElementById("pageTitle").textContent = t(meta[0]);
document.getElementById("pageSubtitle").textContent = t(meta[1]);
const hour = new Date().getHours();
document.getElementById("greeting").textContent = t(hour < 12 ? "goodMorning" : hour < 18 ? "goodAfternoon" : "goodEvening");
document.getElementById("todayDate").textContent = localizedDate(new Date());
document.getElementById("seasonLabel").textContent = t("todayRounded") + ": " + t("season"+seasonForMonth(new Date().getMonth())[0].toUpperCase()+seasonForMonth(new Date().getMonth()).slice(1));
}
function navigate() {
const page = location.hash.slice(1);
state.page = pageMeta[page] ? page : "today";
document.body.dataset.section = state.page;
document.querySelectorAll(".app-page").forEach(el => { el.hidden = el.id !== "page-"+state.page; });
document.querySelectorAll("[data-page]").forEach(el => { el.dataset.active = String(el.dataset.page === state.page); });
const meta = pageMeta[state.page];
document.getElementById("pageTitle").textContent = t(meta[0]);
document.getElementById("pageSubtitle").textContent = t(meta[1]);
document.getElementById("sidebar").dataset.open = "false";
window.scrollTo({top:0,behavior:"instant"});
}
function renderNotice(targetId) {
const target = document.getElementById(targetId);
if (state.weather && state.weather.isDemo) target.innerHTML = `<div class="info-banner">${icon("alert-circle")}<span>${esc(t("demoNotice"))}</span></div>`;
else target.innerHTML = "";
}
function renderWeather() {
const w = state.weather;
if (!w) return;
document.body.dataset.weatherMood = w.isDemo ? "neutral" : w.temp <= 5 ? "cold" : w.temp >= 25 ? "hot" : "mild";
const uv = w.daily[0] ? w.daily[0].uv : 0;
document.getElementById("topbarWeather").textContent = `${w.temp > 0 ? "+" : ""}${w.temp}° · ${t(weatherCodeKey(w.code))}`;
const kpis = [
{label:"temperature",value:`${w.temp > 0 ? "+" : ""}${w.temp}°`,hint:t("feelsLike",{value:w.feels})},
{label:"airQuality",value:w.aqi === null ? "—" : t(aqiKey(w.aqi)),hint:w.aqi === null ? "AQI —" : `AQI ${w.aqi}`},
{label:"uvIndex",value:String(uv),hint:t(uvKey(uv))},
{label:"wind",value:`${w.wind} ${t("windUnit")}`,hint:`${t("humidity")} ${w.humidity}${t("humidityUnit")}`}
];
document.getElementById("todayKpis").innerHTML = kpis.map(k=>`<div class="kt-ai-kpi"><span class="label">${esc(t(k.label))}</span><span class="value">${esc(k.value)}</span><span class="hint">${esc(k.hint)}</span></div>`).join("");
document.getElementById("weatherCurrent").innerHTML = `<div class="current-temperature">${icon(weatherIcon(w.code),"kt-icon weather-icon")}<div><strong>${w.temp > 0 ? "+" : ""}${w.temp}°</strong><h2>${esc(t(weatherCodeKey(w.code)))}</h2><p>${esc(t("feelsLike",{value:w.feels}))}</p></div></div><div class="weather-summary"><p>${esc(weatherSummary(w))}</p><p class="source-note">${esc(t("updated",{time:(w.updated||"").replace("T"," ").slice(0,16)}))}</p></div>`;
document.getElementById("forecast").innerHTML = w.daily.map((d,i)=>`<div class="forecast-day" data-today="${i===0}"><span>${esc(formatDay(d.date,i))}</span>${icon(weatherIcon(d.code))}<strong>${d.max > 0 ? "+" : ""}${d.max}°</strong><small>${d.min > 0 ? "+" : ""}${d.min}°</small></div>`).join("");
const details = [
["alert-circle","airQuality",w.aqi === null ? "—" : `AQI ${w.aqi}`,w.aqi === null ? "—" : t(aqiKey(w.aqi))],
["sun","uvIndex",String(uv),t(uvKey(uv))],
["refresh","wind",`${w.wind} ${t("windUnit")}`,`${t("humidity")} ${w.humidity}${t("humidityUnit")}`]
];
document.getElementById("weatherDetails").innerHTML = details.map(d=>`<div class="detail-card">${icon(d[0])}<strong>${esc(d[2])}</strong><span>${esc(t(d[1]))} · ${esc(d[3])}</span></div>`).join("");
renderNotice("dataNotice"); renderNotice("dataNoticeWeather");
}
function adviceCard(item, doneIds) {
const done = doneIds.includes(item.id);
return `<article class="advice-card ${done ? "is-done" : ""}" data-kind="${esc(item.kind)}"><span class="advice-icon">${icon(item.icon)}</span><div class="advice-body"><h3>${esc(item.title)}</h3><p>${esc(item.text)}</p><div class="advice-meta"><span class="kt-ai-chip" data-tone="${item.kind === "warm" ? "orange" : item.kind === "calm" ? "purple" : item.kind === "outdoor" ? "green" : "blue"}">${esc(t(item.category === "leisure" ? "leisureCategory" : "comfortCategory"))}</span>${done ? `<span class="kt-ai-status-pill" data-status="ok">${esc(t("done"))}</span>` : ""}</div>${item.target ? `<a class="kt-ai-btn advice-link" data-size="sm" href="#${esc(item.target)}">${esc(t(item.target === "music" ? "chooseMusic" : "lookIdeas"))}${icon("arrowRight")}</a>` : ""}</div><button class="kt-ai-icon-button advice-action" data-done-id="${esc(item.id)}" title="${esc(t(done ? "markUndone" : "markDone"))}" aria-label="${esc(t(done ? "markUndone" : "markDone"))}">${icon(done ? "check-circle" : "check")}</button></article>`;
}
function renderRecommendations() {
const done = getDoneIds();
const active = state.recommendations.filter(x=>!done.includes(x.id));
document.getElementById("recCount").textContent = active.length;
document.getElementById("todayCount").textContent = Math.min(active.length,3);
document.getElementById("todayAdvice").innerHTML = active.length ? active.slice(0,3).map(x=>adviceCard(x,done)).join("") : `<div class="kt-ai-empty">${esc(t("noAdvice"))}</div>`;
const filtered = state.recommendations.filter(item => state.recFilter === "all" || state.recFilter === item.category || (state.recFilter === "done" && done.includes(item.id))).filter(item => state.recFilter === "done" || true);
document.getElementById("allAdvice").innerHTML = filtered.length ? filtered.map(x=>adviceCard(x,done)).join("") : `<div class="kt-ai-empty">${esc(t("noFilteredAdvice"))}</div>`;
renderEvening();
}
function renderEvening() {
document.getElementById("eveningCard").innerHTML = eveningMarkup(state.evening,state.weather);
}
function renderMusic() {
const hour = new Date().getHours();
const featured = MUSIC.find(x=>x.id === (hour < 11 ? "morning" : hour >= 15 ? "calm" : "focus"));
document.getElementById("musicFeature").innerHTML = `<div><span class="kt-ai-chip" data-tone="purple">${esc(t("navMusic"))}</span><h2>${esc(pick(featured.title))}</h2><p>${esc(pick(featured.description))}</p></div>${actionLink(youtubeMusicLink(featured.query),t("listenNow"),true)}`;
document.getElementById("musicGrid").innerHTML = MUSIC.map(item=>`<article class="content-card"><div class="content-card-top"><span class="advice-icon">${icon(item.icon)}</span>${icon("play")}</div><h3>${esc(pick(item.title))}</h3><p>${esc(pick(item.description))}</p>${actionLink(youtubeMusicLink(item.query),t("listen"))}</article>`).join("");
const cinema = CINEMAS[0];
document.getElementById("homeEntertainment").innerHTML = `<article class="home-choice"><div><span class="eyebrow">${esc(t("navMusic"))}</span><h3>${esc(pick(featured.title))}</h3><p>${esc(pick(featured.description))}</p></div>${actionLink(youtubeMusicLink(featured.query),t("listenNow"),true)}</article><article class="home-choice"><div><span class="eyebrow">${esc(t("cinema"))}</span><h3>${esc(t("cinemaTitle"))}</h3><p>${esc(pick(cinema.description))}</p></div>${actionLink(cinema.url,t("checkSessions"))}</article>`;
}
function renderEvents() {
document.getElementById("cinemaGrid").innerHTML = CINEMAS.map(cinema=>`<article class="content-card"><div class="content-card-top"><span class="kt-ai-chip" data-tone="orange">${esc(t("officialSchedule"))}</span>${icon("calendar")}</div><h3>${esc(cinema.name)}</h3><p>${esc(pick(cinema.description))}</p>${actionLink(cinema.url,t("checkSessions"))}</article>`).join("");
document.getElementById("cinemaTheaters").innerHTML = `<span>${esc(t("cityToday"))}:</span>${CITY_GUIDES.map(guide=>actionLink(guide.url,guide.name)).join("")}`;
const seasons = ["winter","spring","summer","autumn"];
const current = seasonForMonth(new Date().getMonth());
document.getElementById("seasonFilters").innerHTML = `<button class="seg" data-season="all" data-active="${state.seasonFilter === "all"}">${esc(t("allSeasons"))}</button>` + seasons.map(s=>`<button class="seg" data-season="${s}" data-active="${state.seasonFilter === s}">${esc(t("season"+s[0].toUpperCase()+s.slice(1)))}</button>`).join("");
const filtered = EVENTS.filter(e=>state.seasonFilter === "all" || e.season === state.seasonFilter);
document.getElementById("eventsGrid").innerHTML = filtered.map(event=>`<article class="content-card"><div class="content-card-top"><span class="advice-icon">${icon(event.icon)}</span><span class="kt-ai-chip" data-tone="${event.category === "outside" ? "green" : "blue"}">${esc(t(event.category))}</span></div><h3>${esc(pick(event.title))}</h3><p>${esc(pick(event.description))}</p>${externalLink(mapLink(event.map),t("details"))}</article>`).join("");
document.getElementById("seasonLabel").textContent = t("todayRounded") + ": " + t("season"+current[0].toUpperCase()+current.slice(1));
}
function renderLiveEvents() {
const target=document.getElementById("liveEventsGrid");
const notice=state.eventsLive ? "" : `<div class="info-banner">${icon("info")}<span>${esc(t("liveEventsStale"))}</span></div>`;
target.innerHTML = state.liveEvents.length ? state.liveEvents.slice(0,12).map(event=>`<article class="content-card"><div class="content-card-top"><span class="kt-ai-chip" data-tone="orange">${esc(event.source)}</span>${icon("calendar")}</div><h3>${esc(event.title)}</h3><span class="event-card-date">${esc(event.dateLabel)}</span><p>${esc(event.address||t("details"))}</p>${actionLink(event.url,t("details"))}</article>`).join("")+notice : `<div class="kt-ai-empty">${esc(t("liveEventsEmpty"))}</div>`;
}
async function loadEvening() {
try {
const response=await fetch("api/evening");
if (!response.ok) throw new Error("Афиша недоступна");
state.evening=await response.json();
state.liveEvents=state.evening.events||[];
state.eventsLive=state.evening.eventsLive===true;
} catch (_) {
const w=state.weather||{temp:10,feels:10,wind:0,aqi:null};
const day=Math.floor(new Date(localDateKey()+"T12:00:00Z").getTime()/86400000);
state.evening={kind:"home",homeId:day%HOME_EVENINGS.length,weatherKind:(w.aqi!==null&&w.aqi>40)?"air":(w.temp<=0||w.feels<=-3)?"cold":w.wind>=12?"wind":"mild",date:localDateKey()};
state.liveEvents=[];state.eventsLive=false;
}
renderEvening();renderLiveEvents();
}
function cycleEvening() {
const idea=state.evening;
if (!idea) return;
const date=idea.date||localDateKey();
const available=state.liveEvents.filter(event=>event.start<=date&&event.end>=date);
if (idea.kind==="event") {
const index=available.findIndex(event=>event.title===idea.event.title&&event.start===idea.event.start);
if (available.length && index<available.length-1) {
state.evening={...idea,kind:"event",event:available[index+1]};
} else state.evening={...idea,kind:"home",homeId:(idea.homeId||0)+1};
} else state.evening={...idea,kind:"home",homeId:(idea.homeId||0)+1};
renderEvening();
}
function toast(message) {
const el = document.createElement("div");
el.className = "kt-ai-toast"; el.dataset.tone = "ok"; el.textContent = message;
document.getElementById("toastStack").appendChild(el);
setTimeout(()=>el.remove(),4500);
}
function notificationStatusText() {
if (typeof Notification === "undefined") return t("notificationsUnsupported");
if (Notification.permission === "denied") return t("notificationsDenied");
if (Notification.permission === "granted") return t("notificationsReady");
return t("notificationNote");
}
function renderNotificationDrawer() {
const needsButton = typeof Notification !== "undefined" && Notification.permission === "default";
document.getElementById("notificationPermission").innerHTML = `<div class="info-banner">${icon("bell")}<div><span>${esc(notificationStatusText())}</span>${needsButton ? `<br><button class="kt-ai-btn" data-size="sm" id="enableNotifications">${esc(t("enableNotifications"))}</button>` : ""}</div></div>`;
const history = getNotificationHistory();
const locale = currentLang === "kz" ? "kk-KZ" : currentLang === "en" ? "en-GB" : "ru-RU";
document.getElementById("notificationHistory").innerHTML = history.length ? history.map(item=>{ const current=state.recommendations.find(x=>x.id===item.id)||item; return `<div class="history-item"><strong>${esc(current.title)}</strong><p>${esc(current.text)}</p><time>${esc(new Intl.DateTimeFormat(locale,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(new Date(item.time)))}</time></div>`; }).join("") : `<div class="kt-ai-empty">${esc(t("noNotifications"))}</div>`;
const enable = document.getElementById("enableNotifications");
if (enable) enable.addEventListener("click",enableNotifications);
}
async function enableNotifications() {
if (typeof Notification === "undefined") { renderNotificationDrawer(); return; }
let permission = "denied";
try { permission = await Notification.requestPermission(); } catch (_) { renderNotificationDrawer(); return; }
if (permission === "granted") {
const entry = {id:"welcome",title:t("testNotification"),text:t("testNotificationBody"),time:new Date().toISOString()};
sendBrowserNotification(entry);
}
renderNotificationDrawer();
}
function openNotifications() {
document.getElementById("notificationDrawer").hidden = false;
document.getElementById("drawerBackdrop").hidden = false;
document.getElementById("notificationDot").hidden = true;
renderNotificationDrawer();
}
function closeNotifications() {
document.getElementById("notificationDrawer").hidden = true;
document.getElementById("drawerBackdrop").hidden = true;
}
function evaluateAdvice() {
if (!state.weather) return;
state.recommendations = buildRecommendations(state.weather,state.settings);
const fresh = rememberAdvice(state.recommendations);
fresh.forEach(sendBrowserNotification);
if (fresh.length) document.getElementById("notificationDot").hidden = false;
renderRecommendations();
}
async function loadWeather(showMessage = false) {
const button = document.getElementById("refreshButton");
button.disabled = true;
try {
await WeatherStore.load();
state.weather = WeatherStore.data;
renderWeather(); evaluateAdvice();
if (showMessage) toast(t(state.weather.isDemo ? "weatherError" : "liveNotice"));
} catch (_) { if (showMessage) toast(t("weatherError")); }
finally { button.disabled = false; }
}
function openSettings() {
document.getElementById("workStart").value = state.settings.workStart;
document.getElementById("workEnd").value = state.settings.workEnd;
document.getElementById("musicAdviceEnabled").checked = state.settings.musicAdvice !== false;
document.getElementById("settingsDialog").showModal();
}
function bindEvents() {
window.addEventListener("hashchange",navigate);
document.getElementById("menuButton").addEventListener("click",()=>{const s=document.getElementById("sidebar");s.dataset.open=String(s.dataset.open!=="true");});
document.getElementById("refreshButton").addEventListener("click",()=>loadWeather(true));
document.getElementById("notificationButton").addEventListener("click",openNotifications);
document.getElementById("closeNotifications").addEventListener("click",closeNotifications);
document.getElementById("drawerBackdrop").addEventListener("click",closeNotifications);
document.getElementById("settingsButton").addEventListener("click",openSettings);
["closeSettings","cancelSettings"].forEach(id=>document.getElementById(id).addEventListener("click",()=>document.getElementById("settingsDialog").close()));
document.getElementById("settingsForm").addEventListener("submit",event=>{
event.preventDefault();
state.settings={workStart:document.getElementById("workStart").value,workEnd:document.getElementById("workEnd").value,musicAdvice:document.getElementById("musicAdviceEnabled").checked};
SafeStore.setItem("auada_settings",JSON.stringify(state.settings));
document.getElementById("settingsDialog").close(); evaluateAdvice(); renderNotificationDrawer(); toast(t("saved"));
});
document.getElementById("languageSwitch").addEventListener("click",event=>{
const button=event.target.closest("[data-lang]");if(!button)return;
currentLang=button.dataset.lang;SafeStore.setItem("auada_lang",currentLang);
applyTranslations();renderWeather();evaluateAdvice();renderMusic();renderEvents();renderLiveEvents();renderNotificationDrawer();
});
document.getElementById("recFilters").addEventListener("click",event=>{
const button=event.target.closest("[data-filter]");if(!button)return;
state.recFilter=button.dataset.filter;
document.querySelectorAll("[data-filter]").forEach(x=>x.dataset.active=String(x===button));renderRecommendations();
});
document.getElementById("seasonFilters").addEventListener("click",event=>{
const button=event.target.closest("[data-season]");if(!button)return;
state.seasonFilter=button.dataset.season;renderEvents();
});
document.body.addEventListener("click",event=>{
const button=event.target.closest("[data-done-id]");if(!button)return;
toggleDone(button.dataset.doneId);renderRecommendations();
});
document.body.addEventListener("click",event=>{if(event.target.closest("#anotherEvening"))cycleEvening();});
document.addEventListener("keydown",event=>{if(event.key==="Escape")closeNotifications();});
}
async function init() {
applyTranslations();navigate();renderMusic();renderEvents();renderLiveEvents();bindEvents();renderNotificationDrawer();
await Promise.all([loadWeather(),loadEvening()]);
renderMusic();renderEvents();
setInterval(()=>loadWeather(),30*60*1000);
setInterval(evaluateAdvice,15*60*1000);
}
init();