: asapien/signet

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 
856 
857 
858 
859 
860 
861 
862 
863 
864 
865 
866 
867 
868 
869 
870 
871 
872 
873 
874 
875 
876 
877 
878 
879 
880 
881 
882 
883 
884 
885 
886 
887 
888 
889 
890 
891 
892 
893 
894 
895 
896 
897 
898 
899 
900 
901 
902 
903 
904 
905 
906 
907 
908 
909 
910 
911 
912 
913 
914 
915 
916 
917 
918 
919 
920 
921 
922 
923 
924 
925 
926 
927 
928 
929 
930 
931 
932 
933 
934 
935 
936 
937 
938 
939 
940 
941 
942 
943 
944 
/*
 * Signet client.  The layout state lives in the DOM: every imprint is an
 * <area> inside the page's <map>; data-coords holds its coordinates in the
 * page image's natural pixels and `coords` is kept scaled to the displayed
 * size.  Edit and preview mode share everything except what the overlay
 * boxes do: in edit mode they are the draggable layers, in preview mode they
 * are translucent markers above the server-flattened copy.
 */
'use strict';

const API = '/api';
const LOCAL_DEV = ['localhost', '127.0.0.1'].includes(location.hostname);
const REF_WIDTH = 1000;            // natural width every page is rasterised to
const TYPES = {
  pim_text:       { label: 'PIM text',  w: 260, h: 28 },
  pim_image:      { label: 'PIM image', w: 160, h: 160 },
  date:           { label: 'Date',      w: 140, h: 28 },
  serial:         { label: 'Serial no.', w: 280, h: 28 },
  signature_zone: { label: 'Signature zone', w: 200, h: 80 },
};
const TEXT_TYPES = ['pim_text', 'date', 'serial'];
const PIM_TYPES = ['pim_text', 'pim_image'];

const app = { me: null, pim: {}, dam: { images: [], fonts: [] }, series: [], templates: [] };
let doc = null;                    // document currently open
let selected = null;               // selected <area>
let pollTimer = null;
let objectUrls = [];

pdfjsLib.GlobalWorkerOptions.workerSrc = 'vendor/pdf.worker.min.js';

/* ---------- helpers ---------- */

function h(tag, attrs, ...kids) {
  const el = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs || {})) {
    if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
    else if (k === 'class') el.className = v;
    else if (k === 'dataset') Object.assign(el.dataset, v);
    else if (v === true) el.setAttribute(k, '');
    else if (v !== false && v != null) el.setAttribute(k, v);
  }
  el.append(...kids.flat().filter((k) => k != null && k !== false));
  return el;
}

function toast(msg, isError) {
  const t = document.querySelector('.toast');
  t.textContent = msg;
  t.className = isError ? 'toast error' : 'toast';
  t.hidden = false;
  clearTimeout(toast.timer);
  toast.timer = setTimeout(() => { t.hidden = true; }, isError ? 7000 : 3000);
}

/* Local development without the auth proxy: identity headers come from
 * localStorage. The deployment's trusted proxy overwrites these upstream. */
function devHeaders() {
  if (!LOCAL_DEV) return {};
  try {
    const dev = JSON.parse(localStorage.getItem('signetDevIdentity') || 'null');
    return dev ? { 'Remote-User': dev.user, 'Remote-Groups': dev.groups } : {};
  } catch { return {}; }
}

async function api(path, { method = 'GET', fields, raw } = {}) {
  const headers = { ...devHeaders() };
  let body;
  if (method === 'POST') {
    headers['X-Requested-With'] = 'signet';
    body = new FormData();
    for (const [k, v] of Object.entries(fields || {})) body.append(k, v);
  }
  const res = await fetch(API + path, { method, headers, body });
  if (raw) {
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return res.arrayBuffer();
  }
  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    const err = new Error(data.error || res.statusText);
    err.status = res.status;
    throw err;
  }
  return data;
}

async function uploadPdf(file, progress) {
  const chunkSize = 256 * 1024;
  if (file.size < 6 || file.size > 32 * 1024 * 1024) throw new Error('Choose a PDF up to 32 MiB');
  let id;
  try {
    let result = await api('/docs', { method: 'POST', fields: { total_size: file.size, file: file.slice(0, chunkSize) } });
    id = result.id;
    let offset = result.upload_offset;
    if (!id || offset !== Math.min(chunkSize, file.size) || result.upload_total !== file.size) throw new Error('Invalid upload response');
    progress(offset, file.size);
    while (offset < file.size) {
      const fields = { offset, file: file.slice(offset, offset + chunkSize) };
      try { result = await api(`/docs/${id}/upload`, { method: 'POST', fields }); }
      catch (e) {
        if (e.status && e.status < 500) throw e;
        // Exact chunk retries cannot duplicate or replace acknowledged bytes.
        result = await api(`/docs/${id}/upload`, { method: 'POST', fields });
      }
      if (result.upload_offset !== Math.min(offset + chunkSize, file.size) || result.upload_total !== file.size) throw new Error('Invalid upload progress');
      offset = result.upload_offset;
      progress(offset, file.size);
    }
    return { id };
  } catch (e) { e.docId = id; throw e; }
}

const fmtTime = (s) => (s ? new Date(s).toLocaleString() : '');

/* strftime subset shared with the server's date imprints and series patterns */
function strftime(fmt, d) {
  const p2 = (n) => String(n).padStart(2, '0');
  const mon = d.toLocaleString('en', { month: 'long' });
  const day = d.toLocaleString('en', { weekday: 'long' });
  const map = {
    Y: d.getFullYear(), y: p2(d.getFullYear() % 100), m: p2(d.getMonth() + 1),
    d: p2(d.getDate()), e: String(d.getDate()).padStart(2, ' '), B: mon, b: mon.slice(0, 3),
    A: day, a: day.slice(0, 3), H: p2(d.getHours()), M: p2(d.getMinutes()), '%': '%',
  };
  return fmt.replace(/%([a-zA-Z%])/g, (m, c) => (c in map ? map[c] : m));
}

function expandSeries(pattern, date, seq) {
  return pattern.replace(/\{date(?::([^}]*))?\}/g, (m, f) => strftime(f || '%Y%m%d', date))
    .replace(/\{seq(?::(\d+))?\}/g, (m, w) => (seq == null ? '#'.repeat(+w || 1) : String(seq).padStart(+w || 1, '0')));
}

/* ---------- fonts (DAM assets, same files the worker embeds) ---------- */

