Abddeus commited on
Commit
6f37c14
·
verified ·
1 Parent(s): 1d8850f

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +554 -334
index.html CHANGED
@@ -3,7 +3,7 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>OrthoCeph Pro | ABO, McNamara, Tweed & Longitudinal Superimposition</title>
7
  <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/ort.min.js"></script>
8
  <script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
9
  <link rel="preconnect" href="https://fonts.googleapis.com">
@@ -91,7 +91,7 @@
91
  .workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }
92
 
93
  .sidebar {
94
- width: 320px; background: var(--surface-dark);
95
  border-right: 1px solid var(--surface-border);
96
  padding: 12px; display: flex; flex-direction: column;
97
  gap: 10px; overflow-y: auto; flex-shrink: 0;
@@ -118,20 +118,20 @@
118
  }
119
  .input-field:focus { border-color: #3b82f6; }
120
 
121
- .mode-group { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
122
  .mode-btn {
123
  background: #0f172a; border: 1px solid var(--surface-border);
124
- color: var(--text-muted); padding: 5px 3px; border-radius: 5px;
125
- font-size: 10px; font-weight: 600; cursor: pointer; text-align: center;
126
  transition: all 0.15s;
127
  }
128
  .mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; }
129
 
130
- .toggle-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px; }
131
  .toggle-pill {
132
  background: #0f172a; border: 1px solid var(--surface-border);
133
- color: var(--text-muted); padding: 4px; border-radius: 5px;
134
- font-size: 10px; font-weight: 600; cursor: pointer; text-align: center;
135
  }
136
  .toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }
137
 
@@ -143,6 +143,24 @@
143
  }
144
  .cvm-btn.active { background: var(--teal-accent); color: #042f2e; border-color: #5eead4; }
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  .slider-row {
147
  display: flex; align-items: center; justify-content: space-between;
148
  font-size: 10.5px; color: var(--text-muted);
@@ -170,6 +188,21 @@
170
  outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
171
  }
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  #empty-dropzone {
174
  display: flex; flex-direction: column; align-items: center; justify-content: center;
175
  gap: 10px; color: var(--text-muted); text-align: center; padding: 35px;
@@ -219,7 +252,7 @@
219
 
220
  /* Right Analysis Panel */
221
  .analysis-panel {
222
- width: 530px; background: var(--surface-dark);
223
  border-left: 1px solid var(--surface-border);
224
  padding: 12px 16px; display: flex; flex-direction: column;
225
  gap: 10px; overflow-y: auto; flex-shrink: 0;
@@ -311,48 +344,49 @@
311
  box-shadow: 0 10px 25px rgba(0,0,0,0.5); display: none; align-items: center; gap: 8px;
312
  }
313
 
314
- /* Print-Only Report Container: STRICT 1-PAGE US LETTER */
315
  #print-report-container { display: none; }
316
 
317
  @media print {
318
  @page {
319
  size: letter portrait;
320
- margin: 5mm 7mm 5mm 7mm;
321
  }
322
  *, *::before, *::after { box-sizing: border-box !important; }
323
  html, body {
324
  background: #ffffff !important; color: #000000 !important;
325
- height: auto !important; width: 100% !important; overflow: visible !important;
326
- font-size: 8.5px !important; margin: 0 !important; padding: 0 !important;
327
  }
328
  header, .workspace, .sidebar, .viewport, .analysis-panel,
329
- .mobile-nav-bar, .viewport-overlay-controls, #loupe-box,
330
  #empty-dropzone, #security-gate, #toast-msg {
331
  display: none !important; visibility: hidden !important;
332
  height: 0 !important; width: 0 !important; position: absolute !important;
333
  }
334
 
335
  #print-report-container {
336
- display: flex !important; flex-direction: column; justify-content: space-between;
337
- width: 100% !important; height: 98vh !important; max-height: 98vh !important;
338
  page-break-inside: avoid !important; break-inside: avoid !important;
 
339
  }
340
 
341
  .print-header-bar {
342
- border-bottom: 2px solid #0f172a; padding-bottom: 3px;
343
  display: flex; justify-content: space-between; align-items: flex-end;
344
  }
