/* Trekker UI: full-screen MapLibre map; sidebar, slide-out panel, modals. */
"use strict";
const $ = (id) => document.getElementById(id);
const api = async (path, opts = {}) => {
const resp = await fetch(path, opts);
if (!resp.ok) {
let detail = resp.statusText;
try { detail = (await resp.json()).detail || detail; } catch {}
throw new Error(detail);
}
return resp.json();
};
const state = {
config: null,
routes: [],
guides: [],
current: null, // full TrekkerRoute of selected route
weather: null, // cached weather for selected route
online: navigator.onLine,
};
/* ---------- map ---------- */
let map;
function initMap(cfg) {
// Base tiles via the backend-configured source; offline packs are served
// from /api/offline-maps/tiles and tried first when offline.
const sources = {
base: {
type: "raster",
tiles: state.online
? [cfg.tiles_base_url]
: ["/api/offline-maps/tiles/base/{z}/{x}/{y}.png"],
tileSize: 256,
attribution: "© OpenStreetMap contributors",
},
};
map = new maplibregl.Map({
container: "map",
style: { version: 8, sources, layers: [{ id: "base", type: "raster", source: "base" }] },
center: [-84.36, 36.2], // Windrock-ish default
zoom: 11,
});
map.addControl(new maplibregl.NavigationControl());
map.on("load", () => {
map.addSource("route", { type: "geojson", data: emptyFC() });
map.addLayer({
id: "route-line", type: "line", source: "route",
paint: { "line-color": ["coalesce", ["get", "color"], "#2d6cdf"], "line-width": 4 },
});
map.addSource("waypoints", { type: "geojson", data: emptyFC() });
map.addLayer({
id: "wpt-circles", type: "circle", source: "waypoints",
paint: { "circle-radius": 6, "circle-color": "#e67e22", "circle-stroke-color": "#fff", "circle-stroke-width": 1.5 },
});
map.addLayer({
id: "wpt-labels", type: "symbol", source: "waypoints",
layout: { "text-field": ["get", "name"], "text-size": 11, "text-offset": [0, 1.2] },
paint: { "text-color": "#fff", "text-halo-color": "#000", "text-halo-width": 1 },
});
map.on("click", "wpt-circles", (e) => {
const f = e.features[0];
new maplibregl.Popup().setLngLat(f.geometry.coordinates)
.setHTML(`${f.properties.name || "Waypoint"}
${f.properties.desc || ""}`)
.addTo(map);
});
});
}
const emptyFC = () => ({ type: "FeatureCollection", features: [] });
function gradeColor(g) {
const a = Math.abs(g);
return a < 5 ? "#2ecc71" : a < 10 ? "#f1c40f" : a < 18 ? "#e67e22" : "#e74c3c";
}
function precipColor(p) {
p = p || 0;
return p < 20 ? "#d6eaf8" : p < 50 ? "#5dade2" : p < 80 ? "#2e86c1" : "#1b4f72";
}
function renderRouteOnMap() {
const r = state.current;
if (!r || !map.getSource("route")) return;
const useGrade = $("layer-grade").checked;
const useWeather = $("layer-weather").checked && state.weather;
const tier = $("weather-tier").value;
const features = r.segments.map((seg) => {
let color = "#2d6cdf";
if (useWeather) {
const tiers = (state.weather.segments || {})[String(seg.index)] || {};
const buckets = tiers[tier] || tiers.daily || [];
const now = buckets[0] || {};
color = precipColor(now.precip_prob_max);
} else if (useGrade) {
color = gradeColor(seg.grade_pct_max);
}
return {
type: "Feature",
properties: { color, name: seg.name },
geometry: {
type: "LineString",
coordinates: r.points.slice(seg.start_idx, seg.end_idx + 1).map((p) => [p.lon, p.lat]),
},
};
});
if (!features.length && r.points.length > 1) {
features.push({
type: "Feature", properties: { color: "#2d6cdf" },
geometry: { type: "LineString", coordinates: r.points.map((p) => [p.lon, p.lat]) },
});
}
map.getSource("route").setData({ type: "FeatureCollection", features });
map.getSource("waypoints").setData({
type: "FeatureCollection",
features: r.waypoints.map((w) => ({
type: "Feature",
properties: { name: w.name, desc: w.desc },
geometry: { type: "Point", coordinates: [w.lon, w.lat] },
})),
});
}
/* ---------- sidebar: routes ---------- */
async function loadRoutes() {
state.routes = await api("/api/routes");
const filter = $("route-search").value.toLowerCase();
const ul = $("route-list");
ul.innerHTML = "";
for (const r of state.routes) {
if (filter && !r.name.toLowerCase().includes(filter)) continue;
const li = document.createElement("li");
if (state.current && state.current.id === r.id) li.classList.add("active");
const mi = (r.stats.distance_m / 1609.344).toFixed(1);
li.innerHTML = `${r.name}${r.source} · ${mi} mi · ${r.created_at.slice(0, 10)}`;
li.onclick = () => selectRoute(r.id);
ul.appendChild(li);
}
}
async function selectRoute(id) {
state.current = await api(`/api/routes/${id}`);
try { state.weather = await api(`/api/routes/${id}/weather`); }
catch { state.weather = null; }
const b = boundsOf(state.current);
if (b) map.fitBounds(b, { padding: 60 });
renderRouteOnMap();
openRoutePanel();
loadRoutes();
}
function boundsOf(r) {
if (!r.points.length) return null;
const lons = r.points.map((p) => p.lon), lats = r.points.map((p) => p.lat);
return [[Math.min(...lons), Math.min(...lats)], [Math.max(...lons), Math.max(...lats)]];
}
/* ---------- route panel ---------- */
function openRoutePanel() {
const r = state.current;
$("route-panel").hidden = false;
$("rp-name").textContent = r.name;
const mi = (r.stats.distance_m / 1609.344).toFixed(1);
const gain = Math.round(r.stats.elevation_gain_m * 3.28084);
const loss = Math.round(r.stats.elevation_loss_m * 3.28084);
$("rp-meta").textContent = `${r.source} · ${mi} mi · +${gain} ft / −${loss} ft`;
$("rp-export-gpx").href = `/api/routes/${r.id}/export?format=gpx`;
$("rp-export-kml").href = `/api/routes/${r.id}/export?format=kml`;
const ul = $("rp-segments");
ul.innerHTML = "";
for (const s of r.segments) {
const li = document.createElement("li");
li.style.borderLeftColor = gradeColor(s.grade_pct_max);
li.innerHTML = `${s.name}
${(s.distance_m / 1609.344).toFixed(2)} mi · max grade ${s.grade_pct_max}%`;
ul.appendChild(li);
}
const sel = $("rp-guide");
sel.innerHTML = `` +
state.guides.map((g) => ``).join("");
$("rp-card-output").innerHTML = "";
renderWeatherBadge();
}
function renderWeatherBadge() {
const el = $("rp-weather");
if (!state.weather) { el.hidden = true; return; }
const seg0 = (state.weather.segments || {})["0"] || {};
const today = (seg0.daily || [])[0];
if (!today) { el.hidden = true; return; }
el.hidden = false;
el.innerHTML = `🌡 ${Math.round(today.temp_min_f)}–${Math.round(today.temp_max_f)}°F · ` +
`🌧 ${today.precip_prob_max ?? "?"}% · 💨 ${Math.round(today.wind_max_kmh || 0)} km/h` +
(today.lightning_risk ? " · ⚡" : "");
}
/* ---------- modals ---------- */
function openModal(id) {
$("modal-backdrop").hidden = false;
for (const m of document.querySelectorAll(".modal")) m.hidden = m.id !== id;
}
function closeModal() { $("modal-backdrop").hidden = true; }
/* ---------- trail guide review form ---------- */
let guideDraft = null;
function showGuideReview(draft) {
guideDraft = draft;
const f = $("guide-review");
f.hidden = false;
f.name.value = draft.name || "";
f.difficulty.value = draft.difficulty || "";
f.obstacle_types.value = (draft.obstacle_types || []).join(", ");
f.water_crossings.value = (draft.water_crossings || [])
.map((w) => [w.name || "", w.depth_ft ?? "", w.notes || ""].join(" | ")).join("\n");
f.gate_codes.value = (draft.gate_codes || []).join(", ");
f.vehicle_recommendations.value = (draft.vehicle_recommendations || []).join(", ");
f.warnings.value = (draft.warnings || []).join("\n");
f.notes.value = draft.notes || "";
}
const csv = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
const lines = (v) => v.split("\n").map((s) => s.trim()).filter(Boolean);
/* ---------- offline packs ---------- */
async function loadPacks() {
const packs = await api("/api/offline-maps");
const ul = $("pack-list");
ul.innerHTML = "";
let anyActive = false;
for (const p of packs) {
const li = document.createElement("li");
const pct = p.tile_count ? Math.round((p.tiles_done / p.tile_count) * 100) : 0;
const status = p.status === "downloading" ? `downloading ${pct}%` :
p.status === "ready" ? `ready · ${(p.size_bytes / 1e6).toFixed(1)} MB` : p.status;
li.innerHTML = `${p.name}z${p.min_zoom}–${p.max_zoom} · ${status}`;
li.title = "Click to delete";
li.onclick = async () => {
if (confirm(`Delete offline pack "${p.name}"?`)) {
await api(`/api/offline-maps/${p.id}`, { method: "DELETE" });
loadPacks();
}
};
ul.appendChild(li);
if (p.status === "downloading" || p.status === "queued") anyActive = true;
}
if (anyActive) setTimeout(loadPacks, 2000);
}
/* ---------- online/offline state ---------- */
function updateNetState() {
state.online = navigator.onLine;
const badge = $("net-badge");
badge.textContent = state.online ? "online" : "offline";
badge.className = `badge ${state.online ? "online" : "offline"}`;
$("btn-sync").hidden = !(state.online && state.config && state.config.sync_peer_configured);
$("rp-weather-refresh").disabled = !state.online;
}
/* ---------- wire-up ---------- */
async function main() {
try { state.config = await api("/api/config"); } catch { state.config = {}; }
initMap(state.config);
updateNetState();
window.addEventListener("online", updateNetState);
window.addEventListener("offline", updateNetState);
$("sidebar-toggle").onclick = () => $("sidebar").classList.toggle("collapsed");
$("route-search").oninput = loadRoutes;
$("layer-grade").onchange = renderRouteOnMap;
$("layer-weather").onchange = renderRouteOnMap;
$("weather-tier").onchange = renderRouteOnMap;
document.body.addEventListener("click", (e) => {
const t = e.target.closest("[data-close]");
if (!t) return;
if (t.dataset.close === "modal") closeModal();
else $(t.dataset.close).hidden = true;
});
$("btn-upload").onclick = () => { $("upload-status").textContent = ""; openModal("modal-upload"); };
$("gpx-submit").onclick = async () => {
const file = $("gpx-file").files[0];
if (!file) return;
const fd = new FormData();
fd.append("file", file);
$("upload-status").textContent = "Uploading…";
try {
const route = await api("/api/routes/upload", { method: "POST", body: fd });
closeModal();
await loadRoutes();
selectRoute(route.id);
} catch (err) { $("upload-status").textContent = err.message; }
};
$("btn-scrape").onclick = () => {
$("guide-status").textContent = "";
$("guide-review").hidden = true;
openModal("modal-guide");
};
$("guide-scrape").onclick = async () => {
const url = $("guide-url").value.trim();
if (!url) return;
$("guide-status").textContent = "Scraping + extracting…";
try {
showGuideReview(await api("/api/trails/scrape", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
}));
$("guide-status").textContent = "Review the extraction, then save.";
} catch (err) { $("guide-status").textContent = err.message; }
};
$("guide-pdf-submit").onclick = async () => {
const file = $("guide-pdf").files[0];
if (!file) return;
const fd = new FormData();
fd.append("file", file);
$("guide-status").textContent = "Extracting from PDF…";
try {
showGuideReview(await api("/api/trails/upload-pdf", { method: "POST", body: fd }));
$("guide-status").textContent = "Review the extraction, then save.";
} catch (err) { $("guide-status").textContent = err.message; }
};
$("guide-review").onsubmit = async (e) => {
e.preventDefault();
const f = e.target;
const guide = Object.assign({}, guideDraft, {
name: f.name.value,
difficulty: f.difficulty.value || null,
obstacle_types: csv(f.obstacle_types.value),
water_crossings: lines(f.water_crossings.value).map((ln) => {
const [name, depth, notes] = ln.split("|").map((s) => s.trim());
return { name: name || null, depth_ft: depth ? parseFloat(depth) : null, notes: notes || null };
}),
gate_codes: csv(f.gate_codes.value),
vehicle_recommendations: csv(f.vehicle_recommendations.value),
warnings: lines(f.warnings.value),
notes: f.notes.value || null,
});
await api("/api/trails", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(guide),
});
state.guides = await api("/api/trails");
closeModal();
if (state.current) openRoutePanel();
};
$("rp-guide").onchange = async (e) => {
const r = state.current;
state.current = await api(`/api/routes/${r.id}/trail-guide`, {
method: "PUT", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ trail_guide_id: e.target.value || null }),
});
};
$("rp-delete").onclick = async () => {
if (!confirm(`Delete route "${state.current.name}"?`)) return;
await api(`/api/routes/${state.current.id}`, { method: "DELETE" });
state.current = null;
$("route-panel").hidden = true;
map.getSource("route").setData(emptyFC());
map.getSource("waypoints").setData(emptyFC());
loadRoutes();
};
$("rp-weather-refresh").onclick = async () => {
const btn = $("rp-weather-refresh");
btn.disabled = true;
try {
state.weather = await api(`/api/routes/${state.current.id}/refresh-weather`, { method: "POST" });
renderWeatherBadge();
renderRouteOnMap();
} catch (err) { alert(`Weather refresh failed: ${err.message}`); }
btn.disabled = false;
};
$("rp-card").onclick = async () => {
try {
const asset = await api(`/api/routes/${state.current.id}/generate/trail_card`, { method: "POST" });
renderTrailCard(asset.data);
} catch (err) { alert(err.message); }
};
$("btn-offline").onclick = () => { $("pack-estimate").textContent = ""; openModal("modal-offline"); };
const packBody = () => {
const b = map.getBounds();
return {
name: $("pack-name").value,
bbox: [b.getWest(), b.getSouth(), b.getEast(), b.getNorth()],
min_zoom: parseInt($("pack-minz").value, 10),
max_zoom: parseInt($("pack-maxz").value, 10),
layers: $("pack-terrain").checked ? ["base", "terrain"] : ["base"],
};
};
$("pack-estimate-btn").onclick = async () => {
try {
const est = await api("/api/offline-maps/estimate", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(packBody()),
});
$("pack-estimate").textContent =
`${est.tile_count} tiles ≈ ${(est.estimated_bytes / 1e6).toFixed(1)} MB`;
} catch (err) { $("pack-estimate").textContent = err.message; }
};
$("pack-create").onclick = async () => {
try {
await api("/api/offline-maps", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(packBody()),
});
closeModal();
loadPacks();
} catch (err) { $("pack-estimate").textContent = err.message; }
};
$("btn-sync").onclick = async () => {
try {
const res = await api("/api/sync", {
method: "POST", headers: { "Content-Type": "application/json" }, body: "{}",
});
alert(`Synced. Pulled ${res.pulled.routes} routes, ${res.pulled.trail_guides} guides.`);
loadRoutes();
} catch (err) { alert(err.message); }
};
state.guides = await api("/api/trails").catch(() => []);
await loadRoutes();
loadPacks();
}
function renderTrailCard(card) {
const out = $("rp-card-output");
const guide = card.guide;
out.innerHTML = `