const fontFamilies = new Map();
function fontFamily(path) {
  path = path || app.dam.default_font;
  if (!path) return 'Helvetica, Arial, sans-serif';
  if (!fontFamilies.has(path)) {
    const family = 'dam-' + path.replace(/[^A-Za-z0-9]/g, '_');
    const url = '/dam/' + path.split('/').map(encodeURIComponent).join('/');
    const face = new FontFace(family, `url("${url}")`);
    face.load().then((f) => { document.fonts.add(f); refitAll(); }).catch(() => {});
    fontFamilies.set(path, family);
  }
  return `"${fontFamilies.get(path)}", Helvetica, Arial, sans-serif`;
}

/* ---------- geometry: <area> <-> bounding box ---------- */

const getCoords = (area) => area.dataset.coords.split(',').map(Number);

function bboxOf(area) {
  const c = getCoords(area);
  if (area.shape === 'circle') return [c[0] - c[2], c[1] - c[2], c[0] + c[2], c[1] + c[2]];
  if (area.shape === 'poly') {
    const xs = c.filter((_, i) => i % 2 === 0), ys = c.filter((_, i) => i % 2 === 1);
    return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
  }
  return [Math.min(c[0], c[2]), Math.min(c[1], c[3]), Math.max(c[0], c[2]), Math.max(c[1], c[3])];
}

function setBbox(area, [x1, y1, x2, y2]) {
  let c;
  if (area.shape === 'circle') {
    const r = Math.min(x2 - x1, y2 - y1) / 2;
    c = [x1 + r, y1 + r, r];
  } else if (area.shape === 'poly') {
    const [ox1, oy1, ox2, oy2] = bboxOf(area);
    const sx = (x2 - x1) / (ox2 - ox1 || 1), sy = (y2 - y1) / (oy2 - oy1 || 1);
    c = getCoords(area).map((v, i) => (i % 2 ? y1 + (v - oy1) * sy : x1 + (v - ox1) * sx));
  } else c = [x1, y1, x2, y2];
  area.dataset.coords = c.map((v) => Math.round(v * 100) / 100).join(',');
  scaleArea(area);
}

/* what imageMapResizer does, without the dependency */
function scaleArea(area) {
  const img = area.closest('.page').querySelector('img');
  const k = img.clientWidth / img.naturalWidth || 1;
  area.coords = getCoords(area).map((v) => Math.round(v * k)).join(',');
}

const resizeWatch = new ResizeObserver((entries) => {
  for (const e of entries) {
    const page = e.target.closest('.page');
    page.querySelectorAll('area').forEach(scaleArea);
    syncOverlay(page);
  }
});

/* ---------- imprint values (edit-mode rendering) ---------- */

function imprintText(area) {
  const d = area.dataset, prefix = d.prefix || '';
  if (d.type === 'pim_text') {
    const org = doc.org_code;
    const key = d.ref;
    const v = org && app.pim[org] && app.pim[org].text && app.pim[org].text[key];
    return v == null ? null : prefix + v;
  }
  if (d.type === 'date') {
    const date = doc.doc_date ? new Date(doc.doc_date + 'T00:00:00') : new Date();
    return prefix + strftime(d.format || app.dam.date_format || '%d-%m-%Y', date);
  }
  if (d.type === 'serial') {
    if (doc.serial) return prefix + doc.serial;
    const s = app.series.find((x) => x.code === currentSeries());
    return s ? prefix + expandSeries(s.pattern, new Date(), null) : null;
  }
  return null;
}

/* Mirror of draw_text() in src/render.c: 70% of box height, shrink to fit. */
const measure = document.createElement('canvas').getContext('2d');
function fitText(box, area, text) {
  const hpx = box.clientHeight, wpx = box.clientWidth;
  const family = fontFamily(area.dataset.font);
  let size = hpx * 0.7;
  measure.font = `${size}px ${family}`;
  const tw = measure.measureText(text).width;
  if (tw > wpx && tw > 0) size *= wpx / tw;
  Object.assign(box.style, {
    fontFamily: family, fontSize: size + 'px', lineHeight: hpx + 'px',
    textAlign: area.dataset.align || 'left',
  });
}

function refitAll() {
  document.querySelectorAll('.page').forEach(syncOverlay);
}

/* ---------- overlay: boxes generated from the <area>s ---------- */

function describe(area) {
  const d = area.dataset;
  return `${TYPES[d.type].label}${d.ref ? ': ' + d.ref : ''}`;
}

function syncOverlay(page) {
  const img = page.querySelector('img'), overlay = page.querySelector('.overlay');
  const editing = !!doc && doc.mode === 'edit';
  overlay.replaceChildren();
  page.querySelectorAll('area').forEach((area) => {
    const [x1, y1, x2, y2] = bboxOf(area);
    const box = h('div', { class: `box t-${area.dataset.type}${area.shape === 'circle' ? ' circle' : ''}` });
    Object.assign(box.style, {
      left: (x1 / img.naturalWidth) * 100 + '%', top: (y1 / img.naturalHeight) * 100 + '%',
      width: ((x2 - x1) / img.naturalWidth) * 100 + '%', height: ((y2 - y1) / img.naturalHeight) * 100 + '%',
    });
    area.title = describe(area);
    overlay.append(box);
    if (area.dataset.placement) {
      box.classList.add('placement');
      if (area === selected) box.classList.add('selected');
      box.tabIndex = 0;
      box.setAttribute('aria-label', 'Signature placement: arrow keys move, Shift and arrows resize');
      box.append(h('span', { class: 'grip' }));
      box.addEventListener('pointerdown', (e) => startDrag(e, area, box, page));
      box.addEventListener('keydown', (e) => {
        if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;
        e.preventDefault();
        const b = bboxOf(area), dx = e.key === 'ArrowLeft' ? -5 : e.key === 'ArrowRight' ? 5 : 0;
        const dy = e.key === 'ArrowUp' ? -5 : e.key === 'ArrowDown' ? 5 : 0;
        constrainPlacement(area, e.shiftKey ? [b[0], b[1], b[2] + dx + dy, b[3]] : b.map((v, i) => v + (i % 2 ? dy : dx)), e.shiftKey);
        syncOverlay(page);
        page.querySelector('.placement').focus();
      });
      return;
    }
    if (!editing) return;

    /* edit mode: the box is the layer itself */
    const type = area.dataset.type;
    if (TEXT_TYPES.includes(type)) {
      const text = imprintText(area);
      if (text == null) box.append(h('span', { class: 'ph' }, 'choose a value'));
      else { box.textContent = text; fitText(box, area, text); }
    } else if (type === 'pim_image' && area.dataset.ref) {
      const org = doc.org_code;
      const key = area.dataset.ref;
      const path = org && app.pim[org] && app.pim[org].images && app.pim[org].images[key];
      if (path) {
        box.append(h('img', { src: '/dam/' + path.split('/').map(encodeURIComponent).join('/'), alt: '' }));
      } else {
        box.append(h('span', { class: 'ph' }, '[PIM image not found]'));
      }
    } else if (type === 'signature_zone') {
      box.append(h('span', { class: 'ph' }, 'Signature zone: ' + (area.dataset.party || '(choose party)')));
    } else {
      box.append(h('span', { class: 'ph' }, 'choose an image'));
    }
    if (area === selected) box.classList.add('selected');
    box.append(h('span', { class: 'grip' }));
    box.addEventListener('pointerdown', (e) => startDrag(e, area, box, page));
  });
}

