File size: 46,427 Bytes
fcb5ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eecd03
 
 
 
 
 
 
 
 
 
 
 
fcb5ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
 
 
 
 
 
 
 
4eecd03
 
 
 
 
 
 
 
fcb5ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eecd03
 
 
fcb5ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
 
 
 
 
4eecd03
fcb5ab9
4eecd03
fcb5ab9
 
 
 
 
 
 
4eecd03
fcb5ab9
 
 
 
4eecd03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
// Operator console front end: no framework, talks to console_server.py.
"use strict";

const $ = (sel) => document.querySelector(sel);
const STATUS = {
  ready_to_paint: ["Ready to paint", "The gate passes. Check the green area, then approve."],
  prep_required: ["Prep first", "Damage must be scraped/treated and primed, then the wall rescanned before the coat."],
  touch_up_only: ["Touch-up only", "The wall is signed off; only small unconfirmed patches remain."],
  complete: ["Complete", "The wall is signed off. Nothing to paint."],
  blocked: ["Blocked", "The safety gate stops this job. Fix or confirm the reasons below."],
  approved: ["Approved", "This work order is frozen and recorded."],
};
const RELEVANT = { not_wallpaper: /wallpaper/i, depth_waived: /depth/i, uncertainty_reviewed: /uncertain|re-observ/i,
                   colour_checked: /colour|ΔE00|tin/i };

let health = null;
let job = null;
let tool = "none";
let dirty = false;
let drawing = false;
const editCanvas = $("#edits");
const ectx = editCanvas.getContext("2d");

// a non-blocking message instead of a modal alert(): errors stay a little longer, and a screen reader hears it (aria-live)
function toast(message, kind = "error") {
  const box = $("#toasts");
  if (!box) { console.warn(message); return; }
  const el = document.createElement("div");
  el.className = `toast ${kind}`;
  el.textContent = String(message);
  box.appendChild(el);
  while (box.children.length > 3) box.firstChild.remove();
  setTimeout(() => { el.classList.add("out"); setTimeout(() => el.remove(), 260); }, kind === "error" ? 6500 : 3200);
}

function esc(s) {
  return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
function sqft(mm2) {
  const ft = mm2 / 92903.04;
  return ft < 0.1 ? "< 0.1 sq ft" : `${fmt(ft, ft < 10 ? 1 : 0)} sq ft`;
}
function fmt(n, digits = 0) {
  return n == null ? "—" : Number(n).toLocaleString(undefined, { maximumFractionDigits: digits });
}
async function api(path, options = {}) {
  const res = await fetch(path, options);
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(body.error || `${res.status} ${res.statusText}`);
  return body;
}
function store(key, value) {
  try { value === undefined ? localStorage.getItem(key) : localStorage.setItem(key, value); } catch (_) { /* private mode */ }
}
function recall(key) {
  try { return localStorage.getItem(key) || ""; } catch (_) { return ""; }
}

// ------------------------------------------------------------------ boot
async function boot() {
  $("#operator").value = recall("pv.operator");
  $("#operator").addEventListener("change", (e) => store("pv.operator", e.target.value.trim()));
  try {
    health = await api("/api/health");
    const m = health.model || {};
    $("#model").textContent = `${m.checkpoint || "model"} · ${m.arch || ""} · ${m.device || ""}`;
    if ((m.warnings || []).length) {
      $("#banner").hidden = false;
      $("#banner").textContent = "Model not fully calibrated: " + m.warnings.join(" · ");
    }
  } catch (err) {
    $("#model").textContent = "console offline: " + err.message;
  }
  renderConfirmations();
  await refreshJobs();
  const id = new URLSearchParams(location.hash.slice(1)).get("job");
  if (id) openJob(id);
}

async function refreshJobs() {
  const jobs = await api("/api/jobs").catch(() => []);
  const list = $("#job-list");
  list.innerHTML = "";
  for (const j of jobs) {
    const li = document.createElement("li");
    const b = document.createElement("button");
    const status = j.approved ? "approved" : j.status;
    b.innerHTML = `<span class="name">${esc(j.wall_id || j.filename || j.id)}</span>
      <span class="small muted">${esc(new Date(j.created).toLocaleString())}</span>
      <span class="pill ${esc(status)}">${esc((STATUS[status] || [status])[0])}</span>`;
    if (job && job.id === j.id) b.classList.add("active");
    b.addEventListener("click", () => openJob(j.id));
    li.appendChild(b);
    list.appendChild(li);
  }
  if (typeof loadEvidence === "function") loadEvidence();      // drawings count as evidence (a generated one does not)
}

// ------------------------------------------------------------------ upload
async function upload(file) {
  if (!file) return;
  const status = $("#upload-status");
  status.textContent = `Analysing ${file.name}… (about 10–20 s on CPU)`;
  try {
    const q = new URLSearchParams({ filename: file.name, wall_id: $("#wall-id").value.trim() });
    const created = await api(`/api/jobs?${q}`, { method: "POST", body: file, headers: { "Content-Type": file.type || "application/octet-stream" } });
    status.textContent = "";
    $("#wall-id").value = "";
    showJob(created);
    refreshJobs();
  } catch (err) {
    status.textContent = "Upload failed: " + err.message;
  }
}
$("#file").addEventListener("change", (e) => upload(e.target.files[0]));
const drop = $("#drop");
["dragenter", "dragover"].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.add("over"); }));
["dragleave", "drop"].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.remove("over"); }));
drop.addEventListener("drop", (e) => upload(e.dataTransfer.files[0]));

