File size: 122,742 Bytes
1d8850f
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f37c14
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
 
1d8850f
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
 
1d8850f
 
fe8ed1d
1d8850f
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
 
1d8850f
 
fe8ed1d
 
1d8850f
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
fe8ed1d
 
1d8850f
 
fe8ed1d
 
1d8850f
fe8ed1d
 
1d8850f
fe8ed1d
1d8850f
 
fe8ed1d
 
 
 
 
 
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
 
1d8850f
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
 
 
6f37c14
fe8ed1d
 
 
 
 
6f37c14
1d8850f
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
 
 
 
1d8850f
fe8ed1d
 
 
 
 
 
 
 
1d8850f
fe8ed1d
 
1d8850f
 
 
 
 
 
fe8ed1d
1d8850f
 
 
fe8ed1d
 
 
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
 
 
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
1d8850f
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
fe8ed1d
 
1d8850f
 
 
 
 
 
 
 
 
 
fe8ed1d
 
6f37c14
 
 
fe8ed1d
6f37c14
fe8ed1d
6f37c14
 
fe8ed1d
 
6f37c14
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
fe8ed1d
1d8850f
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
 
 
 
 
 
 
1d8850f
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
1d8850f
fe8ed1d
1d8850f
fe8ed1d
1d8850f
8567f51
fe8ed1d
 
 
1d8850f
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
fe8ed1d
1d8850f
 
 
fe8ed1d
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
 
 
 
 
1d8850f
 
fe8ed1d
 
 
 
8567f51
1d8850f
fe8ed1d
 
1d8850f
 
fe8ed1d
1d8850f
fe8ed1d
 
 
8567f51
fe8ed1d
 
 
1d8850f
 
fe8ed1d
1d8850f
 
fe8ed1d
 
8567f51
 
1d8850f
 
fe8ed1d
 
 
1d8850f
 
 
fe8ed1d
1d8850f
 
fe8ed1d
1d8850f
fe8ed1d
1d8850f
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
1d8850f
fe8ed1d
 
 
 
 
 
 
 
 
1d8850f
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
6f37c14
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
1d8850f
 
 
fe8ed1d
 
8567f51
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
fe8ed1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8850f
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
 
 
 
 
 
 
 
 
 
1d8850f
fe8ed1d
1d8850f
fe8ed1d
1d8850f
fe8ed1d
1d8850f
 
 
fe8ed1d
1d8850f
 
 
 
 
fe8ed1d
 
 
1d8850f
 
 
fe8ed1d
6f37c14
 
1d8850f
fe8ed1d
 
 
 
 
1d8850f
 
fe8ed1d
 
 
1d8850f
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
 
6f37c14
 
 
 
 
 
fe8ed1d
6f37c14
 
 
fe8ed1d
6f37c14
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
1d8850f
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
6f37c14
 
 
fe8ed1d
 
 
 
 
 
6f37c14
 
 
 
 
 
fe8ed1d
6f37c14
 
 
 
 
 
fe8ed1d
 
 
 
8567f51
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
6f37c14
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
fe8ed1d
 
1d8850f
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
fe8ed1d
 
 
 
1d8850f
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
1d8850f
 
fe8ed1d
 
 
 
1d8850f
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
 
6f37c14
 
fe8ed1d
 
 
 
 
 
 
 
6f37c14
 
fe8ed1d
 
 
 
 
 
 
 
6f37c14
 
fe8ed1d
 
 
6f37c14
 
fe8ed1d
 
6f37c14
 
1d8850f
 
 
fe8ed1d
1d8850f
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
fe8ed1d
1d8850f
 
 
 
fe8ed1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8850f
fe8ed1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8850f
fe8ed1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8850f
fe8ed1d
1d8850f
 
 
 
 
fe8ed1d
 
 
 
 
1d8850f
 
fe8ed1d
 
 
 
 
1d8850f
 
fe8ed1d
 
 
 
 
1d8850f
fe8ed1d
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
fe8ed1d
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8ed1d
1d8850f
 