function signingFacsimile() {
  const key = document.getElementById('signing-facsimile')?.value;
  return app.me.facsimiles.find((f) => f.id === key) || app.me.facsimile;
}

function constrainPlacement(area, bounds, resizing) {
  const zone = [...area.closest('.page').querySelectorAll('area:not([data-placement])')].find((a) => a.dataset.type === 'signature_zone' && a.dataset.party === area.dataset.party);
  const facsimile = signingFacsimile();
  const z = bboxOf(zone), ratio = facsimile.width / facsimile.height;
  let [x, y, x2, y2] = bounds, w = x2 - x, height = y2 - y;
  if (resizing) {
    w = Math.min(z[2] - x, (z[3] - y) * ratio, Math.max(+zone.dataset.min_w, +zone.dataset.min_h * ratio, w));
    height = w / ratio;
  }
  x = Math.max(z[0], Math.min(z[2] - w, x));
  y = Math.max(z[1], Math.min(z[3] - height, y));
  setBbox(area, [x, y, x + w, y + height]);
}

function setupPlacement() {
  const party = doc.route.parties[doc.current_party - 1];
  const zone = [...document.querySelectorAll('area[data-type="signature_zone"]')].find((a) => a.dataset.party === party.name);
  if (!zone) return;
  document.querySelectorAll('area[data-placement]').forEach((area) => area.remove());
  document.getElementById('placement-fit-error')?.remove();
  selected = null;
  const page = zone.closest('.page'), z = bboxOf(zone);
  const facsimile = signingFacsimile();
  const ratio = facsimile.width / facsimile.height;
  let w = z[2] - z[0], height = w / ratio;
  if (height > z[3] - z[1]) { height = z[3] - z[1]; w = height * ratio; }
  const x = z[0] + (z[2] - z[0] - w) / 2, y = z[1] + (z[3] - z[1] - height) / 2;
  addArea(page, { type: 'signature_zone', party: party.name, placement: true, coords: [x, y, x + w, y + height] });
  if (w < +zone.dataset.min_w || height < +zone.dataset.min_h) {
    document.querySelector('.side').append(h('p', { id: 'placement-fit-error', class: 'notice error' }, 'This facsimile cannot fit the zone at its minimum size. Choose another signature or request a correction to enlarge the zone.'));
  }
  syncOverlay(page);
}

function startDrag(e, area, box, page) {
  e.preventDefault();
  select(area);
  const img = page.querySelector('img');
  const k = img.naturalWidth / img.clientWidth;
  const resizing = e.target.classList.contains('grip');
  const start = bboxOf(area), sx = e.clientX, sy = e.clientY;
  const W = img.naturalWidth, H = img.naturalHeight;
  const live = page.querySelector('.box.selected') || box;

  const move = (ev) => {
    const dx = (ev.clientX - sx) * k, dy = (ev.clientY - sy) * k;
    let [x1, y1, x2, y2] = start;
    if (resizing) {
      x2 = Math.min(W, Math.max(x1 + 12, x2 + dx));
      y2 = Math.min(H, Math.max(y1 + 12, y2 + dy));
      if (area.shape === 'circle') { const s = Math.min(x2 - x1, y2 - y1); x2 = x1 + s; y2 = y1 + s; }
    } else {
      const w = x2 - x1, hh = y2 - y1;
      x1 = Math.min(W - w, Math.max(0, x1 + dx)); y1 = Math.min(H - hh, Math.max(0, y1 + dy));
      x2 = x1 + w; y2 = y1 + hh;
    }
    if (area.dataset.placement) {
      if (resizing) {
        const facsimile = signingFacsimile();
        const ratio = facsimile.width / facsimile.height;
        x2 = x1 + start[2] - start[0] + (Math.abs(dx) >= Math.abs(dy * ratio) ? dx : dy * ratio);
      }
      constrainPlacement(area, [x1, y1, x2, y2], resizing);
      [x1, y1, x2, y2] = bboxOf(area);
    } else setBbox(area, [x1, y1, x2, y2]);
    Object.assign(live.style, {
      left: (x1 / W) * 100 + '%', top: (y1 / H) * 100 + '%',
      width: ((x2 - x1) / W) * 100 + '%', height: ((y2 - y1) / H) * 100 + '%',
    });
  };
  const up = () => {
    window.removeEventListener('pointermove', move);
    window.removeEventListener('pointerup', up);
    window.removeEventListener('pointercancel', up);
    syncOverlay(page);
    renderProps();
  };
  window.addEventListener('pointermove', move);
  window.addEventListener('pointerup', up);
  window.addEventListener('pointercancel', up);
}

function select(area) {
  if (selected === area) return;
  selected = area;
  refitAll();
  renderProps();
}

function addArea(page, imp) {
  const map = page.querySelector('map');
  const area = h('area', { shape: imp.shape || 'rect', href: '#', coords: '0,0,0,0' });
  area.addEventListener('click', (e) => e.preventDefault());
  const d = area.dataset;
  d.type = imp.type;
  d.coords = imp.coords.join(',');
  for (const k of ['ref', 'font', 'prefix', 'format', 'align', 'party', 'min_w', 'min_h', 'placement']) if (imp[k]) d[k] = imp[k];
  map.append(area);
  scaleArea(area);
  return area;
}

/* ---------- layout JSON <-> DOM ---------- */

function loadLayout(layout) {
  for (const imp of (layout && layout.imprints) || []) {
    const page = document.querySelector(`.page[data-page="${imp.page || 1}"]`);
    if (!page || !TYPES[imp.type]) continue;
    const img = page.querySelector('img');
    const k = img.naturalWidth / (imp.ref_w || layout.reference_width || img.naturalWidth);
    const ky = img.naturalHeight / (imp.ref_h || layout.reference_height || img.naturalHeight);
    addArea(page, { ...imp, min_w: imp.min_w * k, min_h: imp.min_h * ky,
      coords: imp.coords.map((v, i) => v * (imp.shape === 'circle' || i % 2 === 0 ? k : ky)) });
  }
  refitAll();
}

