import { DEBUG_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
// Every read-only status endpoint, dumped as raw JSON. No check-update
// routes here — those reach out to Geofabrik/the internet, not just report
// local state.
const ENDPOINTS = [
"/api/health",
"/api/offline-tiles",
"/api/offline-tiles/build-status",
"/api/offline-regions",
"/api/offline-tiles/cache",
"/api/terrain-tiles",
"/api/terrain-tiles/build-status",
"/api/hiking-trails",
"/api/kiwix",
"/api/plugins",
"/api/gnss/position",
"/api/livetrack/sessions",
];
const REFRESH_MS = 5000; // while open — a running build's progress shows up live
// Sidebar icon pinned to the bottom of the rail, logged-in only (map.js).
export class DebugControl {
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item sidebar-item--bottom";
this._container.innerHTML = ``;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("debug-panel");
this._body = this._panel.querySelector(".debug-panel__body");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
onlyOneSidePanelOpen(this._panel, () => this._stop());
sidebar.appendChild(this._container);
}
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
if (!open) return this._stop();
this._icon.classList.add("active");
notifySidePanelOpen(this._panel);
this._refresh();
this._timer = setInterval(() => this._refresh(), REFRESH_MS);
}
_stop() {
this._icon.classList.remove("active");
clearInterval(this._timer);
}
async _refresh() {
const sections = await Promise.all(
ENDPOINTS.map(async (url) => {
let text;
try {
const response = await fetch(url);
const body = await response.text();
try {
text = JSON.stringify(JSON.parse(body), null, 2);
} catch {
text = body;
}
if (!response.ok) text = `HTTP ${response.status}\n${text}`;
} catch (error) {
text = `request failed: ${error.message}`;
}
return { url, text };
}),
);
if (this._panel.hidden) return;
// Keep whichever sections the user collapsed collapsed across refreshes.
const closed = new Set([...this._body.querySelectorAll("details:not([open])")].map((el) => el.dataset.url));
this._body.innerHTML = sections
.map(
({ url, text }) => `
${url}
${escapeHtml(text)}
`,
)
.join("");
}
}