async function refresh() {
  const { lastSync } = await chrome.storage.local.get("lastSync");
  if (!lastSync) {
    document.getElementById("ts").textContent = "jamais";
    document.getElementById("count").textContent = "0";
    document.getElementById("status").innerHTML = '<span class="ko">En attente</span>';
    return;
  }
  const age = Math.round((Date.now() - lastSync.ts) / 1000);
  document.getElementById("ts").textContent = age + " s";
  document.getElementById("count").textContent = lastSync.count;
  document.getElementById("status").innerHTML =
    age < 90 ? '<span class="ok">OK</span>' : '<span class="ko">Retard</span>';
}

document.getElementById("sync").addEventListener("click", async () => {
  document.getElementById("status").textContent = "Sync…";
  const r = await chrome.runtime.sendMessage({ type: "XDOCK_SYNC_NOW" });
  if (r?.ok) {
    document.getElementById("status").innerHTML = '<span class="ok">OK (' + r.trucks + ')</span>';
    refresh();
  } else {
    document.getElementById("status").innerHTML = '<span class="ko">' + (r?.error || "Erreur") + '</span>';
  }
});

refresh();
setInterval(refresh, 2000);