function collectLayout() {
  const first = document.querySelector('.page img');
  const imprints = [...document.querySelectorAll('.page area:not([data-placement])')].map((area) => {
    const img = area.closest('.page').querySelector('img'), d = area.dataset;
    const imp = {
      page: +area.closest('.page').dataset.page, shape: area.shape || 'rect', type: d.type,
      ref: d.ref || '', coords: getCoords(area), ref_w: img.naturalWidth, ref_h: img.naturalHeight,
    };
    for (const k of ['font', 'prefix', 'format', 'align', 'party']) if (d[k]) imp[k] = d[k];
    for (const k of ['min_w', 'min_h']) if (d[k]) imp[k] = +d[k];
    return imp;
  });
  return { reference_width: first.naturalWidth, reference_height: first.naturalHeight, imprints };
}

/* ---------- PDF -> <img> + <map> + overlay per page ---------- */

async function renderPdf(container, data) {
  objectUrls.forEach(URL.revokeObjectURL);
  objectUrls = [];
  container.replaceChildren();
  const pdf = await pdfjsLib.getDocument({ data, isEvalSupported: false }).promise;
  for (let n = 1; n <= pdf.numPages; n++) {
    const pg = await pdf.getPage(n);
    const vp = pg.getViewport({ scale: REF_WIDTH / pg.getViewport({ scale: 1 }).width });
    const canvas = h('canvas', { width: Math.round(vp.width), height: Math.round(vp.height) });
    await pg.render({ canvasContext: canvas.getContext('2d'), viewport: vp }).promise;
    const blob = await new Promise((ok) => canvas.toBlob(ok, 'image/png'));
    const url = URL.createObjectURL(blob);
    objectUrls.push(url);
    canvas.width = canvas.height = 0;
    const img = h('img', { usemap: '#map-' + n, alt: 'Page ' + n, draggable: 'false' });
    const page = h('section', { class: 'page', dataset: { page: n } },
      img, h('map', { name: 'map-' + n }), h('div', { class: 'overlay' }), h('span', { class: 'pageno' }, String(n)));
    container.append(page);
    img.src = url;
    await img.decode();
    resizeWatch.observe(img);
    if (doc.mode === 'edit') enableDrop(page);
  }
  pdf.destroy();
}

function enableDrop(page) {
  page.addEventListener('dragover', (e) => { e.preventDefault(); page.classList.add('dragover'); });
  page.addEventListener('dragleave', () => page.classList.remove('dragover'));
  page.addEventListener('drop', (e) => {
    e.preventDefault();
    page.classList.remove('dragover');
    const type = e.dataTransfer.getData('text/x-signet-type');
    if (!TYPES[type]) return;
    const img = page.querySelector('img'), r = img.getBoundingClientRect();
    const k = img.naturalWidth / r.width;
    placeNew(page, type, (e.clientX - r.left) * k, (e.clientY - r.top) * k);
  });
  page.querySelector('.overlay').addEventListener('pointerdown', (e) => {
    if (e.target.classList.contains('overlay')) select(null);
  });
}

function placeNew(page, type, cx, cy) {
  const img = page.querySelector('img'), t = TYPES[type];
  const x1 = Math.max(0, Math.min(img.naturalWidth - t.w, cx - t.w / 2));
  const y1 = Math.max(0, Math.min(img.naturalHeight - t.h, cy - t.h / 2));
  const imp = { type, coords: [x1, y1, x1 + t.w, y1 + t.h] };
  if (type === 'signature_zone') Object.assign(imp, { party: collectRoute().parties[0]?.name || '', min_w: 50, min_h: 30 });
  select(addArea(page, imp));
}

/* ---------- side panel pieces ---------- */

const currentSeries = () => {
  const el = document.getElementById('f-series');
  return el ? el.value : doc && doc.series_code;
};

function field(label, control) { return [h('label', {}, label), control]; }

function selectEl(options, value, onchange, attrs) {
  const el = h('select', { ...attrs, onchange: (e) => onchange(e.target.value) },
    options.map(([v, text]) => h('option', { value: v }, text)));
  el.value = value || '';
  return el;
}

function renderProps() {
  const host = document.getElementById('props');
  if (!host) return;
  host.replaceChildren();
  if (!selected) { host.append(h('p', { class: 'empty' }, 'Drag an item onto a page, or select a box to edit it.')); return; }
  const d = selected.dataset, type = d.type;
  const set = (k) => (v) => { if (v) d[k] = v; else delete d[k]; refitAll(); };
  host.append(h('strong', {}, TYPES[type].label));

  if (type === 'pim_text') {
    const org = doc.org_code;
    const keys = org && app.pim[org] && app.pim[org].text ? Object.entries(app.pim[org].text) : [];
    if (!org) {
      host.append(h('p', { class: 'empty' }, 'Choose an organisation first'));
    } else {
      host.append(...field('PIM text key', selectEl([['', '(choose)'], ...keys.map(([k, v]) => [k, `${k} = ${v}`])], d.ref, set('ref'))));
    }
  }
  if (type === 'pim_image') {
    const org = doc.org_code;
    const keys = org && app.pim[org] && app.pim[org].images ? Object.entries(app.pim[org].images) : [];
    if (!org) {
      host.append(h('p', { class: 'empty' }, 'Choose an organisation first'));
    } else {
      host.append(...field('PIM image key', selectEl([['', '(choose)'], ...keys.map(([k, p]) => [k, `${k} → ${p}`])], d.ref, set('ref'))));
    }
    host.append(...field('Shape', selectEl([['rect', 'Rectangle'], ['circle', 'Circle']], selected.shape || 'rect', (v) => {
      const b = bboxOf(selected); selected.shape = v; setBbox(selected, b); refitAll();
    })));
  }
  if (type === 'signature_zone') {
    const parties = collectRoute().parties || [];
    host.append(...field('Party', selectEl([['', '(choose)'], ...parties.map((p) => [p.name, p.name])], d.party, set('party'))));
    host.append(...field('Min width (px)', h('input', { type: 'number', value: d.min_w || '', oninput: (e) => set('min_w')(e.target.value) })));
    host.append(...field('Min height (px)', h('input', { type: 'number', value: d.min_h || '', oninput: (e) => set('min_h')(e.target.value) })));
  }
  if (type === 'date') {
    host.append(...field('Format (strftime)', h('input', { value: d.format || '', placeholder: app.dam.date_format || '%d-%m-%Y', oninput: (e) => set('format')(e.target.value) })));
  }
  if (TEXT_TYPES.includes(type)) {
    host.append(...field('Prefix', h('input', { value: d.prefix || '', placeholder: type === 'pim_text' ? 'e.g. GSTIN: ' : '', oninput: (e) => set('prefix')(e.target.value) })));
    host.append(...field('Font', selectEl([['', `Default (${app.dam.default_font || 'Helvetica'})`], ...app.dam.fonts.map((p) => [p, p])], d.font, set('font'))));
    host.append(...field('Align', selectEl([['', 'Left'], ['center', 'Center'], ['right', 'Right']], d.align, set('align'))));
  }
  host.append(h('p', { class: 'mono' }, `page ${selected.closest('.page').dataset.page} · ${selected.shape || 'rect'} · ${d.coords}`));
  host.append(h('button', { class: 'danger', onclick: () => { const p = selected.closest('.page'); selected.remove(); selected = null; syncOverlay(p); renderProps(); } }, 'Remove imprint'));
}