// ------------------------------------------------------------------ job view
async function openJob(id) {
  try { showJob(await api(`/api/jobs/${encodeURIComponent(id)}`)); } catch (err) { toast(err.message); }
}

function showJob(j) {
  job = j;
  history.replaceState(null, "", `#job=${j.id}`);
  const v = `?v=${encodeURIComponent(j.updated || j.created)}`;
  $("#empty").hidden = true;
  $("#stage").hidden = false;
  const photo = $("#photo");
  photo.src = `/api/jobs/${j.id}/photo.jpg`;
  for (const name of ["paint", "keepout", "uncertain", "touchup"]) {
    const fill = document.querySelector(`img.layer[data-layer="${name}"]:not(.edge)`);
    fill.src = `/api/jobs/${j.id}/layer_${name}.png${v}`;
    // the outline twin of each fill: a coloured ring with a white halo, readable on any wall colour
    let edge = document.querySelector(`img.layer.edge[data-layer="${name}"]`);
    if (!edge) { edge = document.createElement("img"); edge.className = "layer edge"; edge.alt = ""; edge.dataset.layer = name; fill.after(edge); }
    edge.hidden = false;
    edge.classList.toggle("off", !document.querySelector(`#layer-toggles input[data-layer="${name}"]`).checked);
    edge.src = `/api/jobs/${j.id}/layer_${name}_edge.png${v}`;
  }
  editCanvas.width = j.width;
  editCanvas.height = j.height;
  ectx.clearRect(0, 0, j.width, j.height);
  if (j.has_edits) {
    const img = new Image();
    img.onload = () => ectx.drawImage(img, 0, 0);
    img.src = `/api/jobs/${j.id}/layer_edits.png${v}`;
  }
  setDirty(false);
  renderVector();
  renderPanel();
  applyLayerToggles();
  document.querySelectorAll(".job-list button").forEach((b) => b.classList.remove("active"));
  refreshJobs();
}

function svgEl(name, attrs) {
  const el = document.createElementNS("http://www.w3.org/2000/svg", name);
  for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
  return el;
}
const pts = (poly) => (poly || []).map(([x, y]) => `${x},${y}`).join(" ");

