Abddeus commited on
Commit
fac29d3
·
verified ·
1 Parent(s): f78c8ec

Upload index.html.html

Browse files
Files changed (1) hide show
  1. index.html.html +1965 -0
index.html.html ADDED
@@ -0,0 +1,1965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>OrthoCeph Pro | ABO, Regional Superimposition & CVM 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">
10
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
12
+ <style>
13
+ :root {
14
+ --bg-dark: #080c14;
15
+ --surface-dark: #0f172a;
16
+ --surface-card: #1e293b;
17
+ --surface-border: #334155;
18
+ --accent: #2563eb;
19
+ --accent-hover: #1d4ed8;
20
+ --text-main: #f8fafc;
21
+ --text-muted: #94a3b8;
22
+ --status-green: #10b981;
23
+ --status-red: #f43f5e;
24
+ --status-amber: #f59e0b;
25
+ --ruler-cyan: #06b6d4;
26
+ --cvm-teal: #14b8a6;
27
+ }
28
+
29
+ * { box-sizing: border-box; margin: 0; padding: 0; }
30
+ body {
31
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
32
+ background-color: var(--bg-dark);
33
+ color: var(--text-main);
34
+ height: 100vh;
35
+ display: flex;
36
+ flex-direction: column;
37
+ overflow: hidden;
38
+ -webkit-font-smoothing: antialiased;
39
+ }
40
+
41
+ header {
42
+ background: var(--surface-dark);
43
+ border-bottom: 1px solid var(--surface-border);
44
+ height: 56px;
45
+ padding: 0 16px;
46
+ display: flex;
47
+ align-items: center;
48
+ justify-content: space-between;
49
+ flex-shrink: 0;
50
+ z-index: 30;
51
+ }
52
+
53
+ .brand { display: flex; align-items: center; gap: 10px; }
54
+ .brand-icon {
55
+ width: 32px; height: 32px;
56
+ background: linear-gradient(135deg, #3b82f6, #1d4ed8);
57
+ border-radius: 8px; display: flex; align-items: center;
58
+ justify-content: center; font-weight: 700; font-size: 16px; color: white;
59
+ box-shadow: 0 2px 8px rgba(37,99,235,0.4);
60
+ }
61
+ .brand-title { font-size: 14.5px; font-weight: 700; letter-spacing: -0.01em; }
62
+ .brand-subtitle { font-size: 9.5px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; }
63
+
64
+ .header-actions { display: flex; align-items: center; gap: 6px; }
65
+
66
+ #status-badge {
67
+ display: flex; align-items: center; gap: 7px; font-size: 11px;
68
+ font-weight: 600; background: rgba(30, 41, 59, 0.85);
69
+ border: 1px solid var(--surface-border); padding: 5px 11px;
70
+ border-radius: 20px; color: var(--text-muted); margin-right: 4px;
71
+ }
72
+ #status-badge .indicator { width: 8px; height: 8px; border-radius: 50%; background-color: var(--status-amber); }
73
+
74
+ .workspace { display: flex; flex: 1; height: calc(100vh - 56px); overflow: hidden; }
75
+
76
+ .sidebar {
77
+ width: 310px; background: var(--surface-dark);
78
+ border-right: 1px solid var(--surface-border);
79
+ padding: 12px; display: flex; flex-direction: column;
80
+ gap: 10px; overflow-y: auto; flex-shrink: 0;
81
+ }
82
+
83
+ .section-header {
84
+ font-size: 10px; font-weight: 700; text-transform: uppercase;
85
+ letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 5px;
86
+ display: flex; justify-content: space-between; align-items: center;
87
+ }
88
+
89
+ .card {
90
+ background: var(--surface-card); border: 1px solid var(--surface-border);
91
+ border-radius: 8px; padding: 10px; display: flex; flex-direction: column; gap: 7px;
92
+ }
93
+
94
+ .form-group { display: flex; flex-direction: column; gap: 3px; }
95
+ .form-group label { font-size: 10px; font-weight: 600; color: var(--text-muted); }
96
+
97
+ .input-field {
98
+ background: #090e1a; border: 1px solid var(--surface-border);
99
+ border-radius: 6px; padding: 6px 9px; color: var(--text-main);
100
+ font-size: 11.5px; outline: none; width: 100%; transition: border-color 0.15s;
101
+ }
102
+ .input-field:focus { border-color: #3b82f6; }
103
+
104
+ .btn {
105
+ background: var(--accent); color: white; border: none; padding: 6px 11px;
106
+ border-radius: 6px; font-weight: 600; font-size: 11px; cursor: pointer;
107
+ display: inline-flex; align-items: center; justify-content: center; gap: 5px;
108
+ transition: all 0.15s ease; white-space: nowrap; user-select: none;
109
+ }
110
+ .btn:hover:not(:disabled) { background: var(--accent-hover); }
111
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
112
+ .btn-secondary { background: #131c2e; border: 1px solid var(--surface-border); color: var(--text-main); }
113
+ .btn-secondary:hover { background: #1e293b; border-color: #475569; }
114
+ .btn-danger { background: rgba(244, 63, 94, 0.15); border: 1px solid rgba(244, 63, 94, 0.35); color: #fda4af; }
115
+ .btn-danger:hover { background: rgba(244, 63, 94, 0.28); }
116
+ .btn-teal { background: rgba(20, 184, 166, 0.15); border: 1px solid rgba(20, 184, 166, 0.4); color: #5eead4; }
117
+ .btn-teal:hover { background: rgba(20, 184, 166, 0.25); }
118
+
119
+ .mode-group { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
120
+ .mode-btn {
121
+ background: #090e1a; border: 1px solid var(--surface-border);
122
+ color: var(--text-muted); padding: 5px 3px; border-radius: 5px;
123
+ font-size: 10.5px; font-weight: 600; cursor: pointer; text-align: center;
124
+ transition: all 0.15s; user-select: none;
125
+ }
126
+ .mode-btn.active { background: var(--accent); color: white; border-color: #60a5fa; box-shadow: 0 0 8px rgba(37,99,235,0.4); }
127
+
128
+ .toggle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; }
129
+ .toggle-pill {
130
+ background: #090e1a; border: 1px solid var(--surface-border);
131
+ color: var(--text-muted); padding: 5px; border-radius: 5px;
132
+ font-size: 10px; font-weight: 600; cursor: pointer; text-align: center; user-select: none;
133
+ }
134
+ .toggle-pill.active { background: rgba(16, 185, 129, 0.15); color: var(--status-green); border-color: var(--status-green); }
135
+
136
+ .cvm-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 3px; }
137
+ .cvm-btn {
138
+ background: #090e1a; border: 1px solid var(--surface-border);
139
+ color: var(--text-muted); padding: 5px 1px; border-radius: 5px;
140
+ font-size: 10.5px; font-weight: 700; cursor: pointer; text-align: center; user-select: none;
141
+ }
142
+ .cvm-btn.active { background: var(--cvm-teal); color: #022c22; border-color: #5eead4; font-weight: 800; }
143
+
144
+ .slider-row {
145
+ display: flex; align-items: center; justify-content: space-between;
146
+ font-size: 10.5px; color: var(--text-muted);
147
+ }
148
+ .slider-row input[type="range"] { width: 130px; accent-color: var(--accent); cursor: pointer; }
149
+
150
+ #norms-drawer {
151
+ display: none; flex-direction: column; gap: 5px; max-height: 170px;
152
+ overflow-y: auto; padding-top: 6px; border-top: 1px solid var(--surface-border);
153
+ }
154
+ .norm-edit-row {
155
+ display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 5px; align-items: center; font-size: 10.5px;
156
+ }
157
+ .norm-edit-row input {
158
+ background: #090e1a; border: 1px solid var(--surface-border); color: var(--text-main);
159
+ padding: 3px 5px; border-radius: 4px; font-size: 10.5px; width: 100%; text-align: center;
160
+ }
161
+
162
+ .viewport {
163
+ flex: 1; background: #030712; position: relative;
164
+ overflow: hidden; display: flex; align-items: center; justify-content: center;
165
+ user-select: none;
166
+ }
167
+ .viewport.drag-over {
168
+ outline: 3px dashed #3b82f6; outline-offset: -12px; background: rgba(37, 99, 235, 0.08);
169
+ }
170
+
171
+ #empty-dropzone {
172
+ display: flex; flex-direction: column; align-items: center; justify-content: center;
173
+ gap: 12px; color: var(--text-muted); text-align: center; padding: 45px 30px;
174
+ border: 2px dashed var(--surface-border); border-radius: 16px; cursor: pointer;
175
+ max-width: 520px; transition: all 0.2s;
176
+ }
177
+ #empty-dropzone:hover { border-color: #3b82f6; color: var(--text-main); background: rgba(30,41,59,0.3); }
178
+
179
+ #viewport-container {
180
+ position: absolute; transform-origin: 0 0; user-select: none;
181
+ cursor: crosshair; display: none; left: 0; top: 0;
182
+ }
183
+ #ceph-image { display: block; pointer-events: none; }
184
+ #overlay-svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
185
+
186
+ #loupe-box {
187
+ position: absolute; top: 16px; left: 16px; width: 140px; height: 140px;
188
+ border: 2px solid #38bdf8; border-radius: 50%; overflow: hidden;
189
+ background: #000; box-shadow: 0 8px 24px rgba(0,0,0,0.85);
190
+ display: none; z-index: 25; pointer-events: none;
191
+ }
192
+ #loupe-canvas { width: 100%; height: 100%; display: block; }
193
+ #loupe-label {
194
+ position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%);
195
+ background: rgba(15, 23, 42, 0.9); color: #38bdf8; font-size: 10px;
196
+ font-weight: 700; padding: 2px 8px; border-radius: 10px; border: 1px solid #38bdf8;
197
+ }
198
+
199
+ .viewport-overlay-controls {
200
+ position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%);
201
+ background: rgba(15, 23, 42, 0.9); backdrop-filter: blur(8px);
202
+ border: 1px solid var(--surface-border); border-radius: 30px;
203
+ padding: 4px 14px; display: flex; align-items: center; gap: 8px; z-index: 20;
204
+ white-space: nowrap; box-shadow: 0 4px 14px rgba(0,0,0,0.5);
205
+ }
206
+ .viewport-overlay-controls button {
207
+ background: none; border: none; color: var(--text-main);
208
+ cursor: pointer; font-size: 11px; font-weight: 600; padding: 3px 6px; border-radius: 4px;
209
+ }
210
+ .viewport-overlay-controls button:hover { color: #60a5fa; background: rgba(255,255,255,0.05); }
211
+ .shortcut-hint { font-size: 10px; color: var(--text-muted); }
212
+
213
+ .landmark-handle { pointer-events: all; cursor: grab; transition: r 0.12s ease; }
214
+ .landmark-handle:hover { r: 8 !important; stroke: #ffffff !important; stroke-width: 2.5px !important; }
215
+ .landmark-handle.dragging { cursor: grabbing !important; r: 9 !important; fill: #38bdf8 !important; }
216
+ .landmark-text {
217
+ font-family: 'JetBrains Mono', monospace; font-size: 10.5px; font-weight: 700;
218
+ fill: #ffffff; paint-order: stroke; stroke: #000000; stroke-width: 3px;
219
+ pointer-events: none; user-select: none;
220
+ }
221
+
222
+ .analysis-panel {
223
+ width: 480px; background: var(--surface-dark);
224
+ border-left: 1px solid var(--surface-border);
225
+ padding: 14px; display: flex; flex-direction: column;
226
+ gap: 12px; overflow-y: auto; flex-shrink: 0;
227
+ }
228
+
229
+ .diagnosis-banner {
230
+ background: linear-gradient(135deg, rgba(37, 99, 235, 0.18), rgba(15, 23, 42, 0.95));
231
+ border: 1px solid #3b82f6;
232
+ border-radius: 8px;
233
+ padding: 10px 12px;
234
+ display: flex;
235
+ flex-direction: column;
236
+ gap: 6px;
237
+ }
238
+ .diagnosis-headline { font-size: 12px; font-weight: 700; color: #93c5fd; }
239
+ .diagnosis-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px 10px; font-size: 10.5px; }
240
+ .diag-item { display: flex; flex-direction: column; }
241
+ .diag-label { font-size: 9px; color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
242
+ .diag-val { font-weight: 600; color: var(--text-main); }
243
+
244
+ .analysis-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 11px; }
245
+ .analysis-table th {
246
+ text-align: left; padding: 6px; font-weight: 600; font-size: 9.5px;
247
+ text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);
248
+ border-bottom: 1px solid var(--surface-border);
249
+ }
250
+ .analysis-table td { padding: 5.5px 6px; border-bottom: 1px solid rgba(51, 65, 85, 0.35); }
251
+ .metric-name { font-weight: 600; color: #e2e8f0; }
252
+ .metric-norm { color: var(--text-muted); font-size: 10px; font-family: 'JetBrains Mono', monospace; }
253
+ .metric-val { font-weight: 700; font-family: 'JetBrains Mono', monospace; }
254
+ .metric-diff { font-weight: 600; font-size: 10px; font-family: 'JetBrains Mono', monospace; }
255
+
256
+ .pill { display: inline-flex; align-items: center; padding: 2px 6px; border-radius: 9999px; font-size: 9px; font-weight: 700; }
257
+ .pill-normal { background: rgba(16, 185, 129, 0.15); color: var(--status-green); }
258
+ .pill-deviated { background: rgba(244, 63, 94, 0.15); color: var(--status-red); }
259
+ .pill-neutral { background: #1e293b; color: var(--text-muted); }
260
+
261
+ /* Custom Toast Notification */
262
+ #toast-msg {
263
+ position: fixed; top: 68px; right: 20px; z-index: 100;
264
+ background: #1e293b; border: 1px solid #3b82f6; color: #f8fafc;
265
+ padding: 9px 14px; border-radius: 8px; font-size: 11.5px; font-weight: 600;
266
+ display: none; box-shadow: 0 10px 25px rgba(0,0,0,0.6);
267
+ transform: translateY(-5px); transition: all 0.2s ease;
268
+ }
269
+
270
+ @media print {
271
+ body { background: white !important; color: black !important; height: auto !important; overflow: visible !important; }
272
+ header, .sidebar, .viewport-overlay-controls, #loupe-box, #empty-dropzone, #toast-msg { display: none !important; }
273
+ .workspace { display: block !important; height: auto !important; }
274
+ .viewport { background: white !important; margin-bottom: 14px; justify-content: center; height: 420px; }
275
+ #ceph-image { max-height: 400px !important; }
276
+ .analysis-panel { width: 100% !important; border: none !important; background: white !important; color: black !important; padding: 0 !important; }
277
+ .diagnosis-banner { background: #f8fafc !important; border: 1px solid #94a3b8 !important; color: black !important; margin-bottom: 10px; }
278
+ .diagnosis-headline { color: #1e3a8a !important; }
279
+ .diag-val { color: black !important; }
280
+ .analysis-table th { color: #334155 !important; border-bottom: 2px solid #0f172a !important; }
281
+ .analysis-table td { border-bottom: 1px solid #cbd5e1 !important; color: black !important; }
282
+ .metric-name { color: black !important; }
283
+ .pill { border: 1px solid #94a3b8; }
284
+ }
285
+ </style>
286
+ </head>
287
+ <body>
288
+
289
+ <div id="toast-msg">Notification</div>
290
+
291
+ <header>
292
+ <div class="brand">
293
+ <div class="brand-icon">O</div>
294
+ <div>
295
+ <div class="brand-title">OrthoCeph Pro</div>
296
+ <div class="brand-subtitle">ABO Clinical Superimposition & Anatomical CVM Suite</div>
297
+ </div>
298
+ </div>
299
+
300
+ <div class="header-actions">
301
+ <div id="status-badge">
302
+ <div class="indicator" id="status-ind"></div>
303
+ <span id="status-txt">Loading AI Model...</span>
304
+ </div>
305
+ <button class="btn btn-secondary" id="btn-save-json" title="Save tracing, image & patient data into standalone .json">
306
+ 💾 Save JSON
307
+ </button>
308
+ <button class="btn btn-secondary" onclick="document.getElementById('json-input').click()" title="Load previously saved .json session">
309
+ 📂 Load JSON
310
+ </button>
311
+ <input type="file" id="json-input" accept=".json,application/json" style="display:none;">
312
+ <button class="btn btn-secondary" id="btn-copy-note" title="Copy structured EMR chart note">
313
+ 📋 Copy Note
314
+ </button>
315
+ <button class="btn btn-secondary" id="btn-export-csv" title="Download Excel CSV metrics">
316
+ 📊 CSV
317
+ </button>
318
+ <button class="btn btn-secondary" onclick="window.print()" title="Print full ABO Ceph Report">
319
+ 🖨️ Print
320
+ </button>
321
+ <button class="btn btn-danger" id="btn-next-patient" title="Clear current patient">
322
+ 🔄 Next Patient
323
+ </button>
324
+ </div>
325
+ </header>
326
+
327
+ <div class="workspace">
328
+ <!-- Left Sidebar Controls -->
329
+ <aside class="sidebar">
330
+ <div>
331
+ <div class="section-header"><span>1. Radiograph & Patient</span></div>
332
+ <div class="card">
333
+ <input type="file" id="file-input" accept="image/*,.dcm,application/dicom,.json" class="input-field" style="padding: 4px;">
334
+ <div class="form-group">
335
+ <label>Patient Name</label>
336
+ <input type="text" id="pt-name" class="input-field" placeholder="Full name">
337
+ </div>
338
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
339
+ <div class="form-group">
340
+ <label>Chart # / MRN</label>
341
+ <input type="text" id="pt-chart" class="input-field" placeholder="ID">
342
+ </div>
343
+ <div class="form-group">
344
+ <label>Study Date</label>
345
+ <input type="date" id="pt-date" class="input-field">
346
+ </div>
347
+ </div>
348
+ </div>
349
+ </div>
350
+
351
+ <div>
352
+ <div class="section-header"><span>2. Focus Mode & Layers</span></div>
353
+ <div class="card">
354
+ <div class="mode-group">
355
+ <div class="mode-btn active" data-mode="ABO">🎯 ABO</div>
356
+ <div class="mode-btn" data-mode="WITS">Wits</div>
357
+ <div class="mode-btn" data-mode="HOLDAWAY">Holdaway</div>
358
+ <div class="mode-btn" data-mode="SUPER">疊 T1/T2</div>
359
+ <div class="mode-btn" data-mode="ALL">All</div>
360
+ </div>
361
+
362
+ <div class="toggle-grid" style="margin-top: 4px;">
363
+ <div class="toggle-pill active" id="tog-lines">Lines: ON</div>
364
+ <div class="toggle-pill active" id="tog-points">Dots: ON</div>
365
+ <div class="toggle-pill active" id="tog-labels">Names: ON</div>
366
+ </div>
367
+ </div>
368
+ </div>
369
+
370
+ <div>
371
+ <div class="section-header"><span>3. Retrace & Edit Dot</span></div>
372
+ <div class="card">
373
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
374
+ <button id="btn-retrace-all" class="btn btn-secondary" title="Reset all landmarks back to AI original">
375
+ 🔄 Reset All
376
+ </button>
377
+ <button id="btn-reset-single" class="btn btn-secondary" title="Reset active landmark to AI original">
378
+ 🎯 Reset Dot
379
+ </button>
380
+ </div>
381
+ <button id="btn-retrace-scaled" class="btn btn-secondary" style="background:#1e3a8a; border-color:#3b82f6; color:#93c5fd; font-size:10.5px; padding:6px;" title="Re-run tracing with the newly adjusted 10mm scale">
382
+ ⚡ Re-Trace with Calibrated Scale
383
+ </button>
384
+ <div style="font-size: 10px; color: var(--text-muted); text-align: center; margin-top: 2px;">
385
+ Selected: <strong id="selected-lm-label" style="color: #38bdf8;">None</strong> (Double-click dot on screen to snap)
386
+ </div>
387
+ </div>
388
+ </div>
389
+
390
+ <div>
391
+ <div class="section-header"><span>4. Baccetti Cervical Maturation (CVM Stage)</span></div>
392
+ <div class="card">
393
+ <div class="cvm-grid">
394
+ <div class="cvm-btn" data-cvm="CS1">CS1</div>
395
+ <div class="cvm-btn" data-cvm="CS2">CS2</div>
396
+ <div class="cvm-btn" data-cvm="CS3">CS3</div>
397
+ <div class="cvm-btn" data-cvm="CS4">CS4</div>
398
+ <div class="cvm-btn" data-cvm="CS5">CS5</div>
399
+ <div class="cvm-btn" data-cvm="CS6">CS6</div>
400
+ </div>
401
+ <div id="cvm-desc" style="font-size: 9.5px; color: var(--cvm-teal); font-weight: 600; text-align: center; line-height: 1.35; margin-top: 2px;">
402
+ Select CVM stage to classify skeletal maturation for treatment timing.
403
+ </div>
404
+ </div>
405
+ </div>
406
+
407
+ <div>
408
+ <div class="section-header"><span>5. Superimposition Suite (T1 / T2)</span></div>
409
+ <div class="card">
410
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px;">
411
+ <button id="btn-lock-t1" class="btn btn-teal">📌 Lock as T1</button>
412
+ <button id="btn-clear-t1" class="btn btn-secondary">Clear T1</button>
413
+ </div>
414
+ <div class="form-group" style="margin-top: 3px;">
415
+ <label>Regional Registration</label>
416
+ <select id="super-mode" class="input-field" style="padding: 4px;">
417
+ <option value="CRANIAL">Cranial Base (S-N at S)</option>
418
+ <option value="MAXILLARY">Maxillary (Palatal Plane at PNS)</option>
419
+ <option value="MANDIBULAR">Mandibular (Symphysis & Canal)</option>
420
+ </select>
421
+ </div>
422
+ <div id="super-status" style="font-size: 9.5px; color: var(--text-muted); text-align: center;">
423
+ No T1 baseline locked.
424
+ </div>
425
+ </div>
426
+ </div>
427
+
428
+ <div>
429
+ <div class="section-header">
430
+ <span>6. Calibration & Enhancement</span>
431
+ <span id="reset-filters" style="color: #60a5fa; cursor: pointer; font-size: 10px;">Reset</span>
432
+ </div>
433
+ <div class="card">
434
+ <button id="btn-cal" class="btn btn-secondary">📐 Show / Move 10mm Ruler</button>
435
+ <span id="cal-status" style="font-size: 10px; color: var(--ruler-cyan); text-align: center; font-weight: 600; font-family:'JetBrains Mono',monospace;">
436
+ Scale: 10.00 px/mm
437
+ </span>
438
+ <div class="slider-row">
439
+ <span>Brightness</span>
440
+ <input type="range" id="brightness" min="0.5" max="2.0" step="0.05" value="1.0">
441
+ </div>
442
+ <div class="slider-row">
443
+ <span>Contrast</span>
444
+ <input type="range" id="contrast" min="0.5" max="2.5" step="0.05" value="1.0">
445
+ </div>
446
+ <div class="slider-row">
447
+ <span>Invert Negative</span>
448
+ <input type="checkbox" id="invert">
449
+ </div>
450
+ </div>
451
+ </div>
452
+
453
+ <div>
454
+ <div class="section-header">
455
+ <span>7. Reference Norms</span>
456
+ <span id="reset-norms" style="color: #f43f5e; cursor: pointer; font-size: 10px; display: none;">Restore Defaults</span>
457
+ </div>
458
+ <div class="card">
459
+ <button id="btn-toggle-norms" class="btn btn-secondary" style="font-size: 10.5px; padding: 5px;">
460
+ ⚙️ Customize ABO Norms
461
+ </button>
462
+ <div id="norms-drawer"></div>
463
+ </div>
464
+ </div>
465
+ </aside>
466
+
467
+ <!-- Viewport Center -->
468
+ <main class="viewport" id="viewport-wrapper">
469
+ <div id="loupe-box">
470
+ <canvas id="loupe-canvas" width="140" height="140"></canvas>
471
+ <div id="loupe-label">S</div>
472
+ </div>
473
+
474
+ <div id="empty-dropzone" onclick="document.getElementById('file-input').click()">
475
+ <div style="font-size: 42px;">🦷</div>
476
+ <div style="font-size: 15px; font-weight: 600; color: var(--text-main);">Drop Lateral Cephalogram or Saved .JSON Here</div>
477
+ <div style="font-size: 11.5px; line-height: 1.5;">Supports DICOM (.dcm), JPEG, PNG and OrthoCeph JSON records.<br>Immediate AI landmark detection with full cervical vertebral morphology.</div>
478
+ </div>
479
+
480
+ <div id="viewport-container">
481
+ <img id="ceph-image" src="" alt="Lateral Cephalogram">
482
+ <svg id="overlay-svg"></svg>
483
+ </div>
484
+
485
+ <div class="viewport-overlay-controls">
486
+ <button id="btn-zoom-in" title="Zoom In">Zoom (+)</button>
487
+ <button id="btn-zoom-out" title="Zoom Out">Zoom (-)</button>
488
+ <button id="btn-zoom-reset" title="Fit to screen">Fit</button>
489
+ <span style="color: var(--surface-border);">|</span>
490
+ <span class="shortcut-hint">Drag screen with <strong>Middle Click / Alt-Drag</strong> • Hold <strong>[SPACE]</strong> to peek image</span>
491
+ </div>
492
+ </main>
493
+
494
+ <!-- Right Analysis Panel -->
495
+ <aside class="analysis-panel">
496
+ <div class="diagnosis-banner">
497
+ <div class="diagnosis-headline" id="diag-headline">Awaiting Lateral Cephalogram...</div>
498
+ <div class="diagnosis-grid">
499
+ <div class="diag-item">
500
+ <span class="diag-label">Sagittal Skeletal</span>
501
+ <span class="diag-val" id="diag-sagittal">-</span>
502
+ </div>
503
+ <div class="diag-item">
504
+ <span class="diag-label">Vertical Pattern</span>
505
+ <span class="diag-val" id="diag-vertical">-</span>
506
+ </div>
507
+ <div class="diag-item">
508
+ <span class="diag-label">Dental Inclination</span>
509
+ <span class="diag-val" id="diag-dental">-</span>
510
+ </div>
511
+ <div class="diag-item">
512
+ <span class="diag-label">Soft Profile & CVM</span>
513
+ <span class="diag-val" id="diag-soft">-</span>
514
+ </div>
515
+ </div>
516
+ </div>
517
+
518
+ <div id="section-abo">
519
+ <div class="section-header" style="color: #60a5fa;">Official ABO Cephalometric Analysis</div>
520
+ <table class="analysis-table">
521
+ <thead>
522
+ <tr>
523
+ <th>Parameter</th>
524
+ <th>Norm</th>
525
+ <th>Measured</th>
526
+ <th>Diff</th>
527
+ <th id="th-t1-abo" style="display:none; color:#5eead4;">Δ vs T1</th>
528
+ <th>Status</th>
529
+ </tr>
530
+ </thead>
531
+ <tbody id="abo-rows">
532
+ <tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 16px;">Load radiograph or JSON to view analysis...</td></tr>
533
+ </tbody>
534
+ </table>
535
+ </div>
536
+
537
+ <div id="section-wits">
538
+ <div class="section-header" style="color: #c084fc;">Jacobson Wits Appraisal</div>
539
+ <table class="analysis-table">
540
+ <thead>
541
+ <tr>
542
+ <th>Parameter</th>
543
+ <th>Norm</th>
544
+ <th>Measured</th>
545
+ <th>Diff</th>
546
+ <th>Interpretation</th>
547
+ </tr>
548
+ </thead>
549
+ <tbody id="wits-rows">
550
+ <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting tracing...</td></tr>
551
+ </tbody>
552
+ </table>
553
+ </div>
554
+
555
+ <div id="section-holdaway">
556
+ <div class="section-header" style="color: #f472b6;">Holdaway Soft Tissue Analysis</div>
557
+ <table class="analysis-table">
558
+ <thead>
559
+ <tr>
560
+ <th>Parameter</th>
561
+ <th>Norm</th>
562
+ <th>Measured</th>
563
+ <th>Diff</th>
564
+ <th>Status</th>
565
+ </tr>
566
+ </thead>
567
+ <tbody id="holdaway-rows">
568
+ <tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 12px;">Awaiting tracing...</td></tr>
569
+ </tbody>
570
+ </table>
571
+ </div>
572
+
573
+ </aside>
574
+ </div>
575
+
576
+ <script>
577
+ // -------------------------------------------------------------
578
+ // 1. Constants, Clinical Norms & Cervical Maturation Stages
579
+ // -------------------------------------------------------------
580
+ const MODEL_URL = "https://huggingface.co/MuhammadNabeelSh/cephalometry-landmarks/resolve/main/landmarks-cepha29.onnx";
581
+
582
+ const LM_INDICES = {
583
+ "A": 0, "ANS": 1, "B": 3, "Gn": 5, "Go": 6, "LIA": 7, "LIT": 8,
584
+ "Li": 11, "Ls": 12, "Me": 13, "N": 14, "Or": 16, "Pn": 18,
585
+ "Po": 19, "Pog": 20, "Pog_soft": 21, "S": 23, "Sn": 24, "UIA": 25, "UIT": 26
586
+ };
587
+
588
+ const MODE_LANDMARKS = {
589
+ ABO: new Set(["S", "N", "Po", "Or", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pn", "Ls", "Li", "Pog_soft", "PNS", "ANS"]),
590
+ WITS: new Set(["A", "B", "OP_P", "OP_A"]),
591
+ HOLDAWAY: new Set(["N", "A", "Pog", "Pn", "Sn", "Ls", "Li", "Pog_soft"]),
592
+ SUPER: new Set(["S", "N", "ANS", "PNS", "A", "B", "Me", "Go", "UIT", "UIA", "LIT", "LIA", "Pog"]),
593
+ ALL: new Set([
594
+ "S", "N", "Po", "Or", "A", "B", "Pog", "Me", "Gn", "Go", "ANS", "PNS",
595
+ "UIT", "UIA", "LIT", "LIA", "Pn", "Sn", "Ls", "Li", "Pog_soft", "OP_P", "OP_A"
596
+ ])
597
+ };
598
+
599
+ const CVM_INFO = {
600
+ CS1: "CS1 (Pre-Peak): Lower borders of C2–C4 flat. Peak mandibular growth >2 years away.",
601
+ CS2: "CS2 (Pre-Peak): Concavity at inferior border of C2. Peak growth within 1 year.",
602
+ CS3: "CS3 (Peak Ascending): Concavities at C2 & C3. Peak growth begins (Ideal timing for Class II functional orthopedics).",
603
+ CS4: "CS4 (Peak Deceleration): Concavities at C2, C3, and C4. Peak occurred 1–2 years ago.",
604
+ CS5: "CS5 (Post-Peak): Concavities present on C2–C4; C3 or C4 body square. Peak ended >1 year ago.",
605
+ CS6: "CS6 (Maturation Complete): Prominent concavities on C2–C4; vertebral body vertical rectangular. Growth complete."
606
+ };
607
+
608
+ const DEFAULT_ABO_NORMS = [
609
+ { id: "SNA", name: "SNA Angle", norm: 82.0, sd: 2.0, unit: "°" },
610
+ { id: "SNB", name: "SNB Angle", norm: 80.0, sd: 2.0, unit: "°" },
611
+ { id: "ANB", name: "ANB Difference", norm: 2.0, sd: 2.0, unit: "°" },
612
+ { id: "FMA", name: "FMA (FH to MP)", norm: 25.0, sd: 4.0, unit: "°" },
613
+ { id: "SNMP", name: "SN to MP Angle", norm: 32.0, sd: 5.0, unit: "°" },
614
+ { id: "IMPA", name: "IMPA (L1 to MP)", norm: 90.0, sd: 5.0, unit: "°" },
615
+ { id: "U1SN", name: "U1 to SN Angle", norm: 102.0, sd: 5.0, unit: "°" },
616
+ { id: "U1NA_deg", name: "U1 to NA Angle", norm: 22.0, sd: 4.0, unit: "°" },
617
+ { id: "U1NA_mm", name: "U1 to NA (mm)", norm: 4.0, sd: 2.0, unit: "mm" },
618
+ { id: "L1NB_deg", name: "L1 to NB Angle", norm: 25.0, sd: 4.0, unit: "°" },
619
+ { id: "L1NB_mm", name: "L1 to NB (mm)", norm: 4.0, sd: 2.0, unit: "mm" },
620
+ { id: "IIA", name: "Interincisal Angle", norm: 130.0, sd: 6.0, unit: "°" },
621
+ { id: "UL_E", name: "Upper Lip to E-Line", norm: -3.0, sd: 2.0, unit: "mm" },
622
+ { id: "LL_E", name: "Lower Lip to E-Line", norm: -1.0, sd: 2.0, unit: "mm" }
623
+ ];
624
+
625
+ let ABO_NORMS = JSON.parse(localStorage.getItem("custom_abo_norms_v2")) || JSON.parse(JSON.stringify(DEFAULT_ABO_NORMS));
626
+
627
+ const HOLDAWAY_NORMS = [
628
+ { id: "H_ANGLE", name: "H-Angle (H-Line to N'-Pog')", norm: 10.0, sd: 3.0, unit: "°" },
629
+ { id: "SKEL_CONV", name: "Skeletal Convexity (A to N-Pog)", norm: 0.0, sd: 2.0, unit: "mm" },
630
+ { id: "NOSE_PROM", name: "Nose Prominence (Pn to H-Line)", norm: 18.0, sd: 4.0, unit: "mm" },
631
+ { id: "SN_HLINE", name: "Subnasale to H-Line", norm: 5.0, sd: 2.0, unit: "mm" },
632
+ { id: "LL_HLINE", name: "Lower Lip to H-Line", norm: 0.5, sd: 1.0, unit: "mm" },
633
+ { id: "CHIN_THICK", name: "Soft Chin Thickness (Pog to Pog')", norm: 11.0, sd: 2.0, unit: "mm" }
634
+ ];
635
+
636
+ // App State
637
+ let session = null;
638
+ let coords = {};
639
+ let initialAiCoords = {};
640
+ let t1Baseline = null;
641
+ let selectedLm = null;
642
+ let cvmStage = "Auto";
643
+ let pxPerMm = 10.0;
644
+ let calStep = 0;
645
+ let showRuler = false;
646
+ let focusMode = "ABO";
647
+ let showLines = true;
648
+ let showPoints = true;
649
+ let showLabels = true;
650
+ let spacebarPeek = false;
651
+
652
+ // Viewport Transform State (Smooth Pan/Zoom)
653
+ let zoomLevel = 1.0;
654
+ let panX = 0;
655
+ let panY = 0;
656
+ let isPanning = false;
657
+ let startPanMouseX = 0, startPanMouseY = 0;
658
+
659
+ let draggingLm = null;
660
+ let latestMetrics = {};
661
+ let latestDiagnosis = { headline: "", sagittal: "-", vertical: "-", dental: "-", soft: "-" };
662
+
663
+ const imgElem = document.getElementById("ceph-image");
664
+ const svgElem = document.getElementById("overlay-svg");
665
+ const statusTxt = document.getElementById("status-txt");
666
+ const statusInd = document.getElementById("status-ind");
667
+ const container = document.getElementById("viewport-container");
668
+ const dropzone = document.getElementById("empty-dropzone");
669
+ const calBtn = document.getElementById("btn-cal");
670
+ const calStatus = document.getElementById("cal-status");
671
+ const loupeBox = document.getElementById("loupe-box");
672
+ const loupeCanvas = document.getElementById("loupe-canvas");
673
+ const loupeLabel = document.getElementById("loupe-label");
674
+ const toastElem = document.getElementById("toast-msg");
675
+
676
+ document.getElementById("pt-date").valueAsDate = new Date();
677
+ updateSectionVisibility();
678
+ buildNormsEditor();
679
+
680
+ function notify(text, duration = 2800) {
681
+ toastElem.innerText = text;
682
+ toastElem.style.display = "block";
683
+ setTimeout(() => { toastElem.style.display = "none"; }, duration);
684
+ }
685
+
686
+ // -------------------------------------------------------------
687
+ // 2. Custom Norms Editor
688
+ // -------------------------------------------------------------
689
+ function buildNormsEditor() {
690
+ const drawer = document.getElementById("norms-drawer");
691
+ 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>`;
692
+ ABO_NORMS.forEach((m, idx) => {
693
+ const row = document.createElement("div");
694
+ row.className = "norm-edit-row";
695
+ row.innerHTML = `
696
+ <span>${m.id}</span>
697
+ <input type="number" step="0.5" value="${m.norm}" data-idx="${idx}" data-field="norm">
698
+ <input type="number" step="0.5" value="${m.sd}" data-idx="${idx}" data-field="sd">
699
+ `;
700
+ drawer.appendChild(row);
701
+ });
702
+
703
+ drawer.querySelectorAll("input").forEach(inp => {
704
+ inp.addEventListener("input", (e) => {
705
+ const i = parseInt(e.target.getAttribute("data-idx"));
706
+ const field = e.target.getAttribute("data-field");
707
+ const val = parseFloat(e.target.value);
708
+ if (!isNaN(val)) {
709
+ ABO_NORMS[i][field] = val;
710
+ localStorage.setItem("custom_abo_norms_v2", JSON.stringify(ABO_NORMS));
711
+ renderAnalysis();
712
+ }
713
+ });
714
+ });
715
+ }
716
+
717
+ document.getElementById("btn-toggle-norms").addEventListener("click", () => {
718
+ const drawer = document.getElementById("norms-drawer");
719
+ const resetBtn = document.getElementById("reset-norms");
720
+ const isOpen = drawer.style.display === "flex";
721
+ drawer.style.display = isOpen ? "none" : "flex";
722
+ resetBtn.style.display = isOpen ? "none" : "inline";
723
+ });
724
+
725
+ document.getElementById("reset-norms").addEventListener("click", () => {
726
+ ABO_NORMS = JSON.parse(JSON.stringify(DEFAULT_ABO_NORMS));
727
+ localStorage.removeItem("custom_abo_norms_v2");
728
+ buildNormsEditor();
729
+ renderAnalysis();
730
+ notify("ABO norms restored to default standards.");
731
+ });
732
+
733
+ // -------------------------------------------------------------
734
+ // 3. Initialize AI Model
735
+ // -------------------------------------------------------------
736
+ async function initModel() {
737
+ try {
738
+ ort.env.wasm.numThreads = 2;
739
+ session = await ort.InferenceSession.create(MODEL_URL, { executionProviders: ['wasm'] });
740
+ statusInd.style.backgroundColor = "var(--status-green)";
741
+ statusTxt.innerText = "AI Online";
742
+ if (imgElem.src && imgElem.naturalWidth > 0 && Object.keys(coords).length === 0) {
743
+ runAutoTrace();
744
+ }
745
+ } catch (err) {
746
+ statusInd.style.backgroundColor = "var(--status-red)";
747
+ statusTxt.innerText = "AI Offline (Manual Mode)";
748
+ }
749
+ }
750
+ initModel();
751
+
752
+ // -------------------------------------------------------------
753
+ // 4. File Upload (DICOM, Standard Image, JSON)
754
+ // -------------------------------------------------------------
755
+ const viewportWrapper = document.getElementById("viewport-wrapper");
756
+
757
+ viewportWrapper.addEventListener("dragover", (e) => {
758
+ e.preventDefault();
759
+ viewportWrapper.classList.add("drag-over");
760
+ });
761
+ viewportWrapper.addEventListener("dragleave", () => {
762
+ viewportWrapper.classList.remove("drag-over");
763
+ });
764
+ viewportWrapper.addEventListener("drop", (e) => {
765
+ e.preventDefault();
766
+ viewportWrapper.classList.remove("drag-over");
767
+ if (e.dataTransfer.files && e.dataTransfer.files[0]) {
768
+ handleFile(e.dataTransfer.files[0]);
769
+ }
770
+ });
771
+
772
+ document.getElementById("file-input").addEventListener("change", (e) => {
773
+ if (e.target.files[0]) handleFile(e.target.files[0]);
774
+ });
775
+
776
+ document.getElementById("json-input").addEventListener("change", (e) => {
777
+ if (e.target.files[0]) loadJsonFile(e.target.files[0]);
778
+ });
779
+
780
+ function handleFile(file) {
781
+ const name = file.name.toLowerCase();
782
+ if (name.endsWith('.json') || file.type === 'application/json') {
783
+ loadJsonFile(file);
784
+ return;
785
+ }
786
+ const isDicom = name.endsWith('.dcm') || file.type === 'application/dicom';
787
+ if (isDicom) {
788
+ const reader = new FileReader();
789
+ reader.onload = (evt) => {
790
+ try {
791
+ parseAndDisplayDicom(new Uint8Array(evt.target.result));
792
+ } catch (err) {
793
+ notify("DICOM Parse Error: " + err.message);
794
+ }
795
+ };
796
+ reader.readAsArrayBuffer(file);
797
+ } else {
798
+ const reader = new FileReader();
799
+ reader.onload = (evt) => setupImage(evt.target.result, true);
800
+ reader.readAsDataURL(file);
801
+ }
802
+ }
803
+
804
+ // -------------------------------------------------------------
805
+ // 5. Robust JSON Save & Load (Fixes Blank Screen & Data Drift)
806
+ // -------------------------------------------------------------
807
+ function getExportableImageData() {
808
+ if (imgElem.src && imgElem.src.startsWith("data:image")) {
809
+ return imgElem.src;
810
+ }
811
+ if (imgElem.naturalWidth > 0) {
812
+ try {
813
+ const c = document.createElement("canvas");
814
+ c.width = imgElem.naturalWidth;
815
+ c.height = imgElem.naturalHeight;
816
+ const ctx = c.getContext("2d");
817
+ ctx.drawImage(imgElem, 0, 0);
818
+ return c.toDataURL("image/jpeg", 0.92);
819
+ } catch (e) {
820
+ return null;
821
+ }
822
+ }
823
+ return null;
824
+ }
825
+
826
+ document.getElementById("btn-save-json").addEventListener("click", () => {
827
+ if (!coords.S) {
828
+ notify("No active cephalogram tracing to save.");
829
+ return;
830
+ }
831
+ const ptName = document.getElementById("pt-name").value || "Patient";
832
+ const ptChart = document.getElementById("pt-chart").value || "";
833
+ const ptDate = document.getElementById("pt-date").value || "";
834
+
835
+ const payload = {
836
+ app: "OrthoCephPro",
837
+ version: "3.1",
838
+ patient: { name: ptName, chart: ptChart, date: ptDate },
839
+ pxPerMm,
840
+ cvmStage,
841
+ coords,
842
+ initialAiCoords,
843
+ metrics: latestMetrics,
844
+ diagnosis: latestDiagnosis,
845
+ imageDataUrl: getExportableImageData()
846
+ };
847
+
848
+ const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
849
+ const url = URL.createObjectURL(blob);
850
+ const a = document.createElement("a");
851
+ a.href = url;
852
+ a.download = `Ceph_${ptName.replace(/\s+/g, '_')}_${ptDate || 'record'}.json`;
853
+ a.click();
854
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
855
+ notify("Tracing JSON record with image exported successfully.");
856
+ });
857
+
858
+ function loadJsonFile(file) {
859
+ const reader = new FileReader();
860
+ reader.onload = (e) => {
861
+ try {
862
+ const data = JSON.parse(e.target.result);
863
+ if (data.patient) {
864
+ document.getElementById("pt-name").value = data.patient.name || "";
865
+ document.getElementById("pt-chart").value = data.patient.chart || "";
866
+ if (data.patient.date) document.getElementById("pt-date").value = data.patient.date;
867
+ }
868
+ if (data.pxPerMm && data.pxPerMm > 0) {
869
+ pxPerMm = data.pxPerMm;
870
+ calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (Loaded)`;
871
+ }
872
+ if (data.cvmStage && data.cvmStage !== "Auto") {
873
+ cvmStage = data.cvmStage;
874
+ highlightCvmButton(cvmStage);
875
+ }
876
+
877
+ const loadedCoords = data.coords || data.landmarks || null;
878
+ if (loadedCoords && loadedCoords.S) {
879
+ // Strip out any legacy CVM landmarks
880
+ const cleanCoords = {};
881
+ for (const [k, v] of Object.entries(loadedCoords)) {
882
+ if (!k.startsWith("C2_") && !k.startsWith("C3_") && !k.startsWith("C4_")) {
883
+ cleanCoords[k] = v;
884
+ }
885
+ }
886
+ coords = cleanCoords;
887
+ initialAiCoords = data.initialAiCoords
888
+ ? JSON.parse(JSON.stringify(data.initialAiCoords))
889
+ : JSON.parse(JSON.stringify(cleanCoords));
890
+ }
891
+
892
+ // Check for image or prompt to re-link original x-ray
893
+ if (data.imageDataUrl && data.imageDataUrl.startsWith("data:image")) {
894
+ setupImage(data.imageDataUrl, false);
895
+ } else if (imgElem.src && imgElem.naturalWidth > 0) {
896
+ // Already have an x-ray loaded, overlay the JSON coordinates onto it
897
+ renderAnalysis();
898
+ notify("JSON landmarks mapped onto existing radiograph.");
899
+ } else {
900
+ generateFallbackCanvasFromCoords();
901
+ notify("Loaded JSON. You can now select or drop the patient's X-Ray to overlay it!", 5000);
902
+ }
903
+ } catch (err) {
904
+ notify("Failed to parse JSON file: " + err.message);
905
+ }
906
+ };
907
+ reader.readAsText(file);
908
+ }
909
+
910
+ function generateFallbackCanvasFromCoords() {
911
+ const xs = Object.values(coords).map(p => p.x).filter(x => typeof x === 'number');
912
+ const ys = Object.values(coords).map(p => p.y).filter(y => typeof y === 'number');
913
+ const maxX = xs.length ? Math.max(...xs) + 120 : 1000;
914
+ const maxY = ys.length ? Math.max(...ys) + 120 : 1200;
915
+ const w = Math.max(800, Math.ceil(maxX));
916
+ const h = Math.max(900, Math.ceil(maxY));
917
+
918
+ const c = document.createElement("canvas");
919
+ c.width = w; c.height = h;
920
+ const ctx = c.getContext("2d");
921
+ ctx.fillStyle = "#090d16";
922
+ ctx.fillRect(0, 0, w, h);
923
+
924
+ // Anatomical orientation grid lines
925
+ ctx.strokeStyle = "#172033";
926
+ ctx.lineWidth = 1;
927
+ for (let x = 0; x < w; x += 50) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
928
+ for (let y = 0; y < h; y += 50) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
929
+
930
+ ctx.fillStyle = "#38bdf8";
931
+ ctx.font = "bold 13px Inter, sans-serif";
932
+ ctx.fillText("Tracing Restored. Drop or Choose the Patient's X-Ray to attach background image.", 24, 36);
933
+
934
+ setupImage(c.toDataURL("image/png"), false);
935
+ }
936
+
937
+ // -------------------------------------------------------------
938
+ // 6. DICOM & Canvas Setup
939
+ // -------------------------------------------------------------
940
+ function parseAndDisplayDicom(byteArray) {
941
+ const dataSet = dicomParser.parseDicom(byteArray);
942
+ const ptName = dataSet.string('x00100010');
943
+ if (ptName) document.getElementById('pt-name').value = ptName.replace(/\^/g, ' ').trim();
944
+ const ptId = dataSet.string('x00100020');
945
+ if (ptId) document.getElementById('pt-chart').value = ptId.trim();
946
+ const studyDate = dataSet.string('x00080020');
947
+ if (studyDate && studyDate.length === 8) {
948
+ document.getElementById('pt-date').value = `${studyDate.slice(0,4)}-${studyDate.slice(4,6)}-${studyDate.slice(6,8)}`;
949
+ }
950
+
951
+ const spacingStr = dataSet.string('x00280030') || dataSet.string('x00181164');
952
+ if (spacingStr) {
953
+ const parts = spacingStr.split('\\').map(parseFloat);
954
+ if (parts[0] > 0) {
955
+ pxPerMm = 1.0 / parts[0];
956
+ calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (DICOM)`;
957
+ }
958
+ }
959
+
960
+ const rows = dataSet.uint16('x00280010');
961
+ const cols = dataSet.uint16('x00280011');
962
+ const bitsAllocated = dataSet.uint16('x00280100') || 16;
963
+ const pixelRep = dataSet.uint16('x00280103') || 0;
964
+ const isMonochrome1 = (dataSet.string('x00280004') || '').trim() === 'MONOCHROME1';
965
+ const pixelDataElem = dataSet.elements.x7fe00010;
966
+
967
+ const offCanvas = document.createElement("canvas");
968
+ offCanvas.width = cols; offCanvas.height = rows;
969
+ const ctx = offCanvas.getContext("2d");
970
+ const imgData = ctx.createImageData(cols, rows);
971
+ const numPixels = rows * cols;
972
+
973
+ let slope = parseFloat(dataSet.string('x00281053')) || 1;
974
+ let intercept = parseFloat(dataSet.string('x00281052')) || 0;
975
+ let wc = parseFloat(dataSet.string('x00281050'));
976
+ let ww = parseFloat(dataSet.string('x00281051'));
977
+
978
+ if (bitsAllocated === 16) {
979
+ const u8 = new Uint8Array(byteArray.buffer, byteArray.byteOffset + pixelDataElem.dataOffset, numPixels * 2);
980
+ const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
981
+ const vals = new Float32Array(numPixels);
982
+ let minVal = Infinity, maxVal = -Infinity;
983
+ for (let i = 0; i < numPixels; i++) {
984
+ let raw = pixelRep === 1 ? dv.getInt16(i * 2, true) : dv.getUint16(i * 2, true);
985
+ let v = raw * slope + intercept;
986
+ vals[i] = v;
987
+ if (v < minVal) minVal = v;
988
+ if (v > maxVal) maxVal = v;
989
+ }
990
+ if (isNaN(wc) || isNaN(ww) || ww <= 0) {
991
+ wc = (minVal + maxVal) / 2;
992
+ ww = Math.max(1, maxVal - minVal);
993
+ }
994
+ const low = wc - ww / 2;
995
+ for (let i = 0; i < numPixels; i++) {
996
+ let intensity = Math.min(255, Math.max(0, ((vals[i] - low) / ww) * 255));
997
+ if (isMonochrome1) intensity = 255 - intensity;
998
+ const idx = i * 4;
999
+ imgData.data[idx] = intensity; imgData.data[idx+1] = intensity; imgData.data[idx+2] = intensity; imgData.data[idx+3] = 255;
1000
+ }
1001
+ } else {
1002
+ const u8 = new Uint8Array(byteArray.buffer, byteArray.byteOffset + pixelDataElem.dataOffset, numPixels);
1003
+ for (let i = 0; i < numPixels; i++) {
1004
+ let intensity = isMonochrome1 ? 255 - u8[i] : u8[i];
1005
+ const idx = i * 4;
1006
+ imgData.data[idx] = intensity; imgData.data[idx+1] = intensity; imgData.data[idx+2] = intensity; imgData.data[idx+3] = 255;
1007
+ }
1008
+ }
1009
+ ctx.putImageData(imgData, 0, 0);
1010
+ setupImage(offCanvas.toDataURL("image/png"), true);
1011
+ }
1012
+
1013
+ function setupImage(srcUrl, shouldRunAi = true) {
1014
+ imgElem.onload = () => {
1015
+ dropzone.style.display = "none";
1016
+ container.style.display = "block";
1017
+
1018
+ const w = imgElem.naturalWidth || 1000;
1019
+ const h = imgElem.naturalHeight || 1200;
1020
+ imgElem.width = w;
1021
+ imgElem.height = h;
1022
+
1023
+ svgElem.setAttribute("viewBox", `0 0 ${w} ${h}`);
1024
+ svgElem.setAttribute("width", w);
1025
+ svgElem.setAttribute("height", h);
1026
+
1027
+ fitImageToViewport();
1028
+
1029
+ if (shouldRunAi && session) {
1030
+ runAutoTrace();
1031
+ } else {
1032
+ renderAnalysis();
1033
+ }
1034
+ };
1035
+ imgElem.src = srcUrl;
1036
+ }
1037
+
1038
+ function fitImageToViewport() {
1039
+ if (!imgElem.naturalWidth) return;
1040
+ const vw = viewportWrapper.clientWidth;
1041
+ const vh = viewportWrapper.clientHeight;
1042
+ const iw = imgElem.naturalWidth;
1043
+ const ih = imgElem.naturalHeight;
1044
+
1045
+ const scale = Math.min((vw - 40) / iw, (vh - 40) / ih, 1.0);
1046
+ zoomLevel = Math.max(0.2, scale);
1047
+ panX = (vw - iw * zoomLevel) / 2;
1048
+ panY = (vh - ih * zoomLevel) / 2;
1049
+ updateTransform();
1050
+ }
1051
+
1052
+ function updateTransform() {
1053
+ container.style.transform = `translate(${panX}px, ${panY}px) scale(${zoomLevel})`;
1054
+ }
1055
+
1056
+ // -------------------------------------------------------------
1057
+ // 7. Auto-Tracing, Anatomical CVM Heuristics & Landmark Derivation
1058
+ // -------------------------------------------------------------
1059
+ async function runAutoTrace() {
1060
+ if (!session || !imgElem.src) return;
1061
+ statusInd.style.backgroundColor = "var(--status-amber)";
1062
+ statusTxt.innerText = "Analyzing Radiograph...";
1063
+
1064
+ await new Promise(r => setTimeout(r, 30));
1065
+
1066
+ const off = document.createElement("canvas");
1067
+ off.width = 768; off.height = 768;
1068
+ const ctx = off.getContext("2d");
1069
+ ctx.drawImage(imgElem, 0, 0, 768, 768);
1070
+ const data = ctx.getImageData(0, 0, 768, 768).data;
1071
+
1072
+ const floatArr = new Float32Array(3 * 768 * 768);
1073
+ const mean = [0.485, 0.456, 0.406];
1074
+ const std = [0.229, 0.224, 0.225];
1075
+
1076
+ for (let i = 0; i < 768 * 768; i++) {
1077
+ floatArr[i] = (data[i * 4] / 255.0 - mean[0]) / std[0];
1078
+ floatArr[768 * 768 + i] = (data[i * 4 + 1] / 255.0 - mean[1]) / std[1];
1079
+ floatArr[2 * 768 * 768 + i] = (data[i * 4 + 2] / 255.0 - mean[2]) / std[2];
1080
+ }
1081
+
1082
+ const tensor = new ort.Tensor("float32", floatArr, [1, 3, 768, 768]);
1083
+ const results = await session.run({ [session.inputNames[0]]: tensor });
1084
+ const heatmaps = results[session.outputNames[0]].data;
1085
+
1086
+ const origW = imgElem.naturalWidth;
1087
+ const origH = imgElem.naturalHeight;
1088
+ coords = {};
1089
+
1090
+ for (const [name, ch] of Object.entries(LM_INDICES)) {
1091
+ let maxVal = -Infinity, maxIdx = 0;
1092
+ const offset = ch * 192 * 192;
1093
+ for (let j = 0; j < 192 * 192; j++) {
1094
+ if (heatmaps[offset + j] > maxVal) {
1095
+ maxVal = heatmaps[offset + j];
1096
+ maxIdx = j;
1097
+ }
1098
+ }
1099
+ coords[name] = {
1100
+ x: (maxIdx % 192 / 192) * origW,
1101
+ y: (Math.floor(maxIdx / 192) / 192) * origH
1102
+ };
1103
+ }
1104
+
1105
+ // Derive Posterior Nasal Spine (PNS) along the Palatal Plane
1106
+ if (coords.ANS && coords.Or && coords.Po) {
1107
+ const palatalVec = { x: coords.ANS.x - (coords.Po.x + (coords.Or.x - coords.Po.x) * 0.3), y: 0 };
1108
+ coords.PNS = {
1109
+ x: coords.ANS.x - Math.max(38, Math.min(65, palatalVec.x * 0.35 || 50)),
1110
+ y: coords.ANS.y + 2
1111
+ };
1112
+ } else if (coords.ANS) {
1113
+ coords.PNS = { x: coords.ANS.x - 48, y: coords.ANS.y };
1114
+ }
1115
+
1116
+ // Occlusal Plane Landmarks (OP_A anterior, OP_P posterior)
1117
+ if (coords.UIT && coords.LIT) {
1118
+ coords.OP_A = { x: (coords.UIT.x + coords.LIT.x) / 2, y: (coords.UIT.y + coords.LIT.y) / 2 };
1119
+ }
1120
+ if (coords.Go && coords.OP_A) {
1121
+ coords.OP_P = { x: coords.OP_A.x - (coords.OP_A.x - coords.Go.x) * 0.52, y: coords.OP_A.y - 10 };
1122
+ }
1123
+
1124
+ // 10mm Reference Ruler in upper corner
1125
+ if (!coords.RULER_1 || !coords.RULER_2) {
1126
+ coords.RULER_1 = { x: origW * 0.88, y: origH * 0.12 };
1127
+ coords.RULER_2 = { x: origW * 0.88, y: origH * 0.12 + (pxPerMm * 10.0) };
1128
+ }
1129
+
1130
+ initialAiCoords = JSON.parse(JSON.stringify(coords));
1131
+ statusInd.style.backgroundColor = "var(--status-green)";
1132
+ statusTxt.innerText = "Traced (AI Ready)";
1133
+ renderAnalysis();
1134
+ }
1135
+
1136
+ // Retrace & Calibration Integration Listeners
1137
+ document.getElementById("btn-retrace-scaled").addEventListener("click", () => {
1138
+ if (!imgElem.src) {
1139
+ notify("Upload a lateral cephalogram first.");
1140
+ return;
1141
+ }
1142
+ runAutoTrace();
1143
+ notify(`Re-traced and aligned with scale: ${pxPerMm.toFixed(2)} px/mm.`);
1144
+ });
1145
+
1146
+ document.getElementById("btn-retrace-all").addEventListener("click", () => {
1147
+ if (Object.keys(initialAiCoords).length > 0) {
1148
+ coords = JSON.parse(JSON.stringify(initialAiCoords));
1149
+ renderAnalysis();
1150
+ notify("All points reset to initial AI predictions.");
1151
+ } else {
1152
+ runAutoTrace();
1153
+ }
1154
+ });
1155
+
1156
+ document.getElementById("btn-reset-single").addEventListener("click", () => {
1157
+ if (selectedLm && initialAiCoords[selectedLm]) {
1158
+ coords[selectedLm] = { ...initialAiCoords[selectedLm] };
1159
+ renderAnalysis();
1160
+ notify(`Reset ${selectedLm} to initial position.`);
1161
+ } else {
1162
+ notify("Click any landmark point first to select it.");
1163
+ }
1164
+ });
1165
+
1166
+ // -------------------------------------------------------------
1167
+ // 8. CVM Controls & Regional Superimposition Alignment
1168
+ // -------------------------------------------------------------
1169
+ document.querySelectorAll(".cvm-btn").forEach(btn => {
1170
+ btn.addEventListener("click", () => {
1171
+ const stage = btn.getAttribute("data-cvm");
1172
+ cvmStage = stage;
1173
+ highlightCvmButton(stage);
1174
+ renderAnalysis();
1175
+ });
1176
+ });
1177
+
1178
+ function highlightCvmButton(stage) {
1179
+ document.querySelectorAll(".cvm-btn").forEach(b => {
1180
+ b.classList.toggle("active", b.getAttribute("data-cvm") === stage);
1181
+ });
1182
+ document.getElementById("cvm-desc").innerText = CVM_INFO[stage] || "Select CVM stage to classify skeletal maturation.";
1183
+ }
1184
+
1185
+ document.getElementById("btn-lock-t1").addEventListener("click", () => {
1186
+ if (!coords.S) {
1187
+ notify("Trace a baseline cephalogram first before locking T1.");
1188
+ return;
1189
+ }
1190
+ t1Baseline = {
1191
+ coords: JSON.parse(JSON.stringify(coords)),
1192
+ metrics: JSON.parse(JSON.stringify(latestMetrics)),
1193
+ date: document.getElementById("pt-date").value || "T1"
1194
+ };
1195
+ document.getElementById("super-status").innerHTML = `<span style="color:#5eead4; font-weight:700;">✅ T1 Locked (${t1Baseline.date})</span> — Now load T2 cephalogram.`;
1196
+ document.getElementById("th-t1-abo").style.display = "table-cell";
1197
+ notify("Baseline T1 successfully locked.");
1198
+ renderAnalysis();
1199
+ });
1200
+
1201
+ document.getElementById("btn-clear-t1").addEventListener("click", () => {
1202
+ t1Baseline = null;
1203
+ document.getElementById("super-status").innerText = "No T1 baseline locked.";
1204
+ document.getElementById("th-t1-abo").style.display = "none";
1205
+ renderAnalysis();
1206
+ });
1207
+
1208
+ function getSuperimposedT1Coords() {
1209
+ if (!t1Baseline || !t1Baseline.coords.S || !coords.S) return null;
1210
+ const mode = document.getElementById("super-mode").value;
1211
+
1212
+ const s1 = t1Baseline.coords.S, s2 = coords.S;
1213
+ let origin1 = s1, origin2 = s2;
1214
+ let angle1 = 0, angle2 = 0;
1215
+
1216
+ if (mode === "MAXILLARY" && t1Baseline.coords.PNS && t1Baseline.coords.ANS && coords.PNS && coords.ANS) {
1217
+ origin1 = t1Baseline.coords.PNS;
1218
+ origin2 = coords.PNS;
1219
+ angle1 = Math.atan2(t1Baseline.coords.ANS.y - t1Baseline.coords.PNS.y, t1Baseline.coords.ANS.x - t1Baseline.coords.PNS.x);
1220
+ angle2 = Math.atan2(coords.ANS.y - coords.PNS.y, coords.ANS.x - coords.PNS.x);
1221
+ } else if (mode === "MANDIBULAR" && t1Baseline.coords.Me && t1Baseline.coords.Go && coords.Me && coords.Go) {
1222
+ origin1 = t1Baseline.coords.Me;
1223
+ origin2 = coords.Me;
1224
+ angle1 = Math.atan2(t1Baseline.coords.Go.y - t1Baseline.coords.Me.y, t1Baseline.coords.Go.x - t1Baseline.coords.Me.x);
1225
+ angle2 = Math.atan2(coords.Go.y - coords.Me.y, coords.Go.x - coords.Me.x);
1226
+ } else {
1227
+ // Cranial Base Alignment (S-N at S)
1228
+ if (!t1Baseline.coords.N || !coords.N) return null;
1229
+ angle1 = Math.atan2(t1Baseline.coords.N.y - s1.y, t1Baseline.coords.N.x - s1.x);
1230
+ angle2 = Math.atan2(coords.N.y - s2.y, coords.N.x - s2.x);
1231
+ }
1232
+
1233
+ const dTheta = angle2 - angle1;
1234
+ const cosT = Math.cos(dTheta), sinT = Math.sin(dTheta);
1235
+
1236
+ const aligned = {};
1237
+ for (const [k, pt] of Object.entries(t1Baseline.coords)) {
1238
+ const dx = pt.x - origin1.x;
1239
+ const dy = pt.y - origin1.y;
1240
+ aligned[k] = {
1241
+ x: origin2.x + (dx * cosT - dy * sinT),
1242
+ y: origin2.y + (dx * sinT + dy * cosT)
1243
+ };
1244
+ }
1245
+ return aligned;
1246
+ }
1247
+
1248
+ // -------------------------------------------------------------
1249
+ // 9. Focus Modes, Visibility & Spacebar Peek
1250
+ // -------------------------------------------------------------
1251
+ document.querySelectorAll(".mode-btn").forEach(btn => {
1252
+ btn.addEventListener("click", () => {
1253
+ document.querySelectorAll(".mode-btn").forEach(b => b.classList.remove("active"));
1254
+ btn.classList.add("active");
1255
+ focusMode = btn.getAttribute("data-mode");
1256
+ updateSectionVisibility();
1257
+ renderAnalysis();
1258
+ });
1259
+ });
1260
+
1261
+ function updateSectionVisibility() {
1262
+ document.getElementById("section-abo").style.display = (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") ? "block" : "none";
1263
+ document.getElementById("section-wits").style.display = (focusMode === "WITS" || focusMode === "ALL") ? "block" : "none";
1264
+ document.getElementById("section-holdaway").style.display = (focusMode === "HOLDAWAY" || focusMode === "ALL") ? "block" : "none";
1265
+ }
1266
+
1267
+ function setupToggle(id, label, getter, setter) {
1268
+ const el = document.getElementById(id);
1269
+ el.addEventListener("click", () => {
1270
+ const next = !getter();
1271
+ setter(next);
1272
+ el.classList.toggle("active", next);
1273
+ el.innerText = `${label}: ${next ? 'ON' : 'OFF'}`;
1274
+ renderAnalysis();
1275
+ });
1276
+ }
1277
+ setupToggle("tog-lines", "Lines", () => showLines, v => showLines = v);
1278
+ setupToggle("tog-points", "Dots", () => showPoints, v => showPoints = v);
1279
+ setupToggle("tog-labels", "Names", () => showLabels, v => showLabels = v);
1280
+
1281
+ window.addEventListener("keydown", (e) => {
1282
+ if (e.code === "Space" && document.activeElement.tagName !== "INPUT") {
1283
+ e.preventDefault();
1284
+ if (!spacebarPeek) {
1285
+ spacebarPeek = true;
1286
+ svgElem.style.opacity = "0";
1287
+ }
1288
+ }
1289
+ });
1290
+ window.addEventListener("keyup", (e) => {
1291
+ if (e.code === "Space") {
1292
+ spacebarPeek = false;
1293
+ svgElem.style.opacity = "1";
1294
+ }
1295
+ });
1296
+
1297
+ // -------------------------------------------------------------
1298
+ // 10. Interactive Canvas Pan, Zoom & Landmark Dragging
1299
+ // -------------------------------------------------------------
1300
+ calBtn.addEventListener("click", () => {
1301
+ if (!imgElem.src) return;
1302
+ showRuler = !showRuler;
1303
+ calBtn.style.background = showRuler ? "#0891b2" : "#131c2e";
1304
+ renderAnalysis();
1305
+ });
1306
+
1307
+ function getSVGCoords(e) {
1308
+ const pt = svgElem.createSVGPoint();
1309
+ pt.x = e.clientX;
1310
+ pt.y = e.clientY;
1311
+ return pt.matrixTransform(svgElem.getScreenCTM().inverse());
1312
+ }
1313
+
1314
+ function updateLoupe(pt, name) {
1315
+ if (!imgElem.src || !imgElem.naturalWidth) return;
1316
+ loupeBox.style.display = "block";
1317
+ loupeLabel.innerText = name;
1318
+ const lCtx = loupeCanvas.getContext("2d");
1319
+ const zoom = 3.0;
1320
+ const size = 140;
1321
+ const srcSize = size / zoom;
1322
+
1323
+ lCtx.clearRect(0, 0, size, size);
1324
+ lCtx.filter = imgElem.style.filter || "none";
1325
+ lCtx.drawImage(
1326
+ imgElem,
1327
+ pt.x - srcSize / 2, pt.y - srcSize / 2, srcSize, srcSize,
1328
+ 0, 0, size, size
1329
+ );
1330
+ lCtx.filter = "none";
1331
+
1332
+ // Targeting reticle
1333
+ lCtx.strokeStyle = "#38bdf8";
1334
+ lCtx.lineWidth = 1.5;
1335
+ lCtx.beginPath();
1336
+ lCtx.moveTo(size/2, 0); lCtx.lineTo(size/2, size/2 - 6);
1337
+ lCtx.moveTo(size/2, size/2 + 6); lCtx.lineTo(size/2, size);
1338
+ lCtx.moveTo(0, size/2); lCtx.lineTo(size/2 - 6, size/2);
1339
+ lCtx.moveTo(size/2 + 6, size/2); lCtx.lineTo(size, size/2);
1340
+ lCtx.stroke();
1341
+ }
1342
+
1343
+ viewportWrapper.addEventListener("wheel", (e) => {
1344
+ if (!imgElem.src) return;
1345
+ e.preventDefault();
1346
+ const zoomFactor = e.deltaY < 0 ? 1.15 : 0.88;
1347
+ const newZoom = Math.min(Math.max(0.2, zoomLevel * zoomFactor), 4.5);
1348
+
1349
+ const rect = viewportWrapper.getBoundingClientRect();
1350
+ const mouseX = e.clientX - rect.left;
1351
+ const mouseY = e.clientY - rect.top;
1352
+
1353
+ panX = mouseX - (mouseX - panX) * (newZoom / zoomLevel);
1354
+ panY = mouseY - (mouseY - panY) * (newZoom / zoomLevel);
1355
+ zoomLevel = newZoom;
1356
+ updateTransform();
1357
+ }, { passive: false });
1358
+
1359
+ viewportWrapper.addEventListener("mousedown", (e) => {
1360
+ // Pan on middle-click or Alt-click or background drag
1361
+ if (e.button === 1 || e.altKey || e.target === viewportWrapper || e.target === imgElem) {
1362
+ isPanning = true;
1363
+ startPanMouseX = e.clientX - panX;
1364
+ startPanMouseY = e.clientY - panY;
1365
+ viewportWrapper.style.cursor = "grabbing";
1366
+ }
1367
+ });
1368
+
1369
+ window.addEventListener("mousemove", (e) => {
1370
+ if (isPanning) {
1371
+ panX = e.clientX - startPanMouseX;
1372
+ panY = e.clientY - startPanMouseY;
1373
+ updateTransform();
1374
+ return;
1375
+ }
1376
+
1377
+ if (!draggingLm || !coords[draggingLm]) return;
1378
+ const p = getSVGCoords(e);
1379
+ const oldX = coords[draggingLm].x;
1380
+ const oldY = coords[draggingLm].y;
1381
+ const deltaX = p.x - oldX;
1382
+ const deltaY = p.y - oldY;
1383
+
1384
+ coords[draggingLm].x = p.x;
1385
+ coords[draggingLm].y = p.y;
1386
+
1387
+ if ((draggingLm === "RULER_1" || draggingLm === "RULER_2") && coords.RULER_1 && coords.RULER_2) {
1388
+ const dist = Math.hypot(coords.RULER_2.x - coords.RULER_1.x, coords.RULER_2.y - coords.RULER_1.y);
1389
+ if (dist > 1) {
1390
+ pxPerMm = dist / 10.0;
1391
+ calStatus.innerText = `Scale: ${pxPerMm.toFixed(2)} px/mm (10mm Ruler)`;
1392
+ }
1393
+ }
1394
+
1395
+ updateLoupe(p, draggingLm);
1396
+ renderAnalysis();
1397
+ });
1398
+
1399
+ window.addEventListener("mouseup", () => {
1400
+ if (isPanning) {
1401
+ isPanning = false;
1402
+ viewportWrapper.style.cursor = "default";
1403
+ }
1404
+ if (draggingLm) {
1405
+ draggingLm = null;
1406
+ loupeBox.style.display = "none";
1407
+ document.querySelectorAll(".landmark-handle").forEach(el => el.classList.remove("dragging"));
1408
+ }
1409
+ });
1410
+
1411
+ // Viewport Zoom Buttons
1412
+ document.getElementById("btn-zoom-in").addEventListener("click", () => {
1413
+ zoomLevel = Math.min(zoomLevel * 1.25, 4.0);
1414
+ updateTransform();
1415
+ });
1416
+ document.getElementById("btn-zoom-out").addEventListener("click", () => {
1417
+ zoomLevel = Math.max(zoomLevel * 0.8, 0.25);
1418
+ updateTransform();
1419
+ });
1420
+ document.getElementById("btn-zoom-reset").addEventListener("click", fitImageToViewport);
1421
+
1422
+ // -------------------------------------------------------------
1423
+ // 11. Image Filters & Reset
1424
+ // -------------------------------------------------------------
1425
+ function applyFilters() {
1426
+ const b = document.getElementById("brightness").value;
1427
+ const c = document.getElementById("contrast").value;
1428
+ const inv = document.getElementById("invert").checked ? 1 : 0;
1429
+ imgElem.style.filter = `brightness(${b}) contrast(${c}) invert(${inv})`;
1430
+ }
1431
+ document.getElementById("brightness").addEventListener("input", applyFilters);
1432
+ document.getElementById("contrast").addEventListener("input", applyFilters);
1433
+ document.getElementById("invert").addEventListener("change", applyFilters);
1434
+
1435
+ document.getElementById("reset-filters").addEventListener("click", () => {
1436
+ document.getElementById("brightness").value = 1.0;
1437
+ document.getElementById("contrast").value = 1.0;
1438
+ document.getElementById("invert").checked = false;
1439
+ applyFilters();
1440
+ });
1441
+
1442
+ document.getElementById("btn-next-patient").addEventListener("click", () => {
1443
+ coords = {};
1444
+ initialAiCoords = {};
1445
+ latestMetrics = {};
1446
+ t1Baseline = null;
1447
+ selectedLm = null;
1448
+ cvmStage = "Auto";
1449
+ highlightCvmButton("");
1450
+ document.getElementById("selected-lm-label").innerText = "None";
1451
+ imgElem.src = "";
1452
+ container.style.display = "none";
1453
+ dropzone.style.display = "flex";
1454
+ document.getElementById("file-input").value = "";
1455
+ document.getElementById("pt-name").value = "";
1456
+ document.getElementById("pt-chart").value = "";
1457
+ document.getElementById("pt-date").valueAsDate = new Date();
1458
+ document.getElementById("diag-headline").innerText = "Awaiting Lateral Cephalogram...";
1459
+ document.getElementById("diag-sagittal").innerText = "-";
1460
+ document.getElementById("diag-vertical").innerText = "-";
1461
+ document.getElementById("diag-dental").innerText = "-";
1462
+ document.getElementById("diag-soft").innerText = "-";
1463
+ document.getElementById("th-t1-abo").style.display = "none";
1464
+ svgElem.innerHTML = "";
1465
+ populateAboTable(ABO_NORMS, {});
1466
+ populateTable("holdaway-rows", HOLDAWAY_NORMS, {});
1467
+ populateWitsTable(null);
1468
+ notify("Workspace cleared for next patient.");
1469
+ });
1470
+
1471
+ // -------------------------------------------------------------
1472
+ // 12. Geometric Math & Diagnosis Engine
1473
+ // -------------------------------------------------------------
1474
+ function getAngle(p1, v, p2) {
1475
+ if (!p1 || !v || !p2) return null;
1476
+ const v1 = { x: p1.x - v.x, y: p1.y - v.y };
1477
+ const v2 = { x: p2.x - v.x, y: p2.y - v.y };
1478
+ const dot = v1.x * v2.x + v1.y * v2.y;
1479
+ const m1 = Math.hypot(v1.x, v1.y);
1480
+ const m2 = Math.hypot(v2.x, v2.y);
1481
+ return parseFloat((Math.acos(Math.max(-1, Math.min(1, dot / (m1 * m2 + 1e-7)))) * (180 / Math.PI)).toFixed(1));
1482
+ }
1483
+
1484
+ function getLineAngle(p1, p2, p3, p4) {
1485
+ if (!p1 || !p2 || !p3 || !p4) return null;
1486
+ const v1 = { x: p2.x - p1.x, y: p2.y - p1.y };
1487
+ const v2 = { x: p4.x - p3.x, y: p4.y - p3.y };
1488
+ const dot = v1.x * v2.x + v1.y * v2.y;
1489
+ const m1 = Math.hypot(v1.x, v1.y);
1490
+ const m2 = Math.hypot(v2.x, v2.y);
1491
+ let deg = (Math.acos(Math.max(-1, Math.min(1, dot / (m1 * m2 + 1e-7)))) * (180 / Math.PI));
1492
+ if (deg > 90) deg = 180 - deg;
1493
+ return parseFloat(deg.toFixed(1));
1494
+ }
1495
+
1496
+ function getPerpDist(pt, l1, l2) {
1497
+ if (!pt || !l1 || !l2 || !pxPerMm) return null;
1498
+ const v = { x: l2.x - l1.x, y: l2.y - l1.y };
1499
+ const len = Math.hypot(v.x, v.y);
1500
+ if (len === 0) return null;
1501
+ const cross = v.x * (pt.y - l1.y) - v.y * (pt.x - l1.x);
1502
+ return parseFloat((cross / len / pxPerMm).toFixed(1));
1503
+ }
1504
+
1505
+ function calculateWits(ptA, ptB, opP, opA) {
1506
+ if (!ptA || !ptB || !opP || !opA || !pxPerMm) return null;
1507
+ const vx = opA.x - opP.x, vy = opA.y - opP.y;
1508
+ const len = Math.hypot(vx, vy);
1509
+ if (len === 0) return null;
1510
+ const ux = vx / len, uy = vy / len;
1511
+ const tA = (ptA.x - opP.x) * ux + (ptA.y - opP.y) * uy;
1512
+ const tB = (ptB.x - opP.x) * ux + (ptB.y - opP.y) * uy;
1513
+ const ao = { x: opP.x + tA * ux, y: opP.y + tA * uy };
1514
+ const bo = { x: opP.x + tB * ux, y: opP.y + tB * uy };
1515
+ const distMm = parseFloat(((tA - tB) / pxPerMm).toFixed(1));
1516
+ return { distMm, ao, bo };
1517
+ }
1518
+
1519
+ function getNormObj(id) {
1520
+ return ABO_NORMS.find(x => x.id === id) || { norm: 0, sd: 1 };
1521
+ }
1522
+
1523
+ function updateClinicalDiagnosis(m) {
1524
+ if (m.ANB === null || isNaN(m.ANB)) return;
1525
+
1526
+ const anbN = getNormObj("ANB");
1527
+ const snaN = getNormObj("SNA");
1528
+ const snbN = getNormObj("SNB");
1529
+
1530
+ let skelClass = "Skeletal Class I";
1531
+ if (m.ANB > anbN.norm + anbN.sd) skelClass = "Skeletal Class II";
1532
+ else if (m.ANB < anbN.norm - anbN.sd) skelClass = "Skeletal Class III";
1533
+
1534
+ let jawNote = [];
1535
+ if (m.SNA > snaN.norm + snaN.sd) jawNote.push("Maxillary Prognathism");
1536
+ else if (m.SNA < snaN.norm - snaN.sd) jawNote.push("Maxillary Retrognathism");
1537
+
1538
+ if (m.SNB > snbN.norm + snbN.sd) jawNote.push("Mandibular Prognathism");
1539
+ else if (m.SNB < snbN.norm - snbN.sd) jawNote.push("Mandibular Retrognathism");
1540
+
1541
+ const sagStr = jawNote.length > 0 ? `${skelClass} (${jawNote.join(", ")})` : `${skelClass} (Orthognathic Base)`;
1542
+
1543
+ const fmaN = getNormObj("FMA");
1544
+ const snmpN = getNormObj("SNMP");
1545
+ let vertClass = "Normodivergent";
1546
+ if (m.FMA > fmaN.norm + fmaN.sd || m.SNMP > snmpN.norm + snmpN.sd) {
1547
+ vertClass = "Hyperdivergent (High Angle)";
1548
+ } else if (m.FMA < fmaN.norm - fmaN.sd || m.SNMP < snmpN.norm - snmpN.sd) {
1549
+ vertClass = "Hypodivergent (Low Angle)";
1550
+ }
1551
+
1552
+ const u1N = getNormObj("U1SN");
1553
+ const impaN = getNormObj("IMPA");
1554
+ let u1Str = "Normal U1";
1555
+ if (m.U1SN > u1N.norm + u1N.sd) u1Str = "Proclined U1";
1556
+ else if (m.U1SN < u1N.norm - u1N.sd) u1Str = "Retroclined U1";
1557
+
1558
+ let l1Str = "Normal L1";
1559
+ if (m.IMPA > impaN.norm + impaN.sd) l1Str = "Proclined L1";
1560
+ else if (m.IMPA < impaN.norm - impaN.sd) l1Str = "Retroclined L1";
1561
+
1562
+ const dentStr = `${u1Str}, ${l1Str}`;
1563
+
1564
+ const llN = getNormObj("LL_E");
1565
+ let softStr = "Balanced Lips";
1566
+ if (m.LL_E > llN.norm + llN.sd) softStr = "Protrusive Lips";
1567
+ else if (m.LL_E < llN.norm - llN.sd) softStr = "Retrusive Lips";
1568
+
1569
+ const stageLabel = cvmStage !== "Auto" ? cvmStage : "Unassigned";
1570
+ const softAndCvm = `${softStr} • CVM: ${stageLabel}`;
1571
+ const headline = `${skelClass} • ${vertClass} • ${dentStr}`;
1572
+
1573
+ latestDiagnosis = { headline, sagittal: sagStr, vertical: vertClass, dental: dentStr, soft: softAndCvm };
1574
+
1575
+ document.getElementById("diag-headline").innerText = headline;
1576
+ document.getElementById("diag-sagittal").innerText = sagStr;
1577
+ document.getElementById("diag-vertical").innerText = vertClass;
1578
+ document.getElementById("diag-dental").innerText = dentStr;
1579
+ document.getElementById("diag-soft").innerText = softAndCvm;
1580
+ }
1581
+
1582
+ // -------------------------------------------------------------
1583
+ // 13. High-Fidelity SVG Renderer & Measurement Calculation
1584
+ // -------------------------------------------------------------
1585
+ function renderAnalysis() {
1586
+ svgElem.innerHTML = "";
1587
+ if (!coords.S) return;
1588
+
1589
+ function line(p1, p2, col, w = 2.5, dash = null) {
1590
+ if (!p1 || !p2) return;
1591
+ const l = document.createElementNS("http://www.w3.org/2000/svg", "line");
1592
+ l.setAttribute("x1", p1.x); l.setAttribute("y1", p1.y);
1593
+ l.setAttribute("x2", p2.x); l.setAttribute("y2", p2.y);
1594
+ l.setAttribute("stroke", col);
1595
+ l.setAttribute("stroke-width", w);
1596
+ l.setAttribute("stroke-linecap", "round");
1597
+ if (dash) l.setAttribute("stroke-dasharray", dash);
1598
+ svgElem.appendChild(l);
1599
+ }
1600
+
1601
+ const wits = calculateWits(coords.A, coords.B, coords.OP_P, coords.OP_A);
1602
+
1603
+ // 1. Draw Superimposed T1 Ghost Tracing
1604
+ const t1Aligned = getSuperimposedT1Coords();
1605
+ if (t1Aligned && (focusMode === "SUPER" || focusMode === "ALL" || focusMode === "ABO")) {
1606
+ const drawT1Line = (a, b) => {
1607
+ line(a, b, "#000000", 4.5);
1608
+ line(a, b, "#94a3b8", 2, "5,3");
1609
+ };
1610
+ drawT1Line(t1Aligned.S, t1Aligned.N);
1611
+ drawT1Line(t1Aligned.N, t1Aligned.A);
1612
+ drawT1Line(t1Aligned.N, t1Aligned.B);
1613
+ drawT1Line(t1Aligned.Go, t1Aligned.Me);
1614
+ drawT1Line(t1Aligned.UIT, t1Aligned.UIA);
1615
+ drawT1Line(t1Aligned.LIT, t1Aligned.LIA);
1616
+ if (t1Aligned.ANS && t1Aligned.PNS) drawT1Line(t1Aligned.PNS, t1Aligned.ANS);
1617
+ }
1618
+
1619
+ // 2. Vector Planes
1620
+ if (showLines) {
1621
+ const isSuper = focusMode === "SUPER";
1622
+ if (focusMode === "ABO" || focusMode === "SUPER" || focusMode === "ALL") {
1623
+ line(coords.S, coords.N, isSuper ? "#f43f5e" : "#38bdf8", 3); // S-N Plane
1624
+ line(coords.N, coords.A, isSuper ? "#f43f5e" : "#4ade80", 2); // N-A Line
1625
+ line(coords.N, coords.B, isSuper ? "#f43f5e" : "#4ade80", 2); // N-B Line
1626
+ line(coords.Po, coords.Or, isSuper ? "#f43f5e" : "#fbbf24", 2.5); // Frankfort Horizontal
1627
+ line(coords.Go, coords.Me, isSuper ? "#f43f5e" : "#f43f5e", 3); // Mandibular Plane
1628
+ line(coords.UIT, coords.UIA, isSuper ? "#f43f5e" : "#2dd4bf", 2.5); // Upper Incisor Long Axis
1629
+ line(coords.LIT, coords.LIA, isSuper ? "#f43f5e" : "#d946ef", 2.5); // Lower Incisor Long Axis
1630
+ line(coords.Pn, coords.Pog_soft, isSuper ? "#f43f5e" : "#fb923c", 2); // Ricketts E-Line
1631
+ if (coords.PNS && coords.ANS) line(coords.PNS, coords.ANS, isSuper ? "#f43f5e" : "#a3e635", 2); // Palatal Plane
1632
+ }
1633
+
1634
+ if (focusMode === "HOLDAWAY" || focusMode === "ALL") {
1635
+ line(coords.Ls, coords.Pog_soft, "#ec4899", 2.5); // Harmony Line
1636
+ line(coords.N, coords.Pog_soft, "#c084fc", 1.5, "4,4");
1637
+ line(coords.N, coords.Pog, "#94a3b8", 1.5, "4,4");
1638
+ }
1639
+
1640
+ if ((focusMode === "WITS" || focusMode === "ALL") && coords.OP_P && coords.OP_A) {
1641
+ const dx = coords.OP_A.x - coords.OP_P.x, dy = coords.OP_A.y - coords.OP_P.y;
1642
+ const extP = { x: coords.OP_P.x - dx * 0.35, y: coords.OP_P.y - dy * 0.35 };
1643
+ const extA = { x: coords.OP_A.x + dx * 0.35, y: coords.OP_A.y + dy * 0.35 };
1644
+ line(extP, extA, "#a855f7", 2.5); // Functional Occlusal Plane
1645
+ if (wits) {
1646
+ line(coords.A, wits.ao, "#a855f7", 2, "3,3");
1647
+ line(coords.B, wits.bo, "#a855f7", 2, "3,3");
1648
+ }
1649
+ }
1650
+ }
1651
+
1652
+ // 3. Ruler Display
1653
+ if (showRuler && coords.RULER_1 && coords.RULER_2) {
1654
+ line(coords.RULER_1, coords.RULER_2, "#06b6d4", 3, "4,3");
1655
+ ["RULER_1", "RULER_2"].forEach((rKey, idx) => {
1656
+ const pt = coords[rKey];
1657
+ const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
1658
+ const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1659
+ c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
1660
+ c.setAttribute("r", 7); c.setAttribute("fill", "#06b6d4");
1661
+ c.setAttribute("stroke", "#0f172a"); c.setAttribute("stroke-width", 2);
1662
+ c.setAttribute("class", "landmark-handle");
1663
+ c.addEventListener("mousedown", (e) => {
1664
+ e.stopPropagation();
1665
+ draggingLm = rKey;
1666
+ c.classList.add("dragging");
1667
+ });
1668
+ g.appendChild(c);
1669
+
1670
+ const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
1671
+ t.setAttribute("x", pt.x + 10); t.setAttribute("y", pt.y + 4);
1672
+ t.setAttribute("class", "landmark-text");
1673
+ t.style.fill = "#22d3ee";
1674
+ t.textContent = idx === 0 ? "0 mm" : "10 mm";
1675
+ g.appendChild(t);
1676
+ svgElem.appendChild(g);
1677
+ });
1678
+ }
1679
+
1680
+ // 4. Landmark Interactive Handles
1681
+ const activeSet = MODE_LANDMARKS[focusMode] || MODE_LANDMARKS.ALL;
1682
+
1683
+ if (showPoints) {
1684
+ for (const [name, pt] of Object.entries(coords)) {
1685
+ if (name === "RULER_1" || name === "RULER_2") continue;
1686
+ if (!activeSet.has(name)) continue;
1687
+
1688
+ const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
1689
+ const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
1690
+ c.setAttribute("cx", pt.x); c.setAttribute("cy", pt.y);
1691
+ c.setAttribute("r", selectedLm === name ? 7.5 : 5.5);
1692
+
1693
+ let handleColor = "#facc15";
1694
+ if (name === "Sn") handleColor = "#ec4899";
1695
+ if (name === "PNS" || name === "ANS") handleColor = "#a3e635";
1696
+ if (name === "OP_A" || name === "OP_P") handleColor = "#a855f7";
1697
+ if (selectedLm === name) handleColor = "#38bdf8";
1698
+
1699
+ c.setAttribute("fill", handleColor);
1700
+ c.setAttribute("stroke", "#090d16");
1701
+ c.setAttribute("stroke-width", 2);
1702
+ c.setAttribute("class", "landmark-handle");
1703
+
1704
+ c.addEventListener("mousedown", (e) => {
1705
+ e.stopPropagation();
1706
+ draggingLm = name;
1707
+ selectedLm = name;
1708
+ document.getElementById("selected-lm-label").innerText = name;
1709
+ c.classList.add("dragging");
1710
+ updateLoupe(pt, name);
1711
+ });
1712
+
1713
+ c.addEventListener("dblclick", (e) => {
1714
+ e.stopPropagation();
1715
+ if (initialAiCoords[name]) {
1716
+ coords[name] = { ...initialAiCoords[name] };
1717
+ notify(`Reset ${name} to initial prediction.`);
1718
+ renderAnalysis();
1719
+ }
1720
+ });
1721
+
1722
+ g.appendChild(c);
1723
+
1724
+ if (showLabels) {
1725
+ const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
1726
+ t.setAttribute("x", pt.x + 8); t.setAttribute("y", pt.y - 4);
1727
+ t.setAttribute("class", "landmark-text");
1728
+ t.textContent = name;
1729
+ g.appendChild(t);
1730
+ }
1731
+
1732
+ svgElem.appendChild(g);
1733
+ }
1734
+ }
1735
+
1736
+ // Calculate ABO Metrics
1737
+ const sna = getAngle(coords.S, coords.N, coords.A);
1738
+ const snb = getAngle(coords.S, coords.N, coords.B);
1739
+ const anb = (sna !== null && snb !== null) ? parseFloat((sna - snb).toFixed(1)) : null;
1740
+ const fma = getLineAngle(coords.Po, coords.Or, coords.Go, coords.Me);
1741
+ const snmp = getLineAngle(coords.S, coords.N, coords.Go, coords.Me);
1742
+ const impa = getLineAngle(coords.LIT, coords.LIA, coords.Go, coords.Me);
1743
+ const u1sn = getLineAngle(coords.UIT, coords.UIA, coords.S, coords.N);
1744
+ const u1na_deg = getLineAngle(coords.UIT, coords.UIA, coords.N, coords.A);
1745
+ const u1na_mm = getPerpDist(coords.UIT, coords.N, coords.A);
1746
+ const l1nb_deg = getLineAngle(coords.LIT, coords.LIA, coords.N, coords.B);
1747
+ const l1nb_mm = getPerpDist(coords.LIT, coords.N, coords.B);
1748
+ const iia = getLineAngle(coords.UIT, coords.UIA, coords.LIT, coords.LIA);
1749
+ const ul_e = getPerpDist(coords.Ls, coords.Pn, coords.Pog_soft);
1750
+ const ll_e = getPerpDist(coords.Li, coords.Pn, coords.Pog_soft);
1751
+
1752
+ // Holdaway Metrics
1753
+ const h_angle = getAngle(coords.N, coords.Pog_soft, coords.Ls);
1754
+ const skel_conv = getPerpDist(coords.A, coords.N, coords.Pog);
1755
+ const nose_prom = getPerpDist(coords.Pn, coords.Ls, coords.Pog_soft);
1756
+ const sn_hline = getPerpDist(coords.Sn, coords.Ls, coords.Pog_soft);
1757
+ const ll_hline = getPerpDist(coords.Li, coords.Ls, coords.Pog_soft);
1758
+ const chin_thick = (coords.Pog && coords.Pog_soft && pxPerMm)
1759
+ ? parseFloat((Math.hypot(coords.Pog_soft.x - coords.Pog.x, coords.Pog_soft.y - coords.Pog.y) / pxPerMm).toFixed(1))
1760
+ : null;
1761
+
1762
+ latestMetrics = {
1763
+ SNA: sna, SNB: snb, ANB: anb, FMA: fma, SNMP: snmp, IMPA: impa,
1764
+ U1SN: u1sn, U1NA_deg: u1na_deg, U1NA_mm: u1na_mm, L1NB_deg: l1nb_deg,
1765
+ L1NB_mm: l1nb_mm, IIA: iia, UL_E: ul_e, LL_E: ll_e,
1766
+ WITS: wits ? wits.distMm : null,
1767
+ H_ANGLE: h_angle, SKEL_CONV: skel_conv, NOSE_PROM: nose_prom,
1768
+ SN_HLINE: sn_hline, LL_HLINE: ll_hline, CHIN_THICK: chin_thick
1769
+ };
1770
+
1771
+ updateClinicalDiagnosis(latestMetrics);
1772
+ populateAboTable(ABO_NORMS, latestMetrics);
1773
+ populateTable("holdaway-rows", HOLDAWAY_NORMS, latestMetrics);
1774
+ populateWitsTable(latestMetrics.WITS);
1775
+ }
1776
+
1777
+ function populateAboTable(normsList, valuesDict) {
1778
+ const tbody = document.getElementById("abo-rows");
1779
+ tbody.innerHTML = "";
1780
+
1781
+ normsList.forEach(metric => {
1782
+ const val = valuesDict[metric.id];
1783
+ let statusHtml = `<span class="pill pill-neutral">-</span>`;
1784
+ let measuredText = "-";
1785
+ let diffText = "-";
1786
+ let diffColor = "var(--text-muted)";
1787
+ let deltaT1Html = "";
1788
+
1789
+ if (val !== null && val !== undefined && !isNaN(val)) {
1790
+ measuredText = `${val.toFixed(1)}${metric.unit}`;
1791
+ const rawDiff = val - metric.norm;
1792
+ const isNormal = Math.abs(rawDiff) <= metric.sd;
1793
+
1794
+ diffText = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${metric.unit}`;
1795
+ diffColor = isNormal ? "var(--status-green)" : "var(--status-red)";
1796
+
1797
+ statusHtml = isNormal
1798
+ ? `<span class="pill pill-normal">Normal</span>`
1799
+ : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High (+)' : 'Low (-)'}</span>`;
1800
+ }
1801
+
1802
+ if (t1Baseline && t1Baseline.metrics && t1Baseline.metrics[metric.id] !== undefined) {
1803
+ const t1Val = t1Baseline.metrics[metric.id];
1804
+ if (t1Val !== null && !isNaN(t1Val) && val !== null && !isNaN(val)) {
1805
+ const dT1 = val - t1Val;
1806
+ deltaT1Html = `<td style="color:#5eead4; font-weight:700; font-family:'JetBrains Mono',monospace;">${dT1 > 0 ? '+' : ''}${dT1.toFixed(1)}${metric.unit}</td>`;
1807
+ } else {
1808
+ deltaT1Html = `<td>-</td>`;
1809
+ }
1810
+ } else if (t1Baseline) {
1811
+ deltaT1Html = `<td>-</td>`;
1812
+ }
1813
+
1814
+ const tr = document.createElement("tr");
1815
+ tr.innerHTML = `
1816
+ <td><span class="metric-name">${metric.name}</span></td>
1817
+ <td><span class="metric-norm">${metric.norm}${metric.unit} ± ${metric.sd}</span></td>
1818
+ <td><span class="metric-val">${measuredText}</span></td>
1819
+ <td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
1820
+ ${deltaT1Html}
1821
+ <td>${statusHtml}</td>
1822
+ `;
1823
+ tbody.appendChild(tr);
1824
+ });
1825
+ }
1826
+
1827
+ function populateTable(elementId, normsList, valuesDict) {
1828
+ const tbody = document.getElementById(elementId);
1829
+ tbody.innerHTML = "";
1830
+
1831
+ normsList.forEach(metric => {
1832
+ const val = valuesDict[metric.id];
1833
+ let statusHtml = `<span class="pill pill-neutral">-</span>`;
1834
+ let measuredText = "-";
1835
+ let diffText = "-";
1836
+ let diffColor = "var(--text-muted)";
1837
+
1838
+ if (val !== null && val !== undefined && !isNaN(val)) {
1839
+ measuredText = `${val.toFixed(1)}${metric.unit}`;
1840
+ const rawDiff = val - metric.norm;
1841
+ const isNormal = Math.abs(rawDiff) <= metric.sd;
1842
+ diffText = `${rawDiff > 0 ? '+' : ''}${rawDiff.toFixed(1)}${metric.unit}`;
1843
+ diffColor = isNormal ? "var(--status-green)" : "var(--status-red)";
1844
+ statusHtml = isNormal
1845
+ ? `<span class="pill pill-normal">Normal</span>`
1846
+ : `<span class="pill pill-deviated">${rawDiff > 0 ? 'High (+)' : 'Low (-)'}</span>`;
1847
+ }
1848
+
1849
+ const tr = document.createElement("tr");
1850
+ tr.innerHTML = `
1851
+ <td><span class="metric-name">${metric.name}</span></td>
1852
+ <td><span class="metric-norm">${metric.norm}${metric.unit} ± ${metric.sd}</span></td>
1853
+ <td><span class="metric-val">${measuredText}</span></td>
1854
+ <td><span class="metric-diff" style="color: ${diffColor};">${diffText}</span></td>
1855
+ <td>${statusHtml}</td>
1856
+ `;
1857
+ tbody.appendChild(tr);
1858
+ });
1859
+ }
1860
+
1861
+ function populateWitsTable(val) {
1862
+ const tbody = document.getElementById("wits-rows");
1863
+ tbody.innerHTML = "";
1864
+ if (val === null || val === undefined || isNaN(val)) {
1865
+ tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 10px;">Awaiting occlusal plane tracing...</td></tr>`;
1866
+ return;
1867
+ }
1868
+
1869
+ const diffFromZero = val.toFixed(1);
1870
+ let statusHtml = `<span class="pill pill-normal">Class I</span>`;
1871
+ let diffColor = "var(--status-green)";
1872
+
1873
+ if (val > 1.0) {
1874
+ statusHtml = `<span class="pill pill-deviated">Class II Jaw Base</span>`;
1875
+ diffColor = "var(--status-red)";
1876
+ } else if (val < -2.0) {
1877
+ statusHtml = `<span class="pill pill-deviated">Class III Jaw Base</span>`;
1878
+ diffColor = "var(--status-red)";
1879
+ }
1880
+
1881
+ const tr = document.createElement("tr");
1882
+ tr.innerHTML = `
1883
+ <td><span class="metric-name">Wits (AO to BO)</span></td>
1884
+ <td><span class="metric-norm">-1.0 to 0.0 mm (±1.0)</span></td>
1885
+ <td><span class="metric-val" style="color: #c084fc;">${val > 0 ? '+' : ''}${diffFromZero} mm</span></td>
1886
+ <td><span class="metric-diff" style="color: ${diffColor};">${val > 0 ? '+' : ''}${diffFromZero} mm</span></td>
1887
+ <td>${statusHtml}</td>
1888
+ `;
1889
+ tbody.appendChild(tr);
1890
+ }
1891
+
1892
+ // -------------------------------------------------------------
1893
+ // 14. EMR Copy & CSV Export
1894
+ // -------------------------------------------------------------
1895
+ document.getElementById("btn-copy-note").addEventListener("click", () => {
1896
+ if (!latestMetrics.SNA) {
1897
+ notify("Trace a radiograph first before copying notes.");
1898
+ return;
1899
+ }
1900
+ const ptName = document.getElementById("pt-name").value || "Patient";
1901
+ const m = latestMetrics;
1902
+ const note = [
1903
+ `ORTHODONTIC CEPHALOMETRIC REPORT — ${ptName}`,
1904
+ `Diagnosis: ${latestDiagnosis.headline}`,
1905
+ `• Sagittal: ${latestDiagnosis.sagittal} | SNA: ${m.SNA}°, SNB: ${m.SNB}°, ANB: ${m.ANB}°, Wits: ${m.WITS ?? '-'} mm`,
1906
+ `• Vertical: ${latestDiagnosis.vertical} | FMA: ${m.FMA}°, SN-MP: ${m.SNMP}°`,
1907
+ `• 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}°`,
1908
+ `• Soft Tissue & Maturation: ${latestDiagnosis.soft} | UL to E-Line: ${m.UL_E}mm, LL to E-Line: ${m.LL_E}mm, Holdaway H-Angle: ${m.H_ANGLE}°`
1909
+ ].join("\n");
1910
+
1911
+ // Fallback copy logic for iframes
1912
+ const ta = document.createElement("textarea");
1913
+ ta.value = note;
1914
+ document.body.appendChild(ta);
1915
+ ta.select();
1916
+ try {
1917
+ document.execCommand("copy");
1918
+ notify("EMR clinical note copied to clipboard.");
1919
+ } catch (err) {
1920
+ notify("Clipboard write failed.");
1921
+ }
1922
+ document.body.removeChild(ta);
1923
+ });
1924
+
1925
+ document.getElementById("btn-export-csv").addEventListener("click", () => {
1926
+ if (!latestMetrics.SNA) {
1927
+ notify("Upload and trace a cephalogram first.");
1928
+ return;
1929
+ }
1930
+ const ptName = document.getElementById("pt-name").value || "Unnamed";
1931
+ const ptChart = document.getElementById("pt-chart").value || "N/A";
1932
+ const ptDate = document.getElementById("pt-date").value || "";
1933
+
1934
+ let csv = "Patient Name,Chart ID,Date,Diagnosis,CVM Stage,Category,Parameter,Standard Norm,Measured Value,Difference,Unit,Status\n";
1935
+
1936
+ const addRows = (category, list) => {
1937
+ list.forEach(m => {
1938
+ const val = latestMetrics[m.id];
1939
+ if (val === null || val === undefined || isNaN(val)) return;
1940
+ const diff = (val - m.norm).toFixed(1);
1941
+ const status = Math.abs(val - m.norm) <= m.sd ? "Normal" : (val > m.norm ? "High" : "Low");
1942
+ csv += `"${ptName}","${ptChart}","${ptDate}","${latestDiagnosis.headline}","${cvmStage}","${category}","${m.name}","${m.norm} +/- ${m.sd}",${val.toFixed(1)},${diff > 0 ? '+' + diff : diff},"${m.unit}","${status}"\n`;
1943
+ });
1944
+ };
1945
+
1946
+ addRows("ABO", ABO_NORMS);
1947
+ if (latestMetrics.WITS !== null && !isNaN(latestMetrics.WITS)) {
1948
+ const w = latestMetrics.WITS;
1949
+ const wStat = w > 1.0 ? "Class II" : (w < -2.0 ? "Class III" : "Class I");
1950
+ csv += `"${ptName}","${ptChart}","${ptDate}","${latestDiagnosis.headline}","${cvmStage}","Wits","Wits Appraisal (AO-BO)","0.0 +/- 1.0",${w.toFixed(1)},${w.toFixed(1)},"mm","${wStat}"\n`;
1951
+ }
1952
+ addRows("Holdaway", HOLDAWAY_NORMS);
1953
+
1954
+ const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
1955
+ const url = URL.createObjectURL(blob);
1956
+ const a = document.createElement("a");
1957
+ a.href = url;
1958
+ a.download = `Ceph_Analysis_${ptName.replace(/\s+/g, '_')}_${ptDate || 'export'}.csv`;
1959
+ a.click();
1960
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
1961
+ notify("CSV spreadsheet exported.");
1962
+ });
1963
+ </script>
1964
+ </body>
1965
+ </html>