function routeEditor(route, editable) {
  const host = h('div', { id: 'route' });
  const addParty = (p) => {
    const row = h('div', { class: 'party' },
      h('label', {}, 'Party name'),
      h('input', { class: 'p-name', value: p.name || '', placeholder: 'e.g., Manager', onchange: renderProps }),
      h('label', {}, 'Signer username'),
      h('input', { class: 'p-signer', value: p.signer || '', placeholder: 'e.g., manager', onchange: renderProps }),
      h('button', { class: 'danger', onclick: () => { row.remove(); renderProps(); } }, 'Remove'));
    host.insertBefore(row, host.lastChild);
  };
  if (editable) {
    host.append(h('button', { onclick: () => addParty({}) }, 'Add party'));
    (route.parties || []).forEach(addParty);
  } else {
    (route.parties || []).forEach((p, i) => host.append(h('div', {
      class: 'party' + (doc.current_party === i + 1 && ['PENDING'].includes(doc.status) ? ' current' : ''),
    }, h('div', { class: 'who' }, h('strong', {}, `${i + 1}. ${p.name}: `), p.signer || '(unassigned)'))));
  }
  return host;
}

function collectRoute() {
  const host = document.getElementById('route');
  if (!host || !host.querySelector('.p-name')) return (doc && doc.route) || { parties: [] };
  return {
    parties: [...host.querySelectorAll('.party')].map((row) => ({
      name: row.querySelector('.p-name').value.trim(),
      signer: row.querySelector('.p-signer').value.trim() || '',
    })).filter((p) => p.name.length),
  };
}

function historyList() {
  if (!doc.events?.length) return [];
  return [h('h2', {}, 'Event log'), h('ul', { class: 'history' }, doc.events.map((x) =>
    h('li', {}, h('strong', {}, x.actor), ' · ' + x.action.replace(/_/g, ' '),
      h('span', { class: 'c' }, fmtTime(x.at) + (x.detail ? ' · ' + x.detail : '')))))];
}

/* ---------- document view ---------- */

async function saveDoc() {
  await api(`/docs/${doc.id}/save`, {
    method: 'POST',
    fields: {
      json: JSON.stringify({
        title: document.getElementById('f-title').value,
        org_code: document.getElementById('f-org').value || '',
        series_code: currentSeries() || '',
        layout: collectLayout(), route: collectRoute(),
      }),
    },
  });
}

async function act(fn, okMsg, reload = true) {
  try {
    await fn();
    if (okMsg) toast(okMsg);
    if (reload) await showDoc(doc.id);
  } catch (e) { toast(e.message, true); }
}

