Spaces:
Running

File size: 75,721 Bytes
fa23117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OrthoCeph Pro v3.5 — Accuracy-First Cephalometrics</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/ort.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
<style>
:root{--bg:#0b1220;--panel:#111a2e;--panel2:#0f172a;--line:#1e293b;--txt:#e2e8f0;--mut:#94a3b8;--acc:#38bdf8;--grn:#34d399;--amb:#fbbf24;--red:#f87171;--pur:#c084fc}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--txt);font-family:Segoe UI,system-ui,Arial,sans-serif;font-size:13px;overflow:hidden}
header{display:flex;gap:10px;align-items:center;padding:8px 12px;background:var(--panel);border-bottom:1px solid var(--line);flex-wrap:wrap}
header h1{font-size:16px;color:var(--acc);white-space:nowrap}
header h1 small{color:var(--mut);font-size:11px;display:block;font-weight:400}
header input{background:var(--panel2);border:1px solid var(--line);color:var(--txt);border-radius:6px;padding:6px 8px}
#status-wrap{display:flex;align-items:center;gap:6px;margin-left:auto;font-weight:600}
#status-ind{width:11px;height:11px;border-radius:50%;background:var(--amb)}
main{display:grid;grid-template-columns:270px 1fr 400px;height:calc(100vh - 53px)}
aside{background:var(--panel);overflow-y:auto;padding:10px}
aside.left{border-right:1px solid var(--line)} aside.right{border-left:1px solid var(--line)}
.sec{margin-bottom:14px}.sec h3{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:var(--acc);margin-bottom:7px;border-bottom:1px solid var(--line);padding-bottom:4px}
.btn{background:#1e3a5f;color:var(--txt);border:1px solid #2b4a73;border-radius:6px;padding:6px 9px;cursor:pointer;font-size:12px;margin:2px 0;width:100%;text-align:left}
.btn:hover{background:#274b7a}.btn.primary{background:#0369a1;border-color:#0284c7;font-weight:700;text-align:center}
.btn.warn{background:#713f12;border-color:#92400e}.btn:disabled{opacity:.45;cursor:not-allowed}
.btnrow{display:flex;gap:5px}.btnrow .btn{text-align:center}
input[type=file]{display:none}
label{display:block;color:var(--mut);margin:5px 0 2px;font-size:11px}
input[type=range]{width:100%}
select{background:var(--panel2);color:var(--txt);border:1px solid var(--line);border-radius:6px;padding:5px;width:100%}
#viewport-wrapper{position:relative;overflow:auto;background:#020617;display:flex;flex-direction:column;align-items:center;justify-content:flex-start}
#viewport-container{position:relative;transform-origin:top center;margin:10px}
#ceph-image{max-width:100%;display:block;user-select:none;-webkit-user-drag:none}
#overlay-svg{position:absolute;top:0;left:0;overflow:visible}
#empty-dropzone{position:absolute;inset:0;display:flex;flex-direction:column;gap:10px;align-items:center;justify-content:center;color:var(--mut);text-align:center;padding:30px}
#empty-dropzone .big{font-size:44px}
.drag-over{outline:3px dashed var(--acc);outline-offset:-8px}
#loupe-box{position:fixed;right:420px;top:70px;width:154px;height:178px;background:#000;border:2px solid var(--acc);border-radius:8px;display:none;z-index:50;text-align:center}
#loupe-label{color:var(--acc);font-weight:700;font-size:12px;padding:2px}
table{width:100%;border-collapse:collapse;font-size:12px}
th,td{padding:4px 5px;border-bottom:1px solid var(--line);text-align:right}
th:first-child,td:first-child{text-align:left}
th{color:var(--mut);font-weight:600}
.st-Normal{color:var(--grn)}.st-High{color:var(--red)}.st-Low{color:var(--amb)}.st-na{color:var(--mut)}
.badge{font-size:9px;padding:1px 4px;border-radius:4px;font-weight:700;vertical-align:middle}
.b-est{background:#581c87;color:#e9d5ff}.b-unc{background:#713f12;color:#fde68a}.b-rev{background:#422006;color:#fcd34d}
.tabs{display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px}
.tab{background:var(--panel2);border:1px solid var(--line);color:var(--mut);border-radius:14px;padding:4px 10px;cursor:pointer;font-size:11px}
.tab.active{background:#0369a1;color:#fff;border-color:#0284c7}
.lm-row{display:flex;align-items:center;gap:6px;padding:3px 5px;border-radius:5px;cursor:pointer}
.lm-row:hover{background:#1e293b}.lm-row.sel{background:#164e63}
.lm-dot{width:9px;height:9px;border-radius:50%;flex:none}
.lm-row .nm{flex:1}.lm-row .full{color:var(--mut);font-size:10px;display:block}
.lm-row .vf{color:var(--grn);font-weight:700}
.lm-row .mv{color:var(--mut);font-size:10px}
#progress-wrap{background:var(--panel2);border-radius:6px;height:16px;position:relative;overflow:hidden;border:1px solid var(--line)}
#progress-bar{background:#059669;height:100%;width:0%}
#progress-txt{position:absolute;inset:0;text-align:center;font-size:11px;line-height:16px;font-weight:700}
.diag{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:8px;line-height:1.5}
.diag b{color:var(--acc)}
.kbd{background:#1e293b;border:1px solid #334155;border-radius:3px;padding:0 4px;font-size:10px}
.note{color:var(--mut);font-size:11px;line-height:1.45}
.lm-handle{cursor:grab}.lm-handle.dragging{cursor:grabbing}
#place-banner{display:none;background:#7c2d12;color:#ffedd5;padding:7px 10px;border-radius:6px;margin-bottom:8px;line-height:1.4}
#print-report{display:none}
@media print{ header,main{display:none!important} body{overflow:visible;background:#fff}
 #print-report{display:block!important;color:#000;font-size:12px;font-family:Georgia,serif}
 #print-report h1{font-size:17px;margin-bottom:4px} #print-report h2{font-size:13px;margin:13px 0 5px;border-bottom:2px solid #000;padding-bottom:2px}
 #print-report table{width:100%;border-collapse:collapse;font-size:11.5px}
 #print-report th,#print-report td{border:1px solid #999;padding:3px 5px;text-align:right;color:#000}
 #print-report th:first-child,#print-report td:first-child{text-align:left}
 .pr-film{position:relative;width:100%;max-width:620px;margin:10px auto}
 .pr-film img{width:100%;display:block}
 .pr-film svg{position:absolute;top:0;left:0;width:100%;height:100%}
 #print-report svg text{fill:#000;stroke:none;font-weight:700}
 #print-report svg line{stroke:#555}
 .pr-diag{border:1.5px solid #000;padding:7px 9px;margin:8px 0;line-height:1.55}
 .pr-meta{color:#222;line-height:1.5}
 .pr-foot{margin-top:12px;font-size:10px;color:#444;border-top:1px solid #999;padding-top:5px} }
#overlay-svg{touch-action:none}
.lm-handle{touch-action:none}
#nudge-bar{display:none;width:100%;background:var(--panel);border-top:1px solid var(--line);padding:7px 8px;gap:6px;align-items:center;justify-content:center;flex-wrap:wrap}
#nudge-bar.show{display:flex}
#nudge-bar .nb-name{font-weight:700;color:var(--acc);min-width:110px;text-align:center}
#nudge-bar button{background:#1e3a5f;color:var(--txt);border:1px solid #2b4a73;border-radius:8px;padding:9px 13px;font-size:15px;cursor:pointer;min-width:46px}
#nudge-bar button:active{background:#0369a1}
#nudge-bar button.vf{background:#065f46;border-color:#059669;font-size:13px;font-weight:700}
#nudge-bar button.nx{background:#713f12;border-color:#92400e;font-size:13px;font-weight:700}
@media (max-width:1100px){ body{overflow:auto} main{display:flex;flex-direction:column;height:auto}
  #viewport-wrapper{order:-1;position:sticky;top:0;z-index:40;min-height:52vh;max-height:62vh;width:100%;box-shadow:0 6px 16px rgba(0,0,0,.55)}
  aside.left,aside.right{border:none;width:100%}
  #ceph-image{width:100%}
  #loupe-box{right:8px;top:auto;bottom:8px;position:fixed}
  header input{flex:1;min-width:110px} }
</style>
</head>
<body>
<header>
  <h1>🦷 OrthoCeph Pro v3.5<small>Accuracy-first • AI proposes, you verify • No fake numbers</small></h1>
  <input id="pt-name" placeholder="Patient name" style="width:150px">
  <input id="pt-chart" placeholder="Chart #" style="width:90px">
  <input id="pt-date" type="date">
  <div id="status-wrap"><span id="status-ind"></span><span id="status-txt">Loading AI model…</span></div>
</header>
<main>
<aside class="left">
  <div class="sec"><h3>1 · Film</h3>
    <label class="btn primary" for="file-input" style="text-align:center">📂 Upload Ceph (JPG / PNG / DICOM)</label>
    <input type="file" id="file-input" accept=".jpg,.jpeg,.png,.dcm">
    <label class="btn" for="json-input" style="text-align:center">Open Saved Record (JSON)</label>
    <input type="file" id="json-input" accept=".json">
    <div class="btnrow"><button class="btn" id="btn-bright">Brightness / Contrast</button></div>
    <div id="filter-box" style="display:none">
      <label>Brightness</label><input type="range" id="brightness" min="0.4" max="2" step="0.05" value="1">
      <label>Contrast</label><input type="range" id="contrast" min="0.4" max="2.5" step="0.05" value="1">
      <label style="display:flex;gap:6px;align-items:center"><input type="checkbox" id="invert" style="width:auto"> Invert</label>
      <button class="btn" id="reset-filters">Reset filters</button>
    </div>
    <div class="btnrow">
      <button class="btn" id="btn-zoom-out">−</button><button class="btn" id="btn-zoom-reset">Zoom 100%</button><button class="btn" id="btn-zoom-in">+</button>
    </div>
  </div>
  <div class="sec"><h3>2 · Calibration (required for mm)</h3>
    <div id="cal-status" class="note" style="color:var(--amb)">⚠ UNCALIBRATED — angles valid, mm values are provisional.</div>
    <button class="btn" id="btn-cal">📐 Place 10 mm Ruler</button>
    <p class="note">Click the 0 mm mark, then the 10 mm mark on the ruler in the film — or drag the cyan ruler dots onto two ticks exactly 10 mm apart (zoom in first). <b>The moment the 2nd click lands, every mm value recalculates automatically</b> — no re-trace, nothing else to press, and the points do not move. Angles are unaffected. Redo it for each new film. DICOM spacing is only a starting value — magnification still needs the ruler.</p>
  </div>
  <div class="sec"><h3>3 · Trace</h3>
    <button class="btn primary" id="btn-autotrace">🤖 Run AI Auto-Trace</button>
    <button class="btn" id="btn-manual">✍️ Guided Manual Placement</button>
    <button class="btn" id="btn-review">🔍 Review Queue (worst first)</button>
    <p id="model-detail" class="note" style="color:var(--red)"></p>
    <button class="btn" id="btn-retrace-all">Reset All to AI</button>
    <button class="btn" id="btn-reset-single">Reset Selected to AI</button>
    <div id="place-banner"></div>
    <p class="note">Drag points on the film. Select a point, then: <span class="kbd">←→↑↓</span> nudge 0.5 px · <span class="kbd">Shift</span>+arrows 0.1 px · <span class="kbd">V</span> mark verified · <span class="kbd">Ctrl+Z</span> undo · <span class="kbd">Space</span> hold to peek at clean film.</p>
  </div>
  <div class="sec"><h3>Verification</h3>
    <div id="progress-wrap"><div id="progress-bar"></div><div id="progress-txt">0 / 0 verified</div></div>
    <p class="note" style="margin-top:5px">Selected: <b id="selected-lm-label">None</b></p>
    <button class="btn" id="btn-verify-sel">✓ Mark Selected Verified (V)</button>
    <button class="btn" id="btn-verify-all-conf">✓✓ Verify All High-Confidence AI Points</button>
  </div>
  <div class="sec"><h3>Landmarks</h3>
    <input id="lm-search" placeholder="Search landmarks…" style="width:100%;background:var(--panel2);border:1px solid var(--line);color:var(--txt);border-radius:6px;padding:6px">
    <div id="lm-list" style="margin-top:6px"></div>
    <p class="note">Dot = confidence: <span style="color:var(--grn)">● high</span> <span style="color:var(--amb)">● medium</span> <span style="color:var(--red)">● low</span> <span style="color:var(--pur)">● estimate — place/verify manually</span>. “moved” = how far you moved it from AI, in mm.</p>
  </div>
</aside>

<section id="viewport-wrapper">
  <div id="empty-dropzone"><div class="big">🦷</div><div><b>Drop a lateral ceph here</b><br>JPG / PNG / uncompressed DICOM.</div><label class="btn primary" for="file-input" style="text-align:center;width:auto;padding:10px 22px;font-size:14px">📂 Upload Ceph</label><div>Workflow: Upload → Calibrate ruler → AI trace → Review Queue → Verify → Export.</div></div>
  <div id="viewport-container" style="display:none">
    <img id="ceph-image" alt="cephalogram">
    <svg id="overlay-svg"></svg>
  </div>
  <div id="loupe-box"><div id="loupe-label">—</div><canvas id="loupe-canvas" width="150" height="150"></canvas></div>
  <div id="nudge-bar"><span class="nb-name" id="nb-name">No point selected</span>
    <button data-dx="0" data-dy="-1" title="Nudge up">▲</button>
    <button data-dx="-1" data-dy="0" title="Nudge left">◀</button>
    <button data-dx="1" data-dy="0" title="Nudge right">▶</button>
    <button data-dx="0" data-dy="1" title="Nudge down">▼</button>
    <button id="nb-step" title="Toggle nudge step">Step: 1px</button>
    <button class="vf" id="nb-verify">✓ Verify</button>
    <button class="nx" id="nb-next">Next unverified →</button>
  </div>
</section>

<aside class="right">
  <div class="sec"><h3>Diagnosis (auto, from verified math)</h3>
    <div class="diag" id="diag-box"><b id="diag-headline">Awaiting tracing…</b><br>
    Sagittal: <span id="diag-sagittal">-</span><br>Vertical: <span id="diag-vertical">-</span><br>
    Dental: <span id="diag-dental">-</span><br>Soft tissue: <span id="diag-soft">-</span></div>
  </div>
  <div class="sec"><h3>Analyses</h3>
    <div class="tabs" id="analysis-tabs"></div>
    <div id="analysis-tables"></div>
    <p class="note" style="margin-top:6px">— = a required landmark is missing, the number is <b>not</b> guessed. <span class="badge b-est">EST</span> uses an unverified estimate landmark. <span class="badge b-unc">UNCAL</span> mm value before ruler calibration.</p>
  </div>
  <div class="sec"><h3>Superimposition (T1 / T2)</h3>
    <button class="btn" id="btn-lock-t1">🔒 Lock Current as T1</button>
    <label>Registration</label>
    <select id="super-mode"><option value="CRANIAL">Cranial Base (S–N at S)</option><option value="MAXILLARY">Maxillary (Palatal Plane at PNS)</option><option value="MANDIBULAR">Mandibular (Me–Go at Me)</option></select>
    <div id="super-status" class="note" style="margin-top:5px">No T1 baseline locked.</div>
    <button class="btn" id="btn-clear-t1">Clear T1</button>
  </div>
  <div class="sec"><h3>Export</h3>
    <button class="btn primary" id="btn-save-json">💾 Save Record (JSON — incl. AI vs final + confidence)</button>
    <button class="btn" id="btn-export-csv">📊 Export CSV</button>
    <button class="btn" id="btn-copy-note">📋 Copy Clinical Note</button>
    <button class="btn" id="btn-print">🖨 Print Report</button>
    <button class="btn warn" id="btn-next-patient">⏭ Next Patient (clears everything)</button>
    <p class="note">The JSON is your validation dataset: it stores AI position, your final position, confidence and verified status per landmark. Send me these files and I can measure the AI's real error on your films, landmark by landmark.</p>
  </div>
  <div class="sec"><h3>View</h3>
    <div class="btnrow"><button class="btn" id="tog-lines">Lines: ON</button><button class="btn" id="tog-points">Dots: ON</button><button class="btn" id="tog-labels">Names: ON</button></div>
    <div class="btnrow"><button class="btn" id="tog-trace">Tracing outline: ON</button></div>
  </div>
</aside>
</main>
<div id="print-report"></div>
<script>
"use strict";
/* ============================================================
   OrthoCeph Pro v3.5 — accuracy-first rebuild
   Rules enforced in code:
   1. No measurement is computed from missing landmarks (no guessing,
      no fabricated occlusal plane like v2.3).
   2. mm values require calibration; otherwise they are flagged UNCAL.
   3. Signed distances are anatomy-based (anterior-positive), identical
      for left- and right-facing films.
   4. Every AI landmark carries a confidence score; hard/low-confidence
      points are queued for human review first.
   5. AI vs final positions + verified flags are saved in the JSON —
      that file IS the validation dataset.
   ============================================================ */
const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";

/* Landmark catalogue.
   model: cepha29 channel index verified in v2.3 map, or null = manual/estimate.
   tier: 1 easy, 2 medium, 3 hard (literature: larger mean radial error) */
const LANDMARKS = {
  S:   {full:"Sella",            model:23, tier:1, def:"Center of sella turcica."},
  N:   {full:"Nasion",           model:14, tier:1, def:"Most anterior point of frontonasal suture."},
  Po:  {full:"Porion",           model:19, tier:3, def:"Most superior point of external auditory meatus."},
  Or:  {full:"Orbitale",         model:16, tier:3, def:"Most inferior point of orbital rim."},
  ANS: {full:"Anterior Nasal Spine", model:1, tier:1, def:"Tip of anterior nasal spine."},
  PNS: {full:"Posterior Nasal Spine", model:17, tier:2, def:"Tip of posterior nasal spine (model ch 17, confirmed from the official model card)."},
  A:   {full:"A-Point",          model:0,  tier:2, def:"Deepest point on maxillary alveolar concavity."},
  B:   {full:"B-Point",          model:3,  tier:2, def:"Deepest point on mandibular alveolar concavity."},
  Pog: {full:"Pogonion",         model:20, tier:2, def:"Most anterior point of bony chin."},
  Gn:  {full:"Gnathion",         model:5,  tier:2, def:"Most antero-inferior point of chin."},
  Me:  {full:"Menton",           model:13, tier:1, def:"Most inferior point of symphysis."},
  Go:  {full:"Gonion",           model:6,  tier:3, def:"Most postero-inferior point of mandibular angle (bisector construction)."},
  UIT: {full:"U1 Incisal Tip",   model:26, tier:1, def:"Incisal edge of maxillary central incisor."},
  UIA: {full:"U1 Apex",          model:25, tier:3, def:"Root apex of maxillary central incisor."},
  LIT: {full:"L1 Incisal Tip",   model:8,  tier:1, def:"Incisal edge of mandibular central incisor."},
  LIA: {full:"L1 Apex",          model:7,  tier:3, def:"Root apex of mandibular central incisor."},
  Pn:  {full:"Pronasale (nose tip)", model:18, tier:1, def:"Most anterior point of nose."},
  Sn:  {full:"Subnasale",        model:24, tier:1, def:"Junction of columella and upper lip."},
  Ls:  {full:"Labrale Superius", model:12, tier:2, def:"Most anterior point of upper lip."},
  Li:  {full:"Labrale Inferius", model:11, tier:2, def:"Most anterior point of lower lip."},
  PogS:{full:"Soft Pogonion",    model:21, tier:2, def:"Most anterior point of soft-tissue chin."},
  Co:  {full:"Condylion",        model:4, tier:3, def:"Most postero-superior point of mandibular condyle. Model-predicted (ch 4) but HARD — always verify."},
  Ar:  {full:"Articulare",       model:2, tier:3, def:"Intersection of posterior border of ramus and cranial base. Model-predicted (ch 2), hard — verify."},
  Ba:  {full:"Basion",           model:null, tier:2, def:"Most postero-inferior point of clivus. MANUAL."},
  Pt:  {full:"Pterygoid Point",  model:null, tier:3, def:"Most postero-superior point of pterygomaxillary fissure. MANUAL."},
  D:   {full:"D-Point (SND)",    model:null, tier:2, def:"Center of bony symphysis. MANUAL."},
  U6T: {full:"U6 Mesial Cusp",   model:27, tier:2, def:"Mesial cusp of upper first molar (model UMT, ch 27). Required for a real occlusal plane and Wits."},
  L6T: {full:"L6 Mesial Cusp",   model:9, tier:2, def:"Mesial cusp of lower first molar (model LMT, ch 9). Required for Wits."},
  NS:  {full:"Soft Nasion",      model:15, tier:2, def:"Soft-tissue nasion (model N', ch 15)."},
  MeS: {full:"Soft Menton",      model:null, tier:2, def:"Most inferior soft-tissue point of chin. MANUAL."}
};
const ABO_REQUIRED = ["S","N","A","B","Me","Go","UIT","UIA","LIT","LIA","U6T","L6T","Pn","PogS"];

/* ==================== ENGINE START ====================
   Pure geometry + measurement engine. No DOM access in this block.
   coords: {CODE:{x,y}} in image pixels. pxPerMm converts to mm.
   Every function returns null when a required point is missing. */
function _p(c,k){const v=c&&c[k];return (v&&isFinite(v.x)&&isFinite(v.y))?v:null;}
function _dist(a,b){return Math.hypot(a.x-b.x,a.y-b.y);}
function angleAt(p1,v,p2){ if(!p1||!v||!p2)return null;
  const a={x:p1.x-v.x,y:p1.y-v.y},b={x:p2.x-v.x,y:p2.y-v.y};
  const m=Math.hypot(a.x,a.y)*Math.hypot(b.x,b.y); if(!m)return null;
  return Math.acos(Math.max(-1,Math.min(1,(a.x*b.x+a.y*b.y)/m)))*180/Math.PI; }
function lineIntersect(a1,a2,b1,b2){ if(!a1||!a2||!b1||!b2)return null;
  const d=(a2.x-a1.x)*(b2.y-b1.y)-(a2.y-a1.y)*(b2.x-b1.x); if(Math.abs(d)<1e-9)return null;
  const t=((b1.x-a1.x)*(b2.y-b1.y)-(b1.y-a1.y)*(b2.x-b1.x))/d;
  return {x:a1.x+t*(a2.x-a1.x), y:a1.y+t*(a2.y-a1.y)}; }
/* Angle between two lines at their intersection, rays toward r1 side of line1 and r2 side of line2.
   Used for plane/incisor angles so the CLINICAL (interior/posterior) angle is returned, not a folded acute. */
function planeAngle(l1a,l1b,r1,l2a,l2b,r2){ const X=lineIntersect(l1a,l1b,l2a,l2b); if(!X)return null; return angleAt(r1,X,r2); }
function planeAngleAcute(a1,a2,b1,b2){ if(!a1||!a2||!b1||!b2)return null;
  const v1={x:a2.x-a1.x,y:a2.y-a1.y},v2={x:b2.x-b1.x,y:b2.y-b1.y};
  const m=Math.hypot(v1.x,v1.y)*Math.hypot(v2.x,v2.y); if(!m)return null;
  return Math.acos(Math.min(1,Math.abs(v1.x*v2.x+v1.y*v2.y)/m))*180/Math.PI; }
function faceDir(c){ const s=_p(c,"S"),n=_p(c,"N"); if(!s||!n)return 1; return n.x>=s.x?1:-1; }
/* Signed perpendicular distance in mm. Sign: + = point lies ANTERIOR to the line, − = posterior.
   Independent of image facing because anterior is derived from S→N. */
function signedPerpMm(c,pt,a,b,ppm){ pt=_p(c,pt);a=_p(c,a);b=_p(c,b); if(!pt||!a||!b||!ppm)return null;
  const vx=b.x-a.x, vy=b.y-a.y, len=Math.hypot(vx,vy); if(!len)return null;
  const t=((pt.x-a.x)*vx+(pt.y-a.y)*vy)/(len*len);
  const proj={x:a.x+t*vx,y:a.y+t*vy};
  const px=pt.x-proj.x, py=pt.y-proj.y, mag=Math.hypot(px,py)/ppm;
  if(mag<1e-9)return 0;
  const ant={x:faceDir(c),y:0}; const s=Math.sign(px*ant.x+py*ant.y);
  return (s===0?1:s)*mag; }
function distMm(c,k1,k2,ppm){ const a=_p(c,k1),b=_p(c,k2); if(!a||!b||!ppm)return null; return _dist(a,b)/ppm; }
/* Functional occlusal plane points: anterior = midpoint of incisor tips, posterior = midpoint of molar cusps. */
function occlusalPoints(c){ const uit=_p(c,"UIT"),lit=_p(c,"LIT"),u6=_p(c,"U6T"),l6=_p(c,"L6T");
  if(!uit||!lit||!u6||!l6)return null;
  return {ant:{x:(uit.x+lit.x)/2,y:(uit.y+lit.y)/2}, post:{x:(u6.x+l6.x)/2,y:(u6.y+l6.y)/2}}; }
function projectOnto(pt,o,u){ return (pt.x-o.x)*u.x+(pt.y-o.y)*u.y; }

const MEASURES = [
 /* ---- ABO FOCUS ---- */
 {id:"SNA", an:"ABO", name:"SNA", norm:82, sd:2, unit:"°", req:["S","N","A"], f:c=>angleAt(_p(c,"S"),_p(c,"N"),_p(c,"A"))},
 {id:"SNB", an:"ABO", name:"SNB", norm:80, sd:2, unit:"°", req:["S","N","B"], f:c=>angleAt(_p(c,"S"),_p(c,"N"),_p(c,"B"))},
 {id:"ANB", an:"ABO", name:"ANB", norm:2, sd:2, unit:"°", req:["S","N","A","B"], f:c=>{const a=angleAt(_p(c,"S"),_p(c,"N"),_p(c,"A")),b=angleAt(_p(c,"S"),_p(c,"N"),_p(c,"B"));return (a==null||b==null)?null:a-b;}},
 {id:"WITS", an:"ABO", name:"Wits Appraisal", norm:0, sd:1, unit:"mm", req:["A","B","UIT","LIT","U6T","L6T"], f:(c,ppm)=>{const op=occlusalPoints(c);const A=_p(c,"A"),B=_p(c,"B");if(!op||!A||!B||!ppm)return null;const v={x:op.ant.x-op.post.x,y:op.ant.y-op.post.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const u={x:v.x/L,y:v.y/L};return (projectOnto(A,op.post,u)-projectOnto(B,op.post,u))/ppm;}},
 {id:"SNGOGN", an:"ABO", name:"SN–GoGn", norm:32, sd:5, unit:"°", req:["S","N","Go","Gn"], f:c=>planeAngle(_p(c,"S"),_p(c,"N"),_p(c,"N"),_p(c,"Go"),_p(c,"Gn"),_p(c,"Gn"))},
 {id:"FMA", an:"ABO", name:"FMA (FH–MP)", norm:25, sd:4, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"),_p(c,"Me"))},
 {id:"IMPA", an:"ABO", name:"IMPA (L1–MP)", norm:90, sd:5, unit:"°", req:["LIT","LIA","Go","Me"], f:c=>planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Go"),_p(c,"Go"),_p(c,"Me"),_p(c,"LIT"))},
 {id:"U1SN", an:"ABO", name:"U1–SN", norm:102, sd:5, unit:"°", req:["UIT","UIA","S","N"], f:c=>planeAngle(_p(c,"UIT"),_p(c,"UIA"),_p(c,"S"),_p(c,"S"),_p(c,"N"),_p(c,"UIT"))},
 {id:"U1NA_D", an:"ABO", name:"U1–NA Angle", norm:22, sd:4, unit:"°", req:["UIT","UIA","N","A"], f:c=>planeAngleAcute(_p(c,"UIT"),_p(c,"UIA"),_p(c,"N"),_p(c,"A"))},
 {id:"U1NA_M", an:"ABO", name:"U1–NA", norm:4, sd:2, unit:"mm", req:["UIT","N","A"], f:(c,ppm)=>signedPerpMm(c,"UIT","N","A",ppm)},
 {id:"L1NB_D", an:"ABO", name:"L1–NB Angle", norm:25, sd:4, unit:"°", req:["LIT","LIA","N","B"], f:c=>planeAngleAcute(_p(c,"LIT"),_p(c,"LIA"),_p(c,"N"),_p(c,"B"))},
 {id:"L1NB_M", an:"ABO", name:"L1–NB", norm:4, sd:2, unit:"mm", req:["LIT","N","B"], f:(c,ppm)=>signedPerpMm(c,"LIT","N","B",ppm)},
 {id:"IIA", an:"ABO", name:"Interincisal Angle", norm:130, sd:6, unit:"°", req:["UIT","UIA","LIT","LIA"], f:c=>{const a=_p(c,"UIT"),b=_p(c,"UIA"),d=_p(c,"LIT"),e=_p(c,"LIA");if(!a||!b||!d||!e)return null;const v1={x:a.x-b.x,y:a.y-b.y},v2={x:d.x-e.x,y:d.y-e.y};const m=Math.hypot(v1.x,v1.y)*Math.hypot(v2.x,v2.y);return m?Math.acos(Math.max(-1,Math.min(1,(v1.x*v2.x+v1.y*v2.y)/m)))*180/Math.PI:null;}},
 {id:"OJ", an:"ABO", name:"Overjet (occl. proj.)", norm:2.5, sd:1, unit:"mm", req:["UIT","LIT","U6T","L6T"], f:(c,ppm)=>{const op=occlusalPoints(c);if(!op||!ppm)return null;const v={x:op.ant.x-op.post.x,y:op.ant.y-op.post.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const u={x:v.x/L,y:v.y/L};return (projectOnto(_p(c,"UIT"),op.post,u)-projectOnto(_p(c,"LIT"),op.post,u))/ppm;}},
 {id:"OB", an:"ABO", name:"Overbite (perp. to occl.)", norm:2.5, sd:1, unit:"mm", req:["UIT","LIT","U6T","L6T"], f:(c,ppm)=>{const op=occlusalPoints(c);if(!op||!ppm)return null;const v={x:op.ant.x-op.post.x,y:op.ant.y-op.post.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const n={x:-v.y/L,y:v.x/L};const d=(projectOnto(_p(c,"LIT"),op.post,n)-projectOnto(_p(c,"UIT"),op.post,n));return Math.abs(d)/ppm*(faceDir(c)>0?1:1);}},
 {id:"UL_E", an:"ABO", name:"Upper Lip to E-Line", norm:-3, sd:2, unit:"mm", req:["Ls","Pn","PogS"], f:(c,ppm)=>signedPerpMm(c,"Ls","Pn","PogS",ppm)},
 {id:"LL_E", an:"ABO", name:"Lower Lip to E-Line", norm:-1, sd:2, unit:"mm", req:["Li","Pn","PogS"], f:(c,ppm)=>signedPerpMm(c,"Li","Pn","PogS",ppm)},
 /* ---- STEINER ---- */
 {id:"SND", an:"Steiner", name:"SND", norm:76, sd:2, unit:"°", req:["S","N","D"], f:c=>angleAt(_p(c,"S"),_p(c,"N"),_p(c,"D"))},
 {id:"OCCSN", an:"Steiner", name:"Occlusal Plane–SN", norm:14, sd:4, unit:"°", req:["S","N","UIT","LIT","U6T","L6T"], f:c=>{const op=occlusalPoints(c);if(!op)return null;return planeAngleAcute(_p(c,"S"),_p(c,"N"),op.post,op.ant);}},
 {id:"GOGNSN", an:"Steiner", name:"GoGn–SN", norm:32, sd:5, unit:"°", req:["S","N","Go","Gn"], f:c=>planeAngle(_p(c,"S"),_p(c,"N"),_p(c,"N"),_p(c,"Go"),_p(c,"Gn"),_p(c,"Gn"))},
 {id:"POGNB", an:"Steiner", name:"Pog–NB", norm:null, sd:null, unit:"mm", req:["Pog","N","B"], f:(c,ppm)=>signedPerpMm(c,"Pog","N","B",ppm), note:"Compare with L1–NB mm (Holdaway ratio ≈ 1:1)"},
 {id:"SE", an:"Steiner", name:"S–E (condyle proxy: S to L1-midpoint line)", norm:22, sd:3, unit:"mm", req:["S","LIT","LIA"], f:(c,ppm)=>{const a=_p(c,"LIT"),b=_p(c,"LIA");if(!a||!b)return null;const mid={x:(a.x+b.x)/2,y:(a.y+b.y)/2};const s=_p(c,"S");return ppm?_dist(s,mid)/ppm:null;}},
 {id:"SL", an:"Steiner", name:"S–L (S to Pog-perp on SN)", norm:51, sd:3, unit:"mm", req:["S","N","Pog"], f:(c,ppm)=>{const s=_p(c,"S"),n=_p(c,"N"),g=_p(c,"Pog");if(!s||!n||!g||!ppm)return null;const v={x:n.x-s.x,y:n.y-s.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(g,s,u)/ppm;}},
 /* ---- DOWNS ---- */
 {id:"FACIAL", an:"Downs", name:"Facial Angle (FH–NPog)", norm:87.8, sd:3.6, unit:"°", req:["Po","Or","N","Pog"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"N"),_p(c,"Pog"),_p(c,"Pog"))},
 {id:"CONVEX", an:"Downs", name:"Angle of Convexity (N–A–Pog)", norm:0, sd:5, unit:"°", req:["N","A","Pog"], f:c=>{const a=angleAt(_p(c,"N"),_p(c,"A"),_p(c,"Pog"));if(a==null)return null;const s=signedPerpMm(c,"A","N","Pog",10);return (s==null?1:Math.sign(s))*(180-a);}},
 {id:"ABPLANE", an:"Downs", name:"A–B Plane Angle (to Facial Plane)", norm:-4.6, sd:3.7, unit:"°", req:["A","B","N","Pog"], f:c=>{const x=planeAngleAcute(_p(c,"A"),_p(c,"B"),_p(c,"N"),_p(c,"Pog"));return x==null?null:-x;}},
 {id:"MPFH", an:"Downs", name:"Mandibular Plane–FH", norm:21.9, sd:5, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngleAcute(_p(c,"Po"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"))},
 {id:"YAXIS", an:"Downs", name:"Y-Axis (FH–SGn)", norm:59.4, sd:3.8, unit:"°", req:["Po","Or","S","Gn"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"S"),_p(c,"Gn"),_p(c,"Gn"))},
 {id:"OCCFH", an:"Downs", name:"Occlusal Plane–FH", norm:9.3, sd:3.8, unit:"°", req:["Po","Or","UIT","LIT","U6T","L6T"], f:c=>{const op=occlusalPoints(c);if(!op)return null;return planeAngleAcute(_p(c,"Po"),_p(c,"Or"),op.post,op.ant);}},
 {id:"L1OCC", an:"Downs", name:"L1–Occlusal Plane", norm:14.5, sd:3.5, unit:"°", req:["LIT","LIA","UIT","U6T","L6T"], f:c=>{const op=occlusalPoints(c);if(!op)return null;const x=planeAngleAcute(_p(c,"LIT"),_p(c,"LIA"),op.post,op.ant);return x==null?null:90-x;}},
 {id:"L1MP_D", an:"Downs", name:"L1–Mandibular Plane", norm:-28.8, sd:5.5, unit:"°", req:["LIT","LIA","Go","Me"], f:c=>{const impa=planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Go"),_p(c,"Go"),_p(c,"Me"),_p(c,"LIT"));return impa==null?null:-(90-impa);}},
 {id:"U1APOG_M", an:"Downs", name:"U1–APog", norm:2.7, sd:1.8, unit:"mm", req:["UIT","A","Pog"], f:(c,ppm)=>signedPerpMm(c,"UIT","A","Pog",ppm)},
 /* ---- TWEED ---- */
 {id:"T_FMA", an:"Tweed", name:"FMA", norm:25, sd:4, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"),_p(c,"Me"))},
 {id:"T_IMPA", an:"Tweed", name:"IMPA", norm:90, sd:5, unit:"°", req:["LIT","LIA","Go","Me"], f:c=>planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Go"),_p(c,"Go"),_p(c,"Me"),_p(c,"LIT"))},
 {id:"FMIA", an:"Tweed", name:"FMIA", norm:65, sd:5, unit:"°", req:["LIT","LIA","Po","Or"], f:c=>planeAngle(_p(c,"LIT"),_p(c,"LIA"),_p(c,"Po"),_p(c,"Po"),_p(c,"Or"),_p(c,"LIA"))},
 /* ---- McNAMARA ---- */
 {id:"NPERPA", an:"McNamara", name:"Nasion Perp – A Point", norm:0, sd:3.1, unit:"mm", req:["N","Po","Or","A"], f:(c,ppm)=>{const n=_p(c,"N"),a=_p(c,"A"),po=_p(c,"Po"),or=_p(c,"Or");if(!n||!a||!po||!or||!ppm)return null;const v={x:or.x-po.x,y:or.y-po.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(a,n,u)/ppm;}, note:"Along FH direction from N-perp"},
 {id:"NPERPPOG", an:"McNamara", name:"Nasion Perp – Pog", norm:-4, sd:5.3, unit:"mm", req:["N","Po","Or","Pog"], f:(c,ppm)=>{const n=_p(c,"N"),a=_p(c,"Pog"),po=_p(c,"Po"),or=_p(c,"Or");if(!n||!a||!po||!or||!ppm)return null;const v={x:or.x-po.x,y:or.y-po.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(a,n,u)/ppm;}},
 {id:"COA", an:"McNamara", name:"Effective Midface Length (Co–A)", norm:null, sd:null, unit:"mm", req:["Co","A"], f:(c,ppm)=>distMm(c,"Co","A",ppm), note:"Norm varies with age/sex — compare to Co–Gn"},
 {id:"COGN", an:"McNamara", name:"Effective Mandibular Length (Co–Gn)", norm:null, sd:null, unit:"mm", req:["Co","Gn"], f:(c,ppm)=>distMm(c,"Co","Gn",ppm), note:"Norm varies with age/sex"},
 {id:"MXMDIFF", an:"McNamara", name:"Mx–Md Differential (CoGn − CoA)", norm:null, sd:null, unit:"mm", req:["Co","A","Gn"], f:(c,ppm)=>{const a=distMm(c,"Co","A",ppm),b=distMm(c,"Co","Gn",ppm);return (a==null||b==null)?null:b-a;}, note:"~20 mm small, ~27 medium, ~34 large (McNamara)"},
 {id:"LAFH", an:"McNamara", name:"Lower Anterior Face Height (ANS–Me)", norm:null, sd:null, unit:"mm", req:["ANS","Me"], f:(c,ppm)=>distMm(c,"ANS","Me",ppm), note:"~60–62 mm small, ~65–67 medium, ~70–72 large"},
 {id:"U1AVERT", an:"McNamara", name:"U1 to A-Point Vertical", norm:4, sd:1, unit:"mm", req:["UIT","A","ANS","PNS"], f:(c,ppm)=>{const a=_p(c,"A"),t=_p(c,"UIT"),an=_p(c,"ANS"),pn=_p(c,"PNS");if(!a||!t||!an||!pn||!ppm)return null;const v={x:an.x-pn.x,y:an.y-pn.y};const L=Math.hypot(v.x,v.y);if(!L)return null;const u={x:v.x/L,y:v.y/L};return projectOnto(t,a,u)/ppm;}, note:"Distance along palatal plane from the vertical through A"},
 {id:"L1APOG", an:"McNamara", name:"L1 to A–Pog Line", norm:1, sd:2, unit:"mm", req:["LIT","A","Pog"], f:(c,ppm)=>signedPerpMm(c,"LIT","A","Pog",ppm)},
 /* ---- RICKETTS ---- */
 {id:"FACAXIS", an:"Ricketts", name:"Facial Axis (Ba–N to Pt–Gn)", norm:90, sd:3, unit:"°", req:["Ba","N","Pt","Gn"], f:c=>planeAngleAcute(_p(c,"Ba"),_p(c,"N"),_p(c,"Pt"),_p(c,"Gn"))},
 {id:"FACDEPTH", an:"Ricketts", name:"Facial Depth (FH–NPog)", norm:87, sd:3, unit:"°", req:["Po","Or","N","Pog"], f:c=>planeAngle(_p(c,"Po"),_p(c,"Or"),_p(c,"Or"),_p(c,"N"),_p(c,"Pog"),_p(c,"Pog"))},
 {id:"R_MP", an:"Ricketts", name:"Mandibular Plane Angle (FH–GoMe)", norm:26, sd:4, unit:"°", req:["Po","Or","Go","Me"], f:c=>planeAngleAcute(_p(c,"Po"),_p(c,"Or"),_p(c,"Go"),_p(c,"Me"))},
 {id:"CONVEX_R", an:"Ricketts", name:"Convexity (A to N–Pog)", norm:2, sd:2, unit:"mm", req:["A","N","Pog"], f:(c,ppm)=>signedPerpMm(c,"A","N","Pog",ppm)},
 {id:"L1APOG_D", an:"Ricketts", name:"L1 to A–Pog Angle", norm:22, sd:4, unit:"°", req:["LIT","LIA","A","Pog"], f:c=>planeAngleAcute(_p(c,"LIT"),_p(c,"LIA"),_p(c,"A"),_p(c,"Pog"))},
 {id:"L1APOG_M", an:"Ricketts", name:"L1 to A–Pog", norm:1, sd:2, unit:"mm", req:["LIT","A","Pog"], f:(c,ppm)=>signedPerpMm(c,"LIT","A","Pog",ppm)},
 {id:"U6PTV", an:"Ricketts", name:"U6 to PTV", norm:null, sd:null, unit:"mm", req:["U6T","Pt","Po","Or"], f:(c,ppm)=>{const pt=_p(c,"Pt"),u6=_p(c,"U6T"),po=_p(c,"Po"),or=_p(c,"Or");if(!pt||!u6||!po||!or||!ppm)return null;const v={x:or.x-po.x,y:or.y-po.y};const L=Math.hypot(v.x,v.y);const u={x:v.x/L,y:v.y/L};return projectOnto(u6,pt,u)/ppm;}, note:"Norm ≈ age + 3 mm"},
 {id:"LL_E_R", an:"Ricketts", name:"Lower Lip to E-Plane", norm:-2, sd:2, unit:"mm", req:["Li","Pn","PogS"], f:(c,ppm)=>signedPerpMm(c,"Li","Pn","PogS",ppm)},
 /* ---- HOLDAWAY ---- */
 {id:"HANGLE", an:"Holdaway", name:"H-Angle", norm:10, sd:3, unit:"°", req:["NS","PogS","Sn","Ls"], f:c=>{const a=_p(c,"NS")||_p(c,"N");return planeAngleAcute(a,_p(c,"PogS"),_p(c,"Sn"),_p(c,"Ls"));}},
 {id:"SKELCONV_H", an:"Holdaway", name:"Skeletal Convexity (A to N–Pog)", norm:0, sd:2, unit:"mm", req:["A","N","Pog"], f:(c,ppm)=>signedPerpMm(c,"A","N","Pog",ppm)},
 {id:"NOSEPROM", an:"Holdaway", name:"Nose Prominence (Pn to H-Line)", norm:18, sd:4, unit:"mm", req:["Pn","NS","PogS"], f:(c,ppm)=>{const a=_p(c,"NS")||_p(c,"N");const cc=Object.assign({},c);if(!_p(c,"NS")){return signedPerpMm(c,"Pn","N","PogS",ppm);}return signedPerpMm(c,"Pn","NS","PogS",ppm);}},
 {id:"SNH", an:"Holdaway", name:"Subnasale to H-Line", norm:5, sd:2, unit:"mm", req:["Sn","NS","PogS"], f:(c,ppm)=>signedPerpMm(c,"Sn",_p(c,"NS")?"NS":"N","PogS",ppm)},
 {id:"LLH", an:"Holdaway", name:"Lower Lip to H-Line", norm:0.5, sd:1, unit:"mm", req:["Li","NS","PogS"], f:(c,ppm)=>signedPerpMm(c,"Li",_p(c,"NS")?"NS":"N","PogS",ppm)},
 {id:"CHINTHICK", an:"Holdaway", name:"Soft Tissue Chin Thickness (Pog–Pog')", norm:11, sd:2, unit:"mm", req:["Pog","PogS"], f:(c,ppm)=>distMm(c,"Pog","PogS",ppm)},
 /* ---- JARABAK / BJORK ---- */
 {id:"SADDLE", an:"Jarabak", name:"Saddle Angle (N–S–Ar)", norm:123, sd:5, unit:"°", req:["N","S","Ar"], f:c=>angleAt(_p(c,"N"),_p(c,"S"),_p(c,"Ar"))},
 {id:"ARTIC", an:"Jarabak", name:"Articular Angle (S–Ar–Go)", norm:143, sd:6, unit:"°", req:["S","Ar","Go"], f:c=>angleAt(_p(c,"S"),_p(c,"Ar"),_p(c,"Go"))},
 {id:"GONIAL", an:"Jarabak", name:"Gonial Angle (Ar–Go–Me)", norm:130, sd:7, unit:"°", req:["Ar","Go","Me"], f:c=>angleAt(_p(c,"Ar"),_p(c,"Go"),_p(c,"Me"))},
 {id:"BJORKSUM", an:"Jarabak", name:"Björk Sum", norm:396, sd:6, unit:"°", req:["N","S","Ar","Go","Me"], f:c=>{const a=angleAt(_p(c,"N"),_p(c,"S"),_p(c,"Ar")),b=angleAt(_p(c,"S"),_p(c,"Ar"),_p(c,"Go")),d=angleAt(_p(c,"Ar"),_p(c,"Go"),_p(c,"Me"));return (a==null||b==null||d==null)?null:a+b+d;}},
 {id:"PFHAFH", an:"Jarabak", name:"PFH/AFH Ratio (S–Go / N–Me)", norm:62, sd:4, unit:"%", req:["S","Go","N","Me"], f:(c,ppm)=>{const a=distMm(c,"S","Go",ppm||10),b=distMm(c,"N","Me",ppm||10);return (a==null||b==null||!b)?null:100*a/b;}},
 {id:"ANS_ME_R", an:"Jarabak", name:"LAFH/TAFH (ANS–Me / N–Me)", norm:55, sd:3, unit:"%", req:["ANS","Me","N"], f:(c,ppm)=>{const a=distMm(c,"ANS","Me",ppm||10),b=distMm(c,"N","Me",ppm||10);return (a==null||b==null||!b)?null:100*a/b;}}
];
function computeAll(c, ppm){ const out={}; for(const m of MEASURES){ let v=null; try{ v=m.f(c,ppm); }catch(e){ v=null; } out[m.id]=(v==null||!isFinite(v))?null:Math.round(v*10)/10; } return out; }
/* ==================== ENGINE END ==================== */


/* ==================== APP STATE ==================== */
let session=null, coords={}, aiCoords={}, confidence={}, verified={}, source={}; // source: 'ai'|'manual'|'estimate'
let pxPerMm=null, calibrated=false, calMethod="", calStep=0, showRuler=false;
let selectedLm=null, draggingLm=null, dragMoved=false, lastDragEnd=0, placingLm=null, manualQueue=[];
let t1Baseline=null, latestMetrics={}, undoStack=[];
let showLines=true, showPoints=true, showLabels=true, showTrace=true, zoomLevel=1, spacePeek=false;
const $=id=>document.getElementById(id);
const imgElem=$("ceph-image"), svgElem=$("overlay-svg"), container=$("viewport-container"), dropzone=$("empty-dropzone");
$("pt-date").valueAsDate=new Date();

function setStatus(txt,color){ $("status-txt").innerText=txt; $("status-ind").style.backgroundColor=color||"var(--grn)"; }
function downloadBlob(blob,fn){ const u=URL.createObjectURL(blob); const a=document.createElement("a"); a.href=u; a.download=fn; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(u),4000); }
function pushUndo(){ undoStack.push(JSON.stringify({coords,verified,pxPerMm,calibrated})); if(undoStack.length>60)undoStack.shift(); }
function calStatusUpdate(){ const el=$("cal-status");
  if(calibrated){ el.style.color="var(--grn)"; el.innerHTML=`✓ Calibrated: ${pxPerMm.toFixed(2)} px/mm (${calMethod}). mm values valid.`; }
  else { el.style.color="var(--amb)"; el.innerHTML="⚠ UNCALIBRATED — angles valid, mm values are provisional."; } }

/* ==================== MODEL ==================== */
let modelLoading=false;
async function initModel(){ if(session||modelLoading)return; modelLoading=true;
  const detail=$("model-detail");
  try{
    if(typeof ort==="undefined") throw new Error("AI library (onnxruntime-web) did not download from the CDN — check your internet connection, then tap Run AI Auto-Trace to retry.");
    ort.env.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/";
    ort.env.wasm.numThreads=1;
    setStatus("Downloading AI model (~109 MB, one time — browser caches it)…","var(--amb)");
    const resp=await fetch(MODEL_URL);
    if(!resp.ok) throw new Error("Model download failed: HTTP "+resp.status);
    const total=parseInt(resp.headers.get("Content-Length")||"114226363",10);
    const reader=resp.body.getReader(); const chunks=[]; let got=0;
    while(true){ const rd=await reader.read(); if(rd.done)break; chunks.push(rd.value); got+=rd.value.length;
      setStatus("Downloading AI model… "+Math.round(got/1048576)+" / "+Math.round(total/1048576)+" MB","var(--amb)"); }
    const buf=new Uint8Array(got); let offb=0; for(const ch of chunks){ buf.set(ch,offb); offb+=ch.length; }
    setStatus("Starting AI engine…","var(--amb)");
    session=await ort.InferenceSession.create(buf,{executionProviders:["wasm"]});
    if(detail)detail.innerText="";
    setStatus("AI Ready — upload a film, calibrate, then Auto-Trace","var(--grn)");
    if(imgElem.src&&imgElem.naturalWidth&&!coords.S) runAutoTrace();
  }catch(e){ session=null;
    setStatus("AI model failed to load — tap Run AI Auto-Trace to retry. Manual Placement works now.","var(--red)");
    if(detail)detail.innerText="AI error detail: "+(e&&e.message?e.message:String(e))+" — If you opened this file directly on a phone (content:// or file:// address), use the hosted Hugging Face link instead: phone browsers restrict WebAssembly and large downloads on local files.";
  } finally{ modelLoading=false; } }
initModel();

/* ==================== FILES ==================== */
$("file-input").addEventListener("change",e=>{const f=e.target.files[0]; e.target.value=""; if(f)handleFile(f);});
$("json-input").addEventListener("change",e=>{const f=e.target.files[0]; e.target.value=""; if(f)loadJsonFile(f);});
const vw=$("viewport-wrapper");
vw.addEventListener("dragover",e=>{e.preventDefault();vw.classList.add("drag-over");});
vw.addEventListener("dragleave",()=>vw.classList.remove("drag-over"));
vw.addEventListener("drop",e=>{e.preventDefault();vw.classList.remove("drag-over"); if(e.dataTransfer.files[0])handleFile(e.dataTransfer.files[0]);});
function handleFile(file){ const n=file.name.toLowerCase();
  if(n.endsWith(".json")){loadJsonFile(file);return;}
  if(n.endsWith(".dcm")){ const r=new FileReader(); r.onload=ev=>{try{parseDicom(new Uint8Array(ev.target.result));}catch(err){alert("DICOM error: "+err.message);}}; r.readAsArrayBuffer(file); return; }
  const r=new FileReader(); r.onload=ev=>setupImage(ev.target.result,true); r.readAsDataURL(file); }
function setupImage(src,runAi,onReady){ if(runAi&&!onReady){coords={};aiCoords={};confidence={};verified={};source={};pxPerMm=null;calibrated=false;calMethod="";calStatusUpdate();}
  let fired=false; const done=()=>{ if(fired)return; fired=true; imgElem.style.display=""; dropzone.style.display="none"; container.style.display="block";
    svgElem.setAttribute("viewBox",`0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
    if(onReady)onReady(); else if(runAi&&session)runAutoTrace(); else renderAll(); };
  imgElem.onload=done; imgElem.onerror=()=>{ if(fired)return; fired=true; if(onReady)onReady(); else alert("Could not load that image."); };
  imgElem.src=src; if(imgElem.complete&&imgElem.naturalWidth>0)done(); }
function parseDicom(bytes){ if(typeof dicomParser==="undefined")throw new Error("DICOM library not loaded — check connection and reload.");
  const ds=dicomParser.parseDicom(bytes); const ts=(ds.string("x00020010")||"").trim();
  if(ts.indexOf("1.2.840.10008.1.2.4")===0)throw new Error("JPEG-compressed DICOM can't be decoded in-browser. Export uncompressed (Explicit VR Little Endian) or PNG/JPG.");
  const pn=ds.string("x00100010"); if(pn)$("pt-name").value=pn.replace(/\^/g," ").trim();
  const pid=ds.string("x00100020"); if(pid)$("pt-chart").value=pid.trim();
  const rows=ds.uint16("x00280010"), cols=ds.uint16("x00280011"); const el=ds.elements.x7fe00010;
  if(!rows||!cols||!el)throw new Error("No readable pixel data in this DICOM.");
  const bits=ds.uint16("x00280100")||16, rep=ds.uint16("x00280103")||0, mono1=(ds.string("x00280004")||"").trim()==="MONOCHROME1";
  const slope=parseFloat(ds.string("x00281053"))||1, icept=parseFloat(ds.string("x00281052"))||0;
  let wc=parseFloat(ds.string("x00281050")), ww=parseFloat(ds.string("x00281051"));
  const cv=document.createElement("canvas"); cv.width=cols; cv.height=rows; const ctx=cv.getContext("2d"); const im=ctx.createImageData(cols,rows); const N=rows*cols;
  if(bits===16){ const u8=new Uint8Array(bytes.buffer,bytes.byteOffset+el.dataOffset,N*2); const dv=new DataView(u8.buffer,u8.byteOffset,u8.byteLength);
    const vals=new Float32Array(N); let mn=Infinity,mx=-Infinity;
    for(let i=0;i<N;i++){const v=(rep===1?dv.getInt16(i*2,true):dv.getUint16(i*2,true))*slope+icept; vals[i]=v; if(v<mn)mn=v; if(v>mx)mx=v;}
    if(isNaN(wc)||isNaN(ww)||ww<=0){wc=(mn+mx)/2; ww=Math.max(1,mx-mn);} const low=wc-ww/2;
    for(let i=0;i<N;i++){let g=Math.min(255,Math.max(0,((vals[i]-low)/ww)*255)); if(mono1)g=255-g; const j=i*4; im.data[j]=im.data[j+1]=im.data[j+2]=g; im.data[j+3]=255;}
  } else { const u8=new Uint8Array(bytes.buffer,bytes.byteOffset+el.dataOffset,N);
    for(let i=0;i<N;i++){let g=mono1?255-u8[i]:u8[i]; const j=i*4; im.data[j]=im.data[j+1]=im.data[j+2]=g; im.data[j+3]=255;} }
  ctx.putImageData(im,0,0);
  const sp=ds.string("x00280030")||ds.string("x00181164");
  setupImage(cv.toDataURL("image/png"),true);
  if(sp){ const p0=parseFloat(sp.split("\\")[0]); if(p0>0){ pxPerMm=1/p0; calibrated=false; calMethod="DICOM spacing (unverified — confirm with ruler)"; calStatusUpdate();
    $("cal-status").innerHTML=`DICOM spacing gives ${pxPerMm.toFixed(2)} px/mm — <b>still flagged UNCALIBRATED</b>: detector spacing ≠ magnification-corrected scale. Confirm with the ruler.`; } } }

/* ==================== JSON SAVE / LOAD (v3) ==================== */
$("btn-save-json").addEventListener("click",()=>{ if(!coords.S){alert("No tracing to save.");return;}
  const payload={version:"3.5", patient:{name:$("pt-name").value||"Patient",chart:$("pt-chart").value||"",date:$("pt-date").value||""},
    pxPerMm, calibrated, calMethod, coords, aiCoords, confidence, verified, source, metrics:latestMetrics,
    imageSize:{w:imgElem.naturalWidth||0,h:imgElem.naturalHeight||0}, imageDataUrl:imgElem.src||null};
  downloadBlob(new Blob([JSON.stringify(payload,null,2)],{type:"application/json"}),`Ceph_v3_${(payload.patient.name).replace(/\s+/g,"_")}_${payload.patient.date}.json`);
  setStatus("Record saved (includes AI-vs-final validation data)","var(--grn)"); });
function loadJsonFile(file){ const r=new FileReader(); r.onload=e=>{ try{ const d=JSON.parse(e.target.result);
    const lc=d.coords||d.landmarks; if(!lc||!lc.S)throw new Error("Not an OrthoCeph record — no 'coords' object with landmarks. Only files saved by OrthoCeph can be loaded; send me any other format and I'll build an importer.");
    for(const k of Object.keys(lc)){ if(Array.isArray(lc[k]))lc[k]={x:lc[k][0],y:lc[k][1]}; }
    coords=JSON.parse(JSON.stringify(lc)); aiCoords=d.aiCoords?JSON.parse(JSON.stringify(d.aiCoords)):JSON.parse(JSON.stringify(d.initialAiCoords||lc));
    confidence=d.confidence||{}; verified=d.verified||{}; source=d.source||{};
    if(d.patient){$("pt-name").value=d.patient.name||"";$("pt-chart").value=d.patient.chart||""; if(d.patient.date)$("pt-date").value=d.patient.date;}
    pxPerMm=d.pxPerMm||null; calibrated=!!d.calibrated; calMethod=d.calMethod||""; calStatusUpdate();
    const after=()=>{ dropzone.style.display="none"; container.style.display="block";
      const w=(d.imageSize&&d.imageSize.w)||imgElem.naturalWidth||1200, h=(d.imageSize&&d.imageSize.h)||imgElem.naturalHeight||1200;
      svgElem.setAttribute("viewBox",`0 0 ${w} ${h}`); renderAll(); setStatus(`Record loaded (${Object.keys(coords).length} landmarks)`,"var(--grn)"); };
    if(d.imageDataUrl)setupImage(d.imageDataUrl,false,after); else { imgElem.style.display="none"; after(); }
  }catch(err){ alert("Invalid file: "+err.message); } }; r.readAsText(file); }

/* ==================== AUTO-TRACE (letterboxed, with confidence) ==================== */
async function inferPass(flip){
  const SZ=768, W=imgElem.naturalWidth, H=imgElem.naturalHeight;
  const scale=Math.min(SZ/W,SZ/H), nW=Math.round(W*scale), nH=Math.round(H*scale), padX=(SZ-nW)/2, padY=(SZ-nH)/2;
  const off=document.createElement("canvas"); off.width=SZ; off.height=SZ; const ctx=off.getContext("2d");
  ctx.fillStyle="#000"; ctx.fillRect(0,0,SZ,SZ);
  if(flip){ ctx.save(); ctx.translate(SZ,0); ctx.scale(-1,1); ctx.drawImage(imgElem,padX,padY,nW,nH); ctx.restore(); }
  else ctx.drawImage(imgElem,padX,padY,nW,nH);
  const data=ctx.getImageData(0,0,SZ,SZ).data; const fa=new Float32Array(3*SZ*SZ);
  const mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225];
  for(let i=0;i<SZ*SZ;i++){ fa[i]=(data[i*4]/255-mean[0])/std[0]; fa[SZ*SZ+i]=(data[i*4+1]/255-mean[1])/std[1]; fa[2*SZ*SZ+i]=(data[i*4+2]/255-mean[2])/std[2]; }
  const res=await session.run({[session.inputNames[0]]:new ort.Tensor("float32",fa,[1,3,SZ,SZ])});
  const out=res[session.outputNames[0]]; const hm=out.data, hmH=out.dims[2], hmW=out.dims[3];
  const pts={}, conf={};
  for(const [code,def] of Object.entries(LANDMARKS)){ if(def.model==null)continue; const ch=def.model; const off0=ch*hmH*hmW;
    let peak=-Infinity, mi=0;
    for(let j=0;j<hmH*hmW;j++){ if(hm[off0+j]>peak){peak=hm[off0+j]; mi=j;} }
    const mx=mi%hmW, my=Math.floor(mi/hmW);
    let ws=0,xs=0,ys=0; for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++){ const xx=mx+dx,yy=my+dy; if(xx<0||yy<0||xx>=hmW||yy>=hmH)continue; const w=Math.max(0,hm[off0+yy*hmW+xx]); ws+=w; xs+=xx*w; ys+=yy*w; }
    const fx=ws>0?xs/ws:mx, fy=ws>0?ys/ws:my;
    let varr=0; for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++){ const xx=mx+dx,yy=my+dy; if(xx<0||yy<0||xx>=hmW||yy>=hmH)continue; const w=Math.max(0,hm[off0+yy*hmW+xx]); varr+=w*((xx-fx)**2+(yy-fy)**2); }
    const spread=ws>0?Math.sqrt(varr/ws):9;
    let imgX=((fx/hmW)*SZ-padX)/scale; const imgY=((fy/hmH)*SZ-padY)/scale;
    if(flip) imgX=W-imgX;
    pts[code]={x:imgX,y:imgY};
    let cf=Math.max(0.03,Math.min(0.99,(peak*1.4)*(1/(1+spread*0.55))));
    if(def.tier===3)cf*=0.85; conf[code]=Math.round(cf*100)/100;
  }
  return {pts,conf};
}
async function runAutoTrace(){
  if(!session){ initModel(); alert("AI is (re)loading — watch the status line at the top. If it fails again, the red note in the Trace section shows the exact reason."); return; }
  if(!imgElem.src||!imgElem.naturalWidth)return;
  const W=imgElem.naturalWidth, H=imgElem.naturalHeight;
  setStatus("Auto-tracing\u2026","var(--amb)");
  await new Promise(r=>setTimeout(r,30));
  const a=await inferPass(false);
  pushUndo(); coords={}; aiCoords={}; confidence={}; source={}; verified={};
  for(const code of Object.keys(a.pts)){ coords[code]=a.pts[code]; confidence[code]=a.conf[code]; source[code]="ai"; verified[code]=false; }
  placeEstimates();
  aiCoords=JSON.parse(JSON.stringify(coords));
  coords.RULER_1={x:W*0.84,y:H*0.10}; coords.RULER_2={x:W*0.84,y:H*0.10+(pxPerMm?pxPerMm*10:H*0.08)};
  setStatus("Auto-trace complete — work the Review Queue, verify, then export","var(--grn)");
  renderAll();
}
/* Rough geometric starting positions for landmarks the model cannot predict.
   They are ALWAYS flagged as estimates and must be moved + verified by hand. */
function placeEstimates(){ const g=k=>coords[k]; if(!g("S")||!g("N"))return;
  /* Only Ba, Pt, D, MeS remain manual: the model has no channels for them.
     Starting points use fractions of S–N length, so they scale to any film.
     They are ALWAYS purple ESTIMATES — drag to the true position + verify. */
  const S=g("S"), N=g("N"); const L=Math.hypot(N.x-S.x,N.y-S.y); const fd=faceDir(coords);
  const est={};
  est.Ba={x:S.x-fd*0.30*L, y:S.y+0.12*L};
  if(g("ANS")) est.Pt={x:S.x+fd*0.42*L, y:g("ANS").y-0.18*L};
  if(g("B")&&g("Pog")) est.D={x:(g("B").x+g("Pog").x)/2, y:(g("B").y+g("Pog").y)/2};
  if(g("Me")) est.MeS={x:g("Me").x+fd*0.01*L, y:g("Me").y+0.055*L};
  for(const [k,v] of Object.entries(est)){ if(!coords[k]){ coords[k]=v; source[k]="estimate"; confidence[k]=0.1; verified[k]=false; } } }
$("btn-autotrace").addEventListener("click",runAutoTrace);
$("btn-retrace-all").addEventListener("click",()=>{ if(Object.keys(aiCoords).length){ pushUndo(); coords=JSON.parse(JSON.stringify(aiCoords)); verified={}; renderAll(); setStatus("Reset all to AI positions — re-verify","var(--amb)"); } else runAutoTrace(); });
$("btn-reset-single").addEventListener("click",()=>{ if(selectedLm&&aiCoords[selectedLm]){ pushUndo(); coords[selectedLm]={...aiCoords[selectedLm]}; verified[selectedLm]=false; renderAll(); } else alert("Select a landmark first."); });

/* ==================== MANUAL PLACEMENT ==================== */
$("btn-manual").addEventListener("click",()=>{ manualQueue=Object.keys(LANDMARKS).filter(k=>!coords[k]);
  if(!manualQueue.length){ alert("All landmarks already placed. Click any landmark in the list, then click the film to re-place it."); return; }
  nextPlace(); });
function nextPlace(){ placingLm=manualQueue.shift()||null; const b=$("place-banner");
  if(!placingLm){ b.style.display="none"; setStatus("Manual placement complete","var(--grn)"); renderAll(); return; }
  b.style.display="block"; b.innerHTML=`✍️ <b>Click the film to place ${placingLm} — ${LANDMARKS[placingLm].full}</b><br>${LANDMARKS[placingLm].def}<br>${manualQueue.length} remaining after this.`; renderAll(); }
$("btn-review").addEventListener("click",()=>{ const rows=Object.keys(coords).filter(k=>LANDMARKS[k]&&!verified[k])
  .sort((a,b)=>((confidence[a]??0.1)+(LANDMARKS[a].tier===3?0.25:0))-((confidence[b]??0.1)+(LANDMARKS[b].tier===3?0.25:0)));
  if(!rows.length){alert("Nothing to review — every placed landmark is verified. ✓");return;}
  selectLm(rows[0]); setStatus(`Review Queue: ${rows.length} unverified — starting with ${rows[0]} (lowest confidence / hardest)`,"var(--amb)");
  alert("Review Queue order:\n"+rows.map((k,i)=>`${i+1}. ${k} — ${LANDMARKS[k].full} — confidence ${Math.round((confidence[k]??0)*100)}%${LANDMARKS[k].tier===3?" (hard landmark)":""}${source[k]==="estimate"?" (ESTIMATE — must move)":""}`).join("\n")+"\n\nDrag each point to correct it, press V to verify, and the next in queue is one click on Review Queue away."); });

/* ==================== RENDERING ==================== */
const TRACE_LINES=[["S","N"],["Po","Or"],["N","A"],["N","B"],["N","Pog"],["S","Go"],["Go","Me"],["Go","Gn"],["ANS","PNS"],["UIT","UIA"],["LIT","LIA"],["A","Pog"],["Pn","PogS"],["Sn","Ls"],["Co","Go"],["Co","Gn"],["Ba","N"],["Pt","Gn"],["S","Ar"],["Ar","Go"]];
let activeTab="ABO";
const TABS=["ABO","Steiner","Downs","Tweed","McNamara","Ricketts","Holdaway","Jarabak"];
function confColor(k){ if(source[k]==="estimate")return "var(--pur)"; const c=confidence[k]; if(c==null)return "#94a3b8"; return c>=0.7?"#34d399":c>=0.45?"#fbbf24":"#f87171"; }
function movedMm(k){ if(!aiCoords[k]||!coords[k]||!pxPerMm)return null; return Math.hypot(coords[k].x-aiCoords[k].x,coords[k].y-aiCoords[k].y)/pxPerMm; }
function usesEstimate(m){ return m.req.some(k=>coords[k]&&!verified[k]&&(source[k]==="estimate")); }
function renderAll(){ renderSVG(); renderLmList(); renderAnalyses(); renderProgress(); }
function renderProgress(){ const ks=Object.keys(LANDMARKS).filter(k=>coords[k]); const v=ks.filter(k=>verified[k]).length;
  $("progress-bar").style.width=ks.length?(100*v/ks.length)+"%":"0%"; $("progress-txt").innerText=`${v} / ${ks.length} verified`; }
function renderSVG(){ const W=imgElem.naturalWidth,H=imgElem.naturalHeight; if(!W)return;
  svgElem.setAttribute("width",imgElem.clientWidth); svgElem.setAttribute("height",imgElem.clientHeight);
  const R=Math.max(3,W/260); let h="";
  const op=occlusalPoints(coords);
  if(showLines){ for(const [a,b] of TRACE_LINES){ if(coords[a]&&coords[b])h+=`<line x1="${coords[a].x}" y1="${coords[a].y}" x2="${coords[b].x}" y2="${coords[b].y}" stroke="rgba(56,189,248,.55)" stroke-width="${R*0.45}"/>`; }
    if(op)h+=`<line x1="${op.post.x}" y1="${op.post.y}" x2="${op.ant.x}" y2="${op.ant.y}" stroke="rgba(52,211,153,.8)" stroke-width="${R*0.5}"/>`; }
  if(showRuler||calStep>0){ if(coords.RULER_1&&coords.RULER_2){ h+=`<line x1="${coords.RULER_1.x}" y1="${coords.RULER_1.y}" x2="${coords.RULER_2.x}" y2="${coords.RULER_2.y}" stroke="#22d3ee" stroke-width="${R*0.6}"/>`;
    for(const rk of ["RULER_1","RULER_2"])h+=`<circle class="lm-handle" data-lm="${rk}" cx="${coords[rk].x}" cy="${coords[rk].y}" r="${R*1.5}" fill="#22d3ee" stroke="#fff" stroke-width="1"/>`; } }
  if(t1Baseline){ const al=getSuperCoords(); if(al){ for(const [a,b] of TRACE_LINES){ if(al[a]&&al[b])h+=`<line x1="${al[a].x}" y1="${al[a].y}" x2="${al[b].x}" y2="${al[b].y}" stroke="rgba(251,191,36,.5)" stroke-width="${R*0.4}" stroke-dasharray="6 4"/>`; }
    for(const k of Object.keys(al)){ if(LANDMARKS[k])h+=`<circle cx="${al[k].x}" cy="${al[k].y}" r="${R*0.8}" fill="none" stroke="#fbbf24" stroke-width="1.2"/>`; } } }
  if(showPoints){ for(const k of Object.keys(LANDMARKS)){ const p=coords[k]; if(!p)continue; const sel=k===selectedLm;
      h+=`<circle class="lm-handle" data-lm="${k}" cx="${p.x}" cy="${p.y}" r="${sel?R*1.7:R*1.25}" fill="${confColor(k)}" fill-opacity="${sel?1:.85}" stroke="${verified[k]?"#34d399":sel?"#fff":"#0b1220"}" stroke-width="${verified[k]?2.2:1.2}"/>`;
      if(showLabels)h+=`<text x="${p.x+R*2}" y="${p.y-R*1.4}" fill="#e2e8f0" font-size="${R*2.6}" font-weight="600" style="paint-order:stroke;stroke:#000;stroke-width:3px">${k}${verified[k]?" ✓":""}</text>`; } }
  svgElem.innerHTML=h;
  svgElem.querySelectorAll(".lm-handle").forEach(el=>{ el.addEventListener("pointerdown",e=>{ e.preventDefault(); e.stopPropagation(); draggingLm=el.getAttribute("data-lm"); dragMoved=false; pushUndo(); el.classList.add("dragging"); if(LANDMARKS[draggingLm])selectLm(draggingLm,false); });
    el.addEventListener("dblclick",()=>{ const k=el.getAttribute("data-lm"); if(aiCoords[k]){ pushUndo(); coords[k]={...aiCoords[k]}; verified[k]=false; renderAll(); } }); }); }
function renderLmList(){ const q=($("lm-search").value||"").toLowerCase(); let h="";
  for(const [k,d] of Object.entries(LANDMARKS)){ if(q&&!(k.toLowerCase().includes(q)||d.full.toLowerCase().includes(q)))continue; const p=coords[k]; const mv=movedMm(k);
    h+=`<div class="lm-row ${k===selectedLm?"sel":""}" data-k="${k}"><span class="lm-dot" style="background:${p?confColor(k):"#334155"}"></span><span class="nm"><b>${k}</b>${p&&verified[k]?' <span class="vf">✓ verified</span>':""}<span class="full">${d.full}${d.tentative?" ⚠ index tentative":""}</span></span>${p?`<span class="mv">${confidence[k]!=null?Math.round(confidence[k]*100)+"%":"manual"}${mv!=null?`<br>moved ${mv.toFixed(1)}mm`:""}</span>`:`<span class="mv">not placed</span>`}</div>`; }
  $("lm-list").innerHTML=h||'<p class="note">No match.</p>';
  $("lm-list").querySelectorAll(".lm-row").forEach(r=>r.addEventListener("click",()=>selectLm(r.getAttribute("data-k")))); }
$("lm-search").addEventListener("input",renderLmList);
function selectLm(k,focus=true){ selectedLm=k; $("selected-lm-label").innerText=k?`${k} — ${LANDMARKS[k].full}`:"None"; renderSVG(); renderLmList();
  if(focus&&coords[k]){ /* gentle status hint with the definition */ setStatus(`${k}: ${LANDMARKS[k].def}`,"var(--amb)"); } }
function renderAnalyses(){ latestMetrics=computeAll(coords,pxPerMm||10);
  let tabs=""; for(const t of TABS)tabs+=`<span class="tab ${t===activeTab?"active":""}" data-t="${t}">${t==="ABO"?"ABO Focus":t}</span>`;
  $("analysis-tabs").innerHTML=tabs; $("analysis-tabs").querySelectorAll(".tab").forEach(el=>el.addEventListener("click",()=>{activeTab=el.getAttribute("data-t"); renderAnalyses();}));
  const rows=MEASURES.filter(m=>m.an===activeTab); const t1m=t1Baseline?t1Baseline.metrics:null;
  let h=`<table><tr><th>Measurement</th><th>Norm</th><th>Value</th>${t1m?"<th>T1</th><th>Δ</th>":""}<th>Status</th></tr>`;
  for(const m of rows){ const v=latestMetrics[m.id];
    if(v==null){ h+=`<tr><td>${m.name}${m.note?`<br><span class="note">${m.note}</span>`:""}</td><td>${m.norm==null?"—":m.norm+" ±"+m.sd}</td><td class="st-na">—</td>${t1m?"<td>—</td><td>—</td>":""}<td class="st-na">missing: ${m.req.filter(k=>!coords[k]).join(", ")||"—"}</td></tr>`; continue; }
    const st=m.norm==null?"":(Math.abs(v-m.norm)<=m.sd?"Normal":v>m.norm?"High":"Low");
    const badges=(usesEstimate(m)?' <span class="badge b-est">EST</span>':"")+((m.unit==="mm"&&!calibrated)?' <span class="badge b-unc">UNCAL</span>':"")+((m.req.some(k=>coords[k]&&!verified[k]))?' <span class="badge b-rev">UNVERIFIED</span>':"");
    h+=`<tr><td>${m.name}${m.note?`<br><span class="note">${m.note}</span>`:""}</td><td>${m.norm==null?"see note":m.norm+" ±"+m.sd}</td><td><b>${v.toFixed(1)}${m.unit}</b>${badges}</td>${t1m?`<td>${t1m[m.id]==null?"—":t1m[m.id].toFixed(1)}</td><td>${t1m[m.id]==null?"—":(v-t1m[m.id]).toFixed(1)}</td>`:""}<td class="st-${st}">${st}</td></tr>`; }
  h+="</table>"; $("analysis-tables").innerHTML=h; updateDiagnosis(); }
function updateDiagnosis(){ const m=latestMetrics; if(m.ANB==null){$("diag-headline").innerText="Awaiting tracing…";return;}
  const skel=m.ANB>4?"Skeletal Class II":m.ANB<0?"Skeletal Class III":"Skeletal Class I";
  const sag=`${skel} — SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°${m.WITS!=null?`, Wits ${m.WITS} mm${calibrated?"":" (uncal)"}`:""}`;
  const vert=(m.FMA!=null&&m.FMA>29)||(m.SNGOGN!=null&&m.SNGOGN>37)?"Hyperdivergent (high angle)":(m.FMA!=null&&m.FMA<21)||(m.SNGOGN!=null&&m.SNGOGN<27)?"Hypodivergent (low angle)":"Normodivergent";
  const dent=`U1-SN ${m.U1SN}° (${m.U1SN>107?"proclined":m.U1SN<97?"retroclined":"normal"}), IMPA ${m.IMPA}° (${m.IMPA>95?"proclined":m.IMPA<85?"retroclined":"normal"}), IIA ${m.IIA}°`;
  const soft=`UL E-line ${m.UL_E} mm, LL E-line ${m.LL_E} mm`;
  $("diag-headline").innerText=`${skel} • ${vert}`; $("diag-sagittal").innerText=sag; $("diag-vertical").innerText=vert; $("diag-dental").innerText=dent; $("diag-soft").innerText=soft;
  latestMetrics._diag={skel,vert,dent,soft}; }

/* ==================== INTERACTION ==================== */
function getSVGCoords(e){ const pt=svgElem.createSVGPoint(); pt.x=e.clientX; pt.y=e.clientY; return pt.matrixTransform(svgElem.getScreenCTM().inverse()); }
function updateLoupe(p,name){ if(!imgElem.src)return; $("loupe-box").style.display="block"; $("loupe-label").innerText=name;
  const cv=$("loupe-canvas"),ctx=cv.getContext("2d"); const size=150,zoom=3,src=size/zoom;
  ctx.clearRect(0,0,size,size); ctx.filter=imgElem.style.filter||"none";
  ctx.drawImage(imgElem,p.x-src/2,p.y-src/2,src,src,0,0,size,size); ctx.filter="none";
  ctx.strokeStyle="#38bdf8"; ctx.lineWidth=1.5; ctx.beginPath();
  ctx.moveTo(size/2,0);ctx.lineTo(size/2,size/2-6);ctx.moveTo(size/2,size/2+6);ctx.lineTo(size/2,size);
  ctx.moveTo(0,size/2);ctx.lineTo(size/2-6,size/2);ctx.moveTo(size/2+6,size/2);ctx.lineTo(size,size/2);ctx.stroke(); }
window.addEventListener("pointermove",e=>{ if(!draggingLm||!coords[draggingLm])return; dragMoved=true; const p=getSVGCoords(e);
  coords[draggingLm].x=p.x; coords[draggingLm].y=p.y;
  if(draggingLm==="RULER_1"||draggingLm==="RULER_2"){ const d=Math.hypot(coords.RULER_2.x-coords.RULER_1.x,coords.RULER_2.y-coords.RULER_1.y); if(d>1){ pxPerMm=d/10; calibrated=true; calMethod="10 mm ruler"; calStatusUpdate(); } }
  else if(LANDMARKS[draggingLm]&&source[draggingLm]==="ai") source[draggingLm]="ai-edited";
  updateLoupe(p,draggingLm); renderAll(); });
window.addEventListener("pointerup",()=>{ if(draggingLm){ if(dragMoved)lastDragEnd=Date.now(); draggingLm=null; dragMoved=false; $("loupe-box").style.display="none"; renderAll(); } });
container.addEventListener("click",e=>{ if(Date.now()-lastDragEnd<300)return; if(!imgElem.naturalWidth)return; const p=getSVGCoords(e);
  if(placingLm){ pushUndo(); coords[placingLm]={x:p.x,y:p.y}; source[placingLm]="manual"; confidence[placingLm]=null; verified[placingLm]=false; selectLm(placingLm,false); nextPlace(); return; }
  if(selectedLm&&!coords[selectedLm]&&LANDMARKS[selectedLm]){ pushUndo(); coords[selectedLm]={x:p.x,y:p.y}; source[selectedLm]="manual"; confidence[selectedLm]=null; verified[selectedLm]=false; renderAll(); return; }
  if(calStep===1){ coords.RULER_1={x:p.x,y:p.y}; coords.RULER_2={x:p.x,y:p.y+80}; calStep=2; showRuler=true; $("btn-cal").innerText="Now click the 10 mm mark…"; renderAll(); return; }
  if(calStep===2){ coords.RULER_2={x:p.x,y:p.y}; const d=Math.hypot(coords.RULER_2.x-coords.RULER_1.x,coords.RULER_2.y-coords.RULER_1.y);
    if(d>1){ pxPerMm=d/10; calibrated=true; calMethod="10 mm ruler"; calStatusUpdate(); } calStep=0; $("btn-cal").innerText="📐 Place 10 mm Ruler"; renderAll(); } });
$("btn-cal").addEventListener("click",()=>{ if(!imgElem.src&&!coords.S){alert("Upload a film first.");return;} showRuler=true; calStep=1; $("btn-cal").innerText="Click the 0 mm mark on the ruler…"; renderAll(); });
window.addEventListener("keydown",e=>{ const tag=document.activeElement&&document.activeElement.tagName;
  if(e.code==="Space"&&!["INPUT","SELECT","TEXTAREA"].includes(tag)){ e.preventDefault(); if(!spacePeek){spacePeek=true; svgElem.style.opacity="0";} return; }
  if(["INPUT","TEXTAREA"].includes(tag))return;
  if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="z"){ const s=undoStack.pop(); if(s){ const d=JSON.parse(s); coords=d.coords; verified=d.verified; pxPerMm=d.pxPerMm; calibrated=d.calibrated; calStatusUpdate(); renderAll(); } return; }
  if(!selectedLm||!coords[selectedLm])return;
  const step=e.shiftKey?0.1:0.5; let used=true;
  if(e.key==="ArrowLeft")coords[selectedLm].x-=step; else if(e.key==="ArrowRight")coords[selectedLm].x+=step;
  else if(e.key==="ArrowUp")coords[selectedLm].y-=step; else if(e.key==="ArrowDown")coords[selectedLm].y+=step;
  else if(e.key.toLowerCase()==="v"){ verified[selectedLm]=true; setStatus(`${selectedLm} verified ✓`,"var(--grn)"); }
  else used=false;
  if(used){ e.preventDefault(); renderAll(); } });
window.addEventListener("keyup",e=>{ if(e.code==="Space"){ spacePeek=false; svgElem.style.opacity="1"; } });
$("btn-verify-sel").addEventListener("click",()=>{ if(selectedLm&&coords[selectedLm]){ verified[selectedLm]=true; renderAll(); } });
$("btn-verify-all-conf").addEventListener("click",()=>{ let n=0; for(const k of Object.keys(coords)){ if(LANDMARKS[k]&&source[k]==="ai"&&(confidence[k]||0)>=0.7){ verified[k]=true; n++; } } renderAll(); setStatus(`Verified ${n} high-confidence AI points — hard/low-confidence points still need your eyes`,"var(--grn)"); });

/* ==================== SUPERIMPOSITION ==================== */
$("btn-lock-t1").addEventListener("click",()=>{ if(!coords.S){alert("Trace T1 first.");return;}
  t1Baseline={coords:JSON.parse(JSON.stringify(coords)),metrics:JSON.parse(JSON.stringify(latestMetrics)),date:$("pt-date").value||"T1"};
  $("super-status").innerHTML=`<span style="color:#5eead4;font-weight:700">✓ T1 locked (${t1Baseline.date})</span> — now load the T2 film.`; renderAll(); });
$("btn-clear-t1").addEventListener("click",()=>{ t1Baseline=null; $("super-status").innerText="No T1 baseline locked."; renderAll(); });
$("super-mode").addEventListener("change",renderAll);
function getSuperCoords(){ if(!t1Baseline||!t1Baseline.coords.S||!coords.S)return null; const mode=$("super-mode").value;
  const t=t1Baseline.coords; let o1=t.S,o2=coords.S,a1=0,a2=0;
  if(mode==="MAXILLARY"&&t.PNS&&t.ANS&&coords.PNS&&coords.ANS){ o1=t.PNS; o2=coords.PNS; a1=Math.atan2(t.ANS.y-t.PNS.y,t.ANS.x-t.PNS.x); a2=Math.atan2(coords.ANS.y-coords.PNS.y,coords.ANS.x-coords.PNS.x); }
  else if(mode==="MANDIBULAR"&&t.Me&&t.Go&&coords.Me&&coords.Go){ o1=t.Me; o2=coords.Me; a1=Math.atan2(t.Go.y-t.Me.y,t.Go.x-t.Me.x); a2=Math.atan2(coords.Go.y-coords.Me.y,coords.Go.x-coords.Me.x); }
  else { if(!t.N||!coords.N)return null; a1=Math.atan2(t.N.y-t.S.y,t.N.x-t.S.x); a2=Math.atan2(coords.N.y-coords.S.y,coords.N.x-coords.S.x); }
  const d=a2-a1, co=Math.cos(d), si=Math.sin(d), out={};
  for(const [k,pt] of Object.entries(t)){ const dx=pt.x-o1.x, dy=pt.y-o1.y; out[k]={x:o2.x+dx*co-dy*si, y:o2.y+dx*si+dy*co}; } return out; }

/* ==================== EXPORTS / MISC ==================== */
$("btn-export-csv").addEventListener("click",()=>{ if(latestMetrics.ANB==null){alert("Trace a film first.");return;}
  const nm=$("pt-name").value||"Patient", ch=$("pt-chart").value||"", dt=$("pt-date").value||"";
  let csv="Patient,Chart,Date,Analysis,Measurement,Norm,SD,Value,Unit,Status,Calibrated,UsesEstimate\n";
  for(const m of MEASURES){ const v=latestMetrics[m.id]; if(v==null)continue; const st=m.norm==null?"":(Math.abs(v-m.norm)<=m.sd?"Normal":v>m.norm?"High":"Low");
    csv+=`"${nm}","${ch}","${dt}","${m.an}","${m.name}","${m.norm??""}","${m.sd??""}",${v.toFixed(1)},"${m.unit}","${st}","${calibrated}","${usesEstimate(m)}"\n`; }
  downloadBlob(new Blob([csv],{type:"text/csv"}),`Ceph_v3_${nm.replace(/\s+/g,"_")}_${dt}.csv`); });
$("btn-copy-note").addEventListener("click",()=>{ if(latestMetrics.ANB==null)return; const m=latestMetrics, d=m._diag||{};
  const unver=ABO_REQUIRED.filter(k=>coords[k]&&!verified[k]);
  const note=[`CEPHALOMETRIC ANALYSIS — ${$("pt-name").value||"Patient"} (${$("pt-date").value||""}) — OrthoCeph Pro v3.5`,
   `Diagnosis: ${d.skel||""} • ${d.vert||""}`,
   `Sagittal: SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°, Wits ${m.WITS} mm`,
   `Vertical: FMA ${m.FMA}°, SN-GoGn ${m.SNGOGN}°`,
   `Dental: U1-SN ${m.U1SN}°, U1-NA ${m.U1NA_D}°/${m.U1NA_M}mm, L1-NB ${m.L1NB_D}°/${m.L1NB_M}mm, IMPA ${m.IMPA}°, IIA ${m.IIA}°, OJ ${m.OJ} mm, OB ${m.OB} mm`,
   `Soft tissue: UL E-line ${m.UL_E} mm, LL E-line ${m.LL_E} mm, H-angle ${m.HANGLE}°`,
   `Calibration: ${calibrated?calMethod+" ("+pxPerMm.toFixed(2)+" px/mm)":"UNCALIBRATED — mm values provisional"}`,
   unver.length?`⚠ Unverified ABO landmarks: ${unver.join(", ")}`:"✓ All ABO landmarks verified"].join("\n");
  const done=()=>{ $("btn-copy-note").innerText="✓ Copied"; setTimeout(()=>$("btn-copy-note").innerText="📋 Copy Clinical Note",1800); };
  if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(note).then(done).catch(()=>{prompt("Copy the note:",note);});
  else prompt("Copy the note:",note); });
$("btn-print").addEventListener("click",()=>{ buildPrintReport(); window.print(); });
function buildPrintReport(){ const pr=$("print-report"); const m=latestMetrics;
  const ks=Object.keys(LANDMARKS).filter(k=>coords[k]); const nv=ks.filter(k=>verified[k]).length;
  let tables="";
  for(const t of TABS){ const rows=MEASURES.filter(x=>x.an===t); if(!rows.length)continue;
    tables+=`<h2>${t==="ABO"?"ABO Focus":t} Analysis</h2><table><tr><th>Measurement</th><th>Norm</th><th>Value</th><th>Status</th></tr>`;
    for(const mm of rows){ const v=m[mm.id];
      if(v==null){ tables+=`<tr><td>${mm.name}</td><td>${mm.norm==null?"—":mm.norm+" ±"+mm.sd}</td><td>—</td><td>missing landmark</td></tr>`; continue; }
      const st=mm.norm==null?"":(Math.abs(v-mm.norm)<=mm.sd?"Normal":v>mm.norm?"High":"Low");
      tables+=`<tr><td>${mm.name}</td><td>${mm.norm==null?"see note":mm.norm+" ±"+mm.sd}</td><td>${v.toFixed(1)} ${mm.unit}${usesEstimate(mm)?" (estimate)":""}${mm.unit==="mm"&&!calibrated?" (uncalibrated)":""}</td><td>${st}</td></tr>`; }
    tables+="</table>"; }
  const film=(coords.S&&imgElem.src)?`<div class="pr-film"><img src="${imgElem.src}"><svg viewBox="${svgElem.getAttribute("viewBox")||""}">${svgElem.innerHTML}</svg></div>`:"";
  pr.innerHTML=`<h1>Cephalometric Report — OrthoCeph Pro v3.5</h1>
   <div class="pr-meta">Patient: <b>${$("pt-name").value||"—"}</b> &nbsp;|&nbsp; Chart: ${$("pt-chart").value||"—"} &nbsp;|&nbsp; Date: ${$("pt-date").value||"—"}<br>
   Calibration: ${calibrated?calMethod+" ("+pxPerMm.toFixed(2)+" px/mm)":"UNCALIBRATED — mm values provisional"} &nbsp;|&nbsp; Landmarks verified: ${nv} / ${ks.length}</div>
   <div class="pr-diag"><b>${$("diag-headline").innerText}</b><br>Sagittal: ${$("diag-sagittal").innerText}<br>Vertical: ${$("diag-vertical").innerText}<br>Dental: ${$("diag-dental").innerText}<br>Soft tissue: ${$("diag-soft").innerText}</div>
   ${film}${tables}
   <div class="pr-foot">AI-assisted tracing (HRNet-W32 cepha29; published validation MRE 1.24 mm, 83.1% of points within 2 mm). Every landmark requires clinician verification before clinical use; values marked (estimate) depend on an unverified landmark and (uncalibrated) values await ruler calibration. Generated ${new Date().toLocaleString()}.</div>`;
}
function setZoom(z){ zoomLevel=Math.min(3,Math.max(0.4,z)); container.style.transform=`scale(${zoomLevel})`; }
$("btn-zoom-in").addEventListener("click",()=>setZoom(zoomLevel+0.2));
$("btn-zoom-out").addEventListener("click",()=>setZoom(zoomLevel-0.2));
$("btn-zoom-reset").addEventListener("click",()=>setZoom(1));
vw.addEventListener("wheel",e=>{ if(!coords.S)return; e.preventDefault(); setZoom(zoomLevel+(e.deltaY<0?0.1:-0.1)); },{passive:false});
$("btn-bright").addEventListener("click",()=>{ const b=$("filter-box"); b.style.display=b.style.display==="none"?"block":"none"; });
function applyFilters(){ imgElem.style.filter=`brightness(${$("brightness").value}) contrast(${$("contrast").value}) invert(${$("invert").checked?1:0})`; }
$("brightness").addEventListener("input",applyFilters); $("contrast").addEventListener("input",applyFilters); $("invert").addEventListener("change",applyFilters);
$("reset-filters").addEventListener("click",()=>{ $("brightness").value=1; $("contrast").value=1; $("invert").checked=false; applyFilters(); });
function mkToggle(id,get,set){ $(id).addEventListener("click",()=>{ const v=!get(); set(v); $(id).innerText=$(id).innerText.replace(/ON|OFF/,v?"ON":"OFF"); renderAll(); }); }
mkToggle("tog-lines",()=>showLines,v=>showLines=v); mkToggle("tog-points",()=>showPoints,v=>showPoints=v);
mkToggle("tog-labels",()=>showLabels,v=>showLabels=v); mkToggle("tog-trace",()=>showTrace,v=>{showTrace=v; showLines=v;});
$("btn-next-patient").addEventListener("click",()=>{ if(!confirm("Clear this patient and start fresh? Unsaved work will be lost."))return;
  coords={}; aiCoords={}; confidence={}; verified={}; source={}; t1Baseline=null; pxPerMm=null; calibrated=false; calMethod=""; calStep=0; showRuler=false; selectedLm=null; undoStack=[];
  imgElem.src=""; container.style.display="none"; dropzone.style.display="flex"; svgElem.innerHTML="";
  $("pt-name").value=""; $("pt-chart").value=""; $("pt-date").valueAsDate=new Date(); $("super-status").innerText="No T1 baseline locked.";
  $("selected-lm-label").innerText="None"; calStatusUpdate(); renderAll(); setStatus("Ready for next patient","var(--amb)"); });
window.addEventListener("resize",()=>renderSVG());
/* ==================== NUDGE BAR (touch / no-keyboard control) ==================== */
let nudgeStep=1;
function reviewOrder(){ return Object.keys(coords).filter(k=>LANDMARKS[k]&&!verified[k])
  .sort((a,b)=>((confidence[a]??0.1)+(LANDMARKS[a].tier===3?0.25:0))-((confidence[b]??0.1)+(LANDMARKS[b].tier===3?0.25:0))); }
function updateNudgeBar(){ const bar=$("nudge-bar"); if(!bar)return;
  if(selectedLm&&coords[selectedLm]){ bar.classList.add("show"); $("nb-name").innerText=selectedLm+" — "+LANDMARKS[selectedLm].full+(verified[selectedLm]?" ✓":""); }
  else bar.classList.remove("show"); }
document.querySelectorAll("#nudge-bar button[data-dx]").forEach(b=>b.addEventListener("click",()=>{
  if(!selectedLm||!coords[selectedLm])return; pushUndo();
  coords[selectedLm].x+=parseFloat(b.getAttribute("data-dx"))*nudgeStep;
  coords[selectedLm].y+=parseFloat(b.getAttribute("data-dy"))*nudgeStep;
  if(source[selectedLm]==="ai")source[selectedLm]="ai-edited"; renderAll(); }));
$("nb-step").addEventListener("click",()=>{ nudgeStep=nudgeStep===1?0.2:1; $("nb-step").innerText="Step: "+(nudgeStep===1?"1px":"0.2px"); });
$("nb-verify").addEventListener("click",()=>{ if(selectedLm&&coords[selectedLm]){ verified[selectedLm]=true; renderAll(); updateNudgeBar(); } });
$("nb-next").addEventListener("click",()=>{ const q=reviewOrder(); if(!q.length){ alert("All placed landmarks are verified. ✓"); return; }
  const nxt=q.find(k=>k!==selectedLm)||q[0]; selectLm(nxt); });
const _selectLmOrig=selectLm;
selectLm=function(k,focus=true){ _selectLmOrig(k,focus); updateNudgeBar(); };
calStatusUpdate(); renderAll();
</script>
</body>
</html>