345
- .print-title { font-size: 13px; font-weight: 800; color: #0f172a; letter-spacing: -0.01em; }
346
- .print-demographics { display: flex; gap: 10px; font-size: 9px; font-weight: 600; color: #334155; }
347
 
348
  .print-grid {
349
- display: grid !important; grid-template-columns: 280px 1fr !important;
350
- gap: 10px; align-items: start; flex: 1; margin-top: 3px;
351
  }
352
 
353
  .print-left-col { display: flex; flex-direction: column; gap: 4px; }
354
  .print-ceph-box {
355
- position: relative; width: 280px; height: 300px; border: 1.5px solid #94a3b8;
356
  border-radius: 4px; overflow: hidden; background: #000000;
357
  display: flex; align-items: center; justify-content: center;
358
  }
@@ -360,30 +394,19 @@
360
  .print-ceph-box svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
361
 
362
  .print-diag-card {
363
- border: 1px solid #cbd5e1; border-radius: 4px; padding: 5px 7px;
364
- background: #f8fafc; font-size: 8.5px; display: flex; flex-direction: column; gap: 2px;
365
  }
366
 
367
- .print-right-col { display: flex; flex-direction: column; gap: 4px; }
368
- .print-table { width: 100%; border-collapse: collapse; font-size: 8.5px; }
369
  .print-table th {
370
- border-bottom: 1.5px solid #0f172a; padding: 2px 4px; text-align: left;
371
- font-size: 8px; color: #0f172a; font-weight: 700; text-transform: uppercase;
372
  }
373
- .print-table td { border-bottom: 1px solid #e2e8f0; padding: 2px 4px; color: #0f172a; }
374
  .print-table td.diff-dev { color: #dc2626; font-weight: 700; }
375
  .print-table td.diff-norm { color: #15803d; font-weight: 600; }
376
-
377
- .print-footer-bar {
378
- border-top: 1px solid #cbd5e1; padding-top: 3px; display: flex;
379
- justify-content: space-between; align-items: flex-end; gap: 12px; margin-top: 3px;
380
- }
381
- .print-disclaimer { font-size: 7.5px; color: #64748b; line-height: 1.25; max-width: 65%; }
382
- .print-signature-wrap { display: flex; flex-direction: column; align-items: center; width: 190px; }
383
- .print-sign-line {
384
- border-top: 1px solid #0f172a; width: 100%; text-align: center;
385
- font-size: 8px; font-weight: 600; color: #334155; padding-top: 2px;
386
- }
387
  }
388
  </style>
389
  </head>
@@ -407,7 +430,7 @@
407
  <div class="brand-icon">O</div>
408
  <div>
409
  <div class="brand-title">OrthoCeph Pro</div>
410
- <div class="brand-subtitle">ABO, McNamara, Tweed & Longitudinal Suite</div>
411
  </div>
412
  </div>
413
 
@@ -490,34 +513,66 @@
490
  <div class="mode-btn" data-mode="AIRWAY">Airway</div>
491
  <div class="mode-btn" data-mode="WITS">Wits</div>
492
  <div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
493
- <div class="mode-btn" data-mode="SUPER" style="grid-column: span 3; background: rgba(56,189,248,0.12); border-color:#38bdf8; color:#38bdf8;">📑 T1 / T2 / T3 Longitudinal</div>
 
 
494
  </div>
495
  <div class="toggle-grid" style="margin-top: 3px;">
496
  <div class="toggle-pill active" id="tog-lines">Lines: ON</div>
497
  <div class="toggle-pill active" id="tog-points">Dots: ON</div>
498
  <div class="toggle-pill active" id="tog-labels">Names: ON</div>
 
499
  </div>
500
  </div>
501
  </div>
502
 
503
  <div>
504
- <div class="section-header"><span>3. Retrace & Calibration</span></div>
505
  <div class="card">
506
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
507
- <button id="btn-retrace-all" class="btn btn-secondary">Reset All</button>
508
- <button id="btn-reset-single" class="btn btn-secondary">Reset Dot</button>
 
509
  </div>
510
- <button id="btn-retrace-scale" class="btn" style="background:#0284c7; width:100%; font-size:10.5px;">
511
- ⚡ Recalculate with Calibrated Scale
512
- </button>
513
- <div style="font-size: 9.5px; color: var(--text-muted); text-align: center;">
514
- Selected: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot on x-ray to reset)
 
 
 
 
 
 
 
 
 
 
 
515
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
516
  </div>
517
  </div>
518
 
519
  <div>
520
- <div class="section-header"><span>4. Cervical Maturation (CVM)</span></div>
 
 
 
521
  <div class="card">
522
  <div class="cvm-grid">
523
  <div class="cvm-btn" data-cvm="CS1">CS1</div>
@@ -534,49 +589,32 @@
534
  </div>
535
 
536
  <div>
537
- <div class="section-header"><span>5. Longitudinal Series (T1 / T2 / T3)</span></div>
538
  <div class="card">
539
- <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px;">
540
- <button id="btn-lock-t1" class="btn btn-teal" style="font-size:9.5px; padding:4px;">📌 T1 Initial</button>
541
- <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>
542
- <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>
543
- </div>
544
- <button id="btn-clear-series" class="btn btn-secondary" style="font-size:9.5px; padding:3px; margin-top:2px;">Clear All Baselines</button>
545
- <div class="form-group" style="margin-top: 3px;">
546
- <label>Registration Reference</label>
547
- <select id="super-mode" class="input-field" style="padding: 4px;">
548
- <option value="CRANIAL">Cranial Base (S-N registered at S)</option>
549
- <option value="MAXILLARY">Maxillary Palatal Plane (PNS-ANS at PNS)</option>
550
- <option value="MANDIBULAR">Mandibular Plane (Go-Me registered at Me)</option>
551
- </select>
552
  </div>
553
- <div id="super-status" style="font-size: 9px; color: var(--text-muted); text-align: center; line-height:1.35;">
554
- No baselines locked.
 
555
  </div>
556
- <div style="background: #0f172a; border-radius: 4px; padding: 5px; font-size: 8.5px; color: #94a3b8; line-height: 1.35;">
557
- <strong style="color: #38bdf8;">How to Use:</strong><br>
558
- 1. Upload Initial Ceph & click <em>Lock T1</em>.<br>
559
- 2. Upload Mid-Treatment Ceph & click <em>Lock T2</em>.<br>
560
- 3. Upload Debond/Final Ceph & click <em>Lock T3</em>.<br>
561
- 4. Switch mode to <em>T1/T2/T3 Longitudinal</em> to see growth & treatment superimposition.
562
  </div>
563
  </div>
564
  </div>
565
 
566
  <div>
567
  <div class="section-header">
568
- <span>6. Caliper & Image Equalization</span>
569
  <span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 9.5px;">Reset</span>
570
  </div>
571
  <div class="card">
572
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
573
- <button id="btn-cal" class="btn btn-secondary" style="font-size: 9.5px; padding: 5px 3px;">Ruler: Toggle</button>
574
- <button id="btn-auto-caliper" class="btn" style="background:#0891b2; font-size:9.5px; padding: 5px 3px;">⚡ Auto 10mm</button>
575
- </div>
576
- <span id="cal-status" style="font-size: 10px; color: var(--ruler-cyan); text-align: center; font-weight: 600;">
577
- Scale: 10.00 px/mm
578
- </span>
579
- <div class="form-group" style="margin-top: 2px;">
580
  <label>Density Filter</label>
581
  <select id="filter-mode-select" class="input-field" style="padding: 4px;">
582
  <option value="NORMAL">Standard Radiograph</option>
@@ -597,16 +635,7 @@
597
  <span>Invert Negative</span>
598
  <input type="checkbox" id="invert">
599
  </div>
600
- </div>
601
- </div>
602
-
603
- <div>
604
- <div class="section-header">
605
- <span>7. Reference Norms & Ethnicity</span>
606
- <span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 9.5px; display: none;">Restore</span>
607
- </div>
608
- <div class="card">
609
- <div class="form-group">
610
  <label>Ethnic Population Standard</label>
611
  <select id="ethnicity-select" class="input-field" style="padding: 4px; font-weight: 600; color: #38bdf8;">
612
  <option value="CAUCASIAN">Caucasian (ABO Standard / Michigan)</option>
@@ -618,6 +647,7 @@
618
  <button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 10px; padding: 4px; margin-top: 2px;">
619
  Customize ABO Norms
620
  </button>
 
621
  <div id="norms-drawer"></div>
622
  </div>
623
  </div>
@@ -630,10 +660,20 @@
630
  <div id="loupe-label">S</div>
631
  </div>
632
 
 
 
 
 
 
 
 
 
 
 
633
  <div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
634
  <div style="font-size: 32px;">🦷</div>
635
  <div style="font-size: 14px; font-weight: 600; color: var(--text-main);">Drop Lateral Cephalogram (.DCM, .JPG, .PNG) or .JSON Here</div>
636
- <div style="font-size: 11px;">Instant AI Landmark Localization • Drag Points to Fine-Tune</div>
637
  </div>
638
 
639
  <div id="viewport-container">
@@ -646,7 +686,7 @@
646
  <button id="btn-zoom-out">Zoom (-)</button>
647
  <button id="btn-zoom-reset">Fit</button>
648
  <span style="color: var(--surface-border);">|</span>
649
- <span class="shortcut-hint">Hold <strong>[SPACE]</strong> to inspect radiograph • Double-click dot to reset</span>
650
  </div>
651
  </main>
652
 
@@ -668,7 +708,7 @@
668
  <span class="diag-val" id="diag-dental">-</span>
669
  </div>
670
  <div class="diag-item">
671
- <span class="diag-label">Soft Profile & CVM</span>
672
  <span class="diag-val" id="diag-soft">-</span>
673
  </div>
674
  </div>
@@ -681,14 +721,16 @@
681
  <tr>
682
  <th>Parameter</th>
683
  <th>Norm</th>
684
- <th>Measured</th>
685
  <th>Diff</th>
686
- <th id="th-t1-abo" style="display:none; color:#5eead4;">Δ vs T1</th>
 
 
687
  <th>Status</th>
688
  </tr>
689
  </thead>
690
  <tbody id="abo-rows">
691
- <tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting radiograph...</td></tr>
692
  </tbody>
693
  </table>
694
  </div>
@@ -730,12 +772,12 @@
730
  </div>
731
 
732
  <div id="section-airway">
733
- <div class="section-header" style="color: #2dd4bf;">Pharyngeal Airway Space (OSA & Sleep Screening)</div>
734
  <table class="analysis-table">
735
  <thead>
736
  <tr>
737
- <th>Airway Region</th>
738
- <th>Norm</th>
739
  <th>Measured</th>
740
  <th>Status</th>
741
  </tr>
@@ -746,6 +788,22 @@
746
  </table>
747
  </div>
748
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
  <div id="section-wits">
750
  <div class="section-header" style="color: #c084fc;">Jacobson Wits Appraisal</div>
751
  <table class="analysis-table">
@@ -800,17 +858,17 @@
800
  </button>
801
  </nav>
802
 
803
- <!-- Print 1-Page Letter Layout -->
804
  <div id="print-report-container">
805
  <div class="print-header-bar">
806
  <div>
807
  <div class="print-title">ORTHOCEPH PRO | CLINICAL ABO CEPHALOMETRIC REPORT</div>
808
- <div style="font-size: 8px; color: #64748b; font-weight: 600;">AMERICAN BOARD OF ORTHODONTICS & MCNAMARA COMPLIANT SUMMARY</div>
809
  </div>
810
  <div class="print-demographics">
811
  <div>PATIENT: <strong id="print-pt-name">Unspecified</strong></div>
812
  <div>MRN: <strong id="print-pt-mrn">-</strong></div>
813
- <div>DATE & TIME: <strong id="print-pt-datetime">-</strong></div>
814
  <div id="print-ethnicity-tag" style="color:#0284c7;">ETHNICITY: <strong>Caucasian</strong></div>
815
  </div>
816
  </div>
@@ -822,15 +880,15 @@
822
  <svg id="print-svg" viewBox="0 0 100 100"></svg>
823
  </div>
824
  <div class="print-diag-card">
825
- <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>
826
  <div id="print-diag-sag">Sagittal: -</div>
827
  <div id="print-diag-vert">Vertical: -</div>
828
  <div id="print-diag-dent">Dental: -</div>
829
- <div id="print-diag-soft">Soft Profile: -</div>
830
  </div>
831
  <table class="print-table" id="print-wits-table">
832
  <thead>
833
- <tr><th>Appraisal & Airway</th><th>Norm</th><th>Measured</th><th>Status</th></tr>
834
  </thead>
835
  <tbody id="print-wits-tbody"></tbody>
836
  </table>
@@ -850,7 +908,7 @@
850
  <tbody id="print-abo-tbody"></tbody>
851
  </table>
852
 
853
- <table class="print-table" id="print-mcnamara-table" style="margin-top: 3px;">
854
  <thead>
855
  <tr>
856
  <th>McNamara & Tweed</th>
@@ -863,7 +921,7 @@
863
  <tbody id="print-mcnamara-tbody"></tbody>
864
  </table>
865
 
866
- <table class="print-table" id="print-holdaway-table" style="margin-top: 3px;">
867
  <thead>
868
  <tr>
869
  <th>Holdaway Soft Tissue</th>
@@ -877,15 +935,6 @@
877
  </table>
878
  </div>
879
  </div>
880
-
881
- <div class="print-footer-bar">
882
- <div class="print-disclaimer">
883
- Measurements verified against calibrated millimeter scale. Automated computer-assisted cephalometric analysis generated for clinical orthodontic diagnosis and treatment evaluation.
884
- </div>
885
- <div class="print-signature-wrap">
886
- <div class="print-sign-line">Attending Orthodontist Signature / Stamp</div>
887
- </div>
888
- </div>
889
  </div>
890
 
891
  <div id="toast-msg">Notification</div>
@@ -894,7 +943,7 @@
894
  // =============================================================
895
  // 1. Constants, Ethnic Norm Databases & Configurations
896
  // =============================================================
897
- const MASTER_PASSWORD = "ortho2026"; // Clinic access code
898
  const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
899
 
900
  const LM_INDICES = {
@@ -907,11 +956,17 @@ const MODE_LANDMARKS = {
907
  ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft"]),
908
  MCNAMARA: new Set(["N", "Po", "Or", "A", "Pog", "Co", "Gn", "ANS", "Me"]),
909
  TWEED: new Set(["Po", "Or", "Go", "Me", "LIT", "LIA"]),
910
- AIRWAY: new Set(["PNS", "UPW", "P_Palate", "TB", "LPW", "Go", "B"]),
911
  WITS: new Set(["A", "B", "OP_P", "OP_A"]),
912
  HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
 
913
  SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog", "Co", "Gn"]),
914
- 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", "UPW", "P_Palate", "TB", "LPW"])
 
 
 
 
 
915
  };
916
 
917
  const CVM_INFO = {
@@ -1048,17 +1103,21 @@ const HOLDAWAY_NORMS = [
1048
  let session = null;
1049
  let coords = {};
1050
  let initialAiCoords = {};
 
 
1051
  let t1Baseline = null;
1052
  let t2Baseline = null;
1053
  let t3Baseline = null;
1054
  let selectedLm = null;
1055
  let cvmStage = "CS3";
 
1056
  let pxPerMm = 10.0;
1057
  let showRuler = false;
1058
  let focusMode = "ABO";
1059
  let showLines = true;
1060
  let showPoints = true;
1061
  let showLabels = true;
 
1062
  let spacebarPeek = false;
1063
  let hipaaPrivacyMode = false;
1064
  let currentFilterMode = "NORMAL";
@@ -1078,8 +1137,8 @@ const calStatus = document.getElementById("cal-status");
1078
  const loupeBox = document.getElementById("loupe-box");
1079
  const loupeCanvas = document.getElementById("loupe-canvas");
1080
  const loupeLabel = document.getElementById("loupe-label");
 
1081
 
1082
- // Auto-fill Current Date & Time
1083
  function setAutoDateTime() {
1084
  const now = new Date();
1085
  const pad = (n) => String(n).padStart(2, '0');
@@ -1088,7 +1147,6 @@ function setAutoDateTime() {
1088
  }
1089
  setAutoDateTime();
1090
 
1091
- // Toast Helper
1092
  function notify(msg, dur = 2600) {
1093
  const t = document.getElementById("toast-msg");
1094
  t.innerText = msg;
@@ -1097,7 +1155,7 @@ function notify(msg, dur = 2600) {
1097
  t._tm = setTimeout(() => t.style.display = "none", dur);
1098
  }
1099
 
1100
- // Security Gate Logic
1101
  const gateElem = document.getElementById("security-gate");
1102
  const gatePass = document.getElementById("gate-pass");
1103
  const gateErr = document.getElementById("gate-err");
@@ -1133,7 +1191,7 @@ document.getElementById("btn-lock-suite").addEventListener("click", () => {
1133
  checkSecurity();
1134
  });
1135
 
1136
- // Mobile Tabs Setup
1137
  const mobileTabBtns = document.querySelectorAll(".mobile-tab-btn");
1138
  function setMobileTab(tabName) {
1139
  document.body.classList.remove("tab-tools", "tab-viewport", "tab-analysis");
@@ -1143,7 +1201,7 @@ function setMobileTab(tabName) {
1143
  setMobileTab("tools");
1144
  mobileTabBtns.forEach(b => b.addEventListener("click", () => setMobileTab(b.getAttribute("data-tab"))));
1145
 
1146
- // Custom Norms Drawer
1147
  function buildNormsEditor() {
1148
  const drawer = document.getElementById("norms-drawer");
1149
  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>`;
@@ -1178,7 +1236,7 @@ document.getElementById("btn-toggle-norms").addEventListener("click", () => {
1178
  const r = document.getElementById("reset-norms");
1179
  const open = d.style.display === "flex";
1180
  d.style.display = open ? "none" : "flex";
1181
- r.style.display = open ? "none" : "inline";
1182
  });
1183
 
1184
  document.getElementById("reset-norms").addEventListener("click", () => {
@@ -1190,7 +1248,6 @@ document.getElementById("reset-norms").addEventListener("click", () => {
1190
  notify("Norms restored to ethnic baseline.");
1191
  });
1192
 
1193
- // Ethnicity Select
1194
  document.getElementById("ethnicity-select").addEventListener("change", (e) => {
1195
  activeEthnicity = e.target.value;
1196
  const ethData = ETHNICITY_DATABASE[activeEthnicity] || ETHNICITY_DATABASE.CAUCASIAN;
@@ -1202,7 +1259,6 @@ document.getElementById("ethnicity-select").addEventListener("change", (e) => {
1202
  notify(`Norms adjusted for ${ethData.label}`);
1203
  });
1204
 
1205
- // HIPAA Toggle
1206
  document.getElementById("btn-privacy-toggle").addEventListener("click", () => {
1207
  hipaaPrivacyMode = !hipaaPrivacyMode;
1208
  document.getElementById("privacy-btn-txt").innerText = `HIPAA Mask: ${hipaaPrivacyMode ? 'ON' : 'OFF'}`;
@@ -1211,14 +1267,9 @@ document.getElementById("btn-privacy-toggle").addEventListener("click", () => {
1211
  notify(hipaaPrivacyMode ? "HIPAA De-Identification Mode Enabled." : "De-Identification Disabled.");
1212
  });
1213
 
1214
- // Transparent SVG Export
1215
  document.getElementById("btn-export-svg").addEventListener("click", () => {
1216
- if (!coords.S || !imgElem.naturalWidth) {
1217
- notify("Trace a radiograph first.");
1218
- return;
1219
- }
1220
- const w = imgElem.naturalWidth;
1221
- const h = imgElem.naturalHeight;
1222
  const svgContent = `<?xml version="1.0" encoding="UTF-8"?>
1223
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" style="background:transparent;">
1224
  ${svgElem.innerHTML}
@@ -1233,31 +1284,21 @@ document.getElementById("btn-export-svg").addEventListener("click", () => {
1233
  notify("Transparent vector SVG downloaded.");
1234
  });
1235
 
1236
- // Auto 10mm Caliper Detection
1237
  document.getElementById("btn-auto-caliper").addEventListener("click", () => {
1238
- if (!imgElem.src || imgElem.naturalWidth === 0) {
1239
- notify("Load a cephalogram first.");
1240
- return;
1241
- }
1242
  autoDetect10mmCaliper();
1243
  });
1244
 
1245
  function autoDetect10mmCaliper() {
1246
- notify("Scanning cephalostat scale...");
1247
- const origW = imgElem.naturalWidth;
1248
- const origH = imgElem.naturalHeight;
1249
-
1250
  const scanCanvas = document.createElement("canvas");
1251
- const roiW = Math.floor(origW * 0.28);
1252
- const roiH = Math.floor(origH * 0.4);
1253
  scanCanvas.width = roiW; scanCanvas.height = roiH;
1254
  const ctx = scanCanvas.getContext("2d");
1255
  ctx.drawImage(imgElem, origW * 0.72, 0, roiW, roiH, 0, 0, roiW, roiH);
1256
 
1257
- const imgData = ctx.getImageData(0, 0, roiW, roiH);
1258
- const data = imgData.data;
1259
  let bestCol = -1, bestScore = -1;
1260
-
1261
  for (let x = 8; x < roiW - 8; x += 3) {
1262
  let variance = 0, prev = 0;
1263
  for (let y = 8; y < roiH - 8; y += 2) {
@@ -1266,10 +1307,7 @@ function autoDetect10mmCaliper() {
1266
  variance += Math.abs(gray - prev);
1267
  prev = gray;
1268
  }
1269
- if (variance > bestScore) {
1270
- bestScore = variance;
1271
- bestCol = x;
1272
- }
1273
  }
1274
 
1275
  const detectedX = origW * 0.72 + (bestCol > 0 ? bestCol : roiW * 0.55);
@@ -1283,10 +1321,9 @@ function autoDetect10mmCaliper() {
1283
  calBtn.innerText = "Ruler: ON";
1284
  calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Auto-Locked)`;
1285
  renderAnalysis();
1286
- notify(`Auto-calibrated scale (${pxPerMm.toFixed(2)} px/mm). Micro-drag dots if needed.`);
1287
  }
1288
 
1289
- // Density Filters
1290
  document.getElementById("filter-mode-select").addEventListener("change", (e) => {
1291
  currentFilterMode = e.target.value;
1292
  applyFilters();
@@ -1363,6 +1400,8 @@ function handleFile(file) {
1363
  loadJsonFile(file);
1364
  return;
1365
  }
 
 
1366
  const isDicom = name.endsWith('.dcm') || file.type === 'application/dicom';
1367
  if (isDicom) {
1368
  const reader = new FileReader();
@@ -1393,12 +1432,12 @@ document.getElementById("btn-save-json").addEventListener("click", () => {
1393
  expCanvas.height = imgElem.naturalHeight;
1394
  const expCtx = expCanvas.getContext("2d");
1395
  expCtx.drawImage(imgElem, 0, 0);
1396
- exportDataUrl = expCanvas.toDataURL("image/jpeg", 0.92);
1397
  } catch (e) { exportDataUrl = imgElem.src; }
1398
  }
1399
 
1400
  const payload = {
1401
- version: "3.2",
1402
  patient: { name: ptName, chart: ptChart, datetime: ptDateTime, ethnicity: activeEthnicity },
1403
  pxPerMm, cvmStage, coords, initialAiCoords,
1404
  baselines: { t1: t1Baseline, t2: t2Baseline, t3: t3Baseline },
@@ -1466,6 +1505,7 @@ function loadJsonFile(file) {
1466
  function createReferencePlaceholder() {
1467
  dropzone.style.display = "none";
1468
  container.style.display = "block";
 
1469
  const refCanvas = document.createElement("canvas");
1470
  refCanvas.width = 1200; refCanvas.height = 1400;
1471
  const ctx = refCanvas.getContext("2d");
@@ -1547,6 +1587,7 @@ function setupImage(srcUrl, shouldRunAi = true) {
1547
  imgElem.onload = () => {
1548
  dropzone.style.display = "none";
1549
  container.style.display = "block";
 
1550
  svgElem.setAttribute("viewBox", `0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
1551
  svgElem.setAttribute("width", imgElem.clientWidth);
1552
  svgElem.setAttribute("height", imgElem.clientHeight);
@@ -1558,7 +1599,7 @@ function setupImage(srcUrl, shouldRunAi = true) {
1558
  }
1559
 
1560
  // =============================================================
1561
- // 4. AI Deep Learning Tracing & Derived Landmarks
1562
  // =============================================================
1563
  async function runAutoTrace() {
1564
  if (!session || !imgElem.src) return;
@@ -1603,7 +1644,7 @@ async function runAutoTrace() {
1603
  };
1604
  }
1605
 
1606
- // Derive Occ Plane & PNS (palatal plane)
1607
  if (coords.UIT && coords.LIT) {
1608
  coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
1609
  }
@@ -1614,23 +1655,54 @@ async function runAutoTrace() {
1614
  coords.PNS = { x: coords.ANS.x - (coords.A.x - coords.ANS.x) * 2.8 - 40, y: coords.ANS.y - 4 };
1615
  }
1616
 
1617
- // Derive Condylion (Co) relative to Porion and Ramus
1618
  if (coords.Po && coords.Go) {
1619
  coords.Co = { x: coords.Po.x + (coords.Go.x - coords.Po.x) * 0.28 + 10, y: coords.Po.y + 16 };
1620
  }
1621
 
1622
- // Derive Pharyngeal Airway landmarks
1623
- if (coords.PNS && coords.Go) {
1624
- coords.P_Palate = { x: coords.PNS.x + 8, y: coords.PNS.y + 24 };
1625
- coords.UPW = { x: coords.PNS.x - 38, y: coords.PNS.y + 24 };
1626
- coords.TB = { x: coords.Go.x + (coords.B.x - coords.Go.x) * 0.35, y: coords.Go.y - 15 };
1627
- coords.LPW = { x: coords.TB.x - 30, y: coords.TB.y };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1628
  }
1629
 
1630
  coords.RULER_1 = { x: origW * 0.82, y: origH * 0.12 };
1631
  coords.RULER_2 = { x: origW * 0.82, y: origH * 0.12 + (pxPerMm * 10.0) };
1632
 
1633
  initialAiCoords = JSON.parse(JSON.stringify(coords));
 
1634
  statusInd.style.backgroundColor = "var(--status-green)";
1635
  statusTxt.innerText = "Auto-Trace Complete";
1636
  renderAnalysis();
@@ -1640,6 +1712,7 @@ document.getElementById("btn-retrace-all").addEventListener("click", () => {
1640
  if (!imgElem.src) return;
1641
  if (Object.keys(initialAiCoords).length > 0) {
1642
  coords = JSON.parse(JSON.stringify(initialAiCoords));
 
1643
  renderAnalysis();
1644
  notify("Landmarks reset to AI prediction");
1645
  } else { runAutoTrace(); }
@@ -1653,59 +1726,129 @@ document.getElementById("btn-reset-single").addEventListener("click", () => {
1653
  } else { notify("Click any landmark dot first to reset it."); }
1654
  });
1655
 
1656
- document.getElementById("btn-retrace-scale").addEventListener("click", () => {
1657
- if (coords.RULER_1 && coords.RULER_2) {
1658
- const d = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
1659
- if (d > 1) {
1660
- pxPerMm = d / 10.0;
1661
- calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Recalibrated)`;
1662
- renderAnalysis();
1663
- notify(`Recalculated with ${pxPerMm.toFixed(2)} px/mm scale`);
1664
- }
1665
- }
1666
- });
1667
-
1668
  // =============================================================
1669
- // 5. Longitudinal Superimposition Engine (T1 vs. T2 vs. T3)
1670
  // =============================================================
1671
- function lockBaseline(stageKey, label) {
1672
  if (!coords.S) {
1673
- notify(`Trace a cephalogram first before locking as ${stageKey}.`);
1674
  return;
1675
  }
1676
  const dateStr = (document.getElementById("pt-datetime").value || stageKey).replace("T", " ");
1677
- const payload = {
1678
  coords: JSON.parse(JSON.stringify(coords)),
 
1679
  metrics: JSON.parse(JSON.stringify(latestMetrics)),
 
 
 
 
1680
  date: dateStr
1681
  };
1682
 
1683
- if (stageKey === "T1") t1Baseline = payload;
1684
- else if (stageKey === "T2") t2Baseline = payload;
1685
- else if (stageKey === "T3") t3Baseline = payload;
1686
 
1687
  updateSuperimpositionStatus();
1688
  renderAnalysis();
1689
- notify(`${label} baseline locked (${dateStr}).`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1690
  }
1691
 
 
 
 
 
 
 
 
 
 
 
 
 
1692
  function updateSuperimpositionStatus() {
1693
- const t1Txt = t1Baseline ? `<span style="color:#5eead4; font-weight:700;">T1: ${t1Baseline.date}</span>` : "T1: -";
1694
- const t2Txt = t2Baseline ? `<span style="color:#93c5fd; font-weight:700;">T2: ${t2Baseline.date}</span>` : "T2: -";
1695
- const t3Txt = t3Baseline ? `<span style="color:#f0abfc; font-weight:700;">T3: ${t3Baseline.date}</span>` : "T3: -";
1696
- document.getElementById("super-status").innerHTML = `${t1Txt} | ${t2Txt} | ${t3Txt}`;
1697
- document.getElementById("th-t1-abo").style.display = t1Baseline ? "table-cell" : "none";
 
 
 
1698
  }
1699
 
1700
- document.getElementById("btn-lock-t1").addEventListener("click", () => lockBaseline("T1", "T1 Initial"));
1701
- document.getElementById("btn-lock-t2").addEventListener("click", () => lockBaseline("T2", "T2 Progress"));
1702
- document.getElementById("btn-lock-t3").addEventListener("click", () => lockBaseline("T3", "T3 Final"));
1703
 
1704
  document.getElementById("btn-clear-series").addEventListener("click", () => {
1705
  t1Baseline = null; t2Baseline = null; t3Baseline = null;
 
 
1706
  updateSuperimpositionStatus();
1707
  renderAnalysis();
1708
- notify("Longitudinal baselines cleared.");
1709
  });
1710
 
1711
  function getAlignedCoordsForBaseline(baselineObj) {
@@ -1749,6 +1892,8 @@ function getAlignedCoordsForBaseline(baselineObj) {
1749
  document.querySelectorAll(".cvm-btn").forEach(btn => {
1750
  btn.addEventListener("click", () => {
1751
  cvmStage = btn.getAttribute("data-cvm");
 
 
1752
  highlightCvmButton(cvmStage);
1753
  renderAnalysis();
1754
  });
@@ -1758,7 +1903,7 @@ function highlightCvmButton(stg) {
1758
  document.getElementById("cvm-desc").innerText = CVM_INFO[stg] || "CVM Stage Selected";
1759
  }
1760
 
1761
- // Focus Modes & View Toggles
1762
  document.querySelectorAll(".mode-btn").forEach(btn => {
1763
  btn.addEventListener("click", () => {
1764
  document.querySelectorAll(".mode-btn").forEach(b => b.classList.remove("active"));
@@ -1781,6 +1926,7 @@ function setupToggle(id, label, getter, setter) {
1781
  setupToggle("tog-lines", "Lines", () => showLines, v => showLines = v);
1782
  setupToggle("tog-points", "Dots", () => showPoints, v => showPoints = v);
1783
  setupToggle("tog-labels", "Names", () => showLabels, v => showLabels = v);
 
1784
 
1785
  window.addEventListener("keydown", (e) => {
1786
  if (e.code === "Space" && document.activeElement.tagName !== "INPUT") {
@@ -1838,6 +1984,18 @@ window.addEventListener("mousemove", (e) => {
1838
  }
1839
  updateLoupe(p, draggingLm);
1840
  renderAnalysis();
 
 
 
 
 
 
 
 
 
 
 
 
1841
  });
1842
 
1843
  window.addEventListener("mouseup", () => {
@@ -1848,7 +2006,6 @@ window.addEventListener("mouseup", () => {
1848
  }
1849
  });
1850
 
1851
- // Touch event handlers for mobile
1852
  function handleTouchMove(e) {
1853
  if (!draggingLm || !coords[draggingLm] || !e.touches[0]) return;
1854
  e.preventDefault();
@@ -1875,12 +2032,15 @@ window.addEventListener("touchend", () => {
1875
  document.getElementById("btn-next-patient").addEventListener("click", () => {
1876
  coords = {}; initialAiCoords = {}; latestMetrics = {};
1877
  t1Baseline = null; t2Baseline = null; t3Baseline = null;
1878
- selectedLm = null; cvmStage = "CS3";
 
1879
  highlightCvmButton("CS3");
 
1880
  updateSuperimpositionStatus();
1881
  document.getElementById("selected-lm-label").innerText = "None";
1882
  imgElem.src = "";
1883
  container.style.display = "none";
 
1884
  dropzone.style.display = "flex";
1885
  document.getElementById("file-input").value = "";
1886
  document.getElementById("pt-name").value = "";
@@ -1897,7 +2057,7 @@ document.getElementById("btn-next-patient").addEventListener("click", () => {
1897
  });
1898
 
1899
  // =============================================================
1900
- // 6. Mathematical & Clinical Analysis Engine
1901
  // =============================================================
1902
  function getAngle(p1, v, p2) {
1903
  if (!p1 || !v || !p2) return null;
@@ -1939,6 +2099,50 @@ function calculateWits(ptA, ptB, opP, opA) {
1939
  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 } };
1940
  }
1941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1942
  function getNormObj(id) {
1943
  return ABO_NORMS.find(x => x.id === id) || { norm: 0, sd: 1 };
1944
  }
@@ -1982,8 +2186,10 @@ function updateClinicalDiagnosis(m) {
1982
  if (m.LL_E > llN.norm + llN.sd) softStr = "Protrusive Lips";
1983
  else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";
1984
 
1985
- const softAndCvm = `${softStr} | CVM: ${cvmStage}`;
1986
- const headline = `${skelClass} • ${vertClass} • ${dentStr} • [${cvmStage}]`;
 
 
1987
 
1988
  latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
1989
  document.getElementById("diag-headline").innerText = headline;
@@ -2013,8 +2219,23 @@ function renderAnalysis() {
2013
  }
2014
 
2015
  const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2016
 
2017
- // 1. Draw Longitudinal Superimpositions (T1, T2, T3)
2018
  const drawSuperLines = (alCoords, col, dash) => {
2019
  if (!alCoords) return;
2020
  line(alCoords.S, alCoords.N, col, 2.5, dash);
@@ -2026,12 +2247,18 @@ function renderAnalysis() {
2026
  };
2027
 
2028
  if (focusMode === "SUPER" || focusMode === "ALL") {
2029
- if (t1Baseline) drawSuperLines(getAlignedCoordsForBaseline(t1Baseline), "#94a3b8", "4,3"); // T1: Slate Dashed
2030
- if (t2Baseline) drawSuperLines(getAlignedCoordsForBaseline(t2Baseline), "#3b82f6", "5,2"); // T2: Blue Dashed
2031
- if (t3Baseline) drawSuperLines(getAlignedCoordsForBaseline(t3Baseline), "#d946ef", "3,2"); // T3: Purple
 
 
 
 
 
 
2032
  }
2033
 
2034
- // 2. Current Tracing Vectors
2035
  if (showLines) {
2036
  const isSuper = focusMode === "SUPER";
2037
  if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
@@ -2050,11 +2277,9 @@ function renderAnalysis() {
2050
  line(coords.Co, coords.Gn, "#38bdf8", 2.5);
2051
  line(coords.ANS, coords.Me, "#ec4899", 2.5);
2052
  if (coords.N && coords.Po && coords.Or) {
2053
- // N-Perpendicular line
2054
  const fhAngle = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
2055
  const perpAngle = fhAngle + Math.PI / 2;
2056
- const pLen = 180;
2057
- const nPerpEnd = { x: coords.N.x + Math.cos(perpAngle) * pLen, y: coords.N.y + Math.sin(perpAngle) * pLen };
2058
  line(coords.N, nPerpEnd, "#f59e0b", 2, "4,3");
2059
  }
2060
  }
@@ -2066,8 +2291,30 @@ function renderAnalysis() {
2066
  }
2067
 
2068
  if (focusMode === "AIRWAY" || focusMode === "ALL") {
2069
- if (coords.P_Palate && coords.UPW) line(coords.P_Palate, coords.UPW, "#2dd4bf", 3);
2070
- if (coords.TB && coords.LPW) line(coords.TB, coords.LPW, "#2dd4bf", 3);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2071
  }
2072
 
2073
  if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
@@ -2088,7 +2335,7 @@ function renderAnalysis() {
2088
  }
2089
  }
2090
 
2091
- // 3. Ruler (10mm)
2092
  if (showRuler && coords.RULER_1 && coords.RULER_2) {
2093
  line(coords.RULER_1, coords.RULER_2, "#06b6d4", 2.5, "4,3");
2094
  ["RULER_1", "RULER_2"].forEach((rKey, idx) => {
@@ -2114,7 +2361,7 @@ function renderAnalysis() {
2114
  });
2115
  }
2116
 
2117
- // 4. HIPAA Privacy Mask
2118
  if (hipaaPrivacyMode && coords.N && coords.Or) {
2119
  const mask = document.createElementNS("http://www.w3.org/2000/svg", "rect");
2120
  const mLeft = Math.min(coords.N.x, coords.Or.x) - 40;
@@ -2127,7 +2374,7 @@ function renderAnalysis() {
2127
  svgElem.appendChild(mask);
2128
  }
2129
 
2130
- // 5. Draw Landmark Dots
2131
  const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
2132
  if (showPoints) {
2133
  for (const [name, pt] of Object.entries(coords)) {
@@ -2143,7 +2390,8 @@ function renderAnalysis() {
2143
  if (name === "Sn") handleColor = "#ec4899";
2144
  if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
2145
  if (name === "Co" || name === "Gn") handleColor = "#38bdf8";
2146
- if (name === "P_Palate" || name === "UPW" || name === "TB" || name === "LPW") handleColor = "#2dd4bf";
 
2147
  if (selectedLm === name) handleColor = "#38bdf8";
2148
 
2149
  c.setAttribute("fill", handleColor);
@@ -2182,7 +2430,7 @@ function renderAnalysis() {
2182
  }
2183
  }
2184
 
2185
- // 6. Metrics Calculations
2186
  const sna = getAngle(coords.S, coords.N, coords.A);
2187
  const snb = getAngle(coords.S, coords.N, coords.B);
2188
  const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
@@ -2198,10 +2446,8 @@ function renderAnalysis() {
2198
  const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
2199
  const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);
2200
 
2201
- // Tweed Triangle: FMA + IMPA + FMIA = 180°
2202
  const fmia = (fma !== null && impa !== null) ? parseFloat((180.0 - (fma + impa)).toFixed(1)) : null;
2203
 
2204
- // McNamara Analysis
2205
  let a_n_perp = null, pog_n_perp = null;
2206
  if (coords.N && coords.Po && coords.Or && coords.A && coords.Pog) {
2207
  const fhA = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
@@ -2215,9 +2461,11 @@ function renderAnalysis() {
2215
  const mx_md_diff = (co_a !== null && co_gn !== null) ? parseFloat((co_gn - co_a).toFixed(1)) : null;
2216
  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;
2217
 
2218
- // Pharyngeal Airway Dimensions
2219
  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;
2220
  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;
 
 
2221
 
2222
  // Holdaway
2223
  const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
@@ -2234,7 +2482,7 @@ function renderAnalysis() {
2234
  FMIA: fmia,
2235
  A_N_PERP: a_n_perp, POG_N_PERP: pog_n_perp, CO_A: co_a, CO_GN: co_gn,
2236
  MX_MD_DIFF: mx_md_diff, LAFH: lafh,
2237
- UPS: ups, LPS: lps,
2238
  WITS: wits ? wits.distMm : null,
2239
  H_ANGLE: h_angle, SKEL_CONV: skel_conv, NOSE_PROM: nose_prom,
2240
  SN_HLINE: sn_hline, LL_HLINE: ll_hline, CHIN_THICK: chin_thick
@@ -2246,7 +2494,8 @@ function renderAnalysis() {
2246
  populateTable("tweed-rows", TWEED_NORMS, latestMetrics);
2247
  populateTable("holdaway-rows", HOLDAWAY_NORMS, latestMetrics);
2248
  populateWitsTable(latestMetrics.WITS);
2249
- populateAirwayTable(ups, lps);
 
2250
  }
2251
 
2252
  function populateAboTable(normsList, valuesDict) {
@@ -2256,7 +2505,6 @@ function populateAboTable(normsList, valuesDict) {
2256
  const val = valuesDict[m.id];
2257
  let statusHtml = `<span class="pill pill-neutral">-</span>`;
2258
  let measuredText = "-", diffText = "-", diffColor = "var(--text-muted)";
2259
- let deltaT1Html = "";
2260
 
2261
  if (val !== null && val !== undefined) {
2262
  measuredText = `${val.toFixed(1)}${m.unit}`;
@@ -2267,10 +2515,11 @@ function populateAboTable(normsList, valuesDict) {
2267
  statusHtml = isNormal ? `<span class="pill pill-normal">Normal</span>` : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High' : 'Low'}</span>`;
2268
  }
2269
 
2270
- if (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[m.id] !== undefined) {
2271
- const dT1 = val - t1Baseline.metrics[m.id];
2272
- deltaT1Html = `<td style="color:#5eead4; font-weight:700;">${dT1 > 0 ? '+' : ''}${dT1.toFixed(1)}${m.unit}</td>`;
2273
- } else if (t1Baseline) { deltaT1Html = `<td>-</td>`; }
 
2274
 
2275
  const tr = document.createElement("tr");
2276
  tr.innerHTML = `
@@ -2278,7 +2527,9 @@ function populateAboTable(normsList, valuesDict) {
2278
  <td><span class="metric-norm">${m.norm}${m.unit} ± ${m.sd}</span></td>
2279
  <td><span class="metric-val">${measuredText}</span></td>
2280
  <td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
2281
- ${deltaT1Html}
 
 
2282
  <td>${statusHtml}</td>
2283
  `;
2284
  tbody.appendChild(tr);
@@ -2328,148 +2579,120 @@ function populateWitsTable(val) {
2328
  tbody.appendChild(tr);
2329
  }
2330
 
2331
- function populateAirwayTable(ups, lps) {
2332
  const tbody = document.getElementById("airway-rows");
2333
  tbody.innerHTML = "";
2334
- const makeRow = (name, val, normMin, normMax) => {
2335
  let stat = `<span class="pill pill-neutral">-</span>`;
2336
  let valStr = "-";
2337
- if (val !== null) {
2338
- valStr = `${val.toFixed(1)} mm`;
2339
- if (val < normMin) stat = `<span class="pill pill-deviated">Constricted</span>`;
2340
- else stat = `<span class="pill pill-normal">Patent / Normal</span>`;
2341
  }
2342
  return `<tr>
2343
  <td><span class="metric-name">${name}</span></td>
2344
- <td><span class="metric-norm">${normMin}–${normMax} mm</span></td>
2345
  <td><span class="metric-val" style="color:#2dd4bf;">${valStr}</span></td>
2346
  <td>${stat}</td>
2347
  </tr>`;
2348
  };
2349
- tbody.innerHTML += makeRow("Upper Pharyngeal Space (UPS)", ups, 15, 20);
2350
- tbody.innerHTML += makeRow("Lower Pharyngeal Space (LPS)", lps, 11, 13);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2351
  }
2352
 
2353
  // =============================================================
2354
- // 8. 1-Page Letter Print Synchronization
2355
  // =============================================================
2356
  window.addEventListener("beforeprint", () => {
2357
  const rawName = document.getElementById("pt-name").value || "Patient";
2358
  const rawChart = document.getElementById("pt-chart").value || "MRN-N/A";
2359
  const dtStr = document.getElementById("pt-datetime").value || "";
2360
- const displayDt = dtStr ? dtStr.replace("T", " ") : new Date().toLocaleString();
2361
 
2362
  document.getElementById("print-pt-name").innerText = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
2363
  document.getElementById("print-pt-mrn").innerText = hipaaPrivacyMode ? "ANON-001" : rawChart;
2364
  document.getElementById("print-pt-datetime").innerText = displayDt;
2365
  document.getElementById("print-ethnicity-tag").innerText = `ETHNICITY: ${ETHNICITY_DATABASE[activeEthnicity].label.split(' ')[0]}`;
2366
 
2367
- // Mirror Cephalogram & Vector Overlay
2368
  document.getElementById("print-img").src = imgElem.src;
2369
  const printSvg = document.getElementById("print-svg");
2370
  printSvg.innerHTML = svgElem.innerHTML;
2371
  printSvg.setAttribute("viewBox", svgElem.getAttribute("viewBox") || "0 0 100 100");
2372
 
2373
- // Mirror Diagnosis
2374
  document.getElementById("print-diag-headline").innerText = latestDiagnosis.headline;
2375
  document.getElementById("print-diag-sag").innerText = `Sagittal: ${latestDiagnosis.sagittal}`;
2376
  document.getElementById("print-diag-vert").innerText = `Vertical: ${latestDiagnosis.vertical}`;
2377
  document.getElementById("print-diag-dent").innerText = `Dental: ${latestDiagnosis.dental}`;
2378
- document.getElementById("print-diag-soft").innerText = `Soft & CVM: ${latestDiagnosis.soft}`;
2379
-
2380
- // Populate Print ABO Table
2381
- const pAboBody = document.getElementById("print-abo-tbody");
2382
- pAboBody.innerHTML = "";
2383
- ABO_NORMS.forEach(m => {
2384
- const val = latestMetrics[m.id];
2385
- let diff = "-", stat = "-", diffClass = "";
2386
- if (val !== null && val !== undefined) {
2387
- const rawDiff = val - m.norm;
2388
- const isNorm = Math.abs(rawDiff) <= m.sd;
2389
- diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
2390
- stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
2391
- diffClass = isNorm ? "diff-norm" : "diff-dev";
2392
- }
2393
- pAboBody.innerHTML += `<tr>
2394
- <td><strong>${m.name}</strong></td>
2395
- <td>${m.norm}${m.unit} ± ${m.sd}</td>
2396
- <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
2397
- <td class="${diffClass}">${diff}</td>
2398
- <td>${stat}</td>
2399
- </tr>`;
2400
- });
2401
 
2402
- // Populate Print McNamara & Tweed Table
2403
- const pMcBody = document.getElementById("print-mcnamara-tbody");
2404
- pMcBody.innerHTML = "";
2405
- const combinedSecondary = [...MCNAMARA_NORMS, ...TWEED_NORMS];
2406
- combinedSecondary.forEach(m => {
2407
- const val = latestMetrics[m.id];
2408
- let diff = "-", stat = "-", diffClass = "";
2409
- if (val !== null && val !== undefined) {
2410
- const rawDiff = val - m.norm;
2411
- const isNorm = Math.abs(rawDiff) <= m.sd;
2412
- diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
2413
- stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
2414
- diffClass = isNorm ? "diff-norm" : "diff-dev";
2415
- }
2416
- pMcBody.innerHTML += `<tr>
2417
- <td><strong>${m.name}</strong></td>
2418
- <td>${m.norm}${m.unit} ± ${m.sd}</td>
2419
- <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
2420
- <td class="${diffClass}">${diff}</td>
2421
- <td>${stat}</td>
2422
- </tr>`;
2423
- });
2424
 
2425
- // Populate Print Holdaway Table
2426
- const pHoldBody = document.getElementById("print-holdaway-tbody");
2427
- pHoldBody.innerHTML = "";
2428
- HOLDAWAY_NORMS.forEach(m => {
2429
- const val = latestMetrics[m.id];
2430
- let diff = "-", stat = "-", diffClass = "";
2431
- if (val !== null && val !== undefined) {
2432
- const rawDiff = val - m.norm;
2433
- const isNorm = Math.abs(rawDiff) <= m.sd;
2434
- diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
2435
- stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
2436
- diffClass = isNorm ? "diff-norm" : "diff-dev";
2437
- }
2438
- pHoldBody.innerHTML += `<tr>
2439
- <td><strong>${m.name}</strong></td>
2440
- <td>${m.norm}${m.unit} ± ${m.sd}</td>
2441
- <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
2442
- <td class="${diffClass}">${diff}</td>
2443
- <td>${stat}</td>
2444
- </tr>`;
2445
- });
2446
 
2447
- // Populate Print Wits & Airway Table
2448
  const pWitsBody = document.getElementById("print-wits-tbody");
2449
  pWitsBody.innerHTML = "";
2450
  if (latestMetrics.WITS !== null && latestMetrics.WITS !== undefined) {
2451
  const w = latestMetrics.WITS;
2452
  const stat = w > 1.0 ? "Class II" : (w < -1.0 ? "Class III" : "Class I");
2453
- pWitsBody.innerHTML += `<tr>
2454
- <td>Wits (AO-BO)</td><td>0.0 ± 1.0 mm</td>
2455
- <td><strong>${w > 0 ? '+' : ''}${w.toFixed(1)} mm</strong></td>
2456
- <td>${stat}</td>
2457
- </tr>`;
2458
  }
2459
  if (latestMetrics.UPS !== null) {
2460
- pWitsBody.innerHTML += `<tr>
2461
- <td>Upper Airway</td><td>15–20 mm</td>
2462
- <td><strong>${latestMetrics.UPS.toFixed(1)} mm</strong></td>
2463
- <td>${latestMetrics.UPS < 15 ? 'Constricted' : 'Patent'}</td>
2464
- </tr>`;
2465
  }
2466
  if (latestMetrics.LPS !== null) {
2467
- pWitsBody.innerHTML += `<tr>
2468
- <td>Lower Airway</td><td>11–13 mm</td>
2469
- <td><strong>${latestMetrics.LPS.toFixed(1)} mm</strong></td>
2470
- <td>${latestMetrics.LPS < 11 ? 'Constricted' : 'Patent'}</td>
2471
- </tr>`;
2472
  }
 
2473
  });
2474
 
2475
  // CSV Export
@@ -2480,14 +2703,17 @@ document.getElementById("btn-export-csv").addEventListener("click", () => {
2480
  const ptChart = hipaaPrivacyMode ? "ANON-001" : (document.getElementById("pt-chart").value || "N/A");
2481
  const ptDateTime = document.getElementById("pt-datetime").value || "";
2482
 
2483
- let csv = "Patient,MRN,Date_Time,Diagnosis,Ethnicity,CVM_Stage,Category,Parameter,Norm_SD,Value,Diff,Unit,Status\n";
2484
  const addCategory = (cat, list) => {
2485
  list.forEach(m => {
2486
  const v = latestMetrics[m.id];
2487
  if (v === null || v === undefined) return;
2488
  const diff = (v - m.norm).toFixed(1);
 
 
 
2489
  const stat = Math.abs(v - m.norm) <= m.sd ? "Normal" : (v > m.norm ? "High" : "Low");
2490
- 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`;
2491
  });
2492
  };
2493
 
@@ -2519,16 +2745,10 @@ document.getElementById("btn-copy-note").addEventListener("click", () => {
2519
  `• Vertical & Tweed: ${latestDiagnosis.vertical} | FMA ${m.FMA}°, SNMP ${m.SNMP}°, FMIA ${m.FMIA}°`,
2520
  `• 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`,
2521
  `• 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}°`,
2522
- `• Soft Tissue & Airway: ${latestDiagnosis.soft} | Holdaway H-Angle ${m.H_ANGLE}°, Upper Airway ${m.UPS}mm, Lower Airway ${m.LPS}mm`
2523
  ].join("\n");
2524
 
2525
- const ta = document.createElement("textarea");
2526
- ta.value = note;
2527
- document.body.appendChild(ta);
2528
- ta.select();
2529
- document.execCommand("copy");
2530
- document.body.removeChild(ta);
2531
- notify("Clinical EMR Note Copied");
2532
  });
2533
 
2534
  // Viewport Zoom
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>OrthoCeph Pro | ABO, McNamara, Tweed, Airway & Longitudinal Suite</title>
7
  <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/ort.min.js"></script>
8
  <script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.21/dist/dicomParser.min.js"></script>
9
  <link rel="preconnect" href="https://fonts.googleapis.com">
 
91
  .workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }
92
 
93
  .sidebar {
94
+ width: 325px; background: var(--surface-dark);
95
  border-right: 1px solid var(--surface-border);
96
  padding: 12px; display: flex; flex-direction: column;
97
  gap: 10px; overflow-y: auto; flex-shrink: 0;
 
118
  }
119
  .input-field:focus { border-color: #3b82f6; }
120
 
121
+ .mode-group { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
122
  .mode-btn {
123
  background: #0f172a; border: 1px solid var(--surface-border);
124
+ color: var(--text-muted); padding: 5px 2px; border-radius: 5px;
125
+ font-size: 9.5px; font-weight: 600; cursor: pointer; text-align: center;
126
  transition: all 0.15s;
127
  }
128
  .mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; }
129
 
130
+ .toggle-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
131
  .toggle-pill {
132
  background: #0f172a; border: 1px solid var(--surface-border);
133
+ color: var(--text-muted); padding: 4px 2px; border-radius: 5px;
134
+ font-size: 9.5px; font-weight: 600; cursor: pointer; text-align: center;
135
  }
136
  .toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }
137
 
 
143
  }
144
  .cvm-btn.active { background: var(--teal-accent); color: #042f2e; border-color: #5eead4; }
145
 
146
+ /* Longitudinal Shift Bar */
147
+ .stage-shift-bar {
148
+ display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px;
149
+ background: #090d16; padding: 4px; border-radius: 6px; border: 1px solid var(--surface-border);
150
+ }
151
+ .shift-btn {
152
+ background: transparent; border: 1px solid transparent; color: var(--text-muted);
153
+ font-size: 9.5px; font-weight: 700; padding: 5px 2px; border-radius: 4px; cursor: pointer;
154
+ }
155
+ .shift-btn:hover { color: white; background: rgba(255,255,255,0.05); }
156
+ .shift-btn.active { background: #1e293b; color: #38bdf8; border-color: #38bdf8; }
157
+
158
+ .stage-vis-row {
159
+ display: flex; align-items: center; justify-content: space-between;
160
+ font-size: 9.5px; color: var(--text-muted); padding: 2px 4px;
161
+ }
162
+ .stage-vis-row label { display: flex; align-items: center; gap: 4px; cursor: pointer; font-weight: 600; }
163
+
164
  .slider-row {
165
  display: flex; align-items: center; justify-content: space-between;
166
  font-size: 10.5px; color: var(--text-muted);
 
188
  outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
189
  }
190
 
191
+ /* Floating Stage Switcher HUD on Viewport */
192
+ #stage-hud {
193
+ position: absolute; top: 14px; right: 14px;
194
+ background: rgba(17, 24, 39, 0.92); backdrop-filter: blur(8px);
195
+ border: 1px solid var(--surface-border); border-radius: 8px;
196
+ padding: 6px 10px; display: none; align-items: center; gap: 6px; z-index: 15;
197
+ box-shadow: 0 8px 20px rgba(0,0,0,0.5);
198
+ }
199
+ .hud-tag { font-size: 10px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-right: 4px; }
200
+ .hud-pill {
201
+ background: #0f172a; border: 1px solid var(--surface-border); color: var(--text-muted);
202
+ font-size: 10px; font-weight: 700; padding: 4px 8px; border-radius: 5px; cursor: pointer;
203
+ }
204
+ .hud-pill.active { background: var(--accent); color: white; border-color: #60a5fa; }
205
+
206
  #empty-dropzone {
207
  display: flex; flex-direction: column; align-items: center; justify-content: center;
208
  gap: 10px; color: var(--text-muted); text-align: center; padding: 35px;
 
252
 
253
  /* Right Analysis Panel */
254
  .analysis-panel {
255
+ width: 550px; background: var(--surface-dark);
256
  border-left: 1px solid var(--surface-border);
257
  padding: 12px 16px; display: flex; flex-direction: column;
258
  gap: 10px; overflow-y: auto; flex-shrink: 0;
 
344
  box-shadow: 0 10px 25px rgba(0,0,0,0.5); display: none; align-items: center; gap: 8px;
345
  }
346
 
347
+ /* Print-Only Report Container: STRICT 1-PAGE US LETTER (No Bottom Footer Overflow) */
348
  #print-report-container { display: none; }
349
 
350
  @media print {
351
  @page {
352
  size: letter portrait;
353
+ margin: 4mm 6mm 4mm 6mm;
354
  }
355
  *, *::before, *::after { box-sizing: border-box !important; }
356
  html, body {
357
  background: #ffffff !important; color: #000000 !important;
358
+ height: auto !important; max-height: 265mm !important; width: 100% !important;
359
+ overflow: hidden !important; font-size: 8.2px !important; margin: 0 !important; padding: 0 !important;
360
  }
361
  header, .workspace, .sidebar, .viewport, .analysis-panel,
362
+ .mobile-nav-bar, .viewport-overlay-controls, #loupe-box, #stage-hud,
363
  #empty-dropzone, #security-gate, #toast-msg {
364
  display: none !important; visibility: hidden !important;
365
  height: 0 !important; width: 0 !important; position: absolute !important;
366
  }
367
 
368
  #print-report-container {
369
+ display: flex !important; flex-direction: column; justify-content: flex-start;
370
+ width: 100% !important; height: auto !important;
371
  page-break-inside: avoid !important; break-inside: avoid !important;
372
+ page-break-after: avoid !important; break-after: avoid !important;
373
  }
374
 
375
  .print-header-bar {
376
+ border-bottom: 1.5px solid #0f172a; padding-bottom: 3px;
377
  display: flex; justify-content: space-between; align-items: flex-end;
378
  }
379
+ .print-title { font-size: 12px; font-weight: 800; color: #0f172a; letter-spacing: -0.01em; }
380
+ .print-demographics { display: flex; gap: 9px; font-size: 8.5px; font-weight: 600; color: #334155; }
381
 
382
  .print-grid {
383
+ display: grid !important; grid-template-columns: 270px 1fr !important;
384
+ gap: 8px; align-items: start; margin-top: 4px;
385
  }
386
 
387
  .print-left-col { display: flex; flex-direction: column; gap: 4px; }
388
  .print-ceph-box {
389
+ position: relative; width: 270px; height: 280px; border: 1px solid #94a3b8;
390
  border-radius: 4px; overflow: hidden; background: #000000;
391
  display: flex; align-items: center; justify-content: center;
392
  }
 
394
  .print-ceph-box svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
395
 
396
  .print-diag-card {
397
+ border: 1px solid #cbd5e1; border-radius: 4px; padding: 4px 6px;
398
+ background: #f8fafc; font-size: 8px; display: flex; flex-direction: column; gap: 1.5px;
399
  }
400
 
401
+ .print-right-col { display: flex; flex-direction: column; gap: 3px; }
402
+ .print-table { width: 100%; border-collapse: collapse; font-size: 8px; }
403
  .print-table th {
404
+ border-bottom: 1.2px solid #0f172a; padding: 1.8px 3px; text-align: left;
405
+ font-size: 7.5px; color: #0f172a; font-weight: 700; text-transform: uppercase;
406
  }
407
+ .print-table td { border-bottom: 1px solid #e2e8f0; padding: 1.8px 3px; color: #0f172a; }
408
  .print-table td.diff-dev { color: #dc2626; font-weight: 700; }
409
  .print-table td.diff-norm { color: #15803d; font-weight: 600; }
 
 
 
 
 
 
 
 
 
 
 
410
  }
411
  </style>
412
  </head>
 
430
  <div class="brand-icon">O</div>
431
  <div>
432
  <div class="brand-title">OrthoCeph Pro</div>
433
+ <div class="brand-subtitle">ABO, McNamara, Airway, CVM & T1/T2/T3 Suite</div>
434
  </div>
435
  </div>
436
 
 
513
  <div class="mode-btn" data-mode="AIRWAY">Airway</div>
514
  <div class="mode-btn" data-mode="WITS">Wits</div>
515
  <div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
516
+ <div class="mode-btn" data-mode="CVM">🦴 CVM</div>
517
+ <div class="mode-btn" data-mode="ALL">All</div>
518
+ <div class="mode-btn" data-mode="SUPER" style="grid-column: span 4; background: rgba(56,189,248,0.12); border-color:#38bdf8; color:#38bdf8;">📑 T1 / T2 / T3 Longitudinal Superimposition</div>
519
  </div>
520
  <div class="toggle-grid" style="margin-top: 3px;">
521
  <div class="toggle-pill active" id="tog-lines">Lines: ON</div>
522
  <div class="toggle-pill active" id="tog-points">Dots: ON</div>
523
  <div class="toggle-pill active" id="tog-labels">Names: ON</div>
524
+ <div class="toggle-pill active" id="tog-airway-mask" title="2D Pharyngeal Airway Area Mask">Mask: ON</div>
525
  </div>
526
  </div>
527
  </div>
528
 
529
  <div>
530
+ <div class="section-header"><span>3. Longitudinal T1 / T2 / T3 Manager</span></div>
531
  <div class="card">
532
+ <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px;">
533
+ <button id="btn-lock-t1" class="btn btn-teal" style="font-size:9.5px; padding:4px;">📌 Save T1</button>
534
+ <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;">📌 Save T2</button>
535
+ <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;">📌 Save T3</button>
536
  </div>
537
+
538
+ <div class="form-group" style="margin-top: 2px;">
539
+ <label>Shift / Inspect Stage (Loads Radiograph & Points)</label>
540
+ <div class="stage-shift-bar">
541
+ <button class="shift-btn active" data-shift="LIVE">Live Work</button>
542
+ <button class="shift-btn" data-shift="T1">View T1</button>
543
+ <button class="shift-btn" data-shift="T2">View T2</button>
544
+ <button class="shift-btn" data-shift="T3">View T3</button>
545
+ </div>
546
+ </div>
547
+
548
+ <div class="stage-vis-row">
549
+ <span>Overlay Visibility:</span>
550
+ <label style="color:#5eead4;"><input type="checkbox" id="vis-t1" checked> T1</label>
551
+ <label style="color:#60a5fa;"><input type="checkbox" id="vis-t2" checked> T2</label>
552
+ <label style="color:#f0abfc;"><input type="checkbox" id="vis-t3" checked> T3</label>
553
  </div>
554
+
555
+ <div class="form-group">
556
+ <label>Superimposition Registration Plane</label>
557
+ <select id="super-mode" class="input-field" style="padding: 4px;">
558
+ <option value="CRANIAL">Cranial Base (S-N registered at S)</option>
559
+ <option value="MAXILLARY">Maxillary Palatal Plane (PNS-ANS at PNS)</option>
560
+ <option value="MANDIBULAR">Mandibular Symphysis / Border (at Me)</option>
561
+ </select>
562
+ </div>
563
+
564
+ <div id="super-status" style="font-size: 9px; color: var(--text-muted); text-align: center; line-height:1.3;">
565
+ No stages saved yet.
566
+ </div>
567
+ <button id="btn-clear-series" class="btn btn-secondary" style="font-size:9px; padding:3px;">Clear All Stages</button>
568
  </div>
569
  </div>
570
 
571
  <div>
572
+ <div class="section-header">
573
+ <span>4. CVM Maturation (Hybrid AI + Geometry)</span>
574
+ <span id="cvm-auto-tag" style="color:#2dd4bf; font-size:9px;">Auto-Tracked</span>
575
+ </div>
576
  <div class="card">
577
  <div class="cvm-grid">
578
  <div class="cvm-btn" data-cvm="CS1">CS1</div>
 
589
  </div>
590
 
591
  <div>
592
+ <div class="section-header"><span>5. Retrace & Calibration</span></div>
593
  <div class="card">
594
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
595
+ <button id="btn-retrace-all" class="btn btn-secondary">Reset All</button>
596
+ <button id="btn-reset-single" class="btn btn-secondary">Reset Dot</button>
 
 
 
 
 
 
 
 
 
 
597
  </div>
598
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
599
+ <button id="btn-cal" class="btn btn-secondary" style="font-size: 9.5px; padding: 5px 3px;">Ruler: Toggle</button>
600
+ <button id="btn-auto-caliper" class="btn" style="background:#0891b2; font-size:9.5px; padding: 5px 3px;">⚡ Auto 10mm</button>
601
  </div>
602
+ <span id="cal-status" style="font-size: 10px; color: var(--ruler-cyan); text-align: center; font-weight: 600;">
603
+ Scale: 10.00 px/mm
604
+ </span>
605
+ <div style="font-size: 9px; color: var(--text-muted); text-align: center;">
606
+ Selected: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot to reset)
 
607
  </div>
608
  </div>
609
  </div>
610
 
611
  <div>
612
  <div class="section-header">
613
+ <span>6. Image Equalization & Ethnicity</span>
614
  <span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 9.5px;">Reset</span>
615
  </div>
616
  <div class="card">
617
+ <div class="form-group">
 
 
 
 
 
 
 
618
  <label>Density Filter</label>
619
  <select id="filter-mode-select" class="input-field" style="padding: 4px;">
620
  <option value="NORMAL">Standard Radiograph</option>
 
635
  <span>Invert Negative</span>
636
  <input type="checkbox" id="invert">
637
  </div>
638
+ <div class="form-group" style="margin-top: 2px;">
 
 
 
 
 
 
 
 
 
639
  <label>Ethnic Population Standard</label>
640
  <select id="ethnicity-select" class="input-field" style="padding: 4px; font-weight: 600; color: #38bdf8;">
641
  <option value="CAUCASIAN">Caucasian (ABO Standard / Michigan)</option>
 
647
  <button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 10px; padding: 4px; margin-top: 2px;">
648
  Customize ABO Norms
649
  </button>
650
+ <span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 9.5px; text-align:center; display: none;">Restore Default Norms</span>
651
  <div id="norms-drawer"></div>
652
  </div>
653
  </div>
 
660
  <div id="loupe-label">S</div>
661
  </div>
662
 
663
+ <!-- Floating Longitudinal Stage Switcher HUD -->
664
+ <div id="stage-hud">
665
+ <span class="hud-tag">Stage View:</span>
666
+ <button class="hud-pill active" data-hud-shift="LIVE">Live</button>
667
+ <button class="hud-pill" data-hud-shift="T1">T1</button>
668
+ <button class="hud-pill" data-hud-shift="T2">T2</button>
669
+ <button class="hud-pill" data-hud-shift="T3">T3</button>
670
+ <button class="hud-pill" data-hud-shift="SUPER" style="border-color:#38bdf8; color:#38bdf8;">All Overlay</button>
671
+ </div>
672
+
673
  <div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
674
  <div style="font-size: 32px;">🦷</div>
675
  <div style="font-size: 14px; font-weight: 600; color: var(--text-main);">Drop Lateral Cephalogram (.DCM, .JPG, .PNG) or .JSON Here</div>
676
+ <div style="font-size: 11px;">Instant AI Landmark Localization • Airway Lumen Segmentation • C2–C4 CVM Geometry</div>
677
  </div>
678
 
679
  <div id="viewport-container">
 
686
  <button id="btn-zoom-out">Zoom (-)</button>
687
  <button id="btn-zoom-reset">Fit</button>
688
  <span style="color: var(--surface-border);">|</span>
689
+ <span class="shortcut-hint">Hold <strong>[SPACE]</strong> to inspect bone • Double-click dot to reset</span>
690
  </div>
691
  </main>
692
 
 
708
  <span class="diag-val" id="diag-dental">-</span>
709
  </div>
710
  <div class="diag-item">
711
+ <span class="diag-label">Airway, Soft & CVM</span>
712
  <span class="diag-val" id="diag-soft">-</span>
713
  </div>
714
  </div>
 
721
  <tr>
722
  <th>Parameter</th>
723
  <th>Norm</th>
724
+ <th>Current</th>
725
  <th>Diff</th>
726
+ <th class="col-t1" style="display:none; color:#5eead4;">T1</th>
727
+ <th class="col-t2" style="display:none; color:#60a5fa;">T2</th>
728
+ <th class="col-t3" style="display:none; color:#f0abfc;">T3</th>
729
  <th>Status</th>
730
  </tr>
731
  </thead>
732
  <tbody id="abo-rows">
733
+ <tr><td colspan="8" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting radiograph...</td></tr>
734
  </tbody>
735
  </table>
736
  </div>
 
772
  </div>
773
 
774
  <div id="section-airway">
775
+ <div class="section-header" style="color: #2dd4bf;">2D Pharyngeal Airway Segmentation & McNamara Widths</div>
776
  <table class="analysis-table">
777
  <thead>
778
  <tr>
779
+ <th>Airway Parameter</th>
780
+ <th>Clinical Norm</th>
781
  <th>Measured</th>
782
  <th>Status</th>
783
  </tr>
 
788
  </table>
789
  </div>
790
 
791
+ <div id="section-cvm">
792
+ <div class="section-header" style="color: #14b8a6;">Cervical Vertebral Maturation (C2–C4 Sub-mm Geometry)</div>
793
+ <table class="analysis-table">
794
+ <thead>
795
+ <tr>
796
+ <th>Vertebral Feature</th>
797
+ <th>Measured</th>
798
+ <th>Morphology / Growth Timing</th>
799
+ </tr>
800
+ </thead>
801
+ <tbody id="cvm-rows">
802
+ <tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 8px;">Awaiting radiograph...</td></tr>
803
+ </tbody>
804
+ </table>
805
+ </div>
806
+
807
  <div id="section-wits">
808
  <div class="section-header" style="color: #c084fc;">Jacobson Wits Appraisal</div>
809
  <table class="analysis-table">
 
858
  </button>
859
  </nav>
860
 
861
+ <!-- Print 1-Page Letter Layout (Strictly Single Page - Signature & Disclaimer Footer Removed) -->
862
  <div id="print-report-container">
863
  <div class="print-header-bar">
864
  <div>
865
  <div class="print-title">ORTHOCEPH PRO | CLINICAL ABO CEPHALOMETRIC REPORT</div>
866
+ <div style="font-size: 7.5px; color: #64748b; font-weight: 600;">AMERICAN BOARD OF ORTHODONTICS, MCNAMARA, AIRWAY & CVM SUMMARY</div>
867
  </div>
868
  <div class="print-demographics">
869
  <div>PATIENT: <strong id="print-pt-name">Unspecified</strong></div>
870
  <div>MRN: <strong id="print-pt-mrn">-</strong></div>
871
+ <div>DATE: <strong id="print-pt-datetime">-</strong></div>
872
  <div id="print-ethnicity-tag" style="color:#0284c7;">ETHNICITY: <strong>Caucasian</strong></div>
873
  </div>
874
  </div>
 
880
  <svg id="print-svg" viewBox="0 0 100 100"></svg>
881
  </div>
882
  <div class="print-diag-card">
883
+ <div style="font-weight: 800; color: #1e3a8a; font-size: 8.5px; border-bottom: 1px solid #e2e8f0; padding-bottom: 2px;" id="print-diag-headline">Diagnosis Summary</div>
884
  <div id="print-diag-sag">Sagittal: -</div>
885
  <div id="print-diag-vert">Vertical: -</div>
886
  <div id="print-diag-dent">Dental: -</div>
887
+ <div id="print-diag-soft">Airway, Soft & CVM: -</div>
888
  </div>
889
  <table class="print-table" id="print-wits-table">
890
  <thead>
891
+ <tr><th>Wits, Airway & CVM</th><th>Norm</th><th>Measured</th><th>Status</th></tr>
892
  </thead>
893
  <tbody id="print-wits-tbody"></tbody>
894
  </table>
 
908
  <tbody id="print-abo-tbody"></tbody>
909
  </table>
910
 
911
+ <table class="print-table" id="print-mcnamara-table" style="margin-top: 2px;">
912
  <thead>
913
  <tr>
914
  <th>McNamara & Tweed</th>
 
921
  <tbody id="print-mcnamara-tbody"></tbody>
922
  </table>
923
 
924
+ <table class="print-table" id="print-holdaway-table" style="margin-top: 2px;">
925
  <thead>
926
  <tr>
927
  <th>Holdaway Soft Tissue</th>
 
935
  </table>
936
  </div>
937
  </div>
 
 
 
 
 
 
 
 
 
938
  </div>
939
 
940
  <div id="toast-msg">Notification</div>
 
943
  // =============================================================
944
  // 1. Constants, Ethnic Norm Databases & Configurations
945
  // =============================================================
946
+ const MASTER_PASSWORD = "ortho2026";
947
  const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
948
 
949
  const LM_INDICES = {
 
956
  ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft"]),
957
  MCNAMARA: new Set(["N", "Po", "Or", "A", "Pog", "Co", "Gn", "ANS", "Me"]),
958
  TWEED: new Set(["Po", "Or", "Go", "Me", "LIT", "LIA"]),
959
+ AIRWAY: new Set(["PNS", "UPW", "P_Palate", "MPW", "TB", "LPW", "V_Epiglottis", "HPW", "Go", "B"]),
960
  WITS: new Set(["A", "B", "OP_P", "OP_A"]),
961
  HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
962
+ 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"]),
963
  SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog", "Co", "Gn"]),
964
+ ALL: new Set([
965
+ "S", "N", "Po", "Or", "A", "B", "Pog", "Me", "Gn", "Go", "ANS", "PNS",
966
+ "UIT", "UIA", "LIT", "LIA", "Pn", "Sn", "Ls", "Li", "Pog_soft", "OP_P", "OP_A", "Co",
967
+ "UPW", "P_Palate", "MPW", "TB", "LPW", "V_Epiglottis", "HPW",
968
+ "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"
969
+ ])
970
  };
971
 
972
  const CVM_INFO = {
 
1103
  let session = null;
1104
  let coords = {};
1105
  let initialAiCoords = {};
1106
+ let liveWorkspaceBackup = null; // Stores live state when inspecting T1/T2/T3
1107
+ let activeStageView = "LIVE";
1108
  let t1Baseline = null;
1109
  let t2Baseline = null;
1110
  let t3Baseline = null;
1111
  let selectedLm = null;
1112
  let cvmStage = "CS3";
1113
+ let cvmManualOverride = false;
1114
  let pxPerMm = 10.0;
1115
  let showRuler = false;
1116
  let focusMode = "ABO";
1117
  let showLines = true;
1118
  let showPoints = true;
1119
  let showLabels = true;
1120
+ let showAirwayMask = true;
1121
  let spacebarPeek = false;
1122
  let hipaaPrivacyMode = false;
1123
  let currentFilterMode = "NORMAL";
 
1137
  const loupeBox = document.getElementById("loupe-box");
1138
  const loupeCanvas = document.getElementById("loupe-canvas");
1139
  const loupeLabel = document.getElementById("loupe-label");
1140
+ const stageHud = document.getElementById("stage-hud");
1141
 
 
1142
  function setAutoDateTime() {
1143
  const now = new Date();
1144
  const pad = (n) => String(n).padStart(2, '0');
 
1147
  }
1148
  setAutoDateTime();
1149
 
 
1150
  function notify(msg, dur = 2600) {
1151
  const t = document.getElementById("toast-msg");
1152
  t.innerText = msg;
 
1155
  t._tm = setTimeout(() => t.style.display = "none", dur);
1156
  }
1157
 
1158
+ // Security Gate
1159
  const gateElem = document.getElementById("security-gate");
1160
  const gatePass = document.getElementById("gate-pass");
1161
  const gateErr = document.getElementById("gate-err");
 
1191
  checkSecurity();
1192
  });
1193
 
1194
+ // Mobile Tabs
1195
  const mobileTabBtns = document.querySelectorAll(".mobile-tab-btn");
1196
  function setMobileTab(tabName) {
1197
  document.body.classList.remove("tab-tools", "tab-viewport", "tab-analysis");
 
1201
  setMobileTab("tools");
1202
  mobileTabBtns.forEach(b => b.addEventListener("click", () => setMobileTab(b.getAttribute("data-tab"))));
1203
 
1204
+ // Custom Norms Editor
1205
  function buildNormsEditor() {
1206
  const drawer = document.getElementById("norms-drawer");
1207
  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>`;
 
1236
  const r = document.getElementById("reset-norms");
1237
  const open = d.style.display === "flex";
1238
  d.style.display = open ? "none" : "flex";
1239
+ r.style.display = open ? "none" : "block";
1240
  });
1241
 
1242
  document.getElementById("reset-norms").addEventListener("click", () => {
 
1248
  notify("Norms restored to ethnic baseline.");
1249
  });
1250
 
 
1251
  document.getElementById("ethnicity-select").addEventListener("change", (e) => {
1252
  activeEthnicity = e.target.value;
1253
  const ethData = ETHNICITY_DATABASE[activeEthnicity] || ETHNICITY_DATABASE.CAUCASIAN;
 
1259
  notify(`Norms adjusted for ${ethData.label}`);
1260
  });
1261
 
 
1262
  document.getElementById("btn-privacy-toggle").addEventListener("click", () => {
1263
  hipaaPrivacyMode = !hipaaPrivacyMode;
1264
  document.getElementById("privacy-btn-txt").innerText = `HIPAA Mask: ${hipaaPrivacyMode ? 'ON' : 'OFF'}`;
 
1267
  notify(hipaaPrivacyMode ? "HIPAA De-Identification Mode Enabled." : "De-Identification Disabled.");
1268
  });
1269
 
 
1270
  document.getElementById("btn-export-svg").addEventListener("click", () => {
1271
+ if (!coords.S || !imgElem.naturalWidth) { notify("Trace a radiograph first."); return; }
1272
+ const w = imgElem.naturalWidth, h = imgElem.naturalHeight;
 
 
 
 
1273
  const svgContent = `<?xml version="1.0" encoding="UTF-8"?>
1274
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" style="background:transparent;">
1275
  ${svgElem.innerHTML}
 
1284
  notify("Transparent vector SVG downloaded.");
1285
  });
1286
 
 
1287
  document.getElementById("btn-auto-caliper").addEventListener("click", () => {
1288
+ if (!imgElem.src || imgElem.naturalWidth === 0) { notify("Load a cephalogram first."); return; }
 
 
 
1289
  autoDetect10mmCaliper();
1290
  });
1291
 
1292
  function autoDetect10mmCaliper() {
1293
+ const origW = imgElem.naturalWidth, origH = imgElem.naturalHeight;
 
 
 
1294
  const scanCanvas = document.createElement("canvas");
1295
+ const roiW = Math.floor(origW * 0.28), roiH = Math.floor(origH * 0.4);
 
1296
  scanCanvas.width = roiW; scanCanvas.height = roiH;
1297
  const ctx = scanCanvas.getContext("2d");
1298
  ctx.drawImage(imgElem, origW * 0.72, 0, roiW, roiH, 0, 0, roiW, roiH);
1299
 
1300
+ const data = ctx.getImageData(0, 0, roiW, roiH).data;
 
1301
  let bestCol = -1, bestScore = -1;
 
1302
  for (let x = 8; x < roiW - 8; x += 3) {
1303
  let variance = 0, prev = 0;
1304
  for (let y = 8; y < roiH - 8; y += 2) {
 
1307
  variance += Math.abs(gray - prev);
1308
  prev = gray;
1309
  }
1310
+ if (variance > bestScore) { bestScore = variance; bestCol = x; }
 
 
 
1311
  }
1312
 
1313
  const detectedX = origW * 0.72 + (bestCol > 0 ? bestCol : roiW * 0.55);
 
1321
  calBtn.innerText = "Ruler: ON";
1322
  calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Auto-Locked)`;
1323
  renderAnalysis();
1324
+ notify(`Auto-calibrated scale (${pxPerMm.toFixed(2)} px/mm).`);
1325
  }
1326
 
 
1327
  document.getElementById("filter-mode-select").addEventListener("change", (e) => {
1328
  currentFilterMode = e.target.value;
1329
  applyFilters();
 
1400
  loadJsonFile(file);
1401
  return;
1402
  }
1403
+ activeStageView = "LIVE";
1404
+ syncStageButtons();
1405
  const isDicom = name.endsWith('.dcm') || file.type === 'application/dicom';
1406
  if (isDicom) {
1407
  const reader = new FileReader();
 
1432
  expCanvas.height = imgElem.naturalHeight;
1433
  const expCtx = expCanvas.getContext("2d");
1434
  expCtx.drawImage(imgElem, 0, 0);
1435
+ exportDataUrl = expCanvas.toDataURL("image/jpeg", 0.90);
1436
  } catch (e) { exportDataUrl = imgElem.src; }
1437
  }
1438
 
1439
  const payload = {
1440
+ version: "3.5",
1441
  patient: { name: ptName, chart: ptChart, datetime: ptDateTime, ethnicity: activeEthnicity },
1442
  pxPerMm, cvmStage, coords, initialAiCoords,
1443
  baselines: { t1: t1Baseline, t2: t2Baseline, t3: t3Baseline },
 
1505
  function createReferencePlaceholder() {
1506
  dropzone.style.display = "none";
1507
  container.style.display = "block";
1508
+ stageHud.style.display = "flex";
1509
  const refCanvas = document.createElement("canvas");
1510
  refCanvas.width = 1200; refCanvas.height = 1400;
1511
  const ctx = refCanvas.getContext("2d");
 
1587
  imgElem.onload = () => {
1588
  dropzone.style.display = "none";
1589
  container.style.display = "block";
1590
+ stageHud.style.display = "flex";
1591
  svgElem.setAttribute("viewBox", `0 0 ${imgElem.naturalWidth} ${imgElem.naturalHeight}`);
1592
  svgElem.setAttribute("width", imgElem.clientWidth);
1593
  svgElem.setAttribute("height", imgElem.clientHeight);
 
1599
  }
1600
 
1601
  // =============================================================
1602
+ // 4. AI Deep Learning Tracing & Derived Landmarks (Airway + CVM)
1603
  // =============================================================
1604
  async function runAutoTrace() {
1605
  if (!session || !imgElem.src) return;
 
1644
  };
1645
  }
1646
 
1647
+ // Functional Occlusal Plane & PNS
1648
  if (coords.UIT && coords.LIT) {
1649
  coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
1650
  }
 
1655
  coords.PNS = { x: coords.ANS.x - (coords.A.x - coords.ANS.x) * 2.8 - 40, y: coords.ANS.y - 4 };
1656
  }
1657
 
1658
+ // Condylion (Co)
1659
  if (coords.Po && coords.Go) {
1660
  coords.Co = { x: coords.Po.x + (coords.Go.x - coords.Po.x) * 0.28 + 10, y: coords.Po.y + 16 };
1661
  }
1662
 
1663
+ // 2D Pharyngeal Airway Contour Landmarks (Upper, Middle & Lower Pharynx)
1664
+ if (coords.PNS && coords.Go && coords.B) {
1665
+ coords.P_Palate = { x: coords.PNS.x + 6, y: coords.PNS.y + 22 };
1666
+ coords.UPW = { x: coords.PNS.x - 42, y: coords.PNS.y + 18 };
1667
+ coords.TB = { x: coords.Go.x + (coords.B.x - coords.Go.x) * 0.35, y: coords.Go.y - 12 };
1668
+ coords.MPW = { x: coords.UPW.x - 4, y: (coords.UPW.y + coords.Go.y) / 2 };
1669
+ coords.LPW = { x: coords.TB.x - 32, y: coords.TB.y };
1670
+ coords.V_Epiglottis = { x: coords.TB.x - 6, y: coords.Go.y + 24 };
1671
+ coords.HPW = { x: coords.LPW.x - 2, y: coords.Go.y + 24 };
1672
+ }
1673
+
1674
+ // C2, C3, C4 Cervical Vertebral Landmarks for Sub-mm Concavity & Morphology
1675
+ if (coords.Go && coords.Po) {
1676
+ const cx = coords.Po.x - Math.abs(coords.Go.x - coords.Po.x) * 0.38;
1677
+ const cy = coords.Go.y - Math.abs(coords.Go.y - coords.Po.y) * 0.12;
1678
+ const s = Math.max(16, origW * 0.02);
1679
+
1680
+ // C2 Inferior Border
1681
+ coords.C2_LL = { x: cx - s * 0.9, y: cy - s * 1.4 };
1682
+ coords.C2_INF = { x: cx, y: cy - s * 1.58 };
1683
+ coords.C2_LR = { x: cx + s * 0.9, y: cy - s * 1.4 };
1684
+
1685
+ // C3 Body & Inferior Border
1686
+ coords.C3_UL = { x: cx - s, y: cy - s * 0.6 };
1687
+ coords.C3_UR = { x: cx + s, y: cy - s * 0.45 };
1688
+ coords.C3_LL = { x: cx - s, y: cy + s * 0.85 };
1689
+ coords.C3_INF = { x: cx, y: cy + s * 0.68 };
1690
+ coords.C3_LR = { x: cx + s, y: cy + s * 0.85 };
1691
+
1692
+ // C4 Body & Inferior Border
1693
+ const c4y = cy + s * 2.25;
1694
+ coords.C4_UL = { x: cx - s, y: c4y - s * 0.6 };
1695
+ coords.C4_UR = { x: cx + s, y: c4y - s * 0.45 };
1696
+ coords.C4_LL = { x: cx - s, y: c4y + s * 0.85 };
1697
+ coords.C4_INF = { x: cx, y: c4y + s * 0.72 };
1698
+ coords.C4_LR = { x: cx + s, y: c4y + s * 0.85 };
1699
  }
1700
 
1701
  coords.RULER_1 = { x: origW * 0.82, y: origH * 0.12 };
1702
  coords.RULER_2 = { x: origW * 0.82, y: origH * 0.12 + (pxPerMm * 10.0) };
1703
 
1704
  initialAiCoords = JSON.parse(JSON.stringify(coords));
1705
+ cvmManualOverride = false;
1706
  statusInd.style.backgroundColor = "var(--status-green)";
1707
  statusTxt.innerText = "Auto-Trace Complete";
1708
  renderAnalysis();
 
1712
  if (!imgElem.src) return;
1713
  if (Object.keys(initialAiCoords).length > 0) {
1714
  coords = JSON.parse(JSON.stringify(initialAiCoords));
1715
+ cvmManualOverride = false;
1716
  renderAnalysis();
1717
  notify("Landmarks reset to AI prediction");
1718
  } else { runAutoTrace(); }
 
1726
  } else { notify("Click any landmark dot first to reset it."); }
1727
  });
1728
 
 
 
 
 
 
 
 
 
 
 
 
 
1729
  // =============================================================
1730
+ // 5. Longitudinal T1 / T2 / T3 Manager & Stage Switcher
1731
  // =============================================================
1732
+ function captureStageSnapshot(stageKey, label) {
1733
  if (!coords.S) {
1734
+ notify(`Trace a cephalogram first before saving ${stageKey}.`);
1735
  return;
1736
  }
1737
  const dateStr = (document.getElementById("pt-datetime").value || stageKey).replace("T", " ");
1738
+ const snapshot = {
1739
  coords: JSON.parse(JSON.stringify(coords)),
1740
+ initialAiCoords: JSON.parse(JSON.stringify(initialAiCoords)),
1741
  metrics: JSON.parse(JSON.stringify(latestMetrics)),
1742
+ diagnosis: JSON.parse(JSON.stringify(latestDiagnosis)),
1743
+ pxPerMm,
1744
+ cvmStage,
1745
+ imageSrc: imgElem.src,
1746
  date: dateStr
1747
  };
1748
 
1749
+ if (stageKey === "T1") t1Baseline = snapshot;
1750
+ else if (stageKey === "T2") t2Baseline = snapshot;
1751
+ else if (stageKey === "T3") t3Baseline = snapshot;
1752
 
1753
  updateSuperimpositionStatus();
1754
  renderAnalysis();
1755
+ notify(`${label} saved (${dateStr}). Use Stage Shift buttons to switch between T1, T2 & T3.`);
1756
+ }
1757
+
1758
+ function shiftToStage(targetStage) {
1759
+ if (targetStage === "SUPER") {
1760
+ focusMode = "SUPER";
1761
+ document.querySelectorAll(".mode-btn").forEach(b => b.classList.toggle("active", b.getAttribute("data-mode") === "SUPER"));
1762
+ renderAnalysis();
1763
+ return;
1764
+ }
1765
+
1766
+ if (targetStage !== "LIVE") {
1767
+ const snap = targetStage === "T1" ? t1Baseline : (targetStage === "T2" ? t2Baseline : t3Baseline);
1768
+ if (!snap) {
1769
+ notify(`${targetStage} has not been saved yet. Upload a radiograph and click 'Save ${targetStage}'.`);
1770
+ return;
1771
+ }
1772
+ // Backup live workspace if leaving LIVE for the first time
1773
+ if (activeStageView === "LIVE" && coords.S) {
1774
+ liveWorkspaceBackup = {
1775
+ coords: JSON.parse(JSON.stringify(coords)),
1776
+ initialAiCoords: JSON.parse(JSON.stringify(initialAiCoords)),
1777
+ pxPerMm,
1778
+ cvmStage,
1779
+ imageSrc: imgElem.src,
1780
+ date: document.getElementById("pt-datetime").value
1781
+ };
1782
+ }
1783
+ activeStageView = targetStage;
1784
+ coords = JSON.parse(JSON.stringify(snap.coords));
1785
+ initialAiCoords = JSON.parse(JSON.stringify(snap.initialAiCoords || snap.coords));
1786
+ pxPerMm = snap.pxPerMm || 10.0;
1787
+ cvmStage = snap.cvmStage || "CS3";
1788
+ highlightCvmButton(cvmStage);
1789
+ if (snap.imageSrc && imgElem.src !== snap.imageSrc) {
1790
+ imgElem.src = snap.imageSrc;
1791
+ }
1792
+ notify(`Viewing ${targetStage} (${snap.date}) — Any dot adjustments automatically update ${targetStage}.`);
1793
+ } else {
1794
+ if (activeStageView !== "LIVE" && liveWorkspaceBackup) {
1795
+ coords = JSON.parse(JSON.stringify(liveWorkspaceBackup.coords));
1796
+ initialAiCoords = JSON.parse(JSON.stringify(liveWorkspaceBackup.initialAiCoords));
1797
+ pxPerMm = liveWorkspaceBackup.pxPerMm;
1798
+ cvmStage = liveWorkspaceBackup.cvmStage;
1799
+ if (liveWorkspaceBackup.imageSrc) imgElem.src = liveWorkspaceBackup.imageSrc;
1800
+ }
1801
+ activeStageView = "LIVE";
1802
+ notify("Switched to Live Workspace");
1803
+ }
1804
+
1805
+ syncStageButtons();
1806
+ renderAnalysis();
1807
+ }
1808
+
1809
+ function syncStageButtons() {
1810
+ document.querySelectorAll(".shift-btn").forEach(b => {
1811
+ b.classList.toggle("active", b.getAttribute("data-shift") === activeStageView);
1812
+ });
1813
+ document.querySelectorAll(".hud-pill").forEach(b => {
1814
+ b.classList.toggle("active", b.getAttribute("data-hud-shift") === activeStageView);
1815
+ });
1816
  }
1817
 
1818
+ document.querySelectorAll(".shift-btn").forEach(btn => {
1819
+ btn.addEventListener("click", () => shiftToStage(btn.getAttribute("data-shift")));
1820
+ });
1821
+ document.querySelectorAll(".hud-pill").forEach(btn => {
1822
+ btn.addEventListener("click", () => shiftToStage(btn.getAttribute("data-hud-shift")));
1823
+ });
1824
+
1825
+ ["vis-t1", "vis-t2", "vis-t3"].forEach(id => {
1826
+ document.getElementById(id).addEventListener("change", () => renderAnalysis());
1827
+ });
1828
+ document.getElementById("super-mode").addEventListener("change", () => renderAnalysis());
1829
+
1830
  function updateSuperimpositionStatus() {
1831
+ const t1Txt = t1Baseline ? `<span style="color:#5eead4; font-weight:700;">T1✓</span>` : "T1:-";
1832
+ const t2Txt = t2Baseline ? `<span style="color:#60a5fa; font-weight:700;">T2✓</span>` : "T2:-";
1833
+ const t3Txt = t3Baseline ? `<span style="color:#f0abfc; font-weight:700;">T3✓</span>` : "T3:-";
1834
+ document.getElementById("super-status").innerHTML = `Saved Stages: ${t1Txt} | ${t2Txt} | ${t3Txt}`;
1835
+
1836
+ document.querySelectorAll(".col-t1").forEach(el => el.style.display = t1Baseline ? "table-cell" : "none");
1837
+ document.querySelectorAll(".col-t2").forEach(el => el.style.display = t2Baseline ? "table-cell" : "none");
1838
+ document.querySelectorAll(".col-t3").forEach(el => el.style.display = t3Baseline ? "table-cell" : "none");
1839
  }
1840
 
1841
+ document.getElementById("btn-lock-t1").addEventListener("click", () => captureStageSnapshot("T1", "T1 Initial"));
1842
+ document.getElementById("btn-lock-t2").addEventListener("click", () => captureStageSnapshot("T2", "T2 Progress"));
1843
+ document.getElementById("btn-lock-t3").addEventListener("click", () => captureStageSnapshot("T3", "T3 Final"));
1844
 
1845
  document.getElementById("btn-clear-series").addEventListener("click", () => {
1846
  t1Baseline = null; t2Baseline = null; t3Baseline = null;
1847
+ activeStageView = "LIVE";
1848
+ syncStageButtons();
1849
  updateSuperimpositionStatus();
1850
  renderAnalysis();
1851
+ notify("All longitudinal stages cleared.");
1852
  });
1853
 
1854
  function getAlignedCoordsForBaseline(baselineObj) {
 
1892
  document.querySelectorAll(".cvm-btn").forEach(btn => {
1893
  btn.addEventListener("click", () => {
1894
  cvmStage = btn.getAttribute("data-cvm");
1895
+ cvmManualOverride = true;
1896
+ document.getElementById("cvm-auto-tag").innerText = "Manual Stage";
1897
  highlightCvmButton(cvmStage);
1898
  renderAnalysis();
1899
  });
 
1903
  document.getElementById("cvm-desc").innerText = CVM_INFO[stg] || "CVM Stage Selected";
1904
  }
1905
 
1906
+ // Focus Modes & Layer Toggles
1907
  document.querySelectorAll(".mode-btn").forEach(btn => {
1908
  btn.addEventListener("click", () => {
1909
  document.querySelectorAll(".mode-btn").forEach(b => b.classList.remove("active"));
 
1926
  setupToggle("tog-lines", "Lines", () => showLines, v => showLines = v);
1927
  setupToggle("tog-points", "Dots", () => showPoints, v => showPoints = v);
1928
  setupToggle("tog-labels", "Names", () => showLabels, v => showLabels = v);
1929
+ setupToggle("tog-airway-mask", "Mask", () => showAirwayMask, v => showAirwayMask = v);
1930
 
1931
  window.addEventListener("keydown", (e) => {
1932
  if (e.code === "Space" && document.activeElement.tagName !== "INPUT") {
 
1984
  }
1985
  updateLoupe(p, draggingLm);
1986
  renderAnalysis();
1987
+
1988
+ // Sync back if editing a saved stage directly
1989
+ if (activeStageView === "T1" && t1Baseline) {
1990
+ t1Baseline.coords = JSON.parse(JSON.stringify(coords));
1991
+ t1Baseline.metrics = JSON.parse(JSON.stringify(latestMetrics));
1992
+ } else if (activeStageView === "T2" && t2Baseline) {
1993
+ t2Baseline.coords = JSON.parse(JSON.stringify(coords));
1994
+ t2Baseline.metrics = JSON.parse(JSON.stringify(latestMetrics));
1995
+ } else if (activeStageView === "T3" && t3Baseline) {
1996
+ t3Baseline.coords = JSON.parse(JSON.stringify(coords));
1997
+ t3Baseline.metrics = JSON.parse(JSON.stringify(latestMetrics));
1998
+ }
1999
  });
2000
 
2001
  window.addEventListener("mouseup", () => {
 
2006
  }
2007
  });
2008
 
 
2009
  function handleTouchMove(e) {
2010
  if (!draggingLm || !coords[draggingLm] || !e.touches[0]) return;
2011
  e.preventDefault();
 
2032
  document.getElementById("btn-next-patient").addEventListener("click", () => {
2033
  coords = {}; initialAiCoords = {}; latestMetrics = {};
2034
  t1Baseline = null; t2Baseline = null; t3Baseline = null;
2035
+ liveWorkspaceBackup = null; activeStageView = "LIVE";
2036
+ selectedLm = null; cvmStage = "CS3"; cvmManualOverride = false;
2037
  highlightCvmButton("CS3");
2038
+ syncStageButtons();
2039
  updateSuperimpositionStatus();
2040
  document.getElementById("selected-lm-label").innerText = "None";
2041
  imgElem.src = "";
2042
  container.style.display = "none";
2043
+ stageHud.style.display = "none";
2044
  dropzone.style.display = "flex";
2045
  document.getElementById("file-input").value = "";
2046
  document.getElementById("pt-name").value = "";
 
2057
  });
2058
 
2059
  // =============================================================
2060
+ // 6. Mathematical, 2D Airway Area & CVM Geometry Engine
2061
  // =============================================================
2062
  function getAngle(p1, v, p2) {
2063
  if (!p1 || !v || !p2) return null;
 
2099
  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 } };
2100
  }
2101
 
2102
+ function calculatePolygonAreaMm2(pts) {
2103
+ if (!pts || pts.some(p => !p) || !pxPerMm) return null;
2104
+ let areaPx = 0;
2105
+ for (let i = 0; i < pts.length; i++) {
2106
+ const j = (i + 1) % pts.length;
2107
+ areaPx += pts[i].x * pts[j].y - pts[j].x * pts[i].y;
2108
+ }
2109
+ areaPx = Math.abs(areaPx) / 2.0;
2110
+ return parseFloat((areaPx / (pxPerMm * pxPerMm)).toFixed(1));
2111
+ }
2112
+
2113
+ function evaluateCvmGeometry() {
2114
+ if (!coords.C2_LL || !coords.C2_LR || !coords.C2_INF || !coords.C3_LL || !coords.C3_LR || !coords.C3_INF || !coords.C4_LL || !coords.C4_LR || !coords.C4_INF) return null;
2115
+
2116
+ const c2Conc = Math.abs(getPerpDist(coords.C2_INF, coords.C2_LL, coords.C2_LR));
2117
+ const c3Conc = Math.abs(getPerpDist(coords.C3_INF, coords.C3_LL, coords.C3_LR));
2118
+ const c4Conc = Math.abs(getPerpDist(coords.C4_INF, coords.C4_LL, coords.C4_LR));
2119
+
2120
+ const c3W = Math.hypot(coords.C3_LR.x - coords.C3_LL.x, coords.C3_LR.y - coords.C3_LL.y);
2121
+ const c3H = Math.hypot(coords.C3_LL.x - coords.C3_UL.x, coords.C3_LL.y - coords.C3_UL.y);
2122
+ const c3Ratio = parseFloat((c3W / (c3H + 1e-5)).toFixed(2));
2123
+
2124
+ let shape = "Horizontal Rectangular";
2125
+ if (c3Ratio > 1.32) shape = "Trapezoid / Tapered";
2126
+ else if (c3Ratio >= 0.92 && c3Ratio <= 1.12) shape = "Square";
2127
+ else if (c3Ratio < 0.92) shape = "Vertical Rectangular";
2128
+
2129
+ let autoStg = "CS3";
2130
+ if (c2Conc < 0.8 && c3Conc < 0.8 && c4Conc < 0.8) autoStg = "CS1";
2131
+ else if (c2Conc >= 0.8 && c3Conc < 0.8 && c4Conc < 0.8) autoStg = "CS2";
2132
+ else if (c3Conc >= 0.8 && c4Conc < 0.8) autoStg = "CS3";
2133
+ else if (c4Conc >= 0.8 && shape === "Horizontal Rectangular") autoStg = "CS4";
2134
+ else if (shape === "Square") autoStg = "CS5";
2135
+ else if (shape === "Vertical Rectangular") autoStg = "CS6";
2136
+
2137
+ if (!cvmManualOverride) {
2138
+ cvmStage = autoStg;
2139
+ highlightCvmButton(cvmStage);
2140
+ document.getElementById("cvm-auto-tag").innerText = `Auto: ${autoStg}`;
2141
+ }
2142
+
2143
+ return { c2Conc, c3Conc, c4Conc, c3Ratio, shape, stage: cvmStage };
2144
+ }
2145
+
2146
  function getNormObj(id) {
2147
  return ABO_NORMS.find(x => x.id === id) || { norm: 0, sd: 1 };
2148
  }
 
2186
  if (m.LL_E > llN.norm + llN.sd) softStr = "Protrusive Lips";
2187
  else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";
2188
 
2189
+ const airwayFlag = (m.MIN_AIRWAY !== null && m.MIN_AIRWAY < 10.0) ? "Constricted Airway" : "Patent Airway";
2190
+ const softAndCvm = `${softStr} | ${airwayFlag} | ${cvmStage}`;
2191
+ const stageBadge = activeStageView !== "LIVE" ? `[Viewing ${activeStageView}] ` : "";
2192
+ const headline = `${stageBadge}${skelClass} • ${vertClass} • ${dentStr} • [${cvmStage}]`;
2193
 
2194
  latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
2195
  document.getElementById("diag-headline").innerText = headline;
 
2219
  }
2220
 
2221
  const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
2222
+ const cvmGeom = evaluateCvmGeometry();
2223
+
2224
+ // 1. Draw 2D Segmented Pharyngeal Airway Lumen Mask
2225
+ const airwayPolyPts = [coords.PNS, coords.P_Palate, coords.TB, coords.V_Epiglottis, coords.HPW, coords.LPW, coords.MPW, coords.UPW];
2226
+ const airwayAreaMm2 = calculatePolygonAreaMm2(airwayPolyPts);
2227
+
2228
+ if (showAirwayMask && (focusMode === "AIRWAY" || focusMode === "ALL") && airwayPolyPts.every(p => p)) {
2229
+ const poly = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
2230
+ poly.setAttribute("points", airwayPolyPts.map(p => `${p.x},${p.y}`).join(" "));
2231
+ poly.setAttribute("fill", "rgba(20, 184, 166, 0.25)");
2232
+ poly.setAttribute("stroke", "#14b8a6");
2233
+ poly.setAttribute("stroke-width", "1.8");
2234
+ poly.setAttribute("stroke-dasharray", "3,2");
2235
+ svgElem.appendChild(poly);
2236
+ }
2237
 
2238
+ // 2. Draw Longitudinal Superimpositions (T1, T2, T3) with Individual Visibility Toggles
2239
  const drawSuperLines = (alCoords, col, dash) => {
2240
  if (!alCoords) return;
2241
  line(alCoords.S, alCoords.N, col, 2.5, dash);
 
2247
  };
2248
 
2249
  if (focusMode === "SUPER" || focusMode === "ALL") {
2250
+ if (t1Baseline && document.getElementById("vis-t1").checked) {
2251
+ drawSuperLines(getAlignedCoordsForBaseline(t1Baseline), "#5eead4", "4,3"); // T1: Teal
2252
+ }
2253
+ if (t2Baseline && document.getElementById("vis-t2").checked) {
2254
+ drawSuperLines(getAlignedCoordsForBaseline(t2Baseline), "#3b82f6", "5,2"); // T2: Blue
2255
+ }
2256
+ if (t3Baseline && document.getElementById("vis-t3").checked) {
2257
+ drawSuperLines(getAlignedCoordsForBaseline(t3Baseline), "#d946ef", "3,2"); // T3: Magenta
2258
+ }
2259
  }
2260
 
2261
+ // 3. Current Tracing Vectors
2262
  if (showLines) {
2263
  const isSuper = focusMode === "SUPER";
2264
  if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
 
2277
  line(coords.Co, coords.Gn, "#38bdf8", 2.5);
2278
  line(coords.ANS, coords.Me, "#ec4899", 2.5);
2279
  if (coords.N && coords.Po && coords.Or) {
 
2280
  const fhAngle = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
2281
  const perpAngle = fhAngle + Math.PI / 2;
2282
+ const nPerpEnd = { x: coords.N.x + Math.cos(perpAngle) * 180, y: coords.N.y + Math.sin(perpAngle) * 180 };
 
2283
  line(coords.N, nPerpEnd, "#f59e0b", 2, "4,3");
2284
  }
2285
  }
 
2291
  }
2292
 
2293
  if (focusMode === "AIRWAY" || focusMode === "ALL") {
2294
+ if (coords.P_Palate && coords.UPW) line(coords.P_Palate, coords.UPW, "#fde047", 3);
2295
+ if (coords.TB && coords.LPW) line(coords.TB, coords.LPW, "#fde047", 3);
2296
+ if (coords.V_Epiglottis && coords.HPW) line(coords.V_Epiglottis, coords.HPW, "#38bdf8", 2, "3,2");
2297
+ }
2298
+
2299
+ if ((focusMode === "CVM" || focusMode === "ALL") && coords.C3_UL) {
2300
+ // C2 Inferior Concavity
2301
+ line(coords.C2_LL, coords.C2_INF, "#facc15", 2.5);
2302
+ line(coords.C2_INF, coords.C2_LR, "#facc15", 2.5);
2303
+ line(coords.C2_LL, coords.C2_LR, "#14b8a6", 1.2, "3,3");
2304
+ // C3 Body & Concavity
2305
+ line(coords.C3_UL, coords.C3_UR, "#14b8a6", 2);
2306
+ line(coords.C3_UR, coords.C3_LR, "#14b8a6", 2);
2307
+ line(coords.C3_UL, coords.C3_LL, "#14b8a6", 2);
2308
+ line(coords.C3_LL, coords.C3_INF, "#facc15", 2.5);
2309
+ line(coords.C3_INF, coords.C3_LR, "#facc15", 2.5);
2310
+ line(coords.C3_LL, coords.C3_LR, "#14b8a6", 1.2, "3,3");
2311
+ // C4 Body & Concavity
2312
+ line(coords.C4_UL, coords.C4_UR, "#14b8a6", 2);
2313
+ line(coords.C4_UR, coords.C4_LR, "#14b8a6", 2);
2314
+ line(coords.C4_UL, coords.C4_LL, "#14b8a6", 2);
2315
+ line(coords.C4_LL, coords.C4_INF, "#facc15", 2.5);
2316
+ line(coords.C4_INF, coords.C4_LR, "#facc15", 2.5);
2317
+ line(coords.C4_LL, coords.C4_LR, "#14b8a6", 1.2, "3,3");
2318
  }
2319
 
2320
  if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
 
2335
  }
2336
  }
2337
 
2338
+ // 4. Ruler (10mm)
2339
  if (showRuler && coords.RULER_1 && coords.RULER_2) {
2340
  line(coords.RULER_1, coords.RULER_2, "#06b6d4", 2.5, "4,3");
2341
  ["RULER_1", "RULER_2"].forEach((rKey, idx) => {
 
2361
  });
2362
  }
2363
 
2364
+ // 5. HIPAA Privacy Mask
2365
  if (hipaaPrivacyMode && coords.N && coords.Or) {
2366
  const mask = document.createElementNS("http://www.w3.org/2000/svg", "rect");
2367
  const mLeft = Math.min(coords.N.x, coords.Or.x) - 40;
 
2374
  svgElem.appendChild(mask);
2375
  }
2376
 
2377
+ // 6. Draw Landmark Dots
2378
  const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
2379
  if (showPoints) {
2380
  for (const [name, pt] of Object.entries(coords)) {
 
2390
  if (name === "Sn") handleColor = "#ec4899";
2391
  if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
2392
  if (name === "Co" || name === "Gn") handleColor = "#38bdf8";
2393
+ if (["P_Palate", "UPW", "MPW", "TB", "LPW", "V_Epiglottis", "HPW"].includes(name)) handleColor = "#2dd4bf";
2394
+ if (name.startsWith("C2_") || name.startsWith("C3_") || name.startsWith("C4_")) handleColor = "#14b8a6";
2395
  if (selectedLm === name) handleColor = "#38bdf8";
2396
 
2397
  c.setAttribute("fill", handleColor);
 
2430
  }
2431
  }
2432
 
2433
+ // 7. Metrics Calculations
2434
  const sna = getAngle(coords.S, coords.N, coords.A);
2435
  const snb = getAngle(coords.S, coords.N, coords.B);
2436
  const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
 
2446
  const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
2447
  const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);
2448
 
 
2449
  const fmia = (fma !== null && impa !== null) ? parseFloat((180.0 - (fma + impa)).toFixed(1)) : null;
2450
 
 
2451
  let a_n_perp = null, pog_n_perp = null;
2452
  if (coords.N && coords.Po && coords.Or && coords.A && coords.Pog) {
2453
  const fhA = Math.atan2(coords.Or.y - coords.Po.y, coords.Or.x - coords.Po.x);
 
2461
  const mx_md_diff = (co_a !== null && co_gn !== null) ? parseFloat((co_gn - co_a).toFixed(1)) : null;
2462
  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;
2463
 
2464
+ // Pharyngeal Airway Metrics
2465
  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;
2466
  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;
2467
+ const hps = (coords.V_Epiglottis && coords.HPW && pxPerMm) ? parseFloat((Math.hypot(coords.V_Epiglottis.x - coords.HPW.x, coords.V_Epiglottis.y - coords.HPW.y) / pxPerMm).toFixed(1)) : null;
2468
+ const minAirway = (ups !== null && lps !== null) ? Math.min(ups, lps) : null;
2469
 
2470
  // Holdaway
2471
  const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
 
2482
  FMIA: fmia,
2483
  A_N_PERP: a_n_perp, POG_N_PERP: pog_n_perp, CO_A: co_a, CO_GN: co_gn,
2484
  MX_MD_DIFF: mx_md_diff, LAFH: lafh,
2485
+ UPS: ups, LPS: lps, HPS: hps, AIRWAY_AREA: airwayAreaMm2, MIN_AIRWAY: minAirway,
2486
  WITS: wits ? wits.distMm : null,
2487
  H_ANGLE: h_angle, SKEL_CONV: skel_conv, NOSE_PROM: nose_prom,
2488
  SN_HLINE: sn_hline, LL_HLINE: ll_hline, CHIN_THICK: chin_thick
 
2494
  populateTable("tweed-rows", TWEED_NORMS, latestMetrics);
2495
  populateTable("holdaway-rows", HOLDAWAY_NORMS, latestMetrics);
2496
  populateWitsTable(latestMetrics.WITS);
2497
+ populateAirwayTable(ups, lps, hps, airwayAreaMm2, minAirway);
2498
+ populateCvmTable(cvmGeom);
2499
  }
2500
 
2501
  function populateAboTable(normsList, valuesDict) {
 
2505
  const val = valuesDict[m.id];
2506
  let statusHtml = `<span class="pill pill-neutral">-</span>`;
2507
  let measuredText = "-", diffText = "-", diffColor = "var(--text-muted)";
 
2508
 
2509
  if (val !== null && val !== undefined) {
2510
  measuredText = `${val.toFixed(1)}${m.unit}`;
 
2515
  statusHtml = isNormal ? `<span class="pill pill-normal">Normal</span>` : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High' : 'Low'}</span>`;
2516
  }
2517
 
2518
+ const getStageCol = (snap, colHex) => {
2519
+ if (!snap) return "";
2520
+ const sVal = snap.metrics ? snap.metrics[m.id] : null;
2521
+ return `<td style="color:${colHex}; font-weight:700;">${sVal !== null && sVal !== undefined ? sVal.toFixed(1) + m.unit : '-'}</td>`;
2522
+ };
2523
 
2524
  const tr = document.createElement("tr");
2525
  tr.innerHTML = `
 
2527
  <td><span class="metric-norm">${m.norm}${m.unit} ± ${m.sd}</span></td>
2528
  <td><span class="metric-val">${measuredText}</span></td>
2529
  <td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
2530
+ ${getStageCol(t1Baseline, "#5eead4")}
2531
+ ${getStageCol(t2Baseline, "#60a5fa")}
2532
+ ${getStageCol(t3Baseline, "#f0abfc")}
2533
  <td>${statusHtml}</td>
2534
  `;
2535
  tbody.appendChild(tr);
 
2579
  tbody.appendChild(tr);
2580
  }
2581
 
2582
+ function populateAirwayTable(ups, lps, hps, areaMm2, minW) {
2583
  const tbody = document.getElementById("airway-rows");
2584
  tbody.innerHTML = "";
2585
+ const makeRow = (name, val, unit, normStr, isConstricted) => {
2586
  let stat = `<span class="pill pill-neutral">-</span>`;
2587
  let valStr = "-";
2588
+ if (val !== null && val !== undefined) {
2589
+ valStr = `${val.toFixed(1)} ${unit}`;
2590
+ stat = isConstricted ? `<span class="pill pill-deviated">Constricted</span>` : `<span class="pill pill-normal">Patent / Normal</span>`;
 
2591
  }
2592
  return `<tr>
2593
  <td><span class="metric-name">${name}</span></td>
2594
+ <td><span class="metric-norm">${normStr}</span></td>
2595
  <td><span class="metric-val" style="color:#2dd4bf;">${valStr}</span></td>
2596
  <td>${stat}</td>
2597
  </tr>`;
2598
  };
2599
+ tbody.innerHTML += makeRow("McNamara Upper Pharynx (UPS)", ups, "mm", "15.0–20.0 mm", ups !== null && ups < 12.0);
2600
+ tbody.innerHTML += makeRow("McNamara Lower Pharynx (LPS)", lps, "mm", "11.0–14.0 mm", lps !== null && lps < 10.0);
2601
+ tbody.innerHTML += makeRow("Hypopharyngeal Width (HPS)", hps, "mm", "11.0–15.0 mm", hps !== null && hps < 9.5);
2602
+ tbody.innerHTML += makeRow("Minimum Sagittal Choke (Dmin)", minW, "mm", "> 10.0 mm", minW !== null && minW < 10.0);
2603
+ tbody.innerHTML += makeRow("2D Segmented Airway Area", areaMm2, "mm²", "380–650 mm²", areaMm2 !== null && areaMm2 < 320);
2604
+ }
2605
+
2606
+ function populateCvmTable(cvm) {
2607
+ const tbody = document.getElementById("cvm-rows");
2608
+ if (!cvm) return;
2609
+ tbody.innerHTML = `
2610
+ <tr>
2611
+ <td><span class="metric-name">C2 / C3 / C4 Concavities</span></td>
2612
+ <td><span class="metric-val">${cvm.c2Conc.toFixed(1)} / ${cvm.c3Conc.toFixed(1)} / ${cvm.c4Conc.toFixed(1)} mm</span></td>
2613
+ <td>${cvm.c3Conc >= 0.8 ? '<span class="pill pill-normal">C3 Concave (>0.8mm)</span>' : '<span class="pill pill-neutral">C3 Flat (<0.8mm)</span>'}</td>
2614
+ </tr>
2615
+ <tr>
2616
+ <td><span class="metric-name">C3 Base-to-Height Ratio</span></td>
2617
+ <td><span class="metric-val">${cvm.c3Ratio}</span></td>
2618
+ <td><span style="color:#5eead4; font-weight:600;">${cvm.shape}</span></td>
2619
+ </tr>
2620
+ <tr>
2621
+ <td><span class="metric-name">Baccetti CVM Stage</span></td>
2622
+ <td colspan="2"><span class="metric-val" style="color:#2dd4bf;">${cvm.stage} — ${CVM_INFO[cvm.stage].split(':')[1]}</span></td>
2623
+ </tr>
2624
+ `;
2625
  }
2626
 
2627
  // =============================================================
2628
+ // 8. 1-Page Letter Print Synchronization (No Extra Page Overflow)
2629
  // =============================================================
2630
  window.addEventListener("beforeprint", () => {
2631
  const rawName = document.getElementById("pt-name").value || "Patient";
2632
  const rawChart = document.getElementById("pt-chart").value || "MRN-N/A";
2633
  const dtStr = document.getElementById("pt-datetime").value || "";
2634
+ const displayDt = dtStr ? dtStr.replace("T", " ") : new Date().toLocaleDateString();
2635
 
2636
  document.getElementById("print-pt-name").innerText = hipaaPrivacyMode ? "De-Identified Subject" : rawName;
2637
  document.getElementById("print-pt-mrn").innerText = hipaaPrivacyMode ? "ANON-001" : rawChart;
2638
  document.getElementById("print-pt-datetime").innerText = displayDt;
2639
  document.getElementById("print-ethnicity-tag").innerText = `ETHNICITY: ${ETHNICITY_DATABASE[activeEthnicity].label.split(' ')[0]}`;
2640
 
 
2641
  document.getElementById("print-img").src = imgElem.src;
2642
  const printSvg = document.getElementById("print-svg");
2643
  printSvg.innerHTML = svgElem.innerHTML;
2644
  printSvg.setAttribute("viewBox", svgElem.getAttribute("viewBox") || "0 0 100 100");
2645
 
 
2646
  document.getElementById("print-diag-headline").innerText = latestDiagnosis.headline;
2647
  document.getElementById("print-diag-sag").innerText = `Sagittal: ${latestDiagnosis.sagittal}`;
2648
  document.getElementById("print-diag-vert").innerText = `Vertical: ${latestDiagnosis.vertical}`;
2649
  document.getElementById("print-diag-dent").innerText = `Dental: ${latestDiagnosis.dental}`;
2650
+ document.getElementById("print-diag-soft").innerText = `Airway, Soft & CVM: ${latestDiagnosis.soft}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2651
 
2652
+ const fillPrintRows = (tbodyId, list) => {
2653
+ const body = document.getElementById(tbodyId);
2654
+ body.innerHTML = "";
2655
+ list.forEach(m => {
2656
+ const val = latestMetrics[m.id];
2657
+ let diff = "-", stat = "-", diffClass = "";
2658
+ if (val !== null && val !== undefined) {
2659
+ const rawDiff = val - m.norm;
2660
+ const isNorm = Math.abs(rawDiff) <= m.sd;
2661
+ diff = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${m.unit}`;
2662
+ stat = isNorm ? "Normal" : (rawDiff > 0 ? "High" : "Low");
2663
+ diffClass = isNorm ? "diff-norm" : "diff-dev";
2664
+ }
2665
+ body.innerHTML += `<tr>
2666
+ <td><strong>${m.name}</strong></td>
2667
+ <td>${m.norm}${m.unit} ± ${m.sd}</td>
2668
+ <td><strong>${val !== null && val !== undefined ? val.toFixed(1) + m.unit : '-'}</strong></td>
2669
+ <td class="${diffClass}">${diff}</td>
2670
+ <td>${stat}</td>
2671
+ </tr>`;
2672
+ });
2673
+ };
2674
 
2675
+ fillPrintRows("print-abo-tbody", ABO_NORMS);
2676
+ fillPrintRows("print-mcnamara-tbody", [...MCNAMARA_NORMS, ...TWEED_NORMS]);
2677
+ fillPrintRows("print-holdaway-tbody", HOLDAWAY_NORMS);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2678
 
 
2679
  const pWitsBody = document.getElementById("print-wits-tbody");
2680
  pWitsBody.innerHTML = "";
2681
  if (latestMetrics.WITS !== null && latestMetrics.WITS !== undefined) {
2682
  const w = latestMetrics.WITS;
2683
  const stat = w > 1.0 ? "Class II" : (w < -1.0 ? "Class III" : "Class I");
2684
+ 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>`;
 
 
 
 
2685
  }
2686
  if (latestMetrics.UPS !== null) {
2687
+ pWitsBody.innerHTML += `<tr><td>Upper Airway (UPS)</td><td>15–20 mm</td><td><strong>${latestMetrics.UPS.toFixed(1)} mm</strong></td><td>${latestMetrics.UPS < 12 ? 'Constricted' : 'Patent'}</td></tr>`;
 
 
 
 
2688
  }
2689
  if (latestMetrics.LPS !== null) {
2690
+ pWitsBody.innerHTML += `<tr><td>Lower Airway (LPS)</td><td>11–14 mm</td><td><strong>${latestMetrics.LPS.toFixed(1)} mm</strong></td><td>${latestMetrics.LPS < 10 ? 'Constricted' : 'Patent'}</td></tr>`;
2691
+ }
2692
+ if (latestMetrics.AIRWAY_AREA !== null) {
2693
+ pWitsBody.innerHTML += `<tr><td>2D Airway Area</td><td>380–650 mm²</td><td><strong>${latestMetrics.AIRWAY_AREA.toFixed(0)} mm²</strong></td><td>Segmented</td></tr>`;
 
2694
  }
2695
+ pWitsBody.innerHTML += `<tr><td>CVM Stage</td><td>Baccetti</td><td><strong>${cvmStage}</strong></td><td>Skeletal Timing</td></tr>`;
2696
  });
2697
 
2698
  // CSV Export
 
2703
  const ptChart = hipaaPrivacyMode ? "ANON-001" : (document.getElementById("pt-chart").value || "N/A");
2704
  const ptDateTime = document.getElementById("pt-datetime").value || "";
2705
 
2706
+ let csv = "Patient,MRN,Date_Time,Diagnosis,Ethnicity,CVM_Stage,Category,Parameter,Norm_SD,Current_Value,Diff,T1_Value,T2_Value,T3_Value,Unit,Status\n";
2707
  const addCategory = (cat, list) => {
2708
  list.forEach(m => {
2709
  const v = latestMetrics[m.id];
2710
  if (v === null || v === undefined) return;
2711
  const diff = (v - m.norm).toFixed(1);
2712
+ const t1V = (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[m.id] != null) ? t1Baseline.metrics[m.id].toFixed(1) : "";
2713
+ const t2V = (t2Baseline && t2Baseline.metrics && t2Baseline.metrics[m.id] != null) ? t2Baseline.metrics[m.id].toFixed(1) : "";
2714
+ const t3V = (t3Baseline && t3Baseline.metrics && t3Baseline.metrics[m.id] != null) ? t3Baseline.metrics[m.id].toFixed(1) : "";
2715
  const stat = Math.abs(v - m.norm) <= m.sd ? "Normal" : (v > m.norm ? "High" : "Low");
2716
+ csv += `"${ptName}","${ptChart}","${ptDateTime}","${latestDiagnosis.headline}","${activeEthnicity}","${cvmStage}","${cat}","${m.name}","${m.norm} +/- ${m.sd}",${v.toFixed(1)},${diff > 0 ? '+' + diff : diff},${t1V},${t2V},${t3V},"${m.unit}","${stat}"\n`;
2717
  });
2718
  };
2719
 
 
2745
  `• Vertical & Tweed: ${latestDiagnosis.vertical} | FMA ${m.FMA}°, SNMP ${m.SNMP}°, FMIA ${m.FMIA}°`,
2746
  `• 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`,
2747
  `• 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}°`,
2748
+ `• Airway, Soft Tissue & CVM: ${latestDiagnosis.soft} | Upper Airway ${m.UPS}mm, Lower Airway ${m.LPS}mm, 2D Area ${m.AIRWAY_AREA}mm², Holdaway H-Angle ${m.H_ANGLE}°`
2749
  ].join("\n");
2750
 
2751
+ navigator.clipboard.writeText(note).then(() => notify("Clinical EMR Note Copied"));
 
 
 
 
 
 
2752
  });
2753
 
2754
  // Viewport Zoom