async function showDoc(id) {
  clearTimeout(pollTimer);
  selected = null;
  const view = document.getElementById('view');
  try { doc = await api('/docs/' + id); } catch (e) {
    view.replaceChildren(h('p', { class: 'notice error' }, e.message));
    return;
  }
  if (doc.uploading) {
    const remove = doc.drafter_user === app.me.user && app.me.roles.drafter ? h('button', { class: 'danger', onclick: () => act(async () => {
      await api(`/docs/${id}/delete`, { method: 'POST' }); location.hash = '#/';
    }, 'Incomplete draft deleted', false) }, 'Delete incomplete draft') : null;
    view.replaceChildren(h('div', { class: 'card' }, h('h1', {}, 'Upload incomplete'),
      h('p', {}, 'This draft cannot be edited or submitted until its PDF upload is complete. Delete the incomplete draft and upload the PDF again.'), remove));
    return;
  }
  if (doc.can_decide) app.me = await api('/me');
  doc.mode = doc.can_edit ? 'edit' : 'preview';
  const pending = ['PENDING'].includes(doc.status);
  const rendering = pending && doc.rendering && !doc.render_error;

  /* which flattened copy is the base image */
  let kind = 'source';
  if (doc.mode === 'preview') {
    if (doc.status === 'RELEASED') kind = 'final';
    else if (pending && doc.can_see_stamped) kind = 'stamped';
    else kind = 'proof';
  }

  const pages = h('div', { class: 'pages' });
  const side = h('aside', { class: 'side card' });
  const notices = h('div');
  view.replaceChildren(
    notices,
    h('div', { class: 'workspace ' + doc.mode }, pages, side));

  if (doc.status === 'CORRECTION_REQUIRED') {
    const last = [...doc.decisions].reverse().find((x) => x.decision === 'CORRECTION');
    notices.append(h('p', { class: 'notice' }, `Correction requested by ${last ? last.signer : 'a checker'}: “${last ? last.comment : ''}”`));
  }
  if (doc.render_error) {
    notices.append(h('p', { class: 'notice error' }, 'Rendering failed: ' + doc.render_error));
  }
  if (doc.can_retry) {
    notices.append(h('button', { onclick: () => act(() => api(`/docs/${id}/rerender`, { method: 'POST' }), 'Queued again') }, 'Retry rendering'));
  }
  if (rendering) {
    notices.append(h('p', { class: 'notice' }, 'Rendering in progress…'));
    pollTimer = setTimeout(() => showDoc(id), 1200);
    kind = 'source';
  }
  if (doc.render_error && doc.mode === 'preview') kind = 'source';

  /* side panel */
  if (doc.mode === 'edit') {
    const orgs = Object.keys(app.pim || {}).sort();
    side.append(
      ...field('Title (required)', h('input', { id: 'f-title', value: doc.title, maxlength: 200, required: true, oninput: (e) => { document.getElementById('submit-doc').disabled = !e.target.value.trim(); } })),
      h('p', { style: 'margin: 0.5rem 0; font-size: 12px' }, h('span', { class: 'status ' + doc.status }, doc.status.replace(/_/g, ' '))),
      ...field('Organisation (required)', selectEl([['', '(choose)'], ...orgs.map((org) => [org, org])], doc.org_code, (value) => { doc.org_code = value; refitAll(); renderProps(); }, { id: 'f-org' })),
      ...field('Series', selectEl([['', '(none)'], ...app.series.map((s) => [s.code, `${s.code}  ·  ${s.pattern}`])], doc.series_code, refitAll, { id: 'f-series', disabled: !!doc.serial })),
      doc.serial ? h('p', { class: 'mono' }, doc.serial) : null,
      h('h2', {}, 'Imprints'),
      h('div', { class: 'palette' }, Object.entries(TYPES).map(([type, t]) => h('div', {
        class: 'chip t-' + type, draggable: 'true', title: 'Drag onto a page',
        ondragstart: (e) => e.dataTransfer.setData('text/x-signet-type', type),
        ondblclick: () => { const p = document.querySelector('.page'); const i = p.querySelector('img'); placeNew(p, type, i.naturalWidth / 2, i.naturalHeight / 2); },
      }, t.label))),
      h('div', { id: 'props' }),
      h('h2', {}, 'Signing route'), routeEditor(doc.route, true),
      h('div', { class: 'actions' },
        h('button', { onclick: () => act(saveDoc, 'Saved', false) }, 'Save draft'),
        h('button', { id: 'submit-doc', class: 'primary', disabled: !doc.title.trim(), onclick: () => act(async () => { await saveDoc(); await api(`/docs/${id}/submit`, { method: 'POST' }); }, 'Submitted') }, doc.status === 'CORRECTION_REQUIRED' ? 'Resubmit' : 'Submit'),
        h('button', { onclick: () => { const name = prompt('Template name'); if (name) act(async () => { await saveDoc(); await api('/templates', { method: 'POST', fields: { doc_id: id, name } }); app.templates = await api('/templates'); }, 'Template saved', false); } }, 'Save as template'),
        doc.status === 'DRAFT' && !doc.serial ? h('button', { class: 'danger', onclick: () => { if (confirm('Delete this draft?')) act(async () => { await api(`/docs/${id}/delete`, { method: 'POST' }); location.hash = '#/'; }, 'Deleted', false); } }, 'Delete draft') : null));
  } else {
    side.append(
      h('div', { class: 'legend' }, h('span', {}, h('i', { style: '--c: var(--sig)' }), 'Signature'), h('span', {}, h('i', { style: '--c: var(--img)' }), 'Seal / image'), h('span', {}, h('i', { style: '--c: var(--txt)' }), 'Text')),
      h('label', { class: 'row' }, h('input', { type: 'checkbox', checked: true, style: 'flex:0;width:auto', onchange: (e) => document.querySelector('.workspace').classList.toggle('hide-overlays', !e.target.checked) }), 'Show imprint overlays'),
      h('h2', {}, 'Document'),
      h('p', {}, h('span', { class: 'mono' }, doc.serial || '(no serial)'), h('br'), `Prepared by ${doc.drafter_user}`, h('br'), `Submitted ${fmtTime(doc.submitted_at)} · revision ${doc.revision}`),
      doc.status === 'RELEASED' ? h('p', {}, `Signed at: ${fmtTime(doc.signed_at)} (Signet server time)`, h('br'),
        `Released ${fmtTime(doc.released_at)}`, h('br'), h('span', { class: 'mono' }, 'sha256 ' + doc.final_sha256), h('br'),
        h('button', { class: 'primary', onclick: () => act(async () => { const buf = await api(`/docs/${id}/file/final`, { raw: true }); window.open(URL.createObjectURL(new Blob([buf], { type: 'application/pdf' }))); }, null, false) }, 'Open print copy (PDF)')) : null,
      h('h2', {}, 'Signing route'), routeEditor(doc.route, false));
    if (doc.status === 'RELEASED') {
      const timestampText = doc.timestamp_status === 'timestamped'
        ? `Externally timestamped at: ${fmtTime(doc.timestamped_at)} (timestamp authority)`
        : doc.timestamp_status === 'pending' ? 'External timestamp pending'
        : doc.timestamp_status === 'unavailable' ? 'External timestamp unavailable' : 'External timestamp not requested';
      side.append(h('h2', {}, 'External timestamp'), h('p', {}, timestampText));
      if (doc.timestamp_status === 'pending') side.append(h('button', {
        onclick: () => act(() => showDoc(id), null, false),
      }, 'Refresh timestamp status'));
      if (doc.timestamp_status === 'timestamped') side.append(
        h('p', {}, 'Confirms that this released PDF existed by the timestamp authority’s time; it does not independently verify the earlier sign-off time.'),
        h('button', { onclick: () => act(async () => {
          const buf = await api(`/docs/${id}/file/timestamp`, { raw: true });
          const link = h('a', { href: URL.createObjectURL(new Blob([buf], { type: 'application/timestamp-reply' })), download: 'timestamp.tsr' });
          document.body.append(link);
          link.click();
          link.remove();
          setTimeout(() => URL.revokeObjectURL(link.href), 1000);
        }, null, false) }, 'Download timestamp evidence (.tsr)'));
    }
    if (doc.can_decide) {
      const comment = h('textarea', { rows: 3, placeholder: 'Comment (required unless signing off)' });
      const currentParty = doc.current_party > 0 && doc.route.parties ? doc.route.parties[doc.current_party - 1] : null;
      const hasZone = currentParty && doc.layout && doc.layout.imprints && doc.layout.imprints.some((i) => i.type === 'signature_zone' && i.party === currentParty.name);
      const needsEnrolment = hasZone && !app.me.enrolled;

      if (needsEnrolment) {
        side.append(h('h2', {}, 'Enrol your signature'), enrolmentForm(() => showDoc(id)));
      } else {
        /* Show decision UI */
        const placementInput = hasZone ? h('input', { type: 'hidden', id: 'f-placement', value: '' }) : null;
        const decide = (decision) => act(async () => {
          const fields = { decision, comment: comment.value };
          if (hasZone && decision === 'signoff') {
            const area = document.querySelector('area[data-placement]');
            if (!area) throw new Error('Placement required for signature zones');
            const img = area.closest('.page').querySelector('img');
            fields.placement = JSON.stringify({ page: +area.closest('.page').dataset.page, coords: getCoords(area), ref_w: img.naturalWidth, ref_h: img.naturalHeight });
            fields.facsimile_id = signingFacsimile().id;
          }
          return api(`/docs/${id}/decide`, { method: 'POST', fields });
        }, 'Recorded');
        side.append(h('h2', {}, 'Your decision'), comment);
        if (hasZone) side.append(h('label', { for: 'signing-facsimile' }, 'Signature to use'),
          selectEl(app.me.facsimiles.filter((f) => f.enrolled).map((f) => [f.id, f.label + (f.is_default ? ' (default)' : '')]),
            app.me.facsimile.id, () => setupPlacement(), { id: 'signing-facsimile' }),
          h('a', { href: '#/signatures' }, 'Manage my signatures'));
        if (placementInput) side.append(h('p', { class: 'notice' }, 'Position your facsimile inside the signature zone. Drag the placement or use arrow keys; Shift and arrows resize.'));
        if (placementInput) side.append(placementInput);
        side.append(h('div', { class: 'actions' },
          h('button', { class: 'primary', onclick: () => decide('signoff') }, 'Sign off'),
          h('button', { onclick: () => decide('correction') }, 'Correction required'),
          h('button', { class: 'danger', onclick: () => { if (confirm('Disapprove this document? This is final.')) decide('disapprove'); } }, 'Disapprove')));
      }
    }
  }
  side.append(...(historyList() || []));
  [...side.childNodes].forEach((n) => { if (n.nodeType === 3 && n.data === 'null') n.remove(); });

  try {
    await renderPdf(pages, await api(`/docs/${id}/file/${kind}`, { raw: true }));
    loadLayout(doc.layout);
    if (doc.can_decide && app.me.enrolled) setupPlacement();
    renderProps();
  } catch (e) {
    pages.replaceChildren(h('p', { class: 'notice error' }, 'Could not load the PDF: ' + e.message));
  }
}