function renderVector() {
  const svg = $("#vector");
  svg.innerHTML = "";
  svg.setAttribute("viewBox", `0 0 ${job.width} ${job.height}`);
  svg.setAttribute("preserveAspectRatio", "none");
  const damage = svgEl("g", { "data-layer": "damage" });
  (job.regions || []).forEach((r, i) => {
    if (r.prep_zone_xy && r.prep_zone_xy.length > 2) damage.appendChild(svgEl("polygon", { points: pts(r.prep_zone_xy), class: "prep-zone" }));
    if (r.outline_xy && r.outline_xy.length > 2) damage.appendChild(svgEl("polygon", { points: pts(r.outline_xy), class: "damage", "data-region": i }));
  });
  svg.appendChild(damage);
  const paths = svgEl("g", { "data-layer": "paths" });
  const lines = (strokes, cls) => (strokes || []).forEach(([[x0, y0], [x1, y1]]) =>
    paths.appendChild(svgEl("line", { x1: x0, y1: y0, x2: x1, y2: y1, class: cls })));
  for (const step of (job.work_order || {}).steps || []) {
    if (step.step === "paint" && step.plan) {
      lines(step.plan.plan.strokes, "roller");
      lines(step.plan.plan.trim.strokes, "trim");
    }
    if (step.step === "prep") step.tasks.forEach((t) => lines(t.strokes_px, "prep-path"));
    if (step.step === "touch_up") step.tasks.forEach((t) => lines(t.strokes_px, "touch-path"));
  }
  svg.appendChild(paths);
}