fe8ed1d
 
 
 
 
 
 
1d8850f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>OrthoCeph Pro | Dual AI ABO, McNamara, Tweed & CVM Suite</title>
  <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/ort.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg-dark: #090d16;
      --surface-dark: #111827;
      --surface-card: #1e293b;
      --surface-border: #334155;
      --accent: #2563eb;
      --accent-hover: #1d4ed8;
      --text-main: #f8fafc;
      --text-muted: #94a3b8;
      --status-green: #10b981;
      --status-red: #f43f5e;
      --status-amber: #f59e0b;
      --ruler-cyan: #06b6d4;
      --teal-accent: #14b8a6;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      background-color: var(--bg-dark);
      color: var(--text-main);
      height: 100vh;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      -webkit-font-smoothing: antialiased;
    }

    /* Header Bar */
    header {
      background: var(--surface-dark);
      border-bottom: 1px solid var(--surface-border);
      height: 56px;
      padding: 0 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-shrink: 0;
      z-index: 20;
    }

    .brand { display: flex; align-items: center; gap: 10px; }
    .brand-icon {
      width: 32px; height: 32px;
      background: linear-gradient(135deg, #3b82f6, #1d4ed8);
      border-radius: 8px; display: flex; align-items: center;
      justify-content: center; font-weight: 800; font-size: 16px; color: white;
    }
    .brand-title { font-size: 14.5px; font-weight: 700; letter-spacing: -0.02em; }
    .brand-subtitle { font-size: 9.5px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; }

    .header-actions { display: flex; align-items: center; gap: 6px; }

    #status-badge {
      display: flex; align-items: center; gap: 6px; font-size: 11px;
      font-weight: 600; background: rgba(30, 41, 59, 0.9);
      border: 1px solid var(--surface-border); padding: 5px 10px;
      border-radius: 20px; color: var(--text-muted);
    }
    #status-badge .indicator { width: 8px; height: 8px; border-radius: 50%; background-color: var(--status-amber); }

    .btn {
      background: var(--accent); color: white; border: none; padding: 6px 10px;
      border-radius: 6px; font-weight: 600; font-size: 11px; cursor: pointer;
      display: inline-flex; align-items: center; justify-content: center; gap: 5px;
      transition: all 0.15s ease; white-space: nowrap;
    }
    .btn svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2.2; }
    .btn:hover:not(:disabled) { background: var(--accent-hover); }
    .btn:disabled { background: #1e293b; color: #64748b; cursor: not-allowed; }
    .btn-secondary { background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main); }
    .btn-secondary:hover { background: #334155; }
    .btn-danger { background: rgba(244, 63, 94, 0.15); border: 1px solid rgba(244, 63, 94, 0.4); color: #fda4af; }
    .btn-danger:hover { background: rgba(244, 63, 94, 0.25); }
    .btn-teal { background: rgba(20, 184, 166, 0.15); border: 1px solid rgba(20, 184, 166, 0.45); color: #5eead4; }
    .btn-teal:hover { background: rgba(20, 184, 166, 0.28); }

    /* Workspace */
    .workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }

    .sidebar {
      width: 325px; background: var(--surface-dark);
      border-right: 1px solid var(--surface-border);
      padding: 12px; display: flex; flex-direction: column;
      gap: 10px; overflow-y: auto; flex-shrink: 0;
    }

    .section-header {
      font-size: 10px; font-weight: 700; text-transform: uppercase;
      letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 4px;
      display: flex; justify-content: space-between; align-items: center;
    }

    .card {
      background: var(--surface-card); border: 1px solid var(--surface-border);
      border-radius: 8px; padding: 9px; display: flex; flex-direction: column; gap: 6px;
    }

    .form-group { display: flex; flex-direction: column; gap: 2px; }
    .form-group label { font-size: 9.5px; font-weight: 600; color: var(--text-muted); }

    .input-field {
      background: #0f172a; border: 1px solid var(--surface-border);
      border-radius: 5px; padding: 5px 8px; color: var(--text-main);
      font-size: 11.5px; outline: none; width: 100%;
    }
    .input-field:focus { border-color: #3b82f6; }

    .mode-group { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
    .mode-btn {
      background: #0f172a; border: 1px solid var(--surface-border);
      color: var(--text-muted); padding: 5px 3px; border-radius: 5px;
      font-size: 10px; font-weight: 600; cursor: pointer; text-align: center;
      transition: all 0.15s;
    }
    .mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; }

    .toggle-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px; }
    .toggle-pill {
      background: #0f172a; border: 1px solid var(--surface-border);
      color: var(--text-muted); padding: 4px; border-radius: 5px;
      font-size: 10px; font-weight: 600; cursor: pointer; text-align: center;
    }
    .toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }

    .cvm-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; }
    .cvm-btn {
      background: #0f172a; border: 1px solid var(--surface-border);
      color: var(--text-muted); padding: 5px 2px; border-radius: 4px;
      font-size: 10px; font-weight: 700; cursor: pointer; text-align: center;
    }
    .cvm-btn.active { background: var(--teal-accent); color: #042f2e; border-color: #5eead4; }

    .slider-row {
      display: flex; align-items: center; justify-content: space-between;
      font-size: 10.5px; color: var(--text-muted);
    }
    .slider-row input[type="range"] { width: 130px; accent-color: var(--accent); cursor: pointer; }

    #norms-drawer {
      display: none; flex-direction: column; gap: 5px; max-height: 170px;
      overflow-y: auto; padding-top: 5px; border-top: 1px solid var(--surface-border);
    }
    .norm-edit-row {
      display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 4px; align-items: center; font-size: 10.5px;
    }
    .norm-edit-row input {
      background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-main);
      padding: 3px 4px; border-radius: 4px; font-size: 10.5px; width: 100%; text-align: center;
    }

    /* Viewport */
    .viewport {
      flex: 1; background: #05070c; position: relative;
      overflow: hidden; display: flex; align-items: center; justify-content: center;
    }
    .viewport.drag-over {
      outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
    }

    #empty-dropzone {
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      gap: 10px; color: var(--text-muted); text-align: center; padding: 35px;
      border: 2px dashed var(--surface-border); border-radius: 14px; cursor: pointer;
    }
    #empty-dropzone:hover { border-color: #3b82f6; color: var(--text-main); }

    #viewport-container { position: relative; transform-origin: 0 0; user-select: none; cursor: crosshair; display: none; }
    #ceph-image { display: block; max-height: 85vh; max-width: 100%; pointer-events: none; border-radius: 4px; }
    #overlay-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; }

    #loupe-box {
      position: absolute; top: 14px; left: 14px; width: 140px; height: 140px;
      border: 2px solid #38bdf8; border-radius: 50%; overflow: hidden;
      background: #000; box-shadow: 0 8px 24px rgba(0,0,0,0.7);
      display: none; z-index: 25; pointer-events: none;
    }
    #loupe-canvas { width: 100%; height: 100%; display: block; }
    #loupe-label {
      position: absolute; bottom: 6px; left: 50%; transform: translateX(-50%);
      background: rgba(15, 23, 42, 0.88); color: #38bdf8; font-size: 9.5px;
      font-weight: 700; padding: 2px 7px; border-radius: 8px;
    }

    .viewport-overlay-controls {
      position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%);
      background: rgba(17, 24, 39, 0.92); backdrop-filter: blur(8px);
      border: 1px solid var(--surface-border); border-radius: 25px;
      padding: 4px 12px; display: flex; align-items: center; gap: 7px; z-index: 10;
      white-space: nowrap;
    }
    .viewport-overlay-controls button {
      background: none; border: none; color: var(--text-main);
      cursor: pointer; font-size: 11px; font-weight: 600; padding: 2px 5px;
    }
    .viewport-overlay-controls button:hover { color: #60a5fa; }
    .shortcut-hint { font-size: 9.5px; color: var(--text-muted); }

    .landmark-handle { pointer-events: all; cursor: grab; transition: r 0.1s ease; }
    .landmark-handle:hover { r: 7.5 !important; stroke: #ffffff !important; stroke-width: 2.5px !important; }
    .landmark-handle.dragging { cursor: grabbing !important; r: 9 !important; fill: #38bdf8 !important; }
    .landmark-text {
      font-family: 'Inter', sans-serif; font-size: 10px; font-weight: 700;
      fill: #ffffff; paint-order: stroke; stroke: #000000; stroke-width: 3px;
      pointer-events: none; user-select: none;
    }

    /* Right Analysis Panel */
    .analysis-panel {
      width: 535px; background: var(--surface-dark);
      border-left: 1px solid var(--surface-border);
      padding: 12px 16px; display: flex; flex-direction: column;
      gap: 10px; overflow-y: auto; flex-shrink: 0;
    }

    .diagnosis-banner {
      background: linear-gradient(135deg, rgba(37, 99, 235, 0.14), rgba(15, 23, 42, 0.92));
      border: 1px solid #3b82f6; border-radius: 8px; padding: 10px 12px;
      display: flex; flex-direction: column; gap: 5px;
    }
    .diagnosis-headline { font-size: 12px; font-weight: 800; color: #93c5fd; }
    .diagnosis-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 10px; font-size: 10.5px; }
    .diag-item { display: flex; flex-direction: column; }
    .diag-label { font-size: 9px; color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
    .diag-val { font-weight: 600; color: var(--text-main); }

    .analysis-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 11px; }
    .analysis-table th {
      text-align: left; padding: 5px 6px; font-weight: 600; font-size: 9px;
      text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);
      border-bottom: 1px solid var(--surface-border);
    }
    .analysis-table td { padding: 5px 6px; border-bottom: 1px solid rgba(51, 65, 85, 0.35); }
    .metric-name { font-weight: 600; color: #e2e8f0; }
    .metric-norm { color: var(--text-muted); font-size: 10px; }
    .metric-val { font-weight: 700; font-feature-settings: "tnum"; }
    .metric-diff { font-weight: 600; font-size: 10px; font-feature-settings: "tnum"; }

    .pill { display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 8px; font-size: 9px; font-weight: 600; }
    .pill-normal { background: rgba(16, 185, 129, 0.15); color: var(--status-green); }
    .pill-deviated { background: rgba(244, 63, 94, 0.15); color: var(--status-red); }
    .pill-neutral { background: #1e293b; color: var(--text-muted); }

    /* Security Modal Lock Screen */
    #security-gate {
      position: fixed; top: 0; left: 0; right: 0; bottom: 0;
      background: rgba(5, 7, 12, 0.96); backdrop-filter: blur(14px);
      z-index: 999999; display: none; align-items: center; justify-content: center;
    }
    .security-card {
      background: var(--surface-card); border: 1px solid var(--surface-border);
      border-radius: 12px; padding: 24px; width: 340px; display: flex;
      flex-direction: column; gap: 14px; box-shadow: 0 20px 40px rgba(0,0,0,0.8);
      text-align: center;
    }

    /* Mobile Bottom Tab Bar */
    .mobile-nav-bar {
      display: none; height: 50px; background: var(--surface-dark);
      border-top: 1px solid var(--surface-border); position: fixed;
      bottom: 0; left: 0; right: 0; z-index: 40; grid-template-columns: repeat(3, 1fr);
    }
    .mobile-tab-btn {
      background: none; border: none; color: var(--text-muted); display: flex;
      flex-direction: column; align-items: center; justify-content: center; gap: 2px;
      font-size: 9.5px; font-weight: 600; cursor: pointer; padding: 4px;
    }
    .mobile-tab-btn svg { width: 17px; height: 17px; fill: currentColor; }
    .mobile-tab-btn.active { color: #38bdf8; background: rgba(56, 189, 248, 0.08); }

    @media screen and (max-width: 1023px) {
      body { height: 100dvh; }
      header { padding: 0 10px; height: 50px; }
      .brand-subtitle { display: none; }
      .header-actions { gap: 4px; }
      .header-actions .btn { padding: 5px 7px; }
      .header-actions .btn .btn-text { display: none; }
      #status-badge { padding: 3px 6px; font-size: 9.5px; }
      #status-txt { display: none; }

      .workspace { height: calc(100dvh - 50px - 50px); flex-direction: column; position: relative; }
      .mobile-nav-bar { display: grid; }
      .sidebar, .viewport, .analysis-panel { width: 100% !important; height: 100% !important; border: none !important; flex: 1; }

      body.tab-tools .sidebar { display: flex !important; }
      body.tab-tools .viewport, body.tab-tools .analysis-panel { display: none !important; }
      body.tab-viewport .sidebar, body.tab-viewport .analysis-panel { display: none !important; }
      body.tab-viewport .viewport { display: flex !important; }
      body.tab-analysis .sidebar, body.tab-analysis .viewport { display: none !important; }
      body.tab-analysis .analysis-panel { display: flex !important; }

      #overlay-svg { touch-action: none; }
    }

    #toast-msg {
      position: fixed; bottom: 20px; right: 20px; background: #1e293b;
      border: 1px solid #3b82f6; color: #93c5fd; font-size: 11px; font-weight: 600;
      padding: 8px 14px; border-radius: 8px; z-index: 999999;
      box-shadow: 0 10px 25px rgba(0,0,0,0.5); display: none; align-items: center; gap: 8px;
    }

    /* Print-Only Report Container: STRICT 1-PAGE US LETTER */
    #print-report-container { display: none; }

    @media print {
      @page {
        size: letter portrait;
        margin: 5mm 7mm 5mm 7mm;
      }
      *, *::before, *::after { box-sizing: border-box !important; }
      html, body {
        background: #ffffff !important; color: #000000 !important;
        height: auto !important; width: 100% !important; overflow: visible !important;
        font-size: 8.5px !important; margin: 0 !important; padding: 0 !important;
      }
      header, .workspace, .sidebar, .viewport, .analysis-panel,
      .mobile-nav-bar, .viewport-overlay-controls, #loupe-box,
      #empty-dropzone, #security-gate, #toast-msg {
        display: none !important; visibility: hidden !important;
        height: 0 !important; width: 0 !important; position: absolute !important;
      }

      #print-report-container {
        display: flex !important; flex-direction: column; justify-content: space-between;
        width: 100% !important; height: 98vh !important; max-height: 98vh !important;
        page-break-inside: avoid !important; break-inside: avoid !important;
      }

      .print-header-bar {
        border-bottom: 2px solid #0f172a; padding-bottom: 3px;
        display: flex; justify-content: space-between; align-items: flex-end;
      }
      .print-title { font-size: 13px; font-weight: 800; color: #0f172a; letter-spacing: -0.01em; }
      .print-demographics { display: flex; gap: 10px; font-size: 9px; font-weight: 600; color: #334155; }

      .print-grid {
        display: grid !important; grid-template-columns: 280px 1fr !important;
        gap: 10px; align-items: start; flex: 1; margin-top: 3px;
      }

      .print-left-col { display: flex; flex-direction: column; gap: 4px; }
      .print-ceph-box {
        position: relative; width: 280px; height: 300px; border: 1.5px solid #94a3b8;
        border-radius: 4px; overflow: hidden; background: #000000;
        display: flex; align-items: center; justify-content: center;
      }
      .print-ceph-box img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
      .print-ceph-box svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

      .print-diag-card {
        border: 1px solid #cbd5e1; border-radius: 4px; padding: 5px 7px;
        background: #f8fafc; font-size: 8.5px; display: flex; flex-direction: column; gap: 2px;
      }

      .print-right-col { display: flex; flex-direction: column; gap: 4px; }
      .print-table { width: 100%; border-collapse: collapse; font-size: 8.5px; }
      .print-table th {
        border-bottom: 1.5px solid #0f172a; padding: 2px 4px; text-align: left;
        font-size: 8px; color: #0f172a; font-weight: 700; text-transform: uppercase;
      }
      .print-table td { border-bottom: 1px solid #e2e8f0; padding: 2px 4px; color: #0f172a; }
      .print-table td.diff-dev { color: #dc2626; font-weight: 700; }
      .print-table td.diff-norm { color: #15803d; font-weight: 600; }

      .print-footer-bar {
        border-top: 1px solid #cbd5e1; padding-top: 3px; display: flex;
        justify-content: space-between; align-items: flex-end; gap: 12px; margin-top: 3px;
      }
      .print-disclaimer { font-size: 7.5px; color: #64748b; line-height: 1.25; max-width: 65%; }
      .print-signature-wrap { display: flex; flex-direction: column; align-items: center; width: 190px; }
      .print-sign-line {
        border-top: 1px solid #0f172a; width: 100%; text-align: center;
        font-size: 8px; font-weight: 600; color: #334155; padding-top: 2px;
      }
    }
  </style>
</head>
<body>

<!-- Security Gate -->
<div id="security-gate">
  <div class="security-card">
    <div style="font-size: 32px;">🔒</div>
    <div style="font-size: 15px; font-weight: 800; color: #f8fafc;" id="gate-title">Clinical Suite Locked</div>
    <div style="font-size: 11px; color: #94a3b8;" id="gate-desc">Enter clinic master passcode to access cephalometric analysis.</div>
    <input type="password" id="gate-pass" class="input-field" placeholder="Master passcode..." style="text-align: center; font-size: 14px; padding: 8px;">
    <button class="btn" id="btn-unlock-gate" style="padding: 8px; font-size: 12px;">Unlock Suite</button>
    <div id="gate-err" style="color: #f43f5e; font-size: 11px; display: none;">Invalid master password.</div>
  </div>
</div>

<!-- Header -->
<header>
  <div class="brand">
    <div class="brand-icon">O</div>
    <div>
      <div class="brand-title">OrthoCeph Pro</div>
      <div class="brand-subtitle">ABO, McNamara, Tweed & Dual AI CVM Suite</div>
    </div>
  </div>

  <div class="header-actions">
    <div id="status-badge">
      <div class="indicator" id="status-ind"></div>
      <span id="status-txt">Loading AI Engine...</span>
    </div>
    <button class="btn btn-secondary" id="btn-privacy-toggle" title="Toggle HIPAA De-Identification / Presentation Mode">
      <svg viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
      <span class="btn-text" id="privacy-btn-txt">HIPAA Mask: OFF</span>
    </button>
    <button class="btn btn-secondary" id="btn-export-svg" title="Export Transparent Vector Overlay (SVG) for Presentations">
      <svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
      <span class="btn-text">Vector SVG</span>
    </button>
    <button class="btn btn-secondary" id="btn-save-json" title="Save tracing & patient data as .json">
      <svg viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
      <span class="btn-text">Save JSON</span>
    </button>
    <button class="btn btn-secondary" onclick="document.getElementById('json-input').click()" title="Load saved .json tracing">
      <svg viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
      <span class="btn-text">Load JSON</span>
    </button>
    <input type="file" id="json-input" accept=".json,application/json" style="display:none;">
    <button class="btn btn-secondary" id="btn-copy-note" title="Copy clinical summary & diagnosis for chart">
      <svg viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
      <span class="btn-text">Copy Note</span>
    </button>
    <button class="btn btn-secondary" id="btn-export-csv" title="Download measurements to Excel CSV">
      <svg viewBox="0 0 24 24"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
      <span class="btn-text">CSV</span>
    </button>
    <button class="btn btn-secondary" onclick="window.print()" title="Print 1-Page Letter Report">
      <svg viewBox="0 0 24 24"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
      <span class="btn-text">Print</span>
    </button>
    <button class="btn btn-secondary" id="btn-lock-suite" title="Lock workspace">
      <svg viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
      <span class="btn-text">Lock</span>
    </button>
    <button class="btn btn-danger" id="btn-next-patient" title="Clear current patient">
      <svg viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
      <span class="btn-text">Next</span>
    </button>
  </div>
</header>

<div class="workspace">
  <!-- Left Sidebar -->
  <aside class="sidebar">
    <div>
      <div class="section-header"><span>1. Radiograph & Patient</span></div>
      <div class="card">
        <input type="file" id="file-input" accept="image/*,.dcm,application/dicom,.json" class="input-field" style="padding: 4px;">
        <div class="form-group">
          <label>Patient Name</label>
          <input type="text" id="pt-name" class="input-field" placeholder="Patient name...">
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
          <div class="form-group">
            <label>Chart # / MRN</label>
            <input type="text" id="pt-chart" class="input-field" placeholder="MRN">
          </div>
          <div class="form-group">
            <label>Date & Time</label>
            <input type="datetime-local" id="pt-datetime" class="input-field">
          </div>
        </div>
      </div>
    </div>

    <div>
      <div class="section-header"><span>2. Focus Mode & Analyses</span></div>
      <div class="card">
        <div class="mode-group">
          <div class="mode-btn active" data-mode="ABO">ABO</div>
          <div class="mode-btn" data-mode="MCNAMARA">McNamara</div>
          <div class="mode-btn" data-mode="TWEED">Tweed</div>
          <div class="mode-btn" data-mode="AIRWAY">Airway</div>
          <div class="mode-btn" data-mode="CVM">🦴 CVM</div>
          <div class="mode-btn" data-mode="WITS">Wits</div>
          <div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
          <div class="mode-btn" data-mode="ALL">All Vectors</div>
          <div class="mode-btn" data-mode="SUPER" style="background: rgba(56,189,248,0.12); border-color:#38bdf8; color:#38bdf8;">📑 T1/T2/T3</div>
        </div>
        <div class="toggle-grid" style="margin-top: 3px;">
          <div class="toggle-pill active" id="tog-lines">Lines: ON</div>
          <div class="toggle-pill active" id="tog-points">Dots: ON</div>
          <div class="toggle-pill active" id="tog-labels">Names: ON</div>
        </div>
      </div>
    </div>

    <div>
      <div class="section-header"><span>3. Retrace & Calibration</span></div>
      <div class="card">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
          <button id="btn-retrace-all" class="btn btn-secondary">Reset All</button>
          <button id="btn-reset-single" class="btn btn-secondary">Reset Dot</button>
        </div>
        <button id="btn-retrace-scale" class="btn" style="background:#0284c7; width:100%; font-size:10.5px;">
          ⚡ Recalculate with Calibrated Scale
        </button>
        <div style="font-size: 9.5px; color: var(--text-muted); text-align: center;">
          Selected: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot on x-ray to reset)
        </div>
      </div>
    </div>

    <div>
      <div class="section-header"><span>4. Cervical Maturation (CVM)</span></div>
      <div class="card">
        <div class="cvm-grid">
          <div class="cvm-btn" data-cvm="CS1">CS1</div>
          <div class="cvm-btn" data-cvm="CS2">CS2</div>
          <div class="cvm-btn active" data-cvm="CS3">CS3</div>
          <div class="cvm-btn" data-cvm="CS4">CS4</div>
          <div class="cvm-btn" data-cvm="CS5">CS5</div>
          <div class="cvm-btn" data-cvm="CS6">CS6</div>
        </div>
        <div id="cvm-desc" style="font-size: 9.5px; color: var(--teal-accent); font-weight: 600; text-align: center;">
          CS3: Ascending Mandibular Growth Peak (Ideal Timing for Functional Appliances)
        </div>
      </div>
    </div>

    <div>
      <div class="section-header"><span>5. Longitudinal Series (T1 / T2 / T3)</span></div>
      <div class="card">
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px;">
          <button id="btn-lock-t1" class="btn btn-teal" style="font-size:9.5px; padding:4px;">📌 T1 Initial</button>
          <button id="btn-lock-t2" class="btn" style="background:rgba(59,130,246,0.2); border:1px solid #3b82f6; color:#93c5fd; font-size:9.5px; padding:4px;">📌 T2 Prog</button>
          <button id="btn-lock-t3" class="btn" style="background:rgba(217,70,239,0.2); border:1px solid #d946ef; color:#f0abfc; font-size:9.5px; padding:4px;">📌 T3 Final</button>
        </div>
        <button id="btn-clear-series" class="btn btn-secondary" style="font-size:9.5px; padding:3px; margin-top:2px;">Clear All Baselines</button>
        <div class="form-group" style="margin-top: 3px;">
          <label>Registration Reference</label>
          <select id="super-mode" class="input-field" style="padding: 4px;">
            <option value="CRANIAL">Cranial Base (S-N registered at S)</option>
            <option value="MAXILLARY">Maxillary Palatal Plane (PNS-ANS at PNS)</option>
            <option value="MANDIBULAR">Mandibular Plane (Go-Me registered at Me)</option>
          </select>
        </div>
        <div id="super-status" style="font-size: 9px; color: var(--text-muted); text-align: center; line-height:1.35;">
          No baselines locked.
        </div>
      </div>
    </div>

    <div>
      <div class="section-header">
        <span>6. Caliper & Image Equalization</span>
        <span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 9.5px;">Reset</span>
      </div>
      <div class="card">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
          <button id="btn-cal" class="btn btn-secondary" style="font-size: 9.5px; padding: 5px 3px;">Ruler: Toggle</button>
          <button id="btn-auto-caliper" class="btn" style="background:#0891b2; font-size:9.5px; padding: 5px 3px;">⚡ Auto 10mm</button>
        </div>
        <span id="cal-status" style="font-size: 10px; color: var(--ruler-cyan); text-align: center; font-weight: 600;">
          Scale: 10.00 px/mm
        </span>
        <div class="form-group" style="margin-top: 2px;">
          <label>Density Filter</label>
          <select id="filter-mode-select" class="input-field" style="padding: 4px;">
            <option value="NORMAL">Standard Radiograph</option>
            <option value="EQUALIZED">Bone & Soft Profile Equalization (CLAHE)</option>
            <option value="BONE">Cortical Bone Boost</option>
            <option value="SOFT">Soft Tissue Profile Focus</option>
          </select>
        </div>
        <div class="slider-row">
          <span>Brightness</span>
          <input type="range" id="brightness" min="0.5" max="2.0" step="0.05" value="1.0">
        </div>
        <div class="slider-row">
          <span>Contrast</span>
          <input type="range" id="contrast" min="0.5" max="2.5" step="0.05" value="1.0">
        </div>
        <div class="slider-row">
          <span>Invert Negative</span>
          <input type="checkbox" id="invert">
        </div>
      </div>
    </div>

    <div>
      <div class="section-header">
        <span>7. Reference Norms & Ethnicity</span>
        <span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 9.5px; display: none;">Restore</span>
      </div>
      <div class="card">
        <div class="form-group">
          <label>Ethnic Population Standard</label>
          <select id="ethnicity-select" class="input-field" style="padding: 4px; font-weight: 600; color: #38bdf8;">
            <option value="CAUCASIAN">Caucasian (ABO Standard / Michigan)</option>
            <option value="EAST_ASIAN">East Asian (Japanese / Chinese / Korean)</option>
            <option value="AFRICAN_AMERICAN">African American (Drummond / Alexander)</option>
            <option value="HISPANIC">Hispanic / Latino (Bishara / Garcia)</option>
          </select>
        </div>
        <button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 10px; padding: 4px; margin-top: 2px;">
          Customize ABO Norms
        </button>
        <div id="norms-drawer"></div>
      </div>
    </div>
  </aside>

  <!-- Center Viewport -->
  <main class="viewport" id="viewport-wrapper">
    <div id="loupe-box">
      <canvas id="loupe-canvas" width="140" height="140"></canvas>
      <div id="loupe-label">S</div>
    </div>

    <div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
      <div style="font-size: 32px;">🦷</div>
      <div style="font-size: 14px; font-weight: 600; color: var(--text-main);">Drop Lateral Cephalogram (.DCM, .JPG, .PNG) or .JSON Here</div>
      <div style="font-size: 11px;">Dual-Neural Localization Active • Drag Points to Fine-Tune</div>
    </div>

    <div id="viewport-container">
      <img id="ceph-image" src="" alt="">
      <svg id="overlay-svg"></svg>
    </div>

    <div class="viewport-overlay-controls">
      <button id="btn-zoom-in">Zoom (+)</button>
      <button id="btn-zoom-out">Zoom (-)</button>
      <button id="btn-zoom-reset">Fit</button>
      <span style="color: var(--surface-border);">|</span>
      <span class="shortcut-hint">Hold <strong>[SPACE]</strong> to inspect radiograph • Double-click dot to reset</span>
    </div>
  </main>

  <!-- Right Analysis Panel -->
  <aside class="analysis-panel">
    <div class="diagnosis-banner">
      <div class="diagnosis-headline" id="diag-headline">Automated Diagnosis: Awaiting Tracing...</div>
      <div class="diagnosis-grid">
        <div class="diag-item">
          <span class="diag-label">Sagittal Skeletal</span>
          <span class="diag-val" id="diag-sagittal">-</span>
        </div>
        <div class="diag-item">
          <span class="diag-label">Vertical Growth</span>
          <span class="diag-val" id="diag-vertical">-</span>
        </div>
        <div class="diag-item">
          <span class="diag-label">Incisor Posture</span>
          <span class="diag-val" id="diag-dental">-</span>
        </div>
        <div class="diag-item">
          <span class="diag-label">Soft Profile & CVM</span>
          <span class="diag-val" id="diag-soft">-</span>
        </div>
      </div>
    </div>

    <div id="section-abo">
      <div class="section-header" style="color: #60a5fa;">Official ABO Cephalometric Analysis</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Parameter</th>
            <th>Norm</th>
            <th>Measured</th>
            <th>Diff</th>
            <th id="th-t1-abo" style="display:none; color:#5eead4;">Δ vs T1</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="abo-rows">
          <tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting radiograph...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="section-mcnamara">
      <div class="section-header" style="color: #38bdf8;">McNamara Analysis (Maxillomandibular & LAFH)</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Parameter</th>
            <th>Norm</th>
            <th>Measured</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="mcnamara-rows">
          <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="section-tweed">
      <div class="section-header" style="color: #fbbf24;">Tweed Diagnostic Triangle</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Parameter</th>
            <th>Norm</th>
            <th>Measured</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="tweed-rows">
          <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="section-airway">
      <div class="section-header" style="color: #2dd4bf;">Pharyngeal Airway Space (OSA & Sleep Screening)</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Airway Region</th>
            <th>Norm</th>
            <th>Measured</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="airway-rows">
          <tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="section-cvm-table">
      <div class="section-header" style="color: #14b8a6;">Cervical Vertebral Maturation (C2–C4 Morphology)</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Feature</th>
            <th>Measured</th>
            <th>Morphology & Timing</th>
          </tr>
        </thead>
        <tbody id="cvm-metric-rows">
          <tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 8px;">Select CVM mode or upload radiograph...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="section-wits">
      <div class="section-header" style="color: #c084fc;">Jacobson Wits Appraisal</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Parameter</th>
            <th>Norm</th>
            <th>Measured</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="wits-rows">
          <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
        </tbody>
      </table>
    </div>

    <div id="section-holdaway">
      <div class="section-header" style="color: #f472b6;">Holdaway Soft Tissue Analysis</div>
      <table class="analysis-table">
        <thead>
          <tr>
            <th>Parameter</th>
            <th>Norm</th>
            <th>Measured</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="holdaway-rows">
          <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
        </tbody>
      </table>
    </div>
  </aside>
</div>

<!-- Mobile Navigation Bar -->
<nav class="mobile-nav-bar" id="mobile-nav">
  <button class="mobile-tab-btn active" data-tab="tools">
    <svg viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
    <span>Controls</span>
  </button>
  <button class="mobile-tab-btn" data-tab="viewport">
    <svg viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
    <span>Tracing</span>
  </button>
  <button class="mobile-tab-btn" data-tab="analysis">
    <svg viewBox="0 0 24 24"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
    <span>Results</span>
  </button>
</nav>

<!-- Print 1-Page Letter Layout -->
<div id="print-report-container">
  <div class="print-header-bar">
    <div>
      <div class="print-title">ORTHOCEPH PRO | CLINICAL ABO CEPHALOMETRIC REPORT</div>
      <div style="font-size: 8px; color: #64748b; font-weight: 600;">AMERICAN BOARD OF ORTHODONTICS & MCNAMARA COMPLIANT SUMMARY</div>
    </div>
    <div class="print-demographics">
      <div>PATIENT: <strong id="print-pt-name">Unspecified</strong></div>
      <div>MRN: <strong id="print-pt-mrn">-</strong></div>
      <div>DATE & TIME: <strong id="print-pt-datetime">-</strong></div>
      <div id="print-ethnicity-tag" style="color:#0284c7;">ETHNICITY: <strong>Caucasian</strong></div>
    </div>
  </div>

  <div class="print-grid">
    <div class="print-left-col">
      <div class="print-ceph-box">
        <img id="print-img" src="" alt="Cephalogram">
        <svg id="print-svg" viewBox="0 0 100 100"></svg>
      </div>
      <div class="print-diag-card">
        <div style="font-weight: 800; color: #1e3a8a; font-size: 9px; border-bottom: 1px solid #e2e8f0; padding-bottom: 2px;" id="print-diag-headline">Diagnosis Summary</div>
        <div id="print-diag-sag">Sagittal: -</div>
        <div id="print-diag-vert">Vertical: -</div>
        <div id="print-diag-dent">Dental: -</div>
        <div id="print-diag-soft">Soft Profile: -</div>
      </div>
      <table class="print-table" id="print-wits-table">
        <thead>
          <tr><th>Appraisal, Airway & CVM</th><th>Norm</th><th>Measured</th><th>Status</th></tr>
        </thead>
        <tbody id="print-wits-tbody"></tbody>
      </table>
    </div>

    <div class="print-right-col">
      <table class="print-table" id="print-abo-table">
        <thead>
          <tr>
            <th>ABO Parameter</th>
            <th>Norm ± SD</th>
            <th>Value</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="print-abo-tbody"></tbody>
      </table>

      <table class="print-table" id="print-mcnamara-table" style="margin-top: 3px;">
        <thead>
          <tr>
            <th>McNamara & Tweed</th>
            <th>Norm ± SD</th>
            <th>Value</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="print-mcnamara-tbody"></tbody>
      </table>

      <table class="print-table" id="print-holdaway-table" style="margin-top: 3px;">
        <thead>
          <tr>
            <th>Holdaway Soft Tissue</th>
            <th>Norm ± SD</th>
            <th>Value</th>
            <th>Diff</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody id="print-holdaway-tbody"></tbody>
      </table>
    </div>
  </div>

  <div class="print-footer-bar">
    <div class="print-disclaimer">
      Measurements verified against calibrated millimeter scale. Automated dual-neural cephalometric analysis generated for clinical orthodontic diagnosis and treatment evaluation.
    </div>
    <div class="print-signature-wrap">
      <div class="print-sign-line">Attending Orthodontist Signature / Stamp</div>
    </div>
  </div>
</div>

<div id="toast-msg">Notification</div>

<script>
// =============================================================
// 1. Constants, Dual Models & 29-Channel Indices
// =============================================================
const MASTER_PASSWORD = "ortho2026"; // Clinic access code
const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
const CVM_MODEL_URL = "./cvm_airway.onnx"; // Secondary CVM/Airway ONNX model if in Space

// 29 Full Channel Landmark Mapping
const LM_INDICES = {
  "A": 0, "ANS": 1, "Ar": 2, "B": 3, "Co": 4, "Gn": 5, "Go": 6, "LIA": 7, "LIT": 8,
  "LMT": 9, "LPM": 10, "Li": 11, "Ls": 12, "Me": 13, "N": 14, "Or": 16, "PNS": 17,
  "Pn": 18, "Po": 19, "Pog": 20, "Pog_soft": 21, "R": 22, "S": 23, "Sn": 24,
  "UIA": 25, "UIT": 26, "UMT": 27, "UPM": 28
};

const MODE_LANDMARKS = {
  ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft"]),
  MCNAMARA: new Set(["N", "Po", "Or", "A", "Pog", "Co", "Gn", "ANS", "Me"]),
  TWEED: new Set(["Po", "Or", "Go", "Me", "LIT", "LIA"]),
  AIRWAY: new Set(["PNS", "UPW", "P_Palate", "TB", "LPW", "Go", "B", "R"]),
  CVM: new Set(["C2_LL", "C2_INF", "C2_LR", "C3_UL", "C3_UR", "C3_LL", "C3_INF", "C3_LR", "C4_UL", "C4_UR", "C4_LL", "C4_INF", "C4_LR", "Ar", "R", "Go"]),
  WITS: new Set(["A", "B", "OP_P", "OP_A"]),
  HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
  SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog", "Co", "Gn"]),
  ALL: new Set(["S", "N", "Po", "Or", "A", "B", "Pog", "Me", "Gn", "Go", "ANS", "PNS", "UIT", "UIA", "LIT", "LIA", "Pn", "Sn", "Ls", "Li", "Pog_soft", "OP_P", "OP_A", "Co", "Ar", "R", "UPW", "P_Palate", "TB", "LPW", "C2_LL", "C2_INF", "C2_LR", "C3_UL", "C3_UR", "C3_LL", "C3_INF", "C3_LR", "C4_UL", "C4_UR", "C4_LL", "C4_INF", "C4_LR"])
};

const CVM_INFO = {
  CS1: "CS1 (Pre-Peak): Lower borders of C2-C4 are flat. C3 & C4 bodies are tapered trapezoids. Peak is >2 years away.",
  CS2: "CS2 (Pre-Peak): Concavity present at lower border of C2. C3 & C4 are trapezoids. Peak is ~1 year away.",
  CS3: "CS3 (Ascending Peak): Concavities on C2 & C3. Peak mandibular velocity occurs during this stage (Ideal Functional Appliance Timing).",
  CS4: "CS4 (Decelerating Peak): Concavities on C2, C3 & C4. C3 & C4 are horizontal rectangles. Peak occurred 1–2 years ago.",
  CS5: "CS5 (Post-Peak): Concavities on C2–C4. At least one of C3 or C4 is square. Peak ended >1 year ago.",
  CS6: "CS6 (Completion): Concavities on C2–C4. At least one of C3 or C4 is vertical rectangular. Mandibular growth complete."
};

const ETHNICITY_DATABASE = {
  CAUCASIAN: {
    label: "Caucasian (ABO Standard / Michigan)",
    abo: [
      { id: "SNA", name: "SNA Angle", norm: 82.0, sd: 2.0, unit: "°" },
      { id: "SNB", name: "SNB Angle", norm: 80.0, sd: 2.0, unit: "°" },
      { id: "ANB", name: "ANB Difference", norm: 2.0, sd: 2.0, unit: "°" },
      { id: "FMA", name: "FMA (FH to MP)", norm: 25.0, sd: 4.0, unit: "°" },
      { id: "SNMP", name: "SN to MP Angle", norm: 32.0, sd: 5.0, unit: "°" },
      { id: "IMPA", name: "IMPA (L1 to MP)", norm: 90.0, sd: 5.0, unit: "°" },
      { id: "U1SN", name: "U1 to SN Angle", norm: 102.0, sd: 5.0, unit: "°" },
      { id: "U1NA_deg", name: "U1 to NA Angle", norm: 22.0, sd: 4.0, unit: "°" },
      { id: "U1NA_mm", name: "U1 to NA (mm)", norm: 4.0, sd: 2.0, unit: "mm" },
      { id: "L1NB_deg", name: "L1 to NB Angle", norm: 25.0, sd: 4.0, unit: "°" },
      { id: "L1NB_mm", name: "L1 to NB (mm)", norm: 4.0, sd: 2.0, unit: "mm" },
      { id: "IIA", name: "Interincisal Angle", norm: 130.0, sd: 6.0, unit: "°" },
      { id: "UL_E", name: "Upper Lip to E-Line", norm: -3.0, sd: 2.0, unit: "mm" },
      { id: "LL_E", name: "Lower Lip to E-Line", norm: -1.0, sd: 2.0, unit: "mm" }
    ],
    tweed: [
      { id: "FMA", name: "FMA Angle", norm: 25.0, sd: 4.0, unit: "°" },
      { id: "IMPA", name: "IMPA Angle", norm: 90.0, sd: 5.0, unit: "°" },
      { id: "FMIA", name: "FMIA Angle", norm: 65.0, sd: 5.0, unit: "°" }
    ]
  },
  EAST_ASIAN: {
    label: "East Asian (Chinese / Japanese / Korean)",
    abo: [
      { id: "SNA", name: "SNA Angle", norm: 82.5, sd: 2.5, unit: "°" },
      { id: "SNB", name: "SNB Angle", norm: 79.5, sd: 2.5, unit: "°" },
      { id: "ANB", name: "ANB Difference", norm: 3.0, sd: 2.0, unit: "°" },
      { id: "FMA", name: "FMA (FH to MP)", norm: 27.5, sd: 4.0, unit: "°" },
      { id: "SNMP", name: "SN to MP Angle", norm: 34.5, sd: 5.0, unit: "°" },
      { id: "IMPA", name: "IMPA (L1 to MP)", norm: 96.0, sd: 5.5, unit: "°" },
      { id: "U1SN", name: "U1 to SN Angle", norm: 106.0, sd: 5.5, unit: "°" },
      { id: "U1NA_deg", name: "U1 to NA Angle", norm: 26.0, sd: 4.5, unit: "°" },
      { id: "U1NA_mm", name: "U1 to NA (mm)", norm: 5.5, sd: 2.0, unit: "mm" },
      { id: "L1NB_deg", name: "L1 to NB Angle", norm: 29.0, sd: 4.5, unit: "°" },
      { id: "L1NB_mm", name: "L1 to NB (mm)", norm: 6.0, sd: 2.0, unit: "mm" },
      { id: "IIA", name: "Interincisal Angle", norm: 122.0, sd: 6.5, unit: "°" },
      { id: "UL_E", name: "Upper Lip to E-Line", norm: 0.5, sd: 2.0, unit: "mm" },
      { id: "LL_E", name: "Lower Lip to E-Line", norm: 1.5, sd: 2.0, unit: "mm" }
    ],
    tweed: [
      { id: "FMA", name: "FMA Angle", norm: 27.5, sd: 4.0, unit: "°" },
      { id: "IMPA", name: "IMPA Angle", norm: 96.0, sd: 5.0, unit: "°" },
      { id: "FMIA", name: "FMIA Angle", norm: 56.5, sd: 5.0, unit: "°" }
    ]
  },
  AFRICAN_AMERICAN: {
    label: "African American (Drummond / Alexander)",
    abo: [
      { id: "SNA", name: "SNA Angle", norm: 85.0, sd: 3.0, unit: "°" },
      { id: "SNB", name: "SNB Angle", norm: 81.5, sd: 3.0, unit: "°" },
      { id: "ANB", name: "ANB Difference", norm: 3.5, sd: 2.0, unit: "°" },
      { id: "FMA", name: "FMA (FH to MP)", norm: 28.0, sd: 4.5, unit: "°" },
      { id: "SNMP", name: "SN to MP Angle", norm: 35.0, sd: 5.0, unit: "°" },
      { id: "IMPA", name: "IMPA (L1 to MP)", norm: 100.0, sd: 6.0, unit: "°" },
      { id: "U1SN", name: "U1 to SN Angle", norm: 112.0, sd: 6.0, unit: "°" },
      { id: "U1NA_deg", name: "U1 to NA Angle", norm: 30.0, sd: 5.0, unit: "°" },
      { id: "U1NA_mm", name: "U1 to NA (mm)", norm: 7.0, sd: 2.5, unit: "mm" },
      { id: "L1NB_deg", name: "L1 to NB Angle", norm: 33.0, sd: 5.0, unit: "°" },
      { id: "L1NB_mm", name: "L1 to NB (mm)", norm: 7.5, sd: 2.5, unit: "mm" },
      { id: "IIA", name: "Interincisal Angle", norm: 116.0, sd: 7.0, unit: "°" },
      { id: "UL_E", name: "Upper Lip to E-Line", norm: 3.0, sd: 2.5, unit: "mm" },
      { id: "LL_E", name: "Lower Lip to E-Line", norm: 4.0, sd: 2.5, unit: "mm" }
    ],
    tweed: [
      { id: "FMA", name: "FMA Angle", norm: 28.0, sd: 4.5, unit: "°" },
      { id: "IMPA", name: "IMPA Angle", norm: 100.0, sd: 6.0, unit: "°" },
      { id: "FMIA", name: "FMIA Angle", norm: 52.0, sd: 5.5, unit: "°" }
    ]
  },
  HISPANIC: {
    label: "Hispanic / Latino (Bishara / Garcia)",
    abo: [
      { id: "SNA", name: "SNA Angle", norm: 83.5, sd: 2.5, unit: "°" },
      { id: "SNB", name: "SNB Angle", norm: 80.5, sd: 2.5, unit: "°" },
      { id: "ANB", name: "ANB Difference", norm: 3.0, sd: 2.0, unit: "°" },
      { id: "FMA", name: "FMA (FH to MP)", norm: 26.5, sd: 4.0, unit: "°" },
      { id: "SNMP", name: "SN to MP Angle", norm: 33.5, sd: 5.0, unit: "°" },
      { id: "IMPA", name: "IMPA (L1 to MP)", norm: 95.0, sd: 5.5, unit: "°" },
      { id: "U1SN", name: "U1 to SN Angle", norm: 105.0, sd: 5.5, unit: "°" },
      { id: "U1NA_deg", name: "U1 to NA Angle", norm: 25.0, sd: 4.5, unit: "°" },
      { id: "U1NA_mm", name: "U1 to NA (mm)", norm: 5.0, sd: 2.0, unit: "mm" },
      { id: "L1NB_deg", name: "L1 to NB Angle", norm: 28.0, sd: 4.5, unit: "°" },
      { id: "L1NB_mm", name: "L1 to NB (mm)", norm: 5.5, sd: 2.0, unit: "mm" },
      { id: "IIA", name: "Interincisal Angle", norm: 124.0, sd: 6.5, unit: "°" },
      { id: "UL_E", name: "Upper Lip to E-Line", norm: 0.0, sd: 2.0, unit: "mm" },
      { id: "LL_E", name: "Lower Lip to E-Line", norm: 1.0, sd: 2.0, unit: "mm" }
    ],
    tweed: [
      { id: "FMA", name: "FMA Angle", norm: 26.5, sd: 4.0, unit: "°" },
      { id: "IMPA", name: "IMPA Angle", norm: 95.0, sd: 5.0, unit: "°" },
      { id: "FMIA", name: "FMIA Angle", norm: 58.5, sd: 5.0, unit: "°" }
    ]
  }
};

let activeEthnicity = "CAUCASIAN";
let ABO_NORMS = JSON.parse(localStorage.getItem("custom_abo_norms")) || JSON.parse(JSON.stringify(ETHNICITY_DATABASE.CAUCASIAN.abo));
let TWEED_NORMS = JSON.parse(JSON.stringify(ETHNICITY_DATABASE.CAUCASIAN.tweed));

const MCNAMARA_NORMS = [
  { id: "A_N_PERP", name: "Point A to N-Perp", norm: 0.5, sd: 2.0, unit: "mm" },
  { id: "POG_N_PERP", name: "Pog to N-Perp", norm: -1.0, sd: 3.0, unit: "mm" },
  { id: "CO_A", name: "Effective Midface (Co-A)", norm: 94.0, sd: 4.0, unit: "mm" },
  { id: "CO_GN", name: "Effective Mandible (Co-Gn)", norm: 123.0, sd: 5.0, unit: "mm" },
  { id: "MX_MD_DIFF", name: "Maxillo-Mandibular Diff", norm: 27.0, sd: 3.0, unit: "mm" },
  { id: "LAFH", name: "Lower Face Height (ANS-Me)", norm: 66.0, sd: 4.0, unit: "mm" }
];

const HOLDAWAY_NORMS = [
  { id: "H_ANGLE", name: "H-Angle (H-Line to N'-Pog')", norm: 10.0, sd: 3.0, unit: "°" },
  { id: "SKEL_CONV", name: "Skeletal Convexity (A to N-Pog)", norm: 0.0, sd: 2.0, unit: "mm" },
  { id: "NOSE_PROM", name: "Nose Prominence (Pn to H-Line)", norm: 18.0, sd: 4.0, unit: "mm" },
  { id: "SN_HLINE", name: "Subnasale to H-Line", norm: 5.0, sd: 2.0, unit: "mm" },
  { id: "LL_HLINE", name: "Lower Lip to H-Line", norm: 0.5, sd: 1.0, unit: "mm" },
  { id: "CHIN_THICK", name: "Soft Tissue Chin (Pog to Pog')", norm: 11.0, sd: 2.0, unit: "mm" }
];

// App State
let session = null;
let cvmSession = null;
let coords = {};
let initialAiCoords = {};
let t1Baseline = null;
let t2Baseline = null;
let t3Baseline = null;
let selectedLm = null;
let cvmStage = "CS3";
let pxPerMm = 10.0;
let showRuler = false;
let focusMode = "ABO";
let showLines = true;
let showPoints = true;
let showLabels = true;
let spacebarPeek = false;
let hipaaPrivacyMode = false;
let currentFilterMode = "NORMAL";
let zoomLevel = 1.0;
let draggingLm = null;
let latestMetrics = {};
let latestDiagnosis = { headline: "Awaiting Tracing...", sagittal: "-", vertical: "-", dental: "-", soft: "-" };

const imgElem = document.getElementById("ceph-image");
const svgElem = document.getElementById("overlay-svg");
const statusTxt = document.getElementById("status-txt");
const statusInd = document.getElementById("status-ind");
const container = document.getElementById("viewport-container");
const dropzone = document.getElementById("empty-dropzone");
const calBtn = document.getElementById("btn-cal");
const calStatus = document.getElementById("cal-status");
const loupeBox = document.getElementById("loupe-box");
const loupeCanvas = document.getElementById("loupe-canvas");
const loupeLabel = document.getElementById("loupe-label");

// Auto-fill Current Date & Time
function setAutoDateTime() {
  const now = new Date();
  const pad = (n) => String(n).padStart(2, '0');
  const dateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
  document.getElementById("pt-datetime").value = dateStr;
}
setAutoDateTime();

// Toast Helper
function notify(msg, dur = 2600) {
  const t = document.getElementById("toast-msg");
  t.innerText = msg;
  t.style.display = "flex";
  clearTimeout(t._tm);
  t._tm = setTimeout(() => t.style.display = "none", dur);
}

// Security Gate Logic
const gateElem = document.getElementById("security-gate");
const gatePass = document.getElementById("gate-pass");
const gateErr = document.getElementById("gate-err");

function checkSecurity() {
  if (sessionStorage.getItem("orthoceph_auth") === "1") {
    gateElem.style.display = "none";
  } else {
    gateElem.style.display = "flex";
    gatePass.value = "";
    gateErr.style.display = "none";
    setTimeout(() => gatePass.focus(), 100);
  }
}
checkSecurity();

document.getElementById("btn-unlock-gate").addEventListener("click", () => {
  if (gatePass.value === MASTER_PASSWORD) {
    sessionStorage.setItem("orthoceph_auth", "1");
    gateElem.style.display = "none";
    notify("Clinical Suite Unlocked");
  } else {
    gateErr.style.display = "block";
    gatePass.value = "";
    gatePass.focus();
  }
});
gatePass.addEventListener("keydown", (e) => {
  if (e.key === "Enter") document.getElementById("btn-unlock-gate").click();
});
document.getElementById("btn-lock-suite").addEventListener("click", () => {
  sessionStorage.removeItem("orthoceph_auth");
  checkSecurity();
});

// Mobile Tabs Setup
const mobileTabBtns = document.querySelectorAll(".mobile-tab-btn");
function setMobileTab(tabName) {
  document.body.classList.remove("tab-tools", "tab-viewport", "tab-analysis");
  document.body.classList.add(`tab-${tabName}`);
  mobileTabBtns.forEach(b => b.classList.toggle("active", b.getAttribute("data-tab") === tabName));
}
setMobileTab("tools");
mobileTabBtns.forEach(b => b.addEventListener("click", () => setMobileTab(b.getAttribute("data-tab"))));

// Custom Norms Drawer
function buildNormsEditor() {
  const drawer = document.getElementById("norms-drawer");
  drawer.innerHTML = `<div class="norm-edit-row" style="color:var(--text-muted); font-weight:700;"><span>Metric</span><span style="text-align:center;">Mean</span><span style="text-align:center;">± SD</span></div>`;
  ABO_NORMS.forEach((m, idx) => {
    const row = document.createElement("div");
    row.className = "norm-edit-row";
    row.innerHTML = `
      <span>${m.id}</span>
      <input type="number" step="0.5" value="${m.norm}" data-idx="${idx}" data-field="norm">
      <input type="number" step="0.5" value="${m.sd}" data-idx="${idx}" data-field="sd">
    `;
    drawer.appendChild(row);
  });

  drawer.querySelectorAll("input").forEach(inp => {
    inp.addEventListener("input", (e) => {
      const i = parseInt(e.target.getAttribute("data-idx"));
      const field = e.target.getAttribute("data-field");
      const val = parseFloat(e.target.value);
      if (!isNaN(val)) {
        ABO_NORMS[i][field] = val;
        localStorage.setItem("custom_abo_norms", JSON.stringify(ABO_NORMS));
        renderAnalysis();
      }
    });
  });
}
buildNormsEditor();

document.getElementById("btn-toggle-norms").addEventListener("click", () => {
  const d = document.getElementById("norms-drawer");
  const r = document.getElementById("reset-norms");
  const open = d.style.display === "flex";
  d.style.display = open ? "none" : "flex";
  r.style.display = open ? "none" : "inline";
});

document.getElementById("reset-norms").addEventListener("click", () => {
  const ethData = ETHNICITY_DATABASE[activeEthnicity] || ETHNICITY_DATABASE.CAUCASIAN;
  ABO_NORMS = JSON.parse(JSON.stringify(ethData.abo));
  localStorage.removeItem("custom_abo_norms");
  buildNormsEditor();
  renderAnalysis();
  notify("Norms restored to ethnic baseline.");
});

// Ethnicity Select
document.getElementById("ethnicity-select").addEventListener("change", (e) => {
  activeEthnicity = e.target.value;
  const ethData = ETHNICITY_DATABASE[activeEthnicity] || ETHNICITY_DATABASE.CAUCASIAN;
  ABO_NORMS = JSON.parse(JSON.stringify(ethData.abo));
  TWEED_NORMS = JSON.parse(JSON.stringify(ethData.tweed));
  localStorage.setItem("custom_abo_norms", JSON.stringify(ABO_NORMS));
  buildNormsEditor();
  renderAnalysis();
  notify(`Norms adjusted for ${ethData.label}`);
});

// HIPAA Toggle
document.getElementById("btn-privacy-toggle").addEventListener("click", () => {
  hipaaPrivacyMode = !hipaaPrivacyMode;
  document.getElementById("privacy-btn-txt").innerText = `HIPAA Mask: ${hipaaPrivacyMode ? 'ON' : 'OFF'}`;
  document.getElementById("btn-privacy-toggle").classList.toggle("btn-danger", hipaaPrivacyMode);
  renderAnalysis();
  notify(hipaaPrivacyMode ? "HIPAA De-Identification Mode Enabled." : "De-Identification Disabled.");
});

// Transparent SVG Export
document.getElementById("btn-export-svg").addEventListener("click", () => {
  if (!coords.S || !imgElem.naturalWidth) {
    notify("Trace a radiograph first.");
    return;
  }
  const w = imgElem.naturalWidth;
  const h = imgElem.naturalHeight;
  const svgContent = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" style="background:transparent;">
  ${svgElem.innerHTML}
</svg>`;
  const blob = new Blob([svgContent], { type: "image/svg+xml;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  const ptName = (document.getElementById("pt-name").value || "Patient").replace(/\s+/g, '_');
  a.href = url;
  a.download = `Ceph_Vectors_${ptName}.svg`;
  a.click();
  notify("Transparent vector SVG downloaded.");
});

// Auto 10mm Caliper Detection
document.getElementById("btn-auto-caliper").addEventListener("click", () => {
  if (!imgElem.src || imgElem.naturalWidth === 0) {
    notify("Load a cephalogram first.");
    return;
  }
  autoDetect10mmCaliper();
});

function autoDetect10mmCaliper() {
  notify("Scanning cephalostat scale...");
  const origW = imgElem.naturalWidth;
  const origH = imgElem.naturalHeight;

  const scanCanvas = document.createElement("canvas");
  const roiW = Math.floor(origW * 0.28);
  const roiH = Math.floor(origH * 0.4);
  scanCanvas.width = roiW; scanCanvas.height = roiH;
  const ctx = scanCanvas.getContext("2d");
  ctx.drawImage(imgElem, origW * 0.72, 0, roiW, roiH, 0, 0, roiW, roiH);

  const imgData = ctx.getImageData(0, 0, roiW, roiH);
  const data = imgData.data;
  let bestCol = -1, bestScore = -1;

  for (let x = 8; x < roiW - 8; x += 3) {
    let variance = 0, prev = 0;
    for (let y = 8; y < roiH - 8; y += 2) {
      const idx = (y * roiW + x) * 4;
      const gray = data[idx] * 0.299 + data[idx + 1] * 0.587 + data[idx + 2] * 0.114;
      variance += Math.abs(gray - prev);
      prev = gray;
    }
    if (variance > bestScore) {
      bestScore = variance;
      bestCol = x;
    }
  }

  const detectedX = origW * 0.72 + (bestCol > 0 ? bestCol : roiW * 0.55);
  const detectedY = origH * 0.12;
  const estimated10mm = Math.max(70, Math.round(origW * 0.052));

  coords.RULER_1 = { x: detectedX, y: detectedY };
  coords.RULER_2 = { x: detectedX, y: detectedY + estimated10mm };
  pxPerMm = estimated10mm / 10.0;
  showRuler = true;
  calBtn.innerText = "Ruler: ON";
  calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Auto-Locked)`;
  renderAnalysis();
  notify(`Auto-calibrated scale (${pxPerMm.toFixed(2)} px/mm). Micro-drag dots if needed.`);
}

// Density Filters
document.getElementById("filter-mode-select").addEventListener("change", (e) => {
  currentFilterMode = e.target.value;
  applyFilters();
});

function applyFilters() {
  const b = parseFloat(document.getElementById("brightness").value);
  const c = parseFloat(document.getElementById("contrast").value);
  const inv = document.getElementById("invert").checked ? 1 : 0;

  if (currentFilterMode === "EQUALIZED") {
    imgElem.style.filter = `brightness(${b * 1.08}) contrast(${c * 1.55}) invert(${inv})`;
  } else if (currentFilterMode === "BONE") {
    imgElem.style.filter = `brightness(${b * 0.95}) contrast(${c * 1.85}) invert(${inv})`;
  } else if (currentFilterMode === "SOFT") {
    imgElem.style.filter = `brightness(${b * 1.25}) contrast(${c * 0.95}) invert(${inv})`;
  } else {
    imgElem.style.filter = `brightness(${b}) contrast(${c}) invert(${inv})`;
  }
}
document.getElementById("brightness").addEventListener("input", applyFilters);
document.getElementById("contrast").addEventListener("input", applyFilters);
document.getElementById("invert").addEventListener("change", applyFilters);
document.getElementById("reset-filters").addEventListener("click", () => {
  document.getElementById("brightness").value = 1.0;
  document.getElementById("contrast").value = 1.0;
  document.getElementById("invert").checked = false;
  document.getElementById("filter-mode-select").value = "NORMAL";
  currentFilterMode = "NORMAL";
  applyFilters();
});

// =============================================================
// 2. Dual-Engine Neural Model Initialization
// =============================================================
async function initModel() {
  try {
    ort.env.wasm.numThreads = 2;
    // Primary 29-Landmark Cephalometric Neural Model
    session = await ort.InferenceSession.create(MODEL_URL, { executionProviders: ['wasm'] });
    
    // Attempt to load secondary CVM & Airway ONNX model if present in Space
    try {
      cvmSession = await ort.InferenceSession.create(CVM_MODEL_URL, { executionProviders: ['wasm'] });
      statusTxt.innerText = "Dual AI Active (Ceph29 + CVM ONNX)";
      notify("Dual AI Architecture Loaded (Ceph29 + CVM ONNX)");
    } catch (_) {
      statusTxt.innerText = "AI Active (Ceph29 + Corridor Scanner)";
    }
    statusInd.style.backgroundColor = "var(--status-green)";

    if (imgElem.src && imgElem.naturalWidth > 0 && Object.keys(coords).length === 0) {
      runAutoTrace();
    }
  } catch (err) {
    statusInd.style.backgroundColor = "var(--status-red)";
    statusTxt.innerText = "Model Load Error";
  }
}
initModel();

// =============================================================
// 3. File Loading & Drag-and-Drop
// =============================================================
const viewportWrapper = document.getElementById("viewport-wrapper");
viewportWrapper.addEventListener("dragover", (e) => { e.preventDefault(); viewportWrapper.classList.add("drag-over"); });
viewportWrapper.addEventListener("dragleave", () => viewportWrapper.classList.remove("drag-over"));
viewportWrapper.addEventListener("drop", (e) => {
  e.preventDefault();
  viewportWrapper.classList.remove("drag-over");
  if (e.dataTransfer.files && e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
});

document.getElementById("file-input").addEventListener("change", (e) => {
  if (e.target.files[0]) handleFile(e.target.files[0]);
});
document.getElementById("json-input").addEventListener("change", (e) => {
  if (e.target.files[0]) loadJsonFile(e.target.files[0]);
});

function handleFile(file) {
  const name = file.name.toLowerCase();
  if (name.endsWith('.json') || file.type === 'application/json') {
    loadJsonFile(file);
    return;
  }
  const isDicom = name.endsWith('.dcm') || file.type === 'application/dicom';
  if (isDicom) {
    const reader = new FileReader();
    reader.onload = (evt) => {
      try { parseAndDisplayDicom(new Uint8Array(evt.target.result)); }
      catch (err) { notify("DICOM Error: " + err.message); }
    };
    reader.readAsArrayBuffer(file);
  } else {
    const reader = new FileReader();
    reader.onload = (evt) => setupImage(evt.target.result, true);
    reader.readAsDataURL(file);
  }
}

// JSON Load & Save
document.getElementById("btn-save-json").addEventListener("click", () => {
  if (!coords.S) { notify("No active tracing to save."); return; }
  const ptName = document.getElementById("pt-name").value || "Patient";
  const ptChart = document.getElementById("pt-chart").value || "";
  const ptDateTime = document.getElementById("pt-datetime").value || "";

  let exportDataUrl = null;
  if (imgElem.src && imgElem.naturalWidth > 0) {
    try {
      const expCanvas = document.createElement("canvas");
      expCanvas.width = imgElem.naturalWidth;
      expCanvas.height = imgElem.naturalHeight;
      const expCtx = expCanvas.getContext("2d");
      expCtx.drawImage(imgElem, 0, 0);
      exportDataUrl = expCanvas.toDataURL("image/jpeg", 0.92);
    } catch (e) { exportDataUrl = imgElem.src; }
  }

  const payload = {
    version: "3.5",
    patient: { name: ptName, chart: ptChart, datetime: ptDateTime, ethnicity: activeEthnicity },
    pxPerMm, cvmStage, coords, initialAiCoords,
    baselines: { t1: t1Baseline, t2: t2Baseline, t3: t3Baseline },
    metrics: latestMetrics, diagnosis: latestDiagnosis,
    imageDataUrl: exportDataUrl
  };

  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `Ceph_${ptName.replace(/\s+/g, '_')}_${ptDateTime.slice(0, 10)}.json`;
  a.click();
  notify("JSON Case Record Exported");
});

function loadJsonFile(file) {
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = JSON.parse(e.target.result);
      if (data.patient) {
        document.getElementById("pt-name").value = data.patient.name || "";
        document.getElementById("pt-chart").value = data.patient.chart || "";
        if (data.patient.datetime) document.getElementById("pt-datetime").value = data.patient.datetime;
        if (data.patient.ethnicity) {
          activeEthnicity = data.patient.ethnicity;
          document.getElementById("ethnicity-select").value = activeEthnicity;
        }
      }
      if (data.pxPerMm) {
        pxPerMm = data.pxPerMm;
        calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (JSON Loaded)`;
      }
      if (data.cvmStage) {
        cvmStage = data.cvmStage;
        highlightCvmButton(cvmStage);
      }
      if (data.baselines) {
        t1Baseline = data.baselines.t1 || null;
        t2Baseline = data.baselines.t2 || null;
        t3Baseline = data.baselines.t3 || null;
        updateSuperimpositionStatus();
      }

      const loadedCoords = data.coords || data.landmarks || null;
      if (loadedCoords && loadedCoords.S) {
        coords = JSON.parse(JSON.stringify(loadedCoords));
        initialAiCoords = data.initialAiCoords ? JSON.parse(JSON.stringify(data.initialAiCoords)) : JSON.parse(JSON.stringify(loadedCoords));
      }

      if (data.imageDataUrl && data.imageDataUrl.startsWith("data:image")) {
        setupImage(data.imageDataUrl, false);
      } else {
        createReferencePlaceholder();
        renderAnalysis();
      }
      setMobileTab("viewport");
      notify("JSON Record Loaded Successfully");
    } catch (err) { notify("Invalid JSON: " + err.message); }
  };
  reader.readAsText(file);
}

function createReferencePlaceholder() {
  dropzone.style.display = "none";
  container.style.display = "block";
  const refCanvas = document.createElement("canvas");
  refCanvas.width = 1200; refCanvas.height = 1400;
  const ctx = refCanvas.getContext("2d");
  ctx.fillStyle = "#020617"; ctx.fillRect(0, 0, 1200, 1400);
  ctx.strokeStyle = "#1e293b"; ctx.lineWidth = 1;
  for (let x = 0; x < 1200; x += 50) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, 1400); ctx.stroke(); }
  for (let y = 0; y < 1400; y += 50) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(1200, y); ctx.stroke(); }
  imgElem.src = refCanvas.toDataURL("image/png");
  svgElem.setAttribute("viewBox", "0 0 1200 1400");
}

function parseAndDisplayDicom(byteArray) {
  const dataSet = dicomParser.parseDicom(byteArray);
  const ptName = dataSet.string('x00100010');
  if (ptName) document.getElementById('pt-name').value = ptName.replace(/\^/g, ' ').trim();
  const ptId = dataSet.string('x00100020');
  if (ptId) document.getElementById('pt-chart').value = ptId.trim();

  const spacingStr = dataSet.string('x00280030') || dataSet.string('x00181164');
  if (spacingStr) {
    const parts = spacingStr.split('\\').map(parseFloat);
    if (parts[0] > 0) {
      pxPerMm = 1.0 / parts[0];
      calStatus.innerText = `DICOM Calibrated: ${pxPerMm.toFixed(2)} px/mm`;
    }
  }

  const rows = dataSet.uint16('x00280010');
  const cols = dataSet.uint16('x00280011');
  const bitsAllocated = dataSet.uint16('x00280100') || 16;
  const pixelRep = dataSet.uint16('x00280103') || 0;
  const isMonochrome1 = (dataSet.string('x00280004') || '').trim() === 'MONOCHROME1';
  const pixelDataElem = dataSet.elements.x7fe00010;

  const offCanvas = document.createElement("canvas");
  offCanvas.width = cols; offCanvas.height = rows;
  const ctx = offCanvas.getContext("2d");
  const imgData = ctx.createImageData(cols, rows);
  const numPixels = rows * cols;

  let slope = parseFloat(dataSet.string('x00281053')) || 1;
  let intercept = parseFloat(dataSet.string('x00281052')) || 0;
  let wc = parseFloat(dataSet.string('x00281050'));
  let ww = parseFloat(dataSet.string('x00281051'));

  if (bitsAllocated === 16) {
    const u8 = new Uint8Array(byteArray.buffer, byteArray.byteOffset + pixelDataElem.dataOffset, numPixels * 2);
    const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
    const vals = new Float32Array(numPixels);
    let minVal = Infinity, maxVal = -Infinity;
    for (let i = 0; i < numPixels; i++) {
      let raw = pixelRep === 1 ? dv.getInt16(i * 2, true) : dv.getUint16(i * 2, true);
      let v = raw * slope + intercept;
      vals[i] = v;
      if (v < minVal) minVal = v;
      if (v > maxVal) maxVal = v;
    }
    if (isNaN(wc) || isNaN(ww) || ww <= 0) { wc = (minVal + maxVal) / 2; ww = Math.max(1, maxVal - minVal); }
    const low = wc - ww / 2;
    for (let i = 0; i < numPixels; i++) {
      let intensity = Math.min(255, Math.max(0, ((vals[i] - low) / ww) * 255));
      if (isMonochrome1) intensity = 255 - intensity;
      const idx = i * 4;
      imgData.data[idx] = intensity; imgData.data[idx+1] = intensity; imgData.data[idx+2] = intensity; imgData.data[idx+3] = 255;
    }
  } else {
    const u8 = new Uint8Array(byteArray.buffer, byteArray.byteOffset + pixelDataElem.dataOffset, numPixels);
    for (let i = 0; i < numPixels; i++) {
      let intensity = isMonochrome1 ? 255 - u8[i] : u8[i];
      const idx = i * 4;
      imgData.data[idx] = intensity; imgData.data[idx+1] = intensity; imgData.data[idx+2] = intensity; imgData.data[idx+3] = 255;
    }
  }
  ctx.putImageData(imgData, 0, 0);
  setupImage(offCanvas.toDataURL("image/png"), true);
}

function setupImage(srcUrl, shouldRunAi = true) {
  imgElem.onload = () => {
    dropzone.style.display = "none";
    container.style.display = "block";
    svgElem.setAttribute("viewBox", `0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
    svgElem.setAttribute("width", imgElem.clientWidth);
    svgElem.setAttribute("height", imgElem.clientHeight);
    setMobileTab("viewport");
    if (shouldRunAi && session) runAutoTrace();
    else renderAnalysis();
  };
  imgElem.src = srcUrl;
}

// =============================================================
// 4. Dual-Model Inference & Anatomical Corridor Ray-Caster
// =============================================================
async function runAutoTrace() {
  if (!session || !imgElem.src) return;
  statusInd.style.backgroundColor = "var(--status-amber)";
  statusTxt.innerText = "Auto-Tracing Landmarks...";

  await new Promise(r => setTimeout(r, 40));

  const origW = imgElem.naturalWidth;
  const origH = imgElem.naturalHeight;

  // 1. Primary 29-Channel Cephalometric Model Inference
  const off = document.createElement("canvas");
  off.width = 768; off.height = 768;
  const ctx = off.getContext("2d");
  ctx.drawImage(imgElem, 0, 0, 768, 768);
  const data = ctx.getImageData(0, 0, 768, 768).data;

  const floatArr = new Float32Array(3 * 768 * 768);
  const mean = [0.485, 0.456, 0.406];
  const std = [0.229, 0.224, 0.225];

  for (let i = 0; i < 768 * 768; i++) {
    floatArr[i] = (data[i * 4] / 255.0 - mean[0]) / std[0];
    floatArr[768 * 768 + i] = (data[i * 4 + 1] / 255.0 - mean[1]) / std[1];
    floatArr[2 * 768 * 768 + i] = (data[i * 4 + 2] / 255.0 - mean[2]) / std[2];
  }

  const tensor = new ort.Tensor("float32", floatArr, [1, 3, 768, 768]);
  const results = await session.run({ [session.inputNames[0]]: tensor });
  const heatmaps = results[session.outputNames[0]].data;

  coords = {};
  for (const [name, ch] of Object.entries(LM_INDICES)) {
    let maxVal = -Infinity, maxIdx = 0;
    const offset = ch * 192 * 192;
    for (let j = 0; j < 192 * 192; j++) {
      if (heatmaps[offset + j] > maxVal) { maxVal = heatmaps[offset + j]; maxIdx = j; }
    }
    coords[name] = {
      x: (maxIdx % 192 / 192) * origW,
      y: (Math.floor(maxIdx / 192) / 192) * origH
    };
  }

  // Derive Functional Occlusal Plane
  if (coords.UIT && coords.LIT) {
    coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
  }
  if (coords.Go && coords.OP_A) {
    coords.OP_P = { x: coords.OP_A.x - (coords.OP_A.x - coords.Go.x) * 0.55, y: coords.OP_A.y - 12 };
  }

  // 2. Airway & Cervical Spine (C2-C4) Detection Pipeline
  let cvmInferredFromOnnx = false;

  if (cvmSession && coords.Po && coords.Go && coords.Ar) {
    try {
      const ramusX = coords.R ? coords.R.x : (coords.Ar.x + coords.Go.x) / 2;
      const roiX = Math.max(0, Math.floor(coords.Po.x - (ramusX - coords.Po.x) * 0.5));
      const roiY = Math.max(0, Math.floor(coords.Ar.y));
      const roiW = Math.min(origW - roiX, Math.floor((ramusX - roiX) * 1.3));
      const roiH = Math.min(origH - roiY, Math.floor((coords.Go.y - coords.Ar.y) * 2.3));

      const roiCanvas = document.createElement("canvas");
      roiCanvas.width = 256; roiCanvas.height = 256;
      const rCtx = roiCanvas.getContext("2d");
      rCtx.drawImage(imgElem, roiX, roiY, roiW, roiH, 0, 0, 256, 256);
      const rData = rCtx.getImageData(0, 0, 256, 256).data;

      const rFloat = new Float32Array(3 * 256 * 256);
      for (let i = 0; i < 256 * 256; i++) {
        rFloat[i] = (rData[i * 4] / 255.0 - 0.485) / 0.229;
        rFloat[256 * 256 + i] = (rData[i * 4 + 1] / 255.0 - 0.456) / 0.224;
        rFloat[2 * 256 * 256 + i] = (rData[i * 4 + 2] / 255.0 - 0.406) / 0.225;
      }

      const rTensor = new ort.Tensor("float32", rFloat, [1, 3, 256, 256]);
      const cvmOut = await cvmSession.run({ [cvmSession.inputNames[0]]: rTensor });
      const kps = cvmOut[cvmSession.outputNames[0]].data;

      const mapPt = (idx) => ({
        x: roiX + kps[idx * 2] * roiW,
        y: roiY + kps[idx * 2 + 1] * roiH
      });

      coords.C2_LL = mapPt(0); coords.C2_INF = mapPt(1); coords.C2_LR = mapPt(2);
      coords.C3_UL = mapPt(3); coords.C3_UR = mapPt(4);
      coords.C3_LL = mapPt(5); coords.C3_INF = mapPt(6); coords.C3_LR = mapPt(7);
      coords.C4_UL = mapPt(8); coords.C4_UR = mapPt(9);
      coords.C4_LL = mapPt(10); coords.C4_INF = mapPt(11); coords.C4_LR = mapPt(12);

      if (kps.length >= 30) {
        coords.UPW = mapPt(13);
        coords.LPW = mapPt(14);
      }

      // Check if Stage Probabilities output is returned
      if (cvmSession.outputNames.length > 1 && cvmOut[cvmSession.outputNames[1]]) {
        const probs = cvmOut[cvmSession.outputNames[1]].data;
        let bestP = -1, bestS = 2;
        for (let s = 0; s < 6; s++) {
          if (probs[s] > bestP) { bestP = probs[s]; bestS = s; }
        }
        const stageNames = ["CS1", "CS2", "CS3", "CS4", "CS5", "CS6"];
        cvmStage = stageNames[bestS];
        highlightCvmButton(cvmStage);
      }

      cvmInferredFromOnnx = true;
    } catch (err) {
      console.warn("CVM ONNX inference fallback to corridor scanner:", err);
    }
  }

  // Fallback Anatomical Corridor Scanner for Cervical Spine and Pharynx
  if (!cvmInferredFromOnnx && coords.Po && coords.Go && coords.Ar) {
    const rx = coords.R ? coords.R.x : (coords.Ar.x + coords.Go.x) / 2;
    const vW = Math.max(22, pxPerMm * 18.0); // Human vertebra body width ~18mm
    const vH = Math.max(18, pxPerMm * 14.5); // Human vertebra body height ~14.5mm
    const spineX = rx - vW * 0.95; // Positioned behind posterior border of mandibular ramus

    // C2 (Axis) Inferior Border
    const c2Y = coords.Ar.y + (coords.Go.y - coords.Ar.y) * 0.35;
    coords.C2_LL = { x: spineX - vW * 0.45, y: c2Y };
    coords.C2_INF = { x: spineX, y: c2Y - vH * 0.15 };
    coords.C2_LR = { x: spineX + vW * 0.45, y: c2Y + vH * 0.05 };

    // C3 Body
    const c3Y = c2Y + vH * 0.65;
    coords.C3_UL = { x: spineX - vW * 0.45, y: c3Y };
    coords.C3_UR = { x: spineX + vW * 0.45, y: c3Y + vH * 0.05 };
    coords.C3_LL = { x: spineX - vW * 0.45, y: c3Y + vH };
    coords.C3_INF = { x: spineX, y: c3Y + vH - vH * 0.15 };
    coords.C3_LR = { x: spineX + vW * 0.45, y: c3Y + vH + vH * 0.05 };

    // C4 Body (following cervical lordosis curvature)
    const c4Y = c3Y + vH * 1.35;
    const lordosisShift = vW * 0.08;
    coords.C4_UL = { x: spineX - vW * 0.45 - lordosisShift, y: c4Y };
    coords.C4_UR = { x: spineX + vW * 0.45 - lordosisShift, y: c4Y + vH * 0.05 };
    coords.C4_LL = { x: spineX - vW * 0.45 - lordosisShift, y: c4Y + vH };
    coords.C4_INF = { x: spineX - lordosisShift, y: c4Y + vH - vH * 0.12 };
    coords.C4_LR = { x: spineX + vW * 0.45 - lordosisShift, y: c4Y + vH + vH * 0.05 };
  }

  // Derive Airway Reference Points using Channel 17 (PNS), Channel 22 (R), and Go
  if (coords.PNS) {
    coords.P_Palate = { x: coords.PNS.x + 8, y: coords.PNS.y + 24 };
    if (!coords.UPW) coords.UPW = { x: coords.PNS.x - (pxPerMm * 17.5), y: coords.PNS.y + 24 };
  }
  if (coords.Go && coords.B) {
    coords.TB = { x: coords.Go.x + (coords.B.x - coords.Go.x) * 0.35, y: coords.Go.y - 14 };
    if (!coords.LPW) coords.LPW = { x: coords.TB.x - (pxPerMm * 12.0), y: coords.TB.y };
  }

  // Initial Caliper Ruler
  coords.RULER_1 = { x: origW * 0.82, y: origH * 0.12 };
  coords.RULER_2 = { x: origW * 0.82, y: origH * 0.12 + (pxPerMm * 10.0) };

  initialAiCoords = JSON.parse(JSON.stringify(coords));
  statusInd.style.backgroundColor = "var(--status-green)";
  statusTxt.innerText = cvmInferredFromOnnx ? "Dual AI Auto-Trace Complete" : "Auto-Trace Complete (Ceph29 + Corridor)";
  renderAnalysis();
}

document.getElementById("btn-retrace-all").addEventListener("click", () => {
  if (!imgElem.src) return;
  if (Object.keys(initialAiCoords).length > 0) {
    coords = JSON.parse(JSON.stringify(initialAiCoords));
    renderAnalysis();
    notify("Landmarks reset to AI prediction");
  } else { runAutoTrace(); }
});

document.getElementById("btn-reset-single").addEventListener("click", () => {
  if (selectedLm && initialAiCoords[selectedLm]) {
    coords[selectedLm] = { ...initialAiCoords[selectedLm] };
    renderAnalysis();
    notify(`Reset ${selectedLm}`);
  } else { notify("Click any landmark dot first to reset it."); }
});

document.getElementById("btn-retrace-scale").addEventListener("click", () => {
  if (coords.RULER_1 && coords.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.0;
      calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Recalibrated)`;
      renderAnalysis();
      notify(`Recalculated with ${pxPerMm.toFixed(2)} px/mm scale`);
    }
  }
});

// =============================================================
// 5. Longitudinal Superimposition Engine (T1 vs. T2 vs. T3)
// =============================================================
function lockBaseline(stageKey, label) {
  if (!coords.S) {
    notify(`Trace a cephalogram first before locking as ${stageKey}.`);
    return;
  }
  const dateStr = (document.getElementById("pt-datetime").value || stageKey).replace("T", " ");
  const payload = {
    coords: JSON.parse(JSON.stringify(coords)),
    metrics: JSON.parse(JSON.stringify(latestMetrics)),
    date: dateStr
  };

  if (stageKey === "T1") t1Baseline = payload;
  else if (stageKey === "T2") t2Baseline = payload;
  else if (stageKey === "T3") t3Baseline = payload;

  updateSuperimpositionStatus();
  renderAnalysis();
  notify(`${label} baseline locked (${dateStr}).`);
}

function updateSuperimpositionStatus() {
  const t1Txt = t1Baseline ? `<span style="color:#5eead4; font-weight:700;">T1: ${t1Baseline.date}</span>` : "T1: -";
  const t2Txt = t2Baseline ? `<span style="color:#93c5fd; font-weight:700;">T2: ${t2Baseline.date}</span>` : "T2: -";
  const t3Txt = t3Baseline ? `<span style="color:#f0abfc; font-weight:700;">T3: ${t3Baseline.date}</span>` : "T3: -";
  document.getElementById("super-status").innerHTML = `${t1Txt} | ${t2Txt} | ${t3Txt}`;
  document.getElementById("th-t1-abo").style.display = t1Baseline ? "table-cell" : "none";
}

document.getElementById("btn-lock-t1").addEventListener("click", () => lockBaseline("T1", "T1 Initial"));
document.getElementById("btn-lock-t2").addEventListener("click", () => lockBaseline("T2", "T2 Progress"));
document.getElementById("btn-lock-t3").addEventListener("click", () => lockBaseline("T3", "T3 Final"));

document.getElementById("btn-clear-series").addEventListener("click", () => {
  t1Baseline = null; t2Baseline = null; t3Baseline = null;
  updateSuperimpositionStatus();
  renderAnalysis();
  notify("Longitudinal baselines cleared.");
});

function getAlignedCoordsForBaseline(baselineObj) {
  if (!baselineObj || !baselineObj.coords.S || !coords.S) return null;
  const mode = document.getElementById("super-mode").value;

  const s1 = baselineObj.coords.S, s2 = coords.S;
  let origin1 = s1, origin2 = s2;
  let angle1 = 0, angle2 = 0;

  if (mode === "MAXILLARY" && baselineObj.coords.PNS && baselineObj.coords.ANS && coords.PNS && coords.ANS) {
    origin1 = baselineObj.coords.PNS; origin2 = coords.PNS;
    angle1 = Math.atan2(baselineObj.coords.ANS.y - baselineObj.coords.PNS.y, baselineObj.coords.ANS.x - baselineObj.coords.PNS.x);
    angle2 = Math.atan2(coords.ANS.y - coords.PNS.y, coords.ANS.x - coords.PNS.x);
  } else if (mode === "MANDIBULAR" && baselineObj.coords.Me && baselineObj.coords.Go && coords.Me && coords.Go) {
    origin1 = baselineObj.coords.Me; origin2 = coords.Me;
    angle1 = Math.atan2(baselineObj.coords.Go.y - baselineObj.coords.Me.y, baselineObj.coords.Go.x - baselineObj.coords.Me.x);
    angle2 = Math.atan2(coords.Go.y - coords.Me.y, coords.Go.x - coords.Me.x);
  } else {
    if (!baselineObj.coords.N || !coords.N) return null;
    angle1 = Math.atan2(baselineObj.coords.N.y - s1.y, baselineObj.coords.N.x - s1.x);
    angle2 = Math.atan2(coords.N.y - s2.y, coords.N.x - s2.x);
  }

  const dTheta = angle2 - angle1;
  const cosT = Math.cos(dTheta), sinT = Math.sin(dTheta);
  const aligned = {};

  for (const [k, pt] of Object.entries(baselineObj.coords)) {
    const dx = pt.x - origin1.x;
    const dy = pt.y - origin1.y;
    aligned[k] = {
      x: origin2.x + (dx * cosT - dy * sinT),
      y: origin2.y + (dx * sinT + dy * cosT)
    };
  }
  return aligned;
}

// CVM Selector
document.querySelectorAll(".cvm-btn").forEach(btn => {
  btn.addEventListener("click", () => {
    cvmStage = btn.getAttribute("data-cvm");
    highlightCvmButton(cvmStage);
    renderAnalysis();
  });
});
function highlightCvmButton(stg) {
  document.querySelectorAll(".cvm-btn").forEach(b => b.classList.toggle("active", b.getAttribute("data-cvm") === stg));
  document.getElementById("cvm-desc").innerText = CVM_INFO[stg] || "CVM Stage Selected";
}

// Focus Modes & View Toggles
document.querySelectorAll(".mode-btn").forEach(btn => {
  btn.addEventListener("click", () => {
    document.querySelectorAll(".mode-btn").forEach(b => b.classList.remove("active"));
    btn.classList.add("active");
    focusMode = btn.getAttribute("data-mode");
    renderAnalysis();
  });
});

function setupToggle(id, label, getter, setter) {
  const el = document.getElementById(id);
  el.addEventListener("click", () => {
    const next = !getter();
    setter(next);
    el.classList.toggle("active", next);
    el.innerText = `${label}: ${next ? 'ON' : 'OFF'}`;
    renderAnalysis();
  });
}
setupToggle("tog-lines", "Lines", () => showLines, v => showLines = v);
setupToggle("tog-points", "Dots", () => showPoints, v => showPoints = v);
setupToggle("tog-labels", "Names", () => showLabels, v => showLabels = v);

window.addEventListener("keydown", (e) => {
  if (e.code === "Space" && document.activeElement.tagName !== "INPUT") {
    e.preventDefault();
    if (!spacebarPeek) { spacebarPeek = true; svgElem.style.opacity = "0"; }
  }
});
window.addEventListener("keyup", (e) => {
  if (e.code === "Space") { spacebarPeek = false; svgElem.style.opacity = "1"; }
});

// Ruler & Magnifier Loupe
calBtn.addEventListener("click", () => {
  showRuler = !showRuler;
  calBtn.innerText = `Ruler: ${showRuler ? 'ON' : 'OFF'}`;
  renderAnalysis();
});

function getSVGCoords(e) {
  const pt = svgElem.createSVGPoint();
  pt.x = e.clientX; pt.y = e.clientY;
  return pt.matrixTransform(svgElem.getScreenCTM().inverse());
}

function updateLoupe(pt, name) {
  if (!imgElem.src) return;
  loupeBox.style.display = "block";
  loupeLabel.innerText = name;
  const lCtx = loupeCanvas.getContext("2d");
  const zoom = 3.0, size = 140, srcSize = size / zoom;
  lCtx.clearRect(0, 0, size, size);
  lCtx.filter = imgElem.style.filter || "none";
  lCtx.drawImage(imgElem, pt.x - srcSize / 2, pt.y - srcSize / 2, srcSize, srcSize, 0, 0, size, size);
  lCtx.filter = "none";
  lCtx.strokeStyle = "#38bdf8"; lCtx.lineWidth = 1.5;
  lCtx.beginPath();
  lCtx.moveTo(size/2, 0); lCtx.lineTo(size/2, size/2 - 5);
  lCtx.moveTo(size/2, size/2 + 5); lCtx.lineTo(size/2, size);
  lCtx.moveTo(0, size/2); lCtx.lineTo(size/2 - 5, size/2);
  lCtx.moveTo(size/2 + 5, size/2); lCtx.lineTo(size, size/2);
  lCtx.stroke();
}

window.addEventListener("mousemove", (e) => {
  if (!draggingLm || !coords[draggingLm]) return;
  const p = getSVGCoords(e);
  coords[draggingLm].x = p.x;
  coords[draggingLm].y = p.y;
  if ((draggingLm === "RULER_1" || draggingLm === "RULER_2") && coords.RULER_1 && coords.RULER_2) {
    const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
    if (dist > 1) {
      pxPerMm = dist / 10.0;
      calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm`;
    }
  }
  updateLoupe(p, draggingLm);
  renderAnalysis();
});

window.addEventListener("mouseup", () => {
  if (draggingLm) {
    draggingLm = null;
    loupeBox.style.display = "none";
    document.querySelectorAll(".landmark-handle").forEach(el => el.classList.remove("dragging"));
  }
});

// Touch event handlers for mobile
function handleTouchMove(e) {
  if (!draggingLm || !coords[draggingLm] || !e.touches[0]) return;
  e.preventDefault();
  const touch = e.touches[0];
  const p = getSVGCoords(touch);
  coords[draggingLm].x = p.x; coords[draggingLm].y = p.y;
  if ((draggingLm === "RULER_1" || draggingLm === "RULER_2") && coords.RULER_1 && coords.RULER_2) {
    const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
    if (dist > 1) pxPerMm = dist / 10.0;
  }
  updateLoupe(p, draggingLm);
  renderAnalysis();
}
window.addEventListener("touchmove", handleTouchMove, { passive: false });
window.addEventListener("touchend", () => {
  if (draggingLm) {
    draggingLm = null;
    loupeBox.style.display = "none";
    renderAnalysis();
  }
});

// Clear Patient
document.getElementById("btn-next-patient").addEventListener("click", () => {
  coords = {}; initialAiCoords = {}; latestMetrics = {};
  t1Baseline = null; t2Baseline = null; t3Baseline = null;
  selectedLm = null; cvmStage = "CS3";
  highlightCvmButton("CS3");
  updateSuperimpositionStatus();
  document.getElementById("selected-lm-label").innerText = "None";
  imgElem.src = "";
  container.style.display = "none";
  dropzone.style.display = "flex";
  document.getElementById("file-input").value = "";
  document.getElementById("pt-name").value = "";
  document.getElementById("pt-chart").value = "";
  setAutoDateTime();
  document.getElementById("diag-headline").innerText = "Automated Diagnosis: Awaiting Tracing...";
  document.getElementById("diag-sagittal").innerText = "-";
  document.getElementById("diag-vertical").innerText = "-";
  document.getElementById("diag-dental").innerText = "-";
  document.getElementById("diag-soft").innerText = "-";
  svgElem.innerHTML = "";
  setMobileTab("tools");
  notify("Patient Session Reset");
});

// =============================================================
// 6. Mathematical & Clinical Analysis Engine
// =============================================================
function getAngle(p1, v, p2) {
  if (!p1 || !v || !p2) return null;
  const v1 = { x: p1.x - v.x, y: p1.y - v.y };
  const v2 = { x: p2.x - v.x, y: p2.y - v.y };
  const dot = v1.x * v2.x + v1.y * v2.y;
  const m1 = Math.hypot(v1.x, v1.y), m2 = Math.hypot(v2.x, v2.y);
  return parseFloat((Math.acos(Math.max(-1, Math.min(1, dot / (m1 * m2 + 1e-7)))) * (180 / Math.PI)).toFixed(1));
}

function getLineAngle(p1, p2, p3, p4) {
  if (!p1 || !p2 || !p3 || !p4) return null;
  const v1 = { x: p2.x - p1.x, y: p2.y - p1.y };
  const v2 = { x: p4.x - p3.x, y: p4.y - p3.y };
  const dot = v1.x * v2.x + v1.y * v2.y;
  const m1 = Math.hypot(v1.x, v1.y), m2 = Math.hypot(v2.x, v2.y);
  let deg = (Math.acos(Math.max(-1, Math.min(1, dot / (m1 * m2 + 1e-7)))) * (180 / Math.PI));
  if (deg > 90) deg = 180 - deg;
  return parseFloat(deg.toFixed(1));
}

function getPerpDist(pt, l1, l2) {
  if (!pt || !l1 || !l2 || !pxPerMm) return null;
  const v = { x: l2.x - l1.x, y: l2.y - l1.y };
  const len = Math.hypot(v.x, v.y);
  if (len === 0) return null;
  const cross = v.x * (pt.y - l1.y) - v.y * (pt.x - l1.x);
  return parseFloat((cross / len / pxPerMm).toFixed(1));
}

function calculateWits(ptA, ptB, opP, opA) {
  if (!ptA || !ptB || !opP || !opA || !pxPerMm) return null;
  const vx = opA.x - opP.x, vy = opA.y - opP.y;
  const len = Math.hypot(vx, vy);
  if (len === 0) return null;
  const ux = vx / len, uy = vy / len;
  const tA = (ptA.x - opP.x) * ux + (ptA.y - opP.y) * uy;
  const tB = (ptB.x - opP.x) * ux + (ptB.y - opP.y) * uy;
  return { distMm: parseFloat(((tA - tB) / pxPerMm).toFixed(1)), ao: { x: opP.x + tA * ux, y: opP.y + tA * uy }, bo: { x: opP.x + tB * ux, y: opP.y + tB * uy } };
}

function evaluateCvmMorphology() {
  if (!coords.C3_LL || !coords.C3_LR || !coords.C3_INF || !coords.C4_LL || !coords.C4_LR || !coords.C4_INF) return null;
  const c3Concavity = Math.abs(getPerpDist(coords.C3_INF, coords.C3_LL, coords.C3_LR));
  const c4Concavity = Math.abs(getPerpDist(coords.C4_INF, coords.C4_LL, coords.C4_LR));

  const c3W = Math.hypot(coords.C3_LR.x - coords.C3_LL.x, coords.C3_LR.y - coords.C3_LL.y);
  const c3H = Math.hypot(coords.C3_LL.x - coords.C3_UL.x, coords.C3_LL.y - coords.C3_UL.y);
  const c3Ratio = parseFloat((c3W / (c3H + 1e-5)).toFixed(2));

  let shape = "Horizontal Rectangular";
  if (c3Ratio > 1.35) shape = "Trapezoid / Tapered";
  else if (c3Ratio >= 0.92 && c3Ratio <= 1.12) shape = "Square";
  else if (c3Ratio < 0.92) shape = "Vertical Rectangular";

  return { c3Concavity, c4Concavity, c3Ratio, shape };
}

function getNormObj(id) {
  return ABO_NORMS.find(x => x.id === id) || { norm: 0, sd: 1 };
}

function updateClinicalDiagnosis(m) {
  if (m.ANB === null) return;
  const anbN = getNormObj("ANB");
  const snaN = getNormObj("SNA");
  const snbN = getNormObj("SNB");

  let skelClass = "Skeletal Class I";
  if (m.ANB > anbN.norm + anbN.sd) skelClass = "Skeletal Class II";
  else if (m.ANB < anbN.norm - anbN.sd) skelClass = "Skeletal Class III";

  let jawNote = [];
  if (m.SNA > snaN.norm + snaN.sd) jawNote.push("Maxillary Prognathism");
  else if (m.SNA < snaN.norm - snaN.sd) jawNote.push("Maxillary Retrognathism");
  if (m.SNB > snbN.norm + snbN.sd) jawNote.push("Mandibular Prognathism");
  else if (m.SNB < snbN.norm - snbN.sd) jawNote.push("Mandibular Retrognathism");

  const sagStr = jawNote.length > 0 ? `${skelClass} (${jawNote.join(", ")})` : `${skelClass} (Orthognathic Base)`;
  const fmaN = getNormObj("FMA");
  const snmpN = getNormObj("SNMP");
  let vertClass = "Normodivergent";
  if (m.FMA > fmaN.norm + fmaN.sd || m.SNMP > snmpN.norm + snmpN.sd) vertClass = "Hyperdivergent (High Angle)";
  else if (m.FMA < fmaN.norm - fmaN.sd || m.SNMP < snmpN.norm - snmpN.sd) vertClass = "Hypodivergent (Low Angle)";

  const u1N = getNormObj("U1SN");
  const impaN = getNormObj("IMPA");
  let u1Str = "Normal U1";
  if (m.U1SN > u1N.norm + u1N.sd) u1Str = "Proclined U1";
  else if (m.U1SN < u1N.norm - u1N.sd) u1Str = "Retroclined U1";

  let l1Str = "Normal L1";
  if (m.IMPA > impaN.norm + impaN.sd) l1Str = "Proclined L1";
  else if (m.IMPA < impaN.norm - impaN.sd) l1Str = "Retroclined L1";

  const dentStr = `${u1Str}, ${l1Str}`;
  const llN = getNormObj("LL_E");
  let softStr = "Balanced Lips";
  if (m.LL_E > llN.norm + llN.sd) softStr = "Protrusive Lips";
  else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";

  const softAndCvm = `${softStr} | CVM: ${cvmStage}`;
  const headline = `${skelClass} • ${vertClass} • ${dentStr} • [${cvmStage}]`;

  latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
  document.getElementById("diag-headline").innerText = headline;
  document.getElementById("diag-sagittal").innerText = sagStr;
  document.getElementById("diag-vertical").innerText = vertClass;
  document.getElementById("diag-dental").innerText = dentStr;
  document.getElementById("diag-soft").innerText = softAndCvm;
}

// =============================================================
// 7. Vector Rendering Engine & Tables
// =============================================================
function renderAnalysis() {
  svgElem.innerHTML = "";
  if (!coords.S) return;

  function line(p1, p2, col, w = 2.5, dash = null) {
    if (!p1 || !p2) return;
    const l = document.createElementNS("http://www.w3.org/2000/svg", "line");
    l.setAttribute("x1", p1.x); l.setAttribute("y1", p1.y);
    l.setAttribute("x2", p2.x); l.setAttribute("y2", p2.y);
    l.setAttribute("stroke", col);
    l.setAttribute("stroke-width", w);
    l.setAttribute("stroke-linecap", "round");
    if (dash) l.setAttribute("stroke-dasharray", dash);
    svgElem.appendChild(l);
  }

  const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
  const cvmMorph = evaluateCvmMorphology();

  // 1. Draw Longitudinal Superimpositions (T1, T2, T3)
  const drawSuperLines = (alCoords, col, dash) => {
    if (!alCoords) return;
    line(alCoords.S, alCoords.N, col, 2.5, dash);
    line(alCoords.N, alCoords.A, col, 2, dash);
    line(alCoords.N, alCoords.B, col, 2, dash);
    line(alCoords.Go, alCoords.Me, col, 2.5, dash);
    line(alCoords.UIT, alCoords.UIA, col, 2, dash);
    line(alCoords.LIT, alCoords.LIA, col, 2, dash);
  };

  if (focusMode === "SUPER" || focusMode === "ALL") {
    if (t1Baseline) drawSuperLines(getAlignedCoordsForBaseline(t1Baseline), "#94a3b8", "4,3");
    if (t2Baseline) drawSuperLines(getAlignedCoordsForBaseline(t2Baseline), "#3b82f6", "5,2");
    if (t3Baseline) drawSuperLines(getAlignedCoordsForBaseline(t3Baseline), "#d946ef", "3,2");
  }

  // 2. Current Tracing Vectors
  if (showLines) {
    const isSuper = focusMode === "SUPER";
    if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
      line(coords.S, coords.N, isSuper ? "#f43f5e" : "#38bdf8", 3);
      line(coords.N, coords.A, isSuper ? "#f43f5e" : "#4ade80", 2);
      line(coords.N, coords.B, isSuper ? "#f43f5e" : "#4ade80", 2);
      line(coords.Po, coords.Or, isSuper ? "#f43f5e" : "#fbbf24", 2.5);
      line(coords.Go, coords.Me, isSuper ? "#f43f5e" : "#f43f5e", 3);
      line(coords.UIT, coords.UIA, isSuper ? "#f43f5e" : "#2dd4bf", 2.5);
      line(coords.LIT, coords.LIA, isSuper ? "#f43f5e" : "#d946ef", 2.5);
      line(coords.Pn, coords.Pog_soft, isSuper ? "#f43f5e" : "#fb923c", 2);
    }

    if (focusMode === "MCNAMARA" || focusMode === "ALL") {
      line(coords.Co, coords.A, "#38bdf8", 2.5);
      line(coords.Co, coords.Gn, "#38bdf8", 2.5);
      line(coords.ANS, coords.Me, "#ec4899", 2.5);
      if (coords.N && coords.Po && coords.Or) {
        const fhAngle = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
        const perpAngle = fhAngle + Math.PI / 2;
        const pLen = 180;
        const nPerpEnd = { x: coords.N.x + Math.cos(perpAngle) * pLen, y: coords.N.y + Math.sin(perpAngle) * pLen };
        line(coords.N, nPerpEnd, "#f59e0b", 2, "4,3");
      }
    }

    if (focusMode === "TWEED" || focusMode === "ALL") {
      line(coords.Po, coords.Or, "#fbbf24", 2.5);
      line(coords.Go, coords.Me, "#f43f5e", 2.5);
      line(coords.LIT, coords.LIA, "#d946ef", 2.5);
    }

    if (focusMode === "AIRWAY" || focusMode === "ALL") {
      if (coords.P_Palate && coords.UPW) line(coords.P_Palate, coords.UPW, "#2dd4bf", 3);
      if (coords.TB && coords.LPW) line(coords.TB, coords.LPW, "#2dd4bf", 3);
      if (coords.PNS && coords.P_Palate) line(coords.PNS, coords.P_Palate, "#14b8a6", 1.5, "3,3");
    }

    if ((focusMode === "CVM" || focusMode === "ALL") && coords.C3_UL) {
      // C2 Lower Border
      if (coords.C2_LL && coords.C2_INF && coords.C2_LR) {
        line(coords.C2_LL, coords.C2_INF, "#facc15", 2.5);
        line(coords.C2_INF, coords.C2_LR, "#facc15", 2.5);
      }
      // C3 Contour
      line(coords.C3_UL, coords.C3_UR, "#14b8a6", 2);
      line(coords.C3_UR, coords.C3_LR, "#14b8a6", 2);
      line(coords.C3_UL, coords.C3_LL, "#14b8a6", 2);
      line(coords.C3_LL, coords.C3_INF, "#facc15", 2.5);
      line(coords.C3_INF, coords.C3_LR, "#facc15", 2.5);
      line(coords.C3_LL, coords.C3_LR, "#14b8a6", 1.2, "3,3");
      // C4 Contour
      line(coords.C4_UL, coords.C4_UR, "#14b8a6", 2);
      line(coords.C4_UR, coords.C4_LR, "#14b8a6", 2);
      line(coords.C4_UL, coords.C4_LL, "#14b8a6", 2);
      line(coords.C4_LL, coords.C4_INF, "#facc15", 2.5);
      line(coords.C4_INF, coords.C4_LR, "#facc15", 2.5);
      line(coords.C4_LL, coords.C4_LR, "#14b8a6", 1.2, "3,3");
      // Ramus Anterior Guide
      if (coords.Ar && coords.R && coords.Go) {
        line(coords.Ar, coords.R, "#64748b", 1.5, "4,3");
        line(coords.R, coords.Go, "#64748b", 1.5, "4,3");
      }
    }

    if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
      line(coords.Ls, coords.Pog_soft, "#ec4899", 2.5);
      line(coords.N, coords.Pog_soft, "#c084fc", 1.5, "4,4");
      line(coords.N, coords.Pog, "#94a3b8", 1.5, "4,4");
    }

    if ((focusMode === "WITS" || focusMode === "ALL") && coords.OP_P && coords.OP_A) {
      const dx = coords.OP_A.x - coords.OP_P.x, dy = coords.OP_A.y - coords.OP_P.y;
      const extP = { x: coords.OP_P.x - dx * 0.35, y: coords.OP_P.y - dy * 0.35 };
      const extA = { x: coords.OP_A.x + dx * 0.35, y: coords.OP_A.y + dy * 0.35 };
      line(extP, extA, "#a855f7", 2.5);
      if (wits) {
        line(coords.A, wits.ao, "#a855f7", 2, "3,3");
        line(coords.B, wits.bo, "#a855f7", 2, "3,3");
      }
    }
  }

  // 3. Ruler (10mm)
  if (showRuler && coords.RULER_1 && coords.RULER_2) {
    line(coords.RULER_1, coords.RULER_2, "#06b6d4", 2.5, "4,3");
    ["RULER_1", "RULER_2"].forEach((rKey, idx) => {
      const pt = coords[rKey];
      const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
      const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
      c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
      c.setAttribute("r", 6.5); c.setAttribute("fill", "#06b6d4");
      c.setAttribute("stroke", "#0f172a"); c.setAttribute("stroke-width", 2);
      c.setAttribute("class", "landmark-handle");
      const startDrag = (e) => { e.stopPropagation(); draggingLm = rKey; c.classList.add("dragging"); };
      c.addEventListener("mousedown", startDrag);
      c.addEventListener("touchstart", startDrag);
      g.appendChild(c);

      const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
      t.setAttribute("x", pt.x + 10); t.setAttribute("y", pt.y + 4);
      t.setAttribute("class", "landmark-text");
      t.style.fill = "#22d3ee";
      t.textContent = idx === 0 ? "0 mm" : "10 mm";
      g.appendChild(t);
      svgElem.appendChild(g);
    });
  }

  // 4. HIPAA Privacy Mask
  if (hipaaPrivacyMode && coords.N && coords.Or) {
    const mask = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    const mLeft = Math.min(coords.N.x, coords.Or.x) - 40;
    const mTop = Math.min(coords.N.y, coords.Or.y) - 35;
    const mWidth = Math.max(120, Math.abs(coords.N.x - coords.Or.x) + 90);
    mask.setAttribute("x", mLeft); mask.setAttribute("y", mTop);
    mask.setAttribute("width", mWidth); mask.setAttribute("height", 65);
    mask.setAttribute("fill", "#05070c");
    mask.setAttribute("rx", "6");
    svgElem.appendChild(mask);
  }

  // 5. Draw Landmark Dots
  const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
  if (showPoints) {
    for (const [name, pt] of Object.entries(coords)) {
      if (name === "RULER_1" || name === "RULER_2") continue;
      if (!activeSet.has(name)) continue;

      const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
      const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
      c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
      c.setAttribute("r", selectedLm === name ? 7 : 5);

      let handleColor = "#facc15";
      if (name === "Sn") handleColor = "#ec4899";
      if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
      if (name === "Co" || name === "Gn" || name === "Ar" || name === "R" || name === "PNS") handleColor = "#38bdf8";
      if (name === "P_Palate" || name === "UPW" || name === "TB" || name === "LPW") handleColor = "#2dd4bf";
      if (name.startsWith("C2_") || name.startsWith("C3_") || name.startsWith("C4_")) handleColor = "#14b8a6";
      if (selectedLm === name) handleColor = "#38bdf8";

      c.setAttribute("fill", handleColor);
      c.setAttribute("stroke", "#0f172a");
      c.setAttribute("stroke-width", 2);
      c.setAttribute("class", "landmark-handle");

      const onStart = (e) => {
        e.stopPropagation();
        draggingLm = name; selectedLm = name;
        document.getElementById("selected-lm-label").innerText = name;
        c.classList.add("dragging");
        updateLoupe(pt, name);
      };
      c.addEventListener("mousedown", onStart);
      c.addEventListener("touchstart", onStart);

      c.addEventListener("dblclick", (e) => {
        e.stopPropagation();
        if (initialAiCoords[name]) {
          coords[name] = { ...initialAiCoords[name] };
          notify(`Reset ${name} to AI position`);
          renderAnalysis();
        }
      });
      g.appendChild(c);

      if (showLabels) {
        const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
        t.setAttribute("x", pt.x + 8); t.setAttribute("y", pt.y - 4);
        t.setAttribute("class", "landmark-text");
        t.textContent = name;
        g.appendChild(t);
      }
      svgElem.appendChild(g);
    }
  }

  // 6. Metrics Calculations
  const sna = getAngle(coords.S, coords.N, coords.A);
  const snb = getAngle(coords.S, coords.N, coords.B);
  const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
  const fma = getLineAngle(coords.Po, coords.Or, coords.Go, coords.Me);
  const snmp = getLineAngle(coords.S, coords.N, coords.Go, coords.Me);
  const impa = getLineAngle(coords.LIT, coords.LIA, coords.Go, coords.Me);
  const u1sn = getLineAngle(coords.UIT, coords.UIA, coords.S, coords.N);
  const u1na_deg = getLineAngle(coords.UIT, coords.UIA, coords.N, coords.A);
  const u1na_mm = getPerpDist(coords.UIT, coords.N, coords.A);
  const l1nb_deg = getLineAngle(coords.LIT, coords.LIA, coords.N, coords.B);
  const l1nb_mm = getPerpDist(coords.LIT, coords.N, coords.B);
  const iia = getLineAngle(coords.UIT, coords.UIA, coords.LIT, coords.LIA);
  const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
  const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);

  // Tweed Triangle: FMA + IMPA + FMIA = 180°
  const fmia = (fma !== null && impa !== null) ? parseFloat((180.0 - (fma + impa)).toFixed(1)) : null;

  // McNamara Analysis
  let a_n_perp = null, pog_n_perp = null;
  if (coords.N && coords.Po && coords.Or && coords.A && coords.Pog) {
    const fhA = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
    const pA = fhA + Math.PI / 2;
    const nRef = { x: coords.N.x + Math.cos(pA) * 100, y: coords.N.y + Math.sin(pA) * 100 };
    a_n_perp = getPerpDist(coords.A, coords.N, nRef);
    pog_n_perp = getPerpDist(coords.Pog, coords.N, nRef);
  }
  const co_a = (coords.Co && coords.A && pxPerMm) ? parseFloat((Math.hypot(coords.A.x - coords.Co.x, coords.A.y - coords.Co.y) / pxPerMm).toFixed(1)) : null;
  const co_gn = (coords.Co && coords.Gn && pxPerMm) ? parseFloat((Math.hypot(coords.Gn.x - coords.Co.x, coords.Gn.y - coords.Co.y) / pxPerMm).toFixed(1)) : null;
  const mx_md_diff = (co_a !== null && co_gn !== null) ? parseFloat((co_gn - co_a).toFixed(1)) : null;
  const lafh = (coords.ANS && coords.Me && pxPerMm) ? parseFloat((Math.hypot(coords.Me.x - coords.ANS.x, coords.Me.y - coords.ANS.y) / pxPerMm).toFixed(1)) : null;

  // Pharyngeal Airway Dimensions
  const ups = (coords.P_Palate && coords.UPW && pxPerMm) ? parseFloat((Math.hypot(coords.P_Palate.x - coords.UPW.x, coords.P_Palate.y - coords.UPW.y) / pxPerMm).toFixed(1)) : null;
  const lps = (coords.TB && coords.LPW && pxPerMm) ? parseFloat((Math.hypot(coords.TB.x - coords.LPW.x, coords.TB.y - coords.LPW.y) / pxPerMm).toFixed(1)) : null;

  // Holdaway
  const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
  const skel_conv = getPerpDist(coords.A, coords.N, coords.Pog);
  const nose_prom = getPerpDist(coords.Pn, coords.Ls, coords.Pog_soft);
  const sn_hline = getPerpDist(coords.Sn, coords.Ls, coords.Pog_soft);
  const ll_hline = getPerpDist(coords.Li, coords.Ls, coords.Pog_soft);
  const chin_thick = (coords.Pog && coords.Pog_soft && pxPerMm) ? parseFloat((Math.hypot(coords.Pog_soft.x - coords.Pog.x, coords.Pog_soft.y - coords.Pog.y) / pxPerMm).toFixed(1)) : null;

  latestMetrics = {
    SNA: sna, SNB: snb, ANB: anb, FMA: fma, SNMP: snmp, IMPA: impa,
    U1SN: u1sn, U1NA_deg: u1na_deg, U1NA_mm: u1na_mm, L1NB_deg: l1nb_deg,
    L1NB_mm: l1nb_mm, IIA: iia, UL_E: ul_e, LL_E: ll_e,
    FMIA: fmia,
    A_N_PERP: a_n_perp, POG_N_PERP: pog_n_perp, CO_A: co_a, CO_GN: co_gn,
    MX_MD_DIFF: mx_md_diff, LAFH: lafh,
    UPS: ups, LPS: lps,
    WITS: wits ? wits.distMm : null,
    H_ANGLE: h_angle, SKEL_CONV: skel_conv, NOSE_PROM: nose_prom,
    SN_HLINE: sn_hline, LL_HLINE: ll_hline, CHIN_THICK: chin_thick
  };

  updateClinicalDiagnosis(latestMetrics);
  populateAboTable(ABO_NORMS, latestMetrics);
  populateTable("mcnamara-rows", MCNAMARA_NORMS, latestMetrics);
  populateTable("tweed-rows", TWEED_NORMS, latestMetrics);
  populateTable("holdaway-rows", HOLDAWAY_NORMS, latestMetrics);
  populateWitsTable(latestMetrics.WITS);
  populateAirwayTable(ups, lps);
  populateCvmTable(cvmMorph);
}

function populateAboTable(normsList, valuesDict) {
  const tbody = document.getElementById("abo-rows");
  tbody.innerHTML = "";
  normsList.forEach(m => {
    const val = valuesDict[m.id];
    let statusHtml = `<span class="pill pill-neutral">-</span>`;
    let measuredText = "-", diffText = "-", diffColor = "var(--text-muted)";
    let deltaT1Html = "";

    if (val !== null && val !== undefined) {
      measuredText = `${val.toFixed(1)}${m.unit}`;
      const rawDiff = val - m.norm;
      const isNormal = Math.abs(rawDiff) <= m.sd;
      diffText = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
      diffColor = isNormal ? "var(--status-green)" : "var(--status-red)";
      statusHtml = isNormal ? `<span class="pill pill-normal">Normal</span>` : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High' : 'Low'}</span>`;
    }

    if (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[m.id] !== undefined) {
      const dT1 = val - t1Baseline.metrics[m.id];
      deltaT1Html = `<td style="color:#5eead4; font-weight:700;">${dT1 > 0 ? '+' : ''}${dT1.toFixed(1)}${m.unit}</td>`;
    } else if (t1Baseline) { deltaT1Html = `<td>-</td>`; }

    const tr = document.createElement("tr");
    tr.innerHTML = `
      <td><span class="metric-name">${m.name}</span></td>
      <td><span class="metric-norm">${m.norm}${m.unit} ± ${m.sd}</span></td>
      <td><span class="metric-val">${measuredText}</span></td>
      <td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
      ${deltaT1Html}
      <td>${statusHtml}</td>
    `;
    tbody.appendChild(tr);
  });
}

function populateTable(elemId, normsList, valuesDict) {
  const tbody = document.getElementById(elemId);
  tbody.innerHTML = "";
  normsList.forEach(m => {
    const val = valuesDict[m.id];
    let statusHtml = `<span class="pill pill-neutral">-</span>`;
    let measuredText = "-", diffText = "-", diffColor = "var(--text-muted)";
    if (val !== null && val !== undefined) {
      measuredText = `${val.toFixed(1)}${m.unit}`;
      const rawDiff = val - m.norm;
      const isNormal = Math.abs(rawDiff) <= m.sd;
      diffText = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
      diffColor = isNormal ? "var(--status-green)" : "var(--status-red)";
      statusHtml = isNormal ? `<span class="pill pill-normal">Normal</span>` : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High' : 'Low'}</span>`;
    }
    const tr = document.createElement("tr");
    tr.innerHTML = `
      <td><span class="metric-name">${m.name}</span></td>
      <td><span class="metric-norm">${m.norm}${m.unit} ± ${m.sd}</span></td>
      <td><span class="metric-val">${measuredText}</span></td>
      <td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
      <td>${statusHtml}</td>
    `;
    tbody.appendChild(tr);
  });
}

function populateWitsTable(val) {
  const tbody = document.getElementById("wits-rows");
  tbody.innerHTML = "";
  if (val === null || val === undefined) return;
  const isNorm = val >= -1.0 && val <= 1.0;
  const tr = document.createElement("tr");
  tr.innerHTML = `
    <td><span class="metric-name">Wits (AO to BO)</span></td>
    <td><span class="metric-norm">0.0 ± 1.0 mm</span></td>
    <td><span class="metric-val" style="color: #c084fc;">${val > 0 ? '+' : ''}${val.toFixed(1)} mm</span></td>
    <td><span class="metric-diff" style="color: ${isNorm ? 'var(--status-green)' : 'var(--status-red)'};">${val > 0 ? '+' : ''}${val.toFixed(1)} mm</span></td>
    <td><span class="pill ${isNorm ? 'pill-normal' : 'pill-deviated'}">${val > 1.0 ? 'Class II' : (val < -1.0 ? 'Class III' : 'Class I')}</span></td>
  `;
  tbody.appendChild(tr);
}

function populateAirwayTable(ups, lps) {
  const tbody = document.getElementById("airway-rows");
  tbody.innerHTML = "";
  const makeRow = (name, val, normMin, normMax) => {
    let stat = `<span class="pill pill-neutral">-</span>`;
    let valStr = "-";
    if (val !== null) {
      valStr = `${val.toFixed(1)} mm`;
      if (val < normMin) stat = `<span class="pill pill-deviated">Constricted</span>`;
      else stat = `<span class="pill pill-normal">Patent / Normal</span>`;
    }
    return `<tr>
      <td><span class="metric-name">${name}</span></td>
      <td><span class="metric-norm">${normMin}–${normMax} mm</span></td>
      <td><span class="metric-val" style="color:#2dd4bf;">${valStr}</span></td>
      <td>${stat}</td>
    </tr>`;
  };
  tbody.innerHTML += makeRow("Upper Pharyngeal Space (UPS)", ups, 15, 20);
  tbody.innerHTML += makeRow("Lower Pharyngeal Space (LPS)", lps, 11, 13);
}

function populateCvmTable(morph) {
  const tbody = document.getElementById("cvm-metric-rows");
  if (!tbody) return;
  tbody.innerHTML = "";
  if (!morph) {
    tbody.innerHTML = `<tr><td colspan="3" style="text-align:center; color:var(--text-muted); padding:8px;">Switch to CVM focus mode to inspect vertebral boundaries</td></tr>`;
    return;
  }
  tbody.innerHTML = `
    <tr>
      <td><span class="metric-name">C3 Inferior Border Concavity</span></td>
      <td><span class="metric-val">${morph.c3Concavity.toFixed(1)} mm</span></td>
      <td>${morph.c3Concavity >= 0.8 ? '<span class="pill pill-normal">Concavity Present</span>' : '<span class="pill pill-neutral">Flat (&lt;0.8mm)</span>'}</td>
    </tr>
    <tr>
      <td><span class="metric-name">C4 Inferior Border Concavity</span></td>
      <td><span class="metric-val">${morph.c4Concavity.toFixed(1)} mm</span></td>
      <td>${morph.c4Concavity >= 0.8 ? '<span class="pill pill-normal">Concavity Present</span>' : '<span class="pill pill-neutral">Flat (&lt;0.8mm)</span>'}</td>
    </tr>
    <tr>
      <td><span class="metric-name">C3 Width-to-Height Ratio</span></td>
      <td><span class="metric-val">${morph.c3Ratio}</span></td>
      <td><span style="color:#5eead4; font-weight:600;">${morph.shape}</span></td>
    </tr>
    <tr>
      <td><span class="metric-name">Assigned Maturation Stage</span></td>
      <td colspan="2"><span class="metric-val" style="color:#2dd4bf;">${cvmStage}</span></td>
    </tr>
  `;
}

// =============================================================
// 8. 1-Page Letter Print Synchronization
// =============================================================
window.addEventListener("beforeprint", () => {
  const rawName = document.getElementById("pt-name").value || "Patient";
  const rawChart = document.getElementById("pt-chart").value || "MRN-N/A";
  const dtStr = document.getElementById("pt-datetime").value || "";
  const displayDt = dtStr ? dtStr.replace("T", " ") : new Date().toLocaleString();

  document.getElementById("print-pt-name").innerText = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
  document.getElementById("print-pt-mrn").innerText = hipaaPrivacyMode ? "ANON-001" : rawChart;
  document.getElementById("print-pt-datetime").innerText = displayDt;
  document.getElementById("print-ethnicity-tag").innerText = `ETHNICITY: ${ETHNICITY_DATABASE[activeEthnicity].label.split(' ')[0]}`;

  // Mirror Cephalogram & Vector Overlay
  document.getElementById("print-img").src = imgElem.src;
  const printSvg = document.getElementById("print-svg");
  printSvg.innerHTML = svgElem.innerHTML;
  printSvg.setAttribute("viewBox", svgElem.getAttribute("viewBox") || "0 0 100 100");

  // Mirror Diagnosis
  document.getElementById("print-diag-headline").innerText = latestDiagnosis.headline;
  document.getElementById("print-diag-sag").innerText = `Sagittal: ${latestDiagnosis.sagittal}`;
  document.getElementById("print-diag-vert").innerText = `Vertical: ${latestDiagnosis.vertical}`;
  document.getElementById("print-diag-dent").innerText = `Dental: ${latestDiagnosis.dental}`;
  document.getElementById("print-diag-soft").innerText = `Soft & CVM: ${latestDiagnosis.soft}`;

  // Populate Print ABO Table
  const pAboBody = document.getElementById("print-abo-tbody");
  pAboBody.innerHTML = "";
  ABO_NORMS.forEach(m => {
    const val = latestMetrics[m.id];
    let diff = "-", stat = "-", diffClass = "";
    if (val !== null && val !== undefined) {
      const rawDiff = val - m.norm;
      const isNorm = Math.abs(rawDiff) <= m.sd;
      diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
      stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
      diffClass = isNorm ? "diff-norm" : "diff-dev";
    }
    pAboBody.innerHTML += `<tr>
      <td><strong>${m.name}</strong></td>
      <td>${m.norm}${m.unit} ± ${m.sd}</td>
      <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
      <td class="${diffClass}">${diff}</td>
      <td>${stat}</td>
    </tr>`;
  });

  // Populate Print McNamara & Tweed Table
  const pMcBody = document.getElementById("print-mcnamara-tbody");
  pMcBody.innerHTML = "";
  const combinedSecondary = [...MCNAMARA_NORMS, ...TWEED_NORMS];
  combinedSecondary.forEach(m => {
    const val = latestMetrics[m.id];
    let diff = "-", stat = "-", diffClass = "";
    if (val !== null && val !== undefined) {
      const rawDiff = val - m.norm;
      const isNorm = Math.abs(rawDiff) <= m.sd;
      diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
      stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
      diffClass = isNorm ? "diff-norm" : "diff-dev";
    }
    pMcBody.innerHTML += `<tr>
      <td><strong>${m.name}</strong></td>
      <td>${m.norm}${m.unit} ± ${m.sd}</td>
      <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
      <td class="${diffClass}">${diff}</td>
      <td>${stat}</td>
    </tr>`;
  });

  // Populate Print Holdaway Table
  const pHoldBody = document.getElementById("print-holdaway-tbody");
  pHoldBody.innerHTML = "";
  HOLDAWAY_NORMS.forEach(m => {
    const val = latestMetrics[m.id];
    let diff = "-", stat = "-", diffClass = "";
    if (val !== null && val !== undefined) {
      const rawDiff = val - m.norm;
      const isNorm = Math.abs(rawDiff) <= m.sd;
      diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
      stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
      diffClass = isNorm ? "diff-norm" : "diff-dev";
    }
    pHoldBody.innerHTML += `<tr>
      <td><strong>${m.name}</strong></td>
      <td>${m.norm}${m.unit} ± ${m.sd}</td>
      <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
      <td class="${diffClass}">${diff}</td>
      <td>${stat}</td>
    </tr>`;
  });

  // Populate Print Wits, Airway & CVM Table
  const pWitsBody = document.getElementById("print-wits-tbody");
  pWitsBody.innerHTML = "";
  if (latestMetrics.WITS !== null && latestMetrics.WITS !== undefined) {
    const w = latestMetrics.WITS;
    const stat = w > 1.0 ? "Class II" : (w < -1.0 ? "Class III" : "Class I");
    pWitsBody.innerHTML += `<tr>
      <td>Wits (AO-BO)</td><td>0.0 ± 1.0 mm</td>
      <td><strong>${w > 0 ? '+' : ''}${w.toFixed(1)} mm</strong></td>
      <td>${stat}</td>
    </tr>`;
  }
  if (latestMetrics.UPS !== null) {
    pWitsBody.innerHTML += `<tr>
      <td>Upper Airway</td><td>15–20 mm</td>
      <td><strong>${latestMetrics.UPS.toFixed(1)} mm</strong></td>
      <td>${latestMetrics.UPS < 15 ? 'Constricted' : 'Patent'}</td>
    </tr>`;
  }
  if (latestMetrics.LPS !== null) {
    pWitsBody.innerHTML += `<tr>
      <td>Lower Airway</td><td>11–13 mm</td>
      <td><strong>${latestMetrics.LPS.toFixed(1)} mm</strong></td>
      <td>${latestMetrics.LPS < 11 ? 'Constricted' : 'Patent'}</td>
    </tr>`;
  }
  pWitsBody.innerHTML += `<tr>
    <td>Skeletal CVM</td><td>Baccetti Stage</td>
    <td><strong>${cvmStage}</strong></td>
    <td>Active</td>
  </tr>`;
});

// CSV Export
document.getElementById("btn-export-csv").addEventListener("click", () => {
  if (!latestMetrics.SNA) { notify("Trace a cephalogram first."); return; }
  const rawName = document.getElementById("pt-name").value || "Patient";
  const ptName = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
  const ptChart = hipaaPrivacyMode ? "ANON-001" : (document.getElementById("pt-chart").value || "N/A");
  const ptDateTime = document.getElementById("pt-datetime").value || "";

  let csv = "Patient,MRN,Date_Time,Diagnosis,Ethnicity,CVM_Stage,Category,Parameter,Norm_SD,Value,Diff,Unit,Status\n";
  const addCategory = (cat, list) => {
    list.forEach(m => {
      const v = latestMetrics[m.id];
      if (v === null || v === undefined) return;
      const diff = (v - m.norm).toFixed(1);
      const stat = Math.abs(v - m.norm) <= m.sd ? "Normal" : (v > m.norm ? "High" : "Low");
      csv += `"${ptName}","${ptChart}","${ptDateTime}","${latestDiagnosis.headline}","${activeEthnicity}","${cvmStage}","${cat}","${m.name}","${m.norm} +/- ${m.sd}",${v.toFixed(1)},${diff > 0 ? '+' + diff : diff},"${m.unit}","${stat}"\n`;
    });
  };

  addCategory("ABO", ABO_NORMS);
  addCategory("McNamara", MCNAMARA_NORMS);
  addCategory("Tweed", TWEED_NORMS);
  addCategory("Holdaway", HOLDAWAY_NORMS);

  const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `Ceph_Analysis_${ptName.replace(/\s+/g, '_')}_${ptDateTime.slice(0, 10)}.csv`;
  a.click();
  notify("CSV Analysis Exported");
});

// Copy Note
document.getElementById("btn-copy-note").addEventListener("click", () => {
  if (!latestMetrics.SNA) return;
  const rawName = document.getElementById("pt-name").value || "Patient";
  const ptName = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
  const dt = document.getElementById("pt-datetime").value.replace("T", " ") || "";
  const m = latestMetrics;

  const note = [
    `CEPHALOMETRIC DIAGNOSIS (${ptName} | ${dt}): ${latestDiagnosis.headline}`,
    `• Sagittal: ${latestDiagnosis.sagittal} | SNA ${m.SNA}°, SNB ${m.SNB}°, ANB ${m.ANB}°, Wits ${m.WITS} mm`,
    `• Vertical & Tweed: ${latestDiagnosis.vertical} | FMA ${m.FMA}°, SNMP ${m.SNMP}°, FMIA ${m.FMIA}°`,
    `• McNamara: A to N-Perp ${m.A_N_PERP}mm, Pog to N-Perp ${m.POG_N_PERP}mm, Co-A ${m.CO_A}mm, Co-Gn ${m.CO_GN}mm (Diff: ${m.MX_MD_DIFF}mm), LAFH ${m.LAFH}mm`,
    `• Dental: ${latestDiagnosis.dental} | IMPA ${m.IMPA}°, U1-SN ${m.U1SN}°, U1-NA ${m.U1NA_deg}°/${m.U1NA_mm}mm, L1-NB ${m.L1NB_deg}°/${m.L1NB_mm}mm, IIA ${m.IIA}°`,
    `• Soft Tissue & Airway: ${latestDiagnosis.soft} | Holdaway H-Angle ${m.H_ANGLE}°, Upper Airway ${m.UPS}mm, Lower Airway ${m.LPS}mm`
  ].join("\n");

  const ta = document.createElement("textarea");
  ta.value = note;
  document.body.appendChild(ta);
  ta.select();
  document.execCommand("copy");
  document.body.removeChild(ta);
  notify("Clinical EMR Note Copied");
});

// Viewport Zoom
document.getElementById("btn-zoom-in").addEventListener("click", () => {
  zoomLevel += 0.2; container.style.transform = `scale(${zoomLevel})`;
});
document.getElementById("btn-zoom-out").addEventListener("click", () => {
  if (zoomLevel > 0.4) { zoomLevel -= 0.2; container.style.transform = `scale(${zoomLevel})`; }
});
document.getElementById("btn-zoom-reset").addEventListener("click", () => {
  zoomLevel = 1.0; container.style.transform = "scale(1.0)";
});
</script>
</body>
</html>