/* ---------- private signature collection (metadata only) ---------- */

function enrolmentForm(onReady) {
  const label = h('input', { id: 'signature-label', maxlength: 80, value: app.me.enrolled ? '' : 'Signature' });
  const file = h('input', { id: 'signature-upload', type: 'file', accept: 'image/png' });
  const canvas = h('canvas', { width: 400, height: 200, class: 'enrol-canvas', 'aria-label': 'Draw signature' });
  const ctx = canvas.getContext('2d');
  let drawing = false, drawn = false;
  ctx.strokeStyle = '#000'; ctx.lineWidth = 2;
  const point = (e) => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) * canvas.width / r.width, (e.clientY - r.top) * canvas.height / r.height]; };
  canvas.addEventListener('pointerdown', (e) => { drawing = true; canvas.setPointerCapture(e.pointerId); ctx.beginPath(); ctx.moveTo(...point(e)); });
  canvas.addEventListener('pointermove', (e) => { if (drawing) { ctx.lineTo(...point(e)); ctx.stroke(); drawn = true; } });
  canvas.addEventListener('pointerup', () => { drawing = false; });
  canvas.addEventListener('pointercancel', () => { drawing = false; });
  const button = h('button', { class: 'primary', onclick: async () => {
    button.disabled = true;
    try {
      if (!label.value.trim()) throw new Error('Give this signature a label');
      if (!file.files[0] && !drawn) throw new Error('Draw a signature or choose a PNG file');
      const blob = file.files[0] || await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
      const created = await api('/me/facsimile', { method: 'POST', fields: { label: label.value.trim(), file: blob } });
      toast('Waiting for signature activation…');
      for (let i = 0; i < 30; i++) {
        await new Promise((resolve) => setTimeout(resolve, 500));
        if (!button.isConnected) return;
        const me = await api('/me');
        const variant = me.facsimiles.find((f) => f.id === created.id);
        if (variant?.error) throw new Error(variant.error);
        if (variant?.enrolled) { app.me = me; toast('Signature ready'); await onReady(); return; }
      }
      throw new Error('Activation is still pending; check My signatures before uploading again');
    } catch (e) { toast(e.message, true); }
    finally { button.disabled = false; }
  } }, 'Enrol signature');
  return h('div', {}, h('p', {}, 'Draw or upload a PNG (max 1 MiB). Originals remain private. Enrolled images cannot be replaced; add a new variant instead.'),
    h('label', { for: 'signature-label' }, 'Signature label'), label, canvas,
    h('button', { onclick: () => { ctx.clearRect(0, 0, canvas.width, canvas.height); drawn = false; } }, 'Clear drawing'),
    h('label', { for: 'signature-upload' }, 'Or upload PNG'), file,
    h('div', { class: 'actions' }, button));
}

async function showSignatures() {
  clearTimeout(pollTimer);
  doc = null;
  app.me = await api('/me');
  const view = document.getElementById('view');
  if (!app.me.roles.signer) {
    view.replaceChildren(h('p', { class: 'notice' }, 'A signer role is required to manage your signatures.'));
    return;
  }
  view.replaceChildren(h('section', { class: 'signature-collection' }, h('h1', {}, 'My signatures'),
    h('p', {}, 'Choose a default for future sign-offs. Changing it never alters a recorded decision. Up to 32 ready or pending variants.'),
    h('div', { class: 'card' }, app.me.facsimiles.length ? app.me.facsimiles.map((f) => h('div', { class: 'row' },
      h('strong', {}, f.label), h('span', {}, f.error || (!f.enrolled ? 'Awaiting activation' : f.is_default ? 'Default' : 'Ready')),
      !f.enrolled && !f.error ? h('button', { 'aria-label': 'Retry activation of ' + f.label, onclick: () => act(async () => {
        await api('/me/facsimile/retry', { method: 'POST', fields: { facsimile_id: f.id } });
        await showSignatures();
      }, 'Activation queued', false) }, 'Retry activation') : null,
      f.enrolled && !f.is_default ? h('button', { 'aria-label': 'Use ' + f.label + ' as default', onclick: () => act(async () => {
        await api('/me/facsimile/default', { method: 'POST', fields: { facsimile_id: f.id } });
        await showSignatures();
      }, 'Default updated', false) }, 'Use as default') : null)) : h('p', {}, 'No signatures enrolled yet.')),
    h('h2', {}, 'Add a signature'), h('div', { class: 'card' }, enrolmentForm(showSignatures))));
}

/* ---------- dashboard ---------- */

