`;
// Largest first for display (the order itself stays in travel order).
const ranked = step.tasks.map((t, i) => [t, i]).sort((a, b) => (b[0].zone_area_px ?? b[0].area_px) - (a[0].zone_area_px ?? a[0].area_px));
const head = ranked.slice(0, 3).map(([t, i]) => card(t, i)).join("");
const rest = ranked.slice(3).map(([t, i]) => card(t, i)).join("");
inner += `
${head}
` + (rest ? `Show ${ranked.length - 3} more
${rest}
` : "");
}
li.innerHTML = inner;
steps.appendChild(li);
}
// Hovering a prep/prime task highlights its damage region (tasks are in travel order; match by centre).
steps.querySelectorAll(".task").forEach((el) => {
const step = (order.steps || []).find((s) => s.step === el.dataset.step);
const task = step && step.tasks[+el.dataset.task];
const region = task && regionFor(task);
el.addEventListener("mouseenter", () => highlight(region, true));
el.addEventListener("mouseleave", () => highlight(region, false));
});
const locked = !!job.approved;
$("#replan").disabled = locked;
$("#approve").disabled = locked || order.status === "blocked";
$("#approve").title = order.status === "blocked" ? "The safety gate blocks this order" : "";
$("#download").hidden = false;
$("#download").href = `/api/jobs/${job.id}/work_order.json?download=1`;
$("#approved").innerHTML = locked
? `Approved by ${esc(job.approved.by)} at ${esc(new Date(job.approved.at).toLocaleString())} registry ${esc(job.approved.registry_hash.slice(0, 16))}…`
: "";
document.querySelectorAll("[data-tool]").forEach((b) => (b.disabled = locked && b.dataset.tool !== "none"));
$("#clear-edits").disabled = locked;
}
function regionFor(task) {
const poly = JSON.stringify(task.zone_polygon_px || null);
return (job.regions || []).findIndex((r) => JSON.stringify(r.prep_zone_xy || null) === poly);
}
function highlight(index, on) {
if (index == null || index < 0) return;
const el = document.querySelector(`#vector [data-region="${index}"]`);
if (el) el.classList.toggle("hl", on);
}
function renderConfirmations() {
const box = $("#confirmations");
box.innerHTML = "";
for (const [name, meaning] of Object.entries((health && health.confirmations) || {})) {
const label = document.createElement("label");
label.innerHTML = `${esc(meaning)}`;
label.querySelector("input").addEventListener("change", () => setDirty(true));
box.appendChild(label);
}
}
// ------------------------------------------------------------------ layers
function applyLayerToggles() {
const opacity = $("#opacity").value / 100;
document.querySelectorAll("#layer-toggles input").forEach((box) => {
const name = box.dataset.layer;
document.querySelectorAll(`[data-layer="${name}"]:not(input)`).forEach((el) => {
if (el instanceof SVGElement) el.style.display = box.checked ? "" : "none"; // .hidden is HTML-only
else { el.classList.toggle("off", !box.checked); el.hidden = false; } // fade via CSS (.layer.off), not display:none
// the slider sets a variable the stylesheet reads, not an inline opacity: an inline value would beat the Fill / Outline / Both rules
if (el.tagName === "IMG") $("#stage").style.setProperty("--ov-opacity", String(opacity));
});
});
}
document.querySelectorAll("#layer-toggles input").forEach((b) => b.addEventListener("change", applyLayerToggles));
$("#opacity").addEventListener("input", applyLayerToggles);
// ------------------------------------------------------------------ brush
document.querySelectorAll("[data-tool]").forEach((b) => b.addEventListener("click", () => {
tool = b.dataset.tool;
document.querySelectorAll("[data-tool]").forEach((x) => {
x.classList.toggle("on", x === b);
x.setAttribute("aria-pressed", String(x === b));
});
$("#stage").classList.toggle("drawing", tool !== "none");
if (tool !== "none") {
const edits = document.querySelector('#layer-toggles input[data-layer="edits"]');
edits.checked = true;
applyLayerToggles();
}
}));
function toImage(e) {
const r = editCanvas.getBoundingClientRect();
return { x: (e.clientX - r.left) * (editCanvas.width / r.width), y: (e.clientY - r.top) * (editCanvas.height / r.height), scale: editCanvas.width / r.width };
}
function dab(e) {
if (!editCanvas.getBoundingClientRect().width || !$("#photo").complete) return; // photo not laid out yet
const { x, y, scale } = toImage(e);
const radius = ($("#brush").value / 2) * scale;
ectx.globalCompositeOperation = tool === "erase" ? "destination-out" : "source-over";
ectx.fillStyle = tool === "add" ? "rgb(0,255,0)" : "rgb(255,0,0)";
ectx.beginPath();
ectx.arc(x, y, radius, 0, Math.PI * 2);
ectx.fill();
setDirty(true);
}
function moveCursor(e) {
const cursor = $("#cursor");
const stage = $("#stage").getBoundingClientRect();
cursor.hidden = tool === "none";
const size = $("#brush").value;
cursor.style.width = cursor.style.height = `${size}px`;
cursor.style.left = `${e.clientX - stage.left}px`;
cursor.style.top = `${e.clientY - stage.top}px`;
}
editCanvas.addEventListener("pointerdown", (e) => {
if (tool === "none" || (job && job.approved)) return;
drawing = true;
editCanvas.setPointerCapture(e.pointerId);
dab(e);
});
editCanvas.addEventListener("pointermove", (e) => { moveCursor(e); if (drawing) dab(e); });
editCanvas.addEventListener("pointerup", () => (drawing = false));
editCanvas.addEventListener("pointerleave", () => ($("#cursor").hidden = true));
$("#clear-edits").addEventListener("click", () => { ectx.clearRect(0, 0, editCanvas.width, editCanvas.height); setDirty(true); });
function setDirty(on) {
dirty = on;
$("#dirty").hidden = !on;
}
function editsPayload() {
const data = ectx.getImageData(0, 0, editCanvas.width, editCanvas.height).data;
for (let i = 3; i < data.length; i += 4) if (data[i]) return editCanvas.toDataURL("image/png");
return "";
}
// ------------------------------------------------------------------ actions
$("#replan").addEventListener("click", async () => {
if (!job) return;
const confirmations = [...document.querySelectorAll("#confirmations input:checked")].map((b) => b.value);
const btn = $("#replan");
btn.disabled = true;
btn.textContent = "Planning…";
try {
showJob(await api(`/api/jobs/${job.id}/plan`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ edits_png: editsPayload(), confirmations, operator: $("#operator").value.trim() }),
}));
} catch (err) {
toast(err.message);
} finally {
btn.textContent = "Re-plan";
btn.disabled = !!(job && job.approved);
}
});
$("#approve").addEventListener("click", async () => {
if (!job) return;
if (dirty) { toast("Re-plan first: your edits or confirmations are not in this work order yet."); return; }
const operator = $("#operator").value.trim();
if (!operator) { $("#operator").focus(); toast("Enter your name to approve."); return; }
if (!confirm(`Approve this work order as ${operator}? It will be frozen and recorded.`)) return;
try {
showJob(await api(`/api/jobs/${job.id}/approve`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ operator, note: $("#note").value }),
}));
} catch (err) {
toast(err.message);
}
});
boot();
// ------------------------------------------------------------------ job drawings
// A plan or elevation attached to the job: click two points on a known dimension to set the drawing's scale, measure the
// wall (width or height), and use that length to scale the photo. Nothing is read automatically from the drawing.
const dd = { dlg: $("#drawing-dialog"), img: $("#dd-img"), svg: $("#dd-svg"), list: $("#dd-list"), item: null, tool: "calibrate", pts: [] };
function parseLength(text) {
const m = String(text || "").trim().toLowerCase().replace(/[’′]/g, "'").replace(/[”″]/g, '"')
.match(/^(\d+(?:\.\d+)?)\s*(mm|cm|m|meters?|metres?|ft|feet|'|in|inch(?:es)?|")?(?:\s*(\d+(?:\.\d+)?)\s*(in|"|inch(?:es)?)?)?$/);
if (!m) return null;
const a = parseFloat(m[1]), u = m[2] || "m";
if (u === "mm") return a;
if (u === "cm") return a * 10;
if (u.startsWith("m")) return a * 1000;
if (u === "ft" || u === "feet" || u === "'") return a * 304.8 + (m[3] ? parseFloat(m[3]) * 25.4 : 0);
return a * 25.4;
}
function lengthText(mm) {
const inches = mm / 25.4, ft = Math.floor(inches / 12), rem = inches - ft * 12;
return `${(mm / 1000).toFixed(2)} m · ${ft}′ ${rem.toFixed(1)}″`;
}
async function refreshDrawings() {
const list = $("#drawing-list");
$("#drawing-job").textContent = job ? "" : "· open a job first";
$("#gen-btn").disabled = !job;
list.innerHTML = "";
if (!job) return;
const items = await api(`/api/jobs/${job.id}/drawings`).catch(() => []);
for (const d of items) {
const li = document.createElement("li"), b = document.createElement("button");
b.className = "drawing-item";
b.innerHTML = `${esc(d.filename)} ${d.calibration ? "scale set" : "needs scale"} · ${d.measurements.length} measurement(s)
${d.generated ? `${d.provenance && d.provenance.scale_assumed ? "draft · assumed height" : "generated · draft"}` : ""}`;
b.addEventListener("click", () => openDrawing(d));
li.appendChild(b);
list.appendChild(li);
}
}
$("#dfile").addEventListener("change", async (e) => {
const file = e.target.files[0];
e.target.value = "";
if (!file) return;
if (!job) { toast("Open or create a job first: a drawing belongs to one wall."); return; }
try {
const d = await api(`/api/jobs/${job.id}/drawings?filename=${encodeURIComponent(file.name)}`, { method: "POST", body: await file.arrayBuffer() });
await refreshDrawings();
openDrawing(d);
} catch (err) { toast(err.message); }
});
function openDrawing(item) {
dd.item = item; dd.pts = []; dd.tool = item.calibration ? "measure" : "calibrate";
$("#dd-title").textContent = item.filename;
dd.img.onload = () => { dd.svg.setAttribute("viewBox", `0 0 ${item.width} ${item.height}`); drawDrawing(); };
dd.img.src = `/api/jobs/${job.id}/drawings/${item.id}.png`;
setDrawingTool(dd.tool);
if (!dd.dlg.open) dd.dlg.showModal();
resetMatchPanel(item);
renderProvenance(item);
}
function renderProvenance(item) {
const box = $("#dd-prov"), dl = $("#dd-dl");
const p = item.generated && item.provenance;
box.hidden = dl.hidden = !p;
if (!p) return;
box.className = `prov${p.scale_assumed ? " warn" : ""}`;
const notes = (p.notes || []).map((n) => `
${esc(n)}
`).join("");
const SRC = { measured_height: "the wall height you entered", measured_width: "the wall width you entered", depth_scale: "the job's saved scale (mm per pixel)" };
const src = SRC[p.scale_source] || (String(p.scale_source).startsWith("assumed_ceiling_") ? `an assumed ceiling height of ${String(p.scale_source).replace("assumed_ceiling_", "").replace("ft", " ft")}` : p.scale_source);
box.innerHTML = `Draft drawn from a photo. Scale from ${esc(src)}${p.scale_assumed ? " (assumed: check it)" : ""}. ${esc(p.disclaimer || "")}${notes ? `
${notes}
` : ""}`;
const base = `/api/jobs/${job.id}/drawings/${item.id}`;
dl.innerHTML = `View sheet`
+ ["svg", "dxf", "json"].map((x) => `${x.toUpperCase()}`).join("");
}
$("#gen-btn").addEventListener("click", async () => {
if (!job) { toast("Open or create a job first: a drawing is made from one wall's photo."); return; }
const btn = $("#gen-btn"), raw = $("#gen-h").value.trim();
if (raw && !(Number(raw) >= 4 && Number(raw) <= 40)) { toast("Wall height should be between 4 and 40 ft (or leave it empty)."); return; }
btn.disabled = true; btn.textContent = "Drawing…";
try {
const d = await api(`/api/jobs/${job.id}/drawings/generate`, { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(raw ? { wall_height_ft: Number(raw) } : {}) });
await refreshDrawings();
toast(`Drew ${d.openings} opening${d.openings === 1 ? "" : "s"} on a ${(d.wall_mm[0] / 1000).toFixed(2)} × ${(d.wall_mm[1] / 1000).toFixed(2)} m wall.`
+ (d.provenance.scale_assumed ? " Height was assumed: enter the real height for true dimensions." : ""), d.provenance.scale_assumed ? "warn" : "ok");
openDrawing(d);
} catch (e) { toast(e.message || e); }
finally { btn.textContent = "Draw this wall to scale"; btn.disabled = !job; }
});
function setDrawingTool(t) {
dd.tool = t; dd.pts = [];
document.querySelectorAll("[data-dtool]").forEach((b) => b.classList.toggle("on", b.dataset.dtool === t));
$("#dd-hint").textContent = t === "calibrate"
? "Click both ends of a dimension you know (a printed dimension string or a scale bar), then enter its length."
: dd.item.calibration ? "Click both ends of the wall (or any line) to measure it." : "Set the scale first.";
drawDrawing();
}
document.querySelectorAll("[data-dtool]").forEach((b) => b.addEventListener("click", (e) => { e.preventDefault(); setDrawingTool(b.dataset.dtool); }));
const pxLen = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
function svgLine(a, b, cls, label) {
const k = dd.item.width / 900;
return `
${label ? `${esc(label)}` : ""}`;
}
function drawDrawing() {
const it = dd.item; if (!it) return;
const mm = it.calibration && it.calibration.mm_per_px;
let out = "";
if (it.calibration && it.calibration.pts) out += svgLine(it.calibration.pts[0], it.calibration.pts[1], "cal", it.calibration.label || lengthText(it.calibration.length_mm));
it.measurements.forEach((m) => { if (m.pts) out += svgLine(m.pts[0], m.pts[1], "mea", mm ? lengthText(m.length_px * mm) : ""); });
if (dd.pts.length === 1) out += ``;
dd.svg.innerHTML = out;
$("#dd-scale").textContent = mm ? `Scale: ${fmt(mm, 2)} mm per drawing pixel` : "No scale yet";
dd.list.innerHTML = "";
it.measurements.forEach((m, i) => {
const li = document.createElement("li"), len = mm ? m.length_px * mm : null;
li.innerHTML = `
${len ? lengthText(len) : "—"}
${esc(m.label || "Line " + (i + 1))}
${len ? `` : ""}
`;
li.querySelectorAll("[data-axis]").forEach((b) => b.addEventListener("click", () => useAsScale(len, b.dataset.axis, m.label || "Line " + (i + 1))));
li.querySelector("[data-del]").addEventListener("click", async () => {
it.measurements.splice(i, 1);
await saveDrawing({ measurements: it.measurements });
});
dd.list.appendChild(li);
});
}
async function saveDrawing(patch) {
const it = dd.item;
const send = {};
if ("calibration" in patch) send.calibration = patch.calibration;
if ("measurements" in patch) send.measurements = patch.measurements.map((m) => ({ id: m.id, length_px: m.length_px, label: m.label, pts: m.pts }));
const saved = await api(`/api/jobs/${job.id}/drawings/${it.id}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(send) });
Object.assign(it, saved);
drawDrawing();
refreshDrawings();
}
$("#dd-stage").addEventListener("click", async (e) => {
const it = dd.item; if (!it) return;
if (dd.tool === "measure" && !it.calibration) { $("#dd-hint").textContent = "Set the scale first (tool 1)."; return; }
const r = dd.svg.getBoundingClientRect();
dd.pts.push([(e.clientX - r.left) / r.width * it.width, (e.clientY - r.top) / r.height * it.height]);
drawDrawing();
if (dd.pts.length < 2) return;
const [a, b] = dd.pts; dd.pts = [];
const len = pxLen(a, b);
if (len < 8) { drawDrawing(); return; }
try {
if (dd.tool === "calibrate") {
const mm = parseLength(prompt("Real length of that line? e.g. 3.2 m, 10 ft, 10 ft 6 in, 2400 mm"));
if (!mm) { drawDrawing(); return; }
await saveDrawing({ calibration: { length_mm: mm, length_px: len, label: "known", pts: [a, b] } });
setDrawingTool("measure");
} else {
it.measurements.push({ id: Math.random().toString(36).slice(2, 8), length_px: len, label: `Line ${it.measurements.length + 1}`, pts: [a, b] });
await saveDrawing({ measurements: it.measurements });
}
} catch (err) { toast(err.message); drawDrawing(); }
});
async function useAsScale(lengthMm, axis, label) {
try {
const s = await api(`/api/jobs/${job.id}/scale`, { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ length_mm: lengthMm, axis, label }) });
dd.dlg.close();
$("#upload-status").textContent = `Photo scale set from the drawing: ${fmt(s.mm_per_px, 2)} mm/px. Re-planning…`;
$("#replan").click();
} catch (err) { toast(err.message); }
}
// the drawing list follows the open job
const _showJob = showJob;
showJob = function (j) { _showJob(j); refreshDrawings(); };
refreshDrawings();
// ------------------------------------------------------------------ auto-match to the drawing, and the optional AI helper
// Auto-match reads the drawing's windows and doors (needs the scale from tool 1) and finds this photo's wall on it. The scale is only
// applied when the operator presses "Use this scale" AND the match is usable (several openings agree, no equally good alternative).
// The AI helper is advice only: it is off unless the server has an API key, and nothing it says changes a plan, a gate or an approval.
let lastMatch = null;
let aiStatus = null;
function resetMatchPanel(item) {
lastMatch = item && item.auto_match ? item.auto_match : null;
$("#dd-apply").hidden = true;
renderMatch();
loadAiStatus();
}
function renderMatch() {
const out = $("#dd-matchout");
const m = lastMatch;
if (!m) { out.innerHTML = ""; renderAi(); return; }
const rows = [];
if (!m.matched) rows.push(`No match. ${esc(m.reason || "")}`);
else {
rows.push(`${esc(m.confidence)} confidence · ${m.matched_openings.length} opening${m.matched_openings.length === 1 ? "" : "s"} agree`);
if (m.usable_for_scale) rows.push(`Scale ≈ ${fmt(m.mm_per_px_at_centre, 2)} mm per photo pixel${m.applied ? " · applied" : ""}`);
if (m.ambiguous) rows.push(`Several placements fit equally well. Pick the sheet or add a photo that includes a distinguishing feature.`);
if (m.in_photo_not_in_drawing && m.in_photo_not_in_drawing.length) rows.push(`${m.in_photo_not_in_drawing.length} opening(s) in the photo are not on the drawing`);
if (m.in_drawing_not_in_photo && m.in_drawing_not_in_photo.length) rows.push(`${m.in_drawing_not_in_photo.length} drawn opening(s) are not in the photo`);
if (m.note && !m.ambiguous) rows.push(esc(m.note));
}
out.innerHTML = rows.map((r) => `
${r}
`).join("");
$("#dd-apply").hidden = !(m.matched && m.usable_for_scale && !m.applied);
renderAi();
}
$("#dd-match").addEventListener("click", async () => {
const btn = $("#dd-match");
btn.disabled = true;
$("#dd-matchout").textContent = "Matching…";
try {
const res = await api(`/api/jobs/${job.id}/drawings/${dd.item.id}/match`, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
lastMatch = dd.item.auto_match = res.match;
renderMatch();
} catch (e) {
lastMatch = null;
$("#dd-matchout").innerHTML = `${esc(e.message || e)}`;
renderAi();
} finally { btn.disabled = false; }
});
$("#dd-apply").addEventListener("click", async () => {
try {
const res = await api(`/api/jobs/${job.id}/drawings/${dd.item.id}/match`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ apply: true }) });
lastMatch = dd.item.auto_match = res.match;
setDirty(true); // the scale reaches the work order at the next Re-plan
loadEvidence();
renderMatch();
} catch (e) { $("#dd-matchout").innerHTML = `${esc(e.message || e)}`; }
});
async function loadAiStatus() {
try { aiStatus = await api("/api/assist/status"); } catch { aiStatus = { enabled: false, reason: "The AI helper is unavailable." }; }
renderAi();
}
function renderAi() {
const on = !!(aiStatus && aiStatus.enabled);
$("#dd-q").hidden = !on;
$("#dd-ai").disabled = !(on && lastMatch);
$("#dd-aiout").classList.remove("answer");
if (!aiStatus) return;
$("#dd-aiout").textContent = !on ? `AI helper off: ${aiStatus.reason}`
: !lastMatch ? "Run Match to photo first. The AI explains a match and suggests what to check next."
: "Sends a short summary of this match (counts and confidence only: no photo, no file names) and your question to the AI provider. Advice only: it cannot approve or change anything.";
}
$("#dd-ai").addEventListener("click", async () => {
const btn = $("#dd-ai");
btn.disabled = true;
$("#dd-aiout").textContent = "Asking…";
try {
const res = await api("/api/assist", { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ context: lastMatch, question: $("#dd-q").value.trim() }) });
const out = $("#dd-aiout");
out.classList.add("answer");
out.textContent = res.ok ? res.answer : (res.error || "No answer.");
if (res.ok) out.insertAdjacentHTML("beforeend", `
AI advice only · it cannot approve or change anything
`);
} catch (e) { $("#dd-aiout").textContent = e.message || String(e); }
finally { renderAiButton(); }
});
function renderAiButton() { $("#dd-ai").disabled = !(aiStatus && aiStatus.enabled && lastMatch); }
// ------------------------------------------------------------------ overlay style: fill / both / outline
function setOverlayStyle(mode) {
try { localStorage.setItem("pv-overlay", mode); } catch { /* private mode: the choice just is not remembered */ }
$("#stage").dataset.ov = mode;
document.querySelectorAll("[data-ov]").forEach((b) => {
if (b.tagName !== "BUTTON") return;
const on = b.dataset.ov === mode;
b.classList.toggle("on", on);
b.setAttribute("aria-pressed", on ? "true" : "false");
});
}
document.querySelectorAll("button[data-ov]").forEach((b) => b.addEventListener("click", () => setOverlayStyle(b.dataset.ov)));
setOverlayStyle((() => { try { return localStorage.getItem("pv-overlay") || "both"; } catch { return "both"; } })());
// ------------------------------------------------------------------ evidence confidence: the more independent evidence, the higher the score
// The number is an evidence score (evidence.py), not a probability, and the card says so. It is capped while the scale is only an assumption.
const EV_COLOURS = ["#0a84ff", "#34c759", "#af52de", "#ff9f0a", "#64d2ff"];
let evShown = 0, evAnim = 0;
const EV_SUMMARY = { rough: "Not enough to trust the measurements yet.", fair: "Good enough for a rough estimate. Check key sizes by hand.", good: "Measurements are well supported for planning.", high: "Measurements are strongly supported." };
const EV_PART = {
"Scale anchor": { name: "A known size", hint: "Something real in the photo that fixes the scale: a drawing, a door, a tape measure." },
"Wall coverage": { name: "Whole wall in view", hint: "How much of the wall's edges you can see in the photos." },
"Independent views": { name: "Other angles", hint: "Extra photos or video of the same wall." },
"Drawings": { name: "Drawing match", hint: "A plan or elevation that agrees with the photo." },
"Depth plane check": { name: "Depth scan", hint: "A LiDAR or depth capture that confirms the wall is flat." },
};
function countTo(el, target) {
cancelAnimationFrame(evAnim);
const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (reduce) { el.textContent = `${target}%`; evShown = target; return; }
const from = evShown, t0 = performance.now();
const step = (ts) => {
const k = Math.min(1, (ts - t0) / 650), v = Math.round(from + (target - from) * (1 - Math.pow(1 - k, 3)));
el.textContent = `${v}%`;
if (k < 1) evAnim = requestAnimationFrame(step); else evShown = target;
};
evAnim = requestAnimationFrame(step);
}
function renderEvidence(ev) {
const box = $("#evidence");
if (!ev) { box.hidden = true; return; }
box.hidden = false;
box.dataset.level = ev.label.toLowerCase();
$("#ev-label").textContent = ev.label;
$("#ev-sum").textContent = EV_SUMMARY[ev.label.toLowerCase()] || "";
countTo($("#ev-pct"), ev.score);
const bar = $("#ev-bar");
bar.innerHTML = "";
ev.parts.forEach((p, i) => {
const seg = document.createElement("span");
seg.className = "ev-seg"; seg.style.flexGrow = String(p.max); seg.title = `${p.name}: ${p.points} of ${p.max}`;
const fill = document.createElement("i");
fill.style.background = EV_COLOURS[i % EV_COLOURS.length]; fill.style.width = "0%";
seg.appendChild(fill); bar.appendChild(seg);
requestAnimationFrame(() => requestAnimationFrame(() => { fill.style.width = `${Math.round(100 * p.points / p.max)}%`; }));
});
bar.setAttribute("aria-label", `Evidence score ${ev.score} out of 100`);
const errEl = $("#ev-error");
errEl.textContent = "";
const typ = Number(ev.typical_error_pct), hi = Number(ev.high_error_pct);
if (Number.isFinite(typ) && typ > 0) {
const head = document.createElement("strong");
head.textContent = `Sizes could be off by about ${Math.round(typ)}%` + (Number.isFinite(hi) && hi > typ ? ` (worst case ${Math.round(hi)}%)` : "");
const why = document.createElement("span");
why.textContent = ` Why: ${String(ev.expected_error || "").replace(/^\W+/, "").replace(/\.$/, "")}.`;
errEl.append(head, why);
} else errEl.textContent = `Expected size of the error: ${ev.expected_error}.`;
const list = $("#ev-parts");
list.textContent = "";
ev.parts.forEach((p, i) => { // built with DOM calls: the page's CSP forbids inline style attributes
const info = EV_PART[p.name] || { name: p.name, hint: "" };
const frac = p.max ? p.points / p.max : 0, state = frac >= 0.85 ? "full" : frac > 0.05 ? "part" : "none";
const li = document.createElement("li"), dot = document.createElement("i"), txt = document.createElement("div"), name = document.createElement("span"), hint = document.createElement("small");
const pts = document.createElement("b"), meter = document.createElement("div"), fill = document.createElement("i");
li.dataset.state = state; dot.className = "ev-state"; dot.setAttribute("aria-hidden", "true");
dot.textContent = state === "full" ? "✓" : state === "part" ? "◐" : "○";
name.textContent = info.name; hint.textContent = info.hint; txt.className = "ev-txt"; txt.append(name, hint);
pts.textContent = `${Math.round(p.points)} of ${p.max}`; meter.className = "ev-meter"; fill.style.width = `${Math.round(100 * frac)}%`; fill.style.background = EV_COLOURS[i % EV_COLOURS.length];
meter.appendChild(fill); li.title = `${p.name}: ${p.points} of ${p.max} points`;
li.append(dot, txt, pts, meter); list.appendChild(li);
});
const notes = [];
if (ev.conflict) notes.push(`Conflict (−${ev.penalty}): ${esc(ev.conflict)}`);
if (ev.cap) notes.push(`Capped: ${esc(ev.cap)}`);
const bad = (ev.views || []).filter((v) => !v.registered);
if (bad.length) notes.push(`${bad.length} extra view${bad.length === 1 ? "" : "s"} did not register to this wall and ${bad.length === 1 ? "is" : "are"} not counted: ${esc(bad[0].reason || "")}`);
if (ev.depth && ev.depth.warnings && ev.depth.warnings.length) notes.push(esc(ev.depth.warnings[0]));
$("#ev-note").hidden = !notes.length;
$("#ev-note").innerHTML = notes.map((n) => `