function renderPanel() {
  const order = job.work_order || {};
  const status = job.approved ? "approved" : order.status;
  const [title, text] = STATUS[status] || [status || "—", ""];
  const decision = $("#decision");
  decision.className = `decision ${status}`;
  decision.innerHTML = `<h3>${esc(title)}</h3><p>${esc(text)}</p>`;

  const reasons = (order.gate || {}).reasons || [];
  const warnings = order.warnings || [];
  $("#reasons").innerHTML = reasons.length || warnings.length
    ? `<ul class="reasons">${reasons.map((r) => `<li class="bad">${esc(r)}</li>`).join("")}${warnings.map((w) => `<li class="warn">${esc(w)}</li>`).join("")}</ul>`
    : "";

  // Confirmations: check the ones already signed; highlight the ones a reason asks for.
  const signed = new Set((order.confirmations || []).map((c) => c.name));
  document.querySelectorAll("#confirmations input").forEach((box) => {
    box.checked = signed.has(box.value);
    const label = box.closest("label");
    label.classList.toggle("relevant", reasons.some((r) => (RELEVANT[box.value] || /$^/).test(r)));
    box.disabled = !!job.approved;
  });

  const s = order.summary || {};
  const scale = order.scale || {};
  const areaFt = s.paint_area_ft2 != null ? `${fmt(s.paint_area_ft2, 1)} sq ft` : `${fmt(s.paint_area_px)} px`;
  const m = (job.measurements || {}).faces || [];
  // What colour is on the wall (and does it match the spec), and what equipment is on site.
  const colour = job.paint_color || {};
  const objects = job.site_objects || {};
  const coat = colour.dominant;
  const spec = colour.reference;
  const coatCell = coat
    ? `<span class="swatch" data-hex="${esc(coat.hex)}"></span> ${esc(coat.name)}
       <span class="muted">${esc(coat.hex)}</span>${spec ? ` · spec
       <b class="${spec.verdict === "match" ? "" : "warn"}">${esc(spec.verdict)}</b>
       <span class="muted">ΔE00 ${fmt(spec.delta_e, 1)}</span>` : ""}`
    : "not reported";
  const seen = (objects.present || []).map((n) => n.replace(/_/g, " "));
  const equipmentCell = objects.status
    ? `${seen.length ? esc(seen.join(", ")) : "none seen"}${(objects.missing_tools || []).length
        ? ` <span class="warn">· missing ${esc(objects.missing_tools.join(", ").replace(/_/g, " "))}</span>` : ""}`
    : "not reported";
  const paintSwatches = () => document.querySelectorAll("#areas .swatch[data-hex]").forEach((el) => { el.style.background = el.dataset.hex; });
  $("#areas").innerHTML = `
    <dt>Paint area</dt><dd>${areaFt}</dd>
    <dt>Coat colour</dt><dd class="small">${coatCell}</dd>
    <dt>Equipment seen</dt><dd class="small">${equipmentCell}</dd>
    <dt>Prep regions</dt><dd>${fmt(s.prep_regions)}</dd>
    <dt>Touch-up patches</dt><dd>${fmt(s.touch_up_patches)}</dd>
    <dt>Wall faces measured</dt><dd>${fmt(m.length)}</dd>
    <dt>Scale</dt><dd class="small">${scale.mm_per_px ? `${fmt(scale.mm_per_px, 2)} mm/px` : "none"}</dd>
    ${scale.source ? `<dd class="small muted full">${esc(scale.source.replace(/_/g, " "))}</dd>` : ""}`;
  paintSwatches();

  const steps = $("#steps");
  steps.innerHTML = "";
  for (const step of order.steps || []) {
    const li = document.createElement("li");
    let inner = `<span class="step-name">${esc(step.step.replace("_", " "))}</span>`;
    if (step.skipped) inner += ` <span class="small muted">— ${esc(step.skipped)}</span>`;
    if (step.provisional) inner += ` <span class="small warn">provisional until rescan</span>`;
    if (step.hold_minutes) inner += ` <span class="small muted">· hold ${fmt(step.hold_minutes)} min</span>`;
    if (step.step === "rescan") inner += `<div class="small muted">${esc(step.reason)}</div>`;
    if (step.plan) {
      const p = step.plan.plan;
      inner += `<div class="small muted">${fmt(p.passes)} roller passes · ${fmt(p.trim.segments)} trim strokes</div>`;
    }
    if (step.step === "setup") {
      // What has to be on site before any paint: tools the plan needs, colour check, clutter.
      inner += "<ul>" + step.tasks.map((t) => `<li class="task"><b>${esc(String(t.task).replace(/-/g, " "))}</b>
        <div class="muted">${esc(t.detail || "")}</div></li>`).join("") + "</ul>";
    } else if (step.step === "spot_prime") {
      // One line per primer: the zones are the prep zones above.
      const groups = {};
      step.tasks.forEach((t) => {
        const g = (groups[t.primer] = groups[t.primer] || { n: 0, mm2: 0, px: 0 });
        g.n += 1; g.mm2 += t.zone_area_mm2 || 0; g.px += t.zone_area_px || 0;
      });
      inner += "<ul>" + Object.entries(groups).map(([primer, g]) => `<li class="task"><b>${esc(primer)}</b>
        <div class="muted">${g.n} zone${g.n > 1 ? "s" : ""} · ${g.mm2 ? sqft(g.mm2) : fmt(g.px) + " px"}</div></li>`).join("") + "</ul>";
    } else if (step.tasks) {
      const card = (t, i) => `<li class="task" data-task="${i}" data-step="${esc(step.step)}">
        <b>${esc(t.type ? t.type.replace("_", " ") : t.task)}</b>
        ${t.method ? `<div>${esc(t.method)}</div>` : ""}
        <div class="muted">${t.zone_area_mm2 || t.area_mm2 ? sqft(t.zone_area_mm2 || t.area_mm2) : fmt(t.zone_area_px ?? t.area_px) + " px"}
        ${t.confidence ? ` · conf ${fmt(t.confidence.mean, 2)}` : ""}</div></li>`;
      // 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 += `<ul>${head}</ul>` + (rest ? `<details class="more"><summary class="small">Show ${ranked.length - 3} more</summary><ul>${rest}</ul></details>` : "");
    }
    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 <b>${esc(job.approved.by)}</b> at ${esc(new Date(job.approved.at).toLocaleString())}<br><span class="muted">registry ${esc(job.approved.registry_hash.slice(0, 16))}…</span>`
    : "";
  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 = `<input type="checkbox" value="${esc(name)}"><span>${esc(meaning)}</span>`;
    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 = `<img src="/api/jobs/${job.id}/drawings/${d.id}.png" alt=""><span><span class="name">${esc(d.filename)}</span><br>
      <span class="small muted">${d.calibration ? "scale set" : "needs scale"} · ${d.measurements.length} measurement(s)</span>
      ${d.generated ? `<span class="badge${d.provenance && d.provenance.scale_assumed ? " warn" : ""}">${d.provenance && d.provenance.scale_assumed ? "draft · assumed height" : "generated · draft"}</span>` : ""}</span>`;
    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) => `<li>${esc(n)}</li>`).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 = `<strong>Draft drawn from a photo.</strong> Scale from ${esc(src)}${p.scale_assumed ? " (assumed: check it)" : ""}. ${esc(p.disclaimer || "")}${notes ? `<ul>${notes}</ul>` : ""}`;
  const base = `/api/jobs/${job.id}/drawings/${item.id}`;
  dl.innerHTML = `<a class="ghost button small" href="${base}.svg" target="_blank" rel="noopener">View sheet</a>`
    + ["svg", "dxf", "json"].map((x) => `<a class="ghost button small" href="${base}.${x}?download=1">${x.toUpperCase()}</a>`).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 `<line x1="${a[0]}" y1="${a[1]}" x2="${b[0]}" y2="${b[1]}" class="${cls}" stroke-width="${3 * k}" stroke-linecap="round" ${cls === "cal" ? `stroke-dasharray="${10 * k} ${7 * k}"` : ""}/>
    <circle cx="${a[0]}" cy="${a[1]}" r="${5 * k}" class="${cls}"/><circle cx="${b[0]}" cy="${b[1]}" r="${5 * k}" class="${cls}"/>
    ${label ? `<text x="${(a[0] + b[0]) / 2}" y="${(a[1] + b[1]) / 2 - 10 * k}" font-size="${15 * k}" font-weight="700" text-anchor="middle" class="lbl" stroke-width="${4 * k}">${esc(label)}</text>` : ""}`;
}
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 += `<circle cx="${dd.pts[0][0]}" cy="${dd.pts[0][1]}" r="${6 * it.width / 900}" class="pend"/>`;
  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 = `<div class="len">${len ? lengthText(len) : "—"}</div><div class="muted small">${esc(m.label || "Line " + (i + 1))}</div>
      <div class="acts">${len ? `<button data-axis="width">Wall width</button><button data-axis="height">Wall height</button>` : ""}<button data-del="1">Delete</button></div>`;
    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(`<strong>No match.</strong> ${esc(m.reason || "")}`);
  else {
    rows.push(`<strong>${esc(m.confidence)} confidence</strong> · ${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 ? " · <strong>applied</strong>" : ""}`);
    if (m.ambiguous) rows.push(`<span class="warn">Several placements fit equally well. Pick the sheet or add a photo that includes a distinguishing feature.</span>`);
    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) => `<div>${r}</div>`).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 = `<span class="warn">${esc(e.message || e)}</span>`;
    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 = `<span class="warn">${esc(e.message || e)}</span>`; }
});
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", `<div class="muted small">AI advice only · it cannot approve or change anything</div>`);
  } 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(`<strong>Conflict (−${ev.penalty}):</strong> ${esc(ev.conflict)}`);
  if (ev.cap) notes.push(`<strong>Capped:</strong> ${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) => `<div>${n}</div>`).join("");
  $("#ev-next").innerHTML = ev.next.length ? `<div class="small muted">Do this next to raise it</div>` + ev.next.map((n, i) =>
    `<button class="ev-idea" data-i="${i}"><b>+${n.gain}</b><span>${esc(n.do)}</span><em>→ ${n.to}%</em></button>`).join("") : `<div class="small muted">Nothing left to add: more evidence would not change this score.</div>`;
  $("#ev-next").querySelectorAll(".ev-idea").forEach((b) => b.addEventListener("click", () => doIdea(ev.next[Number(b.dataset.i)].do)));
  $("#ev-disc").textContent = ev.disclaimer;
}
function doIdea(text) {
  const t = text.toLowerCase();
  if (/depth plane|depth \/ lidar|lidar/.test(t)) $("#ev-depth-file").click();
  else if (/height/.test(t)) $("#ev-height").focus();
  else if (/drawing/.test(t)) $("#dfile").click();
  else $("#ev-view-file").click();
}
async function loadEvidence() {
  if (!job) { renderEvidence(null); return; }
  const id = job.id;
  try { const ev = await api(`/api/jobs/${id}/evidence`); if (job && job.id === id) renderEvidence(ev); } catch { renderEvidence(null); }
}
$("#ev-view-file").addEventListener("change", async (e) => {
  const file = e.target.files[0]; e.target.value = "";
  if (!file || !job) return;
  toast("Checking the new view against this wall…", "ok");
  try {
    const r = await api(`/api/jobs/${job.id}/views?filename=${encodeURIComponent(file.name)}`, { method: "POST", body: await file.arrayBuffer() });
    const bad = r.added.filter((a) => !a.registered);
    toast(`${r.registered} of ${r.tried} registered to this wall` + (bad.length ? `; ${bad.length} did not (${bad[0].reason}).` : "."), r.registered ? "ok" : "warn");
    renderEvidence(r.evidence);
  } catch (err) { toast(err.message); }
});
$("#ev-depth-file").addEventListener("change", async (e) => {
  const file = e.target.files[0]; e.target.value = "";
  if (!file || !job) return;
  const q = new URLSearchParams({ filename: file.name });
  if ($("#ev-fx").value.trim()) q.set("fx", $("#ev-fx").value.trim());
  if ($("#ev-hfov").value.trim()) q.set("hfov_deg", $("#ev-hfov").value.trim());
  try {
    const r = await api(`/api/jobs/${job.id}/depth?${q}`, { method: "POST", body: await file.arrayBuffer() });
    const rep = r.report;
    toast(rep.plane_ok ? `Depth scan used: wall plane agrees (${Math.round(100 * rep.wall_fraction_on_plane)}% of the wall), scale ${rep.mm_per_px} mm/px${rep.intrinsics_source === "assumed" ? " (focal length assumed)" : ""}. Re-plan to use it.`
      : `Depth scan checked but not used: ${(rep.warnings && rep.warnings[0]) || "the wall plane does not agree with the photo"}`, rep.plane_ok ? "ok" : "warn");
    renderEvidence(r.evidence);
    if (rep.plane_ok) setDirty(true);
  } catch (err) { toast(err.message); }
});
$("#ev-height-set").addEventListener("click", async () => {
  const ft = Number($("#ev-height").value);
  if (!job) { toast("Open or create a job first."); return; }
  if (!(ft >= 4 && ft <= 40)) { toast("Enter the wall's real floor-to-ceiling height in feet (4 to 40)."); return; }
  try {
    const r = await api(`/api/jobs/${job.id}/scale`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ length_mm: ft * 304.8, axis: "height", source: "operator" }) });
    toast(`Scale set from your measured height: ${(r.mm_per_px).toFixed(2)} mm/px. Re-plan to use it.`, "ok");
    renderEvidence(r.evidence); setDirty(true);
  } catch (err) { toast(err.message); }
});
// the evidence follows the open job and refreshes after anything that changes it
const _showJobEv = showJob;
showJob = function (j) { _showJobEv(j); loadEvidence(); };
if (job) loadEvidence();