async function showDashboard(scope) {
  clearTimeout(pollTimer);
  doc = null;
  const r = app.me.roles;
  scope = scope || (r.signer && !r.drafter ? 'pending' : 'mine');
  const tabs = [r.drafter && ['mine', 'My documents'], r.signer && ['pending', 'Awaiting my sign-off'],
    r.signer && ['involved', 'All routed to me'], r.admin && ['all', 'Everything']].filter(Boolean);
  const view = document.getElementById('view');
  let rows = [];
  try { rows = await api('/docs?scope=' + scope); } catch (e) { toast(e.message, true); }

  const file = h('input', { type: 'file', accept: 'application/pdf' });
  const tpl = selectEl([['', 'or start from a template…'], ...app.templates.map((t) => [t.id, t.name])], '', () => {});
  const progress = h('progress', { hidden: true, max: 1, value: 0, 'aria-label': 'PDF upload progress' });
  const create = () => act(async () => {
    if (!tpl.value && !file.files[0]) throw new Error('Choose a PDF or a template first');
    createButton.disabled = file.disabled = tpl.disabled = true;
    try {
      const res = tpl.value ? await api('/docs', { method: 'POST', fields: { template_id: tpl.value } }) :
        await uploadPdf(file.files[0], (offset, total) => { progress.hidden = false; progress.max = total; progress.value = offset; });
      location.hash = '#/doc/' + res.id;
    } catch (e) { if (e.docId) location.hash = '#/doc/' + e.docId; throw e; }
    finally { createButton.disabled = file.disabled = tpl.disabled = false; progress.hidden = true; }
  }, null, false);
  const createButton = h('button', { class: 'primary', style: 'flex:0 0 auto', onclick: create }, 'New document');

  view.replaceChildren(
    h('h1', {}, 'Documents'),
    r.drafter ? h('div', { class: 'card', style: 'margin-bottom:1rem' }, h('div', { class: 'row' }, file, tpl, createButton, progress)) : null,
    h('div', { class: 'tabs', role: 'tablist' }, tabs.map(([k, label]) => h('button', { role: 'tab', 'aria-selected': String(k === scope), onclick: () => showDashboard(k) }, label))),
    h('div', { class: 'card' }, rows.length ? h('table', {},
      h('thead', {}, h('tr', {}, ['Document', 'Status', 'Prepared by', 'Parties', 'Created'].map((t) => h('th', {}, t)))),
      h('tbody', {}, rows.map((d) => h('tr', { class: 'click', onclick: () => { location.hash = '#/doc/' + d.id; } },
        h('td', {}, d.title || d.serial || (d.uploading ? 'Incomplete upload' : 'Untitled draft')),
        h('td', {}, h('span', { class: 'status ' + d.status }, d.status.replace(/_/g, ' '))),
        h('td', {}, d.drafter_user),
        h('td', {}, d.status === 'DRAFT' ? '' : `${Math.min(d.current_party, d.parties)} / ${d.parties}`),
        h('td', {}, fmtTime(d.created_at)))))) : h('p', { class: 'empty' }, 'Nothing here.')));
}

async function showSeries() {
  clearTimeout(pollTimer);
  const view = document.getElementById('view');
  const code = h('input', { placeholder: 'Code, e.g. SCNREPLY' });
  const pattern = h('input', { placeholder: 'SKGA/SCNREPLY/{date:%Y%m%d}/{seq:02}' });
  const sample = h('p', { class: 'mono' });
  pattern.oninput = () => { sample.textContent = pattern.value ? 'Next today: ' + expandSeries(pattern.value, new Date(), 1) : ''; };
  view.replaceChildren(h('h1', {}, 'Serial number series'),
    h('div', { class: 'card' }, h('table', {}, h('thead', {}, h('tr', {}, h('th', {}, 'Code'), h('th', {}, 'Pattern'), h('th', {}, 'Example'))),
      h('tbody', {}, app.series.map((s) => h('tr', {}, h('td', {}, s.code), h('td', { class: 'mono' }, s.pattern), h('td', { class: 'mono' }, expandSeries(s.pattern, new Date(), 1))))))),
    app.me.roles.admin ? h('div', { class: 'card', style: 'margin-top:1rem' }, h('h2', { style: 'margin-top:0' }, 'Add or update'),
      h('div', { class: 'row' }, code, pattern, h('button', { class: 'primary', style: 'flex:0 0 auto', onclick: async () => {
        try { await api('/series', { method: 'POST', fields: { code: code.value.trim(), pattern: pattern.value.trim() } }); app.series = await api('/series'); showSeries(); } catch (e) { toast(e.message, true); }
      } }, 'Save')), sample,
      h('p', { class: 'empty', style: 'padding:0' }, '{date:…} takes strftime codes; {seq:NN} is a counter padded to NN digits that restarts every day.')) : null);
}

/* ---------- boot ---------- */

function route() {
  const m = location.hash.match(/^#\/doc\/([0-9a-f-]{36})$/);
  if (m) showDoc(m[1]);
  else if (location.hash === '#/series') showSeries();
  else if (location.hash === '#/signatures') showSignatures().catch((e) => toast(e.message, true));
  else showDashboard();
}

async function boot() {
  if (location.pathname.startsWith('/pim/')) return;  // Let static PIM portal handle /pim/ paths
  try { app.me = await api('/me'); } catch (e) {
    const view = document.getElementById('view');
    if (e.status === 401) {
      view.replaceChildren(h('section', { class: 'card' },
        h('h1', {}, 'Sign-in required'),
        h('p', {}, 'Sign in through your organisation’s login service, then reload this page.'),
        h('p', {}, 'Your account and permissions come from that service; you do not need to enter a username or groups here. If this message persists, contact your administrator.'),
        h('button', { onclick: () => location.reload() }, 'Reload')));
    } else {
      view.replaceChildren(h('p', { class: 'notice error' }, 'Unable to load Signet: ' + e.message));
    }
    return;
  }
  document.getElementById('signature-nav').hidden = !app.me.roles.signer;
  const who = document.getElementById('whoami');
  const roles = Object.entries(app.me.roles).filter(([, v]) => v).map(([k]) => k).join(', ');
  who.textContent = app.me.user + ' · ' + roles;
  if (!LOCAL_DEV) {
    // Same deployment-owned account menu as Movements; no provider session in Signet.
    import('/js/auth-ui.js').then(() => {
      who.replaceChildren(h('span', {}, roles), ' ',
        h('sso-user-button', { username: app.me.user, 'logout-label': 'Sign Out' }));
    }).catch(() => toast('Account controls unavailable. Reload to try again.', true));
  }
  if (LOCAL_DEV && localStorage.getItem('signetDevIdentity')) {
    who.append(' ', h('a', { href: '#', onclick: (e) => { e.preventDefault(); localStorage.removeItem('signetDevIdentity'); location.reload(); } }, '(clear test identity)'));
  }
  [app.pim, app.dam, app.series, app.templates] = await Promise.all([
    api('/pim').catch(() => ({})), api('/dam').catch(() => ({ images: [], fonts: [] })),
    api('/series').catch(() => []), api('/templates').catch(() => []),
  ]);
  window.addEventListener('hashchange', route);
  route();
}

boot();