import { signal } from "@preact/signals";
import { localGet } from "./api.js";
const POLL_MS = 60000;
export const updateAvailable = signal(false);
let seen = null;
let stale = false;
let poll = null;
const onTerminal = () => /^#\/s\//.test(location.hash);
function reloadOrOffer() {
stale = true;
if (onTerminal()) updateAvailable.value = true;
else location.reload();
}
export function dismissUpdate() {
updateAvailable.value = false;
}
async function checkBuildHash({ shown = false } = {}) {
let hash;
try {
hash = (await localGet("/api/build-info"))?.build_hash;
} catch (_) {
return; }
if (!hash || hash === "unknown") return;
if (seen === hash) {
if (stale && shown) reloadOrOffer();
return;
}
const hadBaseline = seen !== null;
seen = hash;
if (hadBaseline) reloadOrOffer();
}
function startPoll() {
if (poll === null) poll = setInterval(() => checkBuildHash(), POLL_MS);
}
function stopPoll() {
clearInterval(poll);
poll = null;
}
function onVisible() {
if (document.visibilityState !== "visible") return;
startPoll();
checkBuildHash({ shown: true });
}
export function watchBuildHash() {
checkBuildHash();
if (document.visibilityState === "visible") startPoll();
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") onVisible();
else stopPoll();
});
document.addEventListener("freeze", stopPoll);
document.addEventListener("resume", onVisible);
window.addEventListener("hashchange", () => {
if (stale && !onTerminal()) location.reload();
});
window.__mobuxCheckBuildHash = () => checkBuildHash();
window.__mobuxBuildPollActive = () => poll !== null;
}