(function () {
    const downloadLink = document.getElementById("download-link");
    const releaseVersion = document.getElementById("release-version");
    const releaseMeta = document.getElementById("release-meta");
    const releaseNotes = document.getElementById("release-notes");

    const fallbackText = "Последняя версия APK пока не опубликована";

    async function loadRelease() {
        try {
            const response = await fetch("/api/app-updates/android/latest", {
                headers: {
                    "Accept": "application/json"
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const release = await response.json();
            const publishedAt = new Date(release.publishedAt);
            const publishedLabel = Number.isNaN(publishedAt.getTime())
                ? "Дата публикации не указана"
                : publishedAt.toLocaleString("ru-RU", {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                    hour: "2-digit",
                    minute: "2-digit"
                });

            releaseVersion.textContent = `Версия ${release.versionName}`;
            releaseMeta.textContent = `Build ${release.versionCode} • опубликовано ${publishedLabel}`;
            releaseNotes.textContent = release.notes ?? "";
            downloadLink.href = release.downloadPath;
            downloadLink.removeAttribute("aria-disabled");
        } catch (error) {
            releaseVersion.textContent = "APK недоступен";
            releaseMeta.textContent = fallbackText;
            releaseNotes.textContent = "";
        }
    }

    loadRelease();
})();
