File size: 116,159 Bytes
9146d63
d46bde8
9146d63
 
 
 
 
d46bde8
 
9146d63
d46bde8
 
9146d63
 
 
 
 
 
d46bde8
 
 
9146d63
 
d46bde8
5c7853d
d46bde8
bd8eeef
9146d63
bd8eeef
d46bde8
5c7853d
bd8eeef
d46bde8
5c7853d
0980d2c
 
d46bde8
5c7853d
bd8eeef
0980d2c
 
 
 
 
 
 
9146d63
2b2215e
 
9146d63
2b2215e
 
337bb8d
 
 
 
2b2215e
59bb2ab
 
05dc83b
59bb2ab
 
d46bde8
5c7853d
bd8eeef
9146d63
d46bde8
 
9146d63
 
d46bde8
 
bd8eeef
d46bde8
9146d63
d46bde8
 
 
 
9146d63
 
5c7853d
 
 
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
e12462e
 
d46bde8
e12462e
 
 
d46bde8
e12462e
 
 
 
 
 
 
 
 
 
d46bde8
 
e12462e
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
 
 
 
bd8eeef
 
d46bde8
 
 
9146d63
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
9146d63
 
d46bde8
 
9146d63
 
d46bde8
 
9146d63
 
d46bde8
 
9146d63
 
d46bde8
 
9146d63
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
 
 
9146d63
 
 
d46bde8
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
9146d63
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd8eeef
 
d46bde8
 
 
 
 
bd8eeef
 
d46bde8
5c7853d
 
d46bde8
 
5c7853d
d46bde8
 
5c7853d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
bd8eeef
d46bde8
 
5c7853d
 
 
 
 
 
 
 
 
 
 
2b2215e
 
5c7853d
 
 
 
 
 
 
 
 
 
2b2215e
 
 
 
 
 
 
 
 
 
 
 
 
337bb8d
2b2215e
 
 
 
 
337bb8d
 
 
 
2b2215e
 
 
9d595d2
 
 
 
59bb2ab
 
 
 
 
 
 
 
 
 
 
 
 
9d595d2
 
 
59bb2ab
 
 
 
 
 
 
 
 
 
 
9d595d2
59bb2ab
 
9d595d2
 
05dc83b
 
 
 
 
 
 
 
 
9d595d2
59bb2ab
 
 
9d595d2
 
d46bde8
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
 
 
 
 
 
5c7853d
d46bde8
5c7853d
d46bde8
 
 
 
bd8eeef
5c7853d
 
 
 
d46bde8
 
 
 
 
5c7853d
d46bde8
5c7853d
d46bde8
 
 
 
bd8eeef
5c7853d
 
 
 
d46bde8
 
 
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
bd8eeef
d46bde8
 
bd8eeef
 
 
d46bde8
 
 
 
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd8eeef
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d595d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59bb2ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0980d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
9146d63
d46bde8
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
 
 
 
d46bde8
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
337bb8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59bb2ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
9146d63
 
d46bde8
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd8eeef
d46bde8
 
bd8eeef
d46bde8
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd8eeef
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d595d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
0980d2c
9146d63
 
 
d46bde8
 
 
 
 
 
0980d2c
337bb8d
59bb2ab
 
d46bde8
 
337bb8d
59bb2ab
 
0980d2c
d46bde8
0980d2c
d46bde8
 
 
 
 
337bb8d
59bb2ab
 
d46bde8
 
2b2215e
d46bde8
 
2b2215e
d46bde8
 
 
 
 
 
 
 
 
 
5c7853d
d46bde8
 
 
 
 
5c7853d
2b2215e
d46bde8
 
2b2215e
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2215e
9146d63
 
 
 
 
 
d46bde8
 
 
9146d63
 
d46bde8
 
 
5c7853d
 
 
 
 
 
 
9d595d2
5c7853d
 
 
 
337bb8d
 
9d595d2
 
 
 
 
337bb8d
5c7853d
9d595d2
 
 
 
 
 
 
 
 
 
 
 
5c7853d
 
 
 
 
 
 
 
 
 
0980d2c
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c7853d
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
d46bde8
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2215e
337bb8d
 
 
 
 
2b2215e
 
337bb8d
 
2b2215e
 
 
 
d46bde8
 
 
 
5c7853d
9146d63
d46bde8
 
 
5c7853d
d46bde8
 
 
 
5c7853d
d46bde8
 
 
 
5c7853d
d46bde8
 
5c7853d
 
 
d46bde8
0980d2c
 
 
 
 
d46bde8
 
 
5c7853d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
5c7853d
 
 
 
337bb8d
 
 
 
 
 
 
 
 
 
 
d46bde8
 
5c7853d
d46bde8
bd8eeef
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
5c7853d
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd8eeef
9146d63
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
0980d2c
59bb2ab
05dc83b
0980d2c
d46bde8
 
59bb2ab
 
 
 
 
 
 
05dc83b
59bb2ab
05dc83b
59bb2ab
 
05dc83b
 
 
 
d46bde8
9d595d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59bb2ab
 
 
9d595d2
 
d46bde8
 
 
 
 
0980d2c
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
5c7853d
 
 
d46bde8
0980d2c
 
 
 
 
 
 
 
 
 
 
 
5c7853d
 
 
 
 
 
 
 
 
0980d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9146d63
0980d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2215e
0980d2c
2b2215e
0980d2c
 
 
2b2215e
0980d2c
2b2215e
 
59bb2ab
2b2215e
 
59bb2ab
2b2215e
 
 
 
 
 
 
 
 
 
 
 
 
9d595d2
 
2b2215e
0980d2c
 
 
 
 
 
 
 
 
5c7853d
9d595d2
 
 
59bb2ab
9d595d2
 
 
 
 
 
59bb2ab
9d595d2
 
 
 
 
 
 
 
 
 
59bb2ab
9d595d2
 
5c7853d
 
 
 
0980d2c
 
 
 
5c7853d
 
 
 
 
 
 
 
 
 
 
 
d46bde8
5c7853d
2b2215e
 
 
9d595d2
2b2215e
9d595d2
 
59bb2ab
9d595d2
 
2b2215e
59bb2ab
 
 
 
 
 
2b2215e
 
 
 
 
 
 
 
 
 
9d595d2
2b2215e
59bb2ab
 
 
 
 
2b2215e
d46bde8
 
 
5c7853d
d46bde8
 
 
 
5c7853d
d46bde8
 
 
 
 
 
0980d2c
 
 
 
 
 
 
 
 
 
 
d46bde8
5c7853d
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c7853d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
 
 
 
5c7853d
 
 
d46bde8
 
 
9146d63
d46bde8
 
 
 
5c7853d
d46bde8
 
5c7853d
d46bde8
 
 
59bb2ab
 
05dc83b
59bb2ab
 
 
d46bde8
 
 
 
9146d63
 
 
 
 
 
 
 
 
d46bde8
 
 
 
 
 
 
 
9146d63
d46bde8
 
 
 
 
 
 
 
 
 
 
9146d63
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
#!/usr/bin/env python3
"""6-String Optimizer HF Space — mystery shell + optimize/spectrum/physics-audio."""

from __future__ import annotations

import logging
import os
import re
import time
import traceback
from collections.abc import Callable, Iterator
from pathlib import Path

import gradio as gr
import plotly.graph_objects as go

from demo_core import (
    BOOT_QUOTE_STRING,
    BURST_BOOSTS,
    CLAIMS_MD,
    FIGURES_INTRO_MD,
    GITHUB_URL,
    HF_SPACE_URL,
    ONBOARDING_MD,
    OPTIMIZATION_PRESETS,
    PHYSICS_AUDIO_URL,
    PROG_ACTIONS,
    QVPIC_URL,
    SAMPLE_GUITAR_NOTE,
    SIMULATION_BANNER_MD,
    SLIDER_TOOLTIPS,
    STRING_NAMES,
    TERM_KEY_ACTIONS,
    THEORY_MD,
    THEORY_KATEX_HTML,
    KATEX_CDN,
    WALLPAPER_URL,
    WHAT_IS_THIS_MD,
    WINDOWS,
    export_optimization_plots,
    run_comparison_stream,
    synthesize_modal_comparison,
    tension_calculator_table,
    tension_single_string,
    STANDARD_TUNING,
    DEFAULT_SCALE_LENGTH_IN,
    default_run_params,
    friendly_error,
    format_eta_status,
    get_build_label,
    get_run_mode_params,
    estimate_runtime_sec,
    INTRO_WALKTHROUGH_HTML,
    KNOWN_LIMITATIONS_BODY,
    LOCAL_RUN_MD,
    PlotStreamConfig,
    RUN_MODES,
    TRAJECTORY_VIEW_CHOICES,
    WEBGL_PROBE_JS,
    default_trajectory_view,
    resolve_trajectory_mode,
    webgl_status_markdown,
    get_overview_composite_path,
    get_preset_params,
    get_sample_guitar_path,
    is_hf_space,
    render_smith_chart_preview,
    run_analysis,
    run_optimization_stream,
    analyze_audio_signal,
    terminal_directory_help,
    terminal_figures_index,
    terminal_guided_onboarding,
    terminal_keypad_map,
    terminal_optimizer_help,
    terminal_physics_overview,
    terminal_probe_scope,
    terminal_results_snapshot,
    terminal_string_catalog,
)

STRING_TABLE_MD = (
    "### Six-string hierarchy\n\n"
    "| String | Stagnation window | Burst boost | Role |\n"
    "|--------|-------------------|-------------|------|\n"
    + "\n".join(
        f"| **{n}** | {w} steps | {b:.2f}× | Monitors plateau · fires macro-burst |"
        for n, w, b in zip(STRING_NAMES, WINDOWS, BURST_BOOSTS)
    )
    + "\n\nVU meters in **OPTIMIZE** and **STRINGS** light up when a layer's tension triggers a burst."
)


def _figures_grid_html() -> str:
    """Physics-audio reference figures on the Figures page."""
    overview = get_overview_composite_path()
    smith = render_smith_chart_preview()
    overview_src = overview.as_uri() if overview.is_file() else WALLPAPER_URL
    smith_src = Path(smith).as_uri()
    items = (
        (overview_src, "Reconstruction pyramid overview"),
        (smith_src, "Smith chart Γ-mismatch preview"),
        (WALLPAPER_URL, "Physics-audio composite (GitHub)"),
        (f"{GITHUB_URL}/tree/main/physics_audio/training_evaluation/viz.py", "viz.py source"),
    )
    imgs = "".join(
        f'<figure class="vqc-screencast-video-wrap">'
        f'<img class="vqc-screencast-video" src="{url}" alt="{label}" loading="lazy" />'
        f'<figcaption>{label}</figcaption></figure>'
        for url, label in items[:2]
    )
    return f'<div class="vqc-screencast-wrap">{imgs}</div>'


def _figures_links_md() -> str:
    return (
        f"[Overview composite]({WALLPAPER_URL}) · "
        f"[Physics audio]({PHYSICS_AUDIO_URL}) · "
        f"[viz.py]({GITHUB_URL}/blob/main/physics_audio/training_evaluation/viz.py) — "
        "full Smith chart + pyramid plots run locally via `run_real_audio.py`."
    )


_DEFAULTS = default_run_params()

logger = logging.getLogger(__name__)


def _patch_gradio_client_bool_schema() -> None:
    """Avoid gradio_client crash when JSON schema contains bare bool nodes."""
    try:
        from gradio_client import utils as client_utils

        if getattr(client_utils, "_vqc_bool_patch", False):
            return

        orig_get_type = client_utils.get_type

        def get_type(schema):  # noqa: ANN001
            if isinstance(schema, bool):
                return "boolean"
            return orig_get_type(schema)

        client_utils.get_type = get_type
        client_utils._vqc_bool_patch = True
        logger.info("Patched gradio_client bool JSON-schema handling")
    except Exception:
        logger.warning("Could not patch gradio_client", exc_info=True)


_patch_gradio_client_bool_schema()

_VQC_ACCENT = "#c9a227"  # mystery gold — primary accent
_VQC_HF_RUNNING = "#1ed760"
_VQC_FIELD_FILL = "rgba(18, 10, 28, 0.52)"
_VQC_TAB_GREEN_BG = "#1a3d2a"
_VQC_TAB_GREEN_BG_HOVER = "#1f4d34"
_VQC_TAB_GREEN_BORDER = "#33ff66"
_VQC_TAB_GREEN_TEXT = "#86efac"
_VQC_TAB_GREEN_TEXT_HOVER = "#bbf7d0"
_VQC_TAB_ORANGE_BG = "#3d2a5c"
_VQC_TAB_ORANGE_BORDER = "#6a4c93"
_VQC_TAB_ORANGE_TEXT = "#d4b8ff"
_VQC_MATRIX_GREEN = "#33ff66"
_VQC_MATRIX_GREEN_BG = "#0a1f12"
_VQC_LOGO_GOLD = "#FFB000"
_VQC_HOME_KEY_BG = "#000000"

FIGURES_INTRO_MD_LOCAL = FIGURES_INTRO_MD

OPTICS_LOGO_HTML = """
<div class="vqc-optics-logo" role="img" aria-label="6-String Signal Analyzer">
  <span class="vqc-optics-brand">6-STRING</span>
  <span class="vqc-optics-panel-title">Signal Analyzer · S³ Burst</span>
  <span class="vqc-optics-subtitle">OPTIMIZE · SPECTRUM · PHYSICS-AUDIO · CLI</span>
</div>
"""

SIGNAL_SCANNER_HTML = f"""
<div class="myst-signal-scan" role="img" aria-label="Phosphor signal scan">
  <div class="myst-signal-scanlines" aria-hidden="true"></div>
  <div class="myst-signal-beam" aria-hidden="true"></div>
  <pre class="myst-signal-body">PHOSPHOR SIGNAL SCAN — SIX-STRING BURST
{'─' * 72}
High E → Low E   windows 400 → 2400
Rosenbrock S³    stereographic trajectory
Demo guitar G3   {SAMPLE_GUITAR_NOTE}
Smith chart Γ    physics-audio mismatch jumps
{'─' * 72}
▸ OPTIMIZE tab → ▶ RUN OPTIMIZATION
▸ SPECTRUM tab → ▶ DEMO GUITAR (G3)
{GITHUB_URL}
{'─' * 72}
press any keypad to exit</pre>
</div>
"""

_OPTICS_TERM_BAR = "─" * 48
_OPTICS_TERM_CHAR_DELAY_S = 0.014
_OPTICS_TERM_NEWLINE_DELAY_S = 0.048
_OPTICS_TERM_UPLINK_DELAY_S = 0.22
_OPTICS_TERM_CURSOR = "▌"
_OPTICS_TERM_RELEASE_DELAY_S = 0.25
_BOOT_QUOTE_CHAR_DELAY_S = 0.1
_BOOT_POST_QUOTE_DELAY_S = 3.0
_BOOT_DOT_INTERVAL_S = 0.5
_BOOT_DOT_COUNT = 6
_BOOT_TERM_LINES = 14
_BOOT_TERM_COLS = 56


def _strip_md_plain(text: str) -> str:
    """Flatten markdown blockquotes and emphasis for terminal readout."""
    plain = re.sub(r"^>\s*", "", text.strip(), flags=re.MULTILINE)
    plain = re.sub(r"\*\*([^*]+)\*\*", r"\1", plain)
    plain = re.sub(r"`([^`]+)`", r"\1", plain)
    return plain.strip()


def _optics_terminal_frame(title: str, body: str) -> str:
    return f"{title}\n{_OPTICS_TERM_BAR}\n{body}"


TERM_KEYPAD_PROG_COLS = 12
TERM_KEYPAD_PROG_ROWS = 2
TERM_KEYPAD_COUNT = TERM_KEYPAD_PROG_COLS * TERM_KEYPAD_PROG_ROWS
TERM_KEYPAD_DEFINED: dict[int, str] = {
    index: action for index, (action, _desc) in TERM_KEY_ACTIONS.items()
}
TERM_KEYPAD_HOME_KEY = "key01"
TERM_KEYPAD_DESCRIPTIONS: dict[int, str] = {
    index: desc for index, (_action, desc) in TERM_KEY_ACTIONS.items()
}
TERM_MENU_ACTIONS: tuple[str, ...] = (
    "home",
    "status",
    "scope",
    "directory",
    "results",
    "build",
    "help",
    "scan",
)
TERM_UI_MENU = "menu"
TERM_UI_PAGE = "page"
TERM_NAV_KEYS: tuple[str, ...] = (
    "dpad_select",
    "dpad_up",
    "dpad_down",
    "dpad_left",
    "dpad_right",
    "clear",
)
TERM_DPAD_HOLD_KEYS: tuple[str, ...] = (
    "dpad_select",
    "dpad_up",
    "dpad_down",
    "dpad_left",
    "dpad_right",
)
TERM_NAV_DEFINED: dict[str, str] = {
    "dpad_select": "Enter — confirm menu item",
    "dpad_up": "Up — previous menu item",
    "dpad_down": "Down — next menu item",
    "dpad_left": "Left — previous menu item",
    "dpad_right": "Right — next menu item",
    "clear": "Clear — blank display",
}
TERM_KEYPAD_CONTROL_ORDER: tuple[str, ...] = (
    *TERM_NAV_KEYS,
    *(f"key{i:02d}" for i in range(1, TERM_KEYPAD_COUNT + 1)),
)


def _optics_assigned_keypad_lines() -> str:
    """Only keys with real functions — omit latch-only / unassigned slots."""
    lines = []
    for index in sorted(TERM_KEYPAD_DEFINED):
        tag = "01 Home" if index == 1 else f"{index:02d}"
        lines.append(f"  [{tag}]  {TERM_KEYPAD_DESCRIPTIONS[index]}")
    for nav_key in TERM_NAV_KEYS:
        if nav_key in TERM_NAV_DEFINED:
            tag = "CLR" if nav_key == "clear" else nav_key.removeprefix("dpad_").upper()
            lines.append(f"  [{tag}]  {TERM_NAV_DEFINED[nav_key]}")
    return "\n".join(lines)


def _optics_terminal_home() -> str:
    return _optics_terminal_frame("PROGRAMMABLE KEYPAD", terminal_keypad_map())


def _default_term_ui_state() -> dict:
    return {"mode": TERM_UI_MENU, "index": 0, "scan": False}


def _optics_terminal_menu(menu_index: int) -> str:
    lines = [
        "▲▼ ◀▶ move highlight · enter confirm · 01 Home",
        "",
    ]
    for index, (_action, keypad_key, label, _stream) in enumerate(_term_menu_items()):
        mark = "▶" if index == menu_index else " "
        lines.append(f"{keypad_key:02d} --- [{mark}] {label}")
    return _optics_terminal_frame("SELECTION MENU", "\n".join(lines))


def _term_menu_label(action: str) -> str:
    labels = {
        "home": "Home — Keypad Map",
        "status": "Status — Live Constants",
        "scope": "Scope — Space vs Local Suite",
        "directory": "Directory — Repo Layout",
        "results": "Results — Six-String Snapshot",
        "build": "Build — Deploy Stamp",
        "help": "Help — D-pad Navigation",
        "scan": "Scan — Phosphor Display",
    }
    return labels.get(action, action)


def _term_menu_keypad_index(action: str) -> int:
    for index, (key, _desc) in TERM_KEY_ACTIONS.items():
        if key == action:
            return index
    return 1


def _term_menu_items() -> tuple[tuple[str, int, str, Callable[[], Iterator[str]]], ...]:
    items = []
    for action in TERM_MENU_ACTIONS:
        stream_fn = TERM_KEYPAD_STREAMERS.get(action)
        if stream_fn is None:
            continue
        items.append(
            (
                action,
                _term_menu_keypad_index(action),
                _term_menu_label(action),
                stream_fn,
            )
        )
    return tuple(items)


def _term_menu_index_for_action(action: str) -> int:
    for index, (key, _keypad, _label, _stream) in enumerate(_term_menu_items()):
        if key == action:
            return index
    return 0


def _term_menu_step(menu_index: int, delta: int) -> int:
    count = len(_term_menu_items())
    return (menu_index + delta) % count


def _optics_terminal_status() -> str:
    on_hf = is_hf_space()
    env = "Hugging Face Space" if on_hf else "Local Gradio"
    return _optics_terminal_frame(
        "SYSTEM STATUS",
        "\n".join(
            [
                f"Environment : {env}",
                f"Space       : {HF_SPACE_URL}",
                f"Steps (HF)  : {_DEFAULTS['total_steps']:,}",
                f"Demo guitar : {get_sample_guitar_path().name}",
                "Pipeline    : S³ optimize → spectrum → Smith chart viz",
                f"Physics     : {PHYSICS_AUDIO_URL}",
                f"Template    : mystery shell · qvpic signal style",
                "",
                "05 Results · 09 Strings · 10 Physics · Run below.",
            ]
        ),
    )


def _optics_terminal_scope() -> str:
    return _optics_terminal_frame("PROBE SCOPE", terminal_probe_scope())


def _optics_terminal_directory() -> str:
    return _optics_terminal_frame("REPO DIRECTORY", terminal_directory_help())


def _optics_terminal_results() -> str:
    return _optics_terminal_frame("RESULTS SNAPSHOT", terminal_results_snapshot())


def _optics_terminal_strings() -> str:
    return _optics_terminal_frame("STRING CATALOG", terminal_string_catalog())


def _optics_terminal_physics() -> str:
    return _optics_terminal_frame("PHYSICS AUDIO", terminal_physics_overview())


def _optics_terminal_tour() -> str:
    return _optics_terminal_frame("GUIDED TOUR", terminal_guided_onboarding())


def _optics_terminal_figures() -> str:
    return _optics_terminal_frame("FIGURES INDEX", terminal_figures_index())


def _optics_terminal_build() -> str:
    build = get_build_label().replace("`", "")
    return _optics_terminal_frame(
        "BUILD / LAST UPDATED",
        "\n".join(
            [
                build,
                "",
                "Mystery shell + 6-string optimizer core.",
                f"Repo: {GITHUB_URL}",
                f"Space: {HF_SPACE_URL}",
            ]
        ),
    )


def _optics_terminal_help() -> str:
    return _optics_terminal_frame("KEYPAD REFERENCE", terminal_optimizer_help())


def _stream_optics_terminal_text(full_text: str) -> Iterator[str]:
    """Reveal terminal text one character at a time — typewriter / uplink effect."""
    shown = ""
    for ch in full_text:
        shown += ch
        yield shown + _OPTICS_TERM_CURSOR
        time.sleep(_OPTICS_TERM_NEWLINE_DELAY_S if ch == "\n" else _OPTICS_TERM_CHAR_DELAY_S)
    yield shown


def _optics_terminal_uplink_banner(mode: str) -> str:
    stamp = time.strftime("%H:%M:%S", time.gmtime())
    return f"> UPLINK {mode.upper()} @ {stamp} UTC…\n"


def _optics_terminal_stream(builder: Callable[[], str], *, mode: str) -> Iterator[str]:
    """Stream a keyed readout: uplink banner, then body character-by-character."""
    banner = _optics_terminal_uplink_banner(mode)
    yield banner + _OPTICS_TERM_CURSOR
    time.sleep(_OPTICS_TERM_UPLINK_DELAY_S)
    yield from _stream_optics_terminal_text(banner + builder())


def _stream_optics_terminal_home() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_home, mode="home")


def _stream_optics_terminal_status() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_status, mode="status")


def _stream_optics_terminal_scope() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_scope, mode="scope")


def _stream_optics_terminal_directory() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_directory, mode="directory")


def _stream_optics_terminal_results() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_results, mode="results")


def _stream_optics_terminal_strings() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_strings, mode="strings")


def _stream_optics_terminal_physics() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_physics, mode="physics")


def _stream_optics_terminal_tour() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_tour, mode="tour")


def _stream_optics_terminal_figures() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_figures, mode="figures")


def _stream_scan_stub() -> Iterator[str]:
    """Menu placeholder — real scan uses CSS toggle via key 08 / d-pad."""
    return iter(())


def _stream_optics_terminal_build() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_build, mode="build")


def _stream_optics_terminal_help() -> Iterator[str]:
    yield from _optics_terminal_stream(_optics_terminal_help, mode="help")


def _stream_optics_terminal_menu(menu_index: int = 0) -> Iterator[str]:
    yield from _optics_terminal_stream(
        lambda: _optics_terminal_menu(menu_index),
        mode="menu",
    )


def _stream_optics_terminal_clear(current: str) -> Iterator[str]:
    """Erase display in paced chunks — inverse of the typewriter feed."""
    text = current or ""
    if not text:
        yield ""
        return
    chunk = max(1, len(text) // 36)
    for end in range(len(text), -1, -chunk):
        yield text[:end] + (_OPTICS_TERM_CURSOR if end else "")
        time.sleep(0.01)
    yield ""


TERM_KEYPAD_STREAMERS: dict[str, Callable[[], Iterator[str]]] = {}


def _term_key_id(index: int) -> str:
    return f"key{index:02d}"


def _term_keypad_label(index: int) -> str:
    """Home key is '01 Home'; 08 shows matrix glyph hint."""
    if index == 1:
        return "01 Home"
    if index == 8:
        return "08~"
    return f"{index:02d}"


def _term_key_is_defined_prog(key: str) -> bool:
    """True for assigned prog keys (02–24) that have a real function."""
    for index in TERM_KEYPAD_DEFINED:
        if index == 1:
            continue
        if _term_key_id(index) == key:
            return True
    return False


def _term_key_btn_classes(key: str, active: str) -> list[str]:
    """Black/white idle caps; matrix-green latch on active keys (never home)."""
    classes = ["vqc-optics-key"]
    if key in TERM_NAV_KEYS:
        classes.append("vqc-optics-dpad-key")
    if key == TERM_KEYPAD_HOME_KEY:
        classes.append("vqc-optics-key-home")
    elif key.startswith("dpad_"):
        classes.append("vqc-optics-key-dpad")
    if key == "clear":
        classes.append("vqc-optics-key-clear")
    if _term_key_is_defined_prog(key):
        classes.append("vqc-optics-key-defined")
    if key == active and key != TERM_KEYPAD_HOME_KEY:
        classes.append("active")
    return classes


def _term_keypad_btn_updates(active: str) -> tuple:
    return tuple(
        gr.update(elem_classes=_term_key_btn_classes(key_id, active))
        for key_id in TERM_KEYPAD_CONTROL_ORDER
    )


def _term_keypad_outputs(terminal_text: str, active: str, ui_state: dict | None = None) -> tuple:
    state = _default_term_ui_state() if ui_state is None else ui_state
    scanning = bool(state.get("scan"))
    return (
        gr.update(
            value=terminal_text,
            visible=not scanning,
            elem_classes=["vqc-optics-terminal-wrap", "vqc-optics-terminal"],
        ),
        gr.update(visible=scanning),
        *_term_keypad_btn_updates(active),
        active,
        state,
    )


def _term_yield_stream_then_release(
    stream: Iterator[str],
    *,
    active: str,
    ui_state: dict,
    release_delay: float | None = None,
) -> Iterator[tuple]:
    """Stream terminal text, latch while typing, release latch after a short pause."""
    delay = _OPTICS_TERM_RELEASE_DELAY_S if release_delay is None else release_delay
    last_partial = ""
    for partial in stream:
        last_partial = partial
        yield _term_keypad_outputs(partial, active, ui_state)
    time.sleep(delay)
    yield _term_keypad_outputs(last_partial, "", ui_state)


def _term_stream_with_latch(
    stream_fn: Callable[[], Iterator[str]],
    *,
    active: str,
    ui_state: dict,
) -> Iterator[tuple]:
    """Stream terminal text and latch matrix-green active state on the pressed key."""
    yield from _term_yield_stream_then_release(stream_fn(), active=active, ui_state=ui_state)


def _make_term_stream_click(
    active_key: str,
    stream_fn: Callable[[], Iterator[str]],
    *,
    menu_action: str | None = None,
):
    def handler(ui_state: dict) -> Iterator[tuple]:
        state = dict(ui_state) if ui_state else _default_term_ui_state()
        if menu_action is not None:
            state.update(
                {
                    "mode": TERM_UI_PAGE,
                    "index": _term_menu_index_for_action(menu_action),
                    "scan": menu_action == "scan",
                }
            )
        else:
            state["scan"] = False
        yield from _term_stream_with_latch(stream_fn, active=active_key, ui_state=state)

    return handler


def _make_term_clear_click(active_key: str):
    def handler(current: str, ui_state: dict) -> Iterator[tuple]:
        state = dict(ui_state) if ui_state else _default_term_ui_state()
        state["scan"] = False
        yield from _term_yield_stream_then_release(
            _stream_optics_terminal_clear(current),
            active=active_key,
            ui_state=state,
        )

    return handler


def _make_term_momentary_click(active_key: str, *, release_delay: float):
    """Brief latch flash — momentary, no maintained state."""

    def handler(current: str, ui_state: dict) -> Iterator[tuple]:
        state = dict(ui_state) if ui_state else _default_term_ui_state()
        yield _term_keypad_outputs(current, active_key, state)
        time.sleep(release_delay)
        yield _term_keypad_outputs(current, "", state)

    return handler


def _make_term_dpad_click(active_key: str):
    """D-pad click — navigate menu, confirm with SEL, brief matrix-green latch."""

    def handler(_current: str, ui_state: dict) -> Iterator[tuple]:
        state = dict(ui_state) if ui_state else _default_term_ui_state()
        mode = state.get("mode", TERM_UI_MENU)
        menu_index = int(state.get("index", 0))
        nav_delta = {
            "dpad_up": -1,
            "dpad_left": -1,
            "dpad_down": 1,
            "dpad_right": 1,
        }

        if active_key in nav_delta:
            if mode == TERM_UI_PAGE:
                menu_state = {"mode": TERM_UI_MENU, "index": menu_index, "scan": False}
                text = _optics_terminal_menu(menu_index)
            else:
                new_index = _term_menu_step(menu_index, nav_delta[active_key])
                menu_state = {"mode": TERM_UI_MENU, "index": new_index, "scan": False}
                text = _optics_terminal_menu(new_index)
            yield _term_keypad_outputs(text, active_key, menu_state)
            time.sleep(_OPTICS_TERM_RELEASE_DELAY_S)
            yield _term_keypad_outputs(text, "", menu_state)
            return

        if active_key == "dpad_select":
            if mode == TERM_UI_MENU:
                action, _keypad, _label, stream_fn = _term_menu_items()[menu_index]
                if action == "scan":
                    page_state = {
                        "mode": TERM_UI_PAGE,
                        "index": menu_index,
                        "scan": True,
                    }
                    yield _term_keypad_outputs("", "dpad_select", page_state)
                    time.sleep(_OPTICS_TERM_RELEASE_DELAY_S)
                    yield _term_keypad_outputs("", "", page_state)
                    return
                page_state = {
                    "mode": TERM_UI_PAGE,
                    "index": menu_index,
                    "scan": False,
                }
                yield from _term_yield_stream_then_release(
                    stream_fn(),
                    active="dpad_select",
                    ui_state=page_state,
                )
                return
            menu_state = {"mode": TERM_UI_MENU, "index": menu_index, "scan": False}
            text = _optics_terminal_menu(menu_index)
            yield _term_keypad_outputs(text, active_key, menu_state)
            time.sleep(_OPTICS_TERM_RELEASE_DELAY_S)
            yield _term_keypad_outputs(text, "", menu_state)

    return handler


def _make_term_latch_click(active_key: str):
    """Undefined keypad slots — latch matrix-green only, terminal unchanged."""

    def handler(current: str, ui_state: dict) -> tuple:
        state = dict(ui_state) if ui_state else _default_term_ui_state()
        state["scan"] = False
        return _term_keypad_outputs(current, active_key, state)

    return handler


def _make_activate_signal_scan(active_key: str, *, menu_action: str = "scan"):
    """Toggle CSS phosphor scan — one yield, no server animation loop."""

    def handler(ui_state: dict) -> Iterator[tuple]:
        state = dict(ui_state) if ui_state else _default_term_ui_state()
        state.update(
            {
                "mode": TERM_UI_PAGE,
                "index": _term_menu_index_for_action(menu_action),
                "scan": True,
            }
        )
        yield _term_keypad_outputs("", active_key, state)
        time.sleep(_OPTICS_TERM_RELEASE_DELAY_S)
        yield _term_keypad_outputs("", "", state)

    return handler


def _make_term_home_momentary():
    """Home — momentary return to the selection menu."""

    def handler(current_active: str, ui_state: dict) -> Iterator[tuple]:
        menu_state = {"mode": TERM_UI_MENU, "index": 0, "scan": False}
        menu_text = _optics_terminal_menu(0)
        yield _term_keypad_outputs(menu_text, current_active, menu_state)
        time.sleep(_OPTICS_TERM_RELEASE_DELAY_S)
        yield _term_keypad_outputs(menu_text, "", menu_state)

    return handler


def _boot_quote_prefix() -> str:
    """Pad so the quote types out near the middle of the terminal panel."""
    v_pad = max(0, (_BOOT_TERM_LINES - 1) // 2)
    h_pad = max(0, (_BOOT_TERM_COLS - len(BOOT_QUOTE_STRING)) // 2)
    return "\n" * v_pad + (" " * h_pad)


def _stream_term_boot() -> Iterator[tuple]:
    """One-shot startup: centered quote, dot countdown, then selection menu."""
    boot_state = _default_term_ui_state()
    shown = _boot_quote_prefix()
    yield _term_keypad_outputs(shown, "", boot_state)

    for ch in BOOT_QUOTE_STRING:
        shown += ch
        yield _term_keypad_outputs(shown + _OPTICS_TERM_CURSOR, "", boot_state)
        time.sleep(_BOOT_QUOTE_CHAR_DELAY_S)

    yield _term_keypad_outputs(shown, "", boot_state)
    time.sleep(_BOOT_POST_QUOTE_DELAY_S)

    for _ in range(_BOOT_DOT_COUNT):
        shown += "."
        yield _term_keypad_outputs(shown, "", boot_state)
        time.sleep(_BOOT_DOT_INTERVAL_S)

    menu_text = _optics_terminal_menu(0)
    yield _term_keypad_outputs(menu_text, "", boot_state)


def _register_term_keypad_streamers() -> None:
    TERM_KEYPAD_STREAMERS.update(
        {
            "home": _stream_optics_terminal_home,
            "status": _stream_optics_terminal_status,
            "scope": _stream_optics_terminal_scope,
            "directory": _stream_optics_terminal_directory,
            "results": _stream_optics_terminal_results,
            "build": _stream_optics_terminal_build,
            "help": _stream_optics_terminal_help,
            "scan": _stream_scan_stub,
            "strings": _stream_optics_terminal_strings,
            "physics": _stream_optics_terminal_physics,
            "tour": _stream_optics_terminal_tour,
            "figures": _stream_optics_terminal_figures,
        }
    )


_register_term_keypad_streamers()


def _external_tab_html(label: str, url: str, tab_id: str) -> str:
    """External Source bookmark — opens in a new tab."""
    return (
        f'<a href="{url}" class="vqc-source-tab" data-tab="{tab_id}" '
        f'target="_blank" rel="noopener noreferrer">{label}</a>'
    )


def _source_tab_btn_update(*, active: bool) -> gr.Update:
    """Animations tab — orange only when that page is open; otherwise green."""
    if active:
        return gr.update(interactive=False, elem_classes=["vqc-source-tab", "active"])
    return gr.update(interactive=True, elem_classes=["vqc-source-tab"], variant="secondary")


def _home_tab_update(*, on_demo_page: bool) -> gr.Update:
    """Live demo tab: orange on demo page, green link back from Animations."""
    if on_demo_page:
        return gr.update(interactive=False, elem_classes=["vqc-source-tab", "active"], variant="secondary")
    return gr.update(interactive=True, elem_classes=["vqc-source-tab"], variant="secondary")


def _close_links_panels() -> tuple:
    """Hide Links-bar panels (Claims, New here?, Theory) and reset tab highlights."""
    off = _source_tab_btn_update(active=False)
    return (
        gr.update(visible=False),
        off,
        False,
        gr.update(visible=False),
        off,
        False,
        gr.update(visible=False),
        off,
        False,
    )


def _toggle_theory(is_open: bool) -> tuple:
    show = not is_open
    off = _source_tab_btn_update(active=False)
    return (
        gr.update(visible=show),
        _source_tab_btn_update(active=show),
        show,
        gr.update(visible=False),
        off,
        False,
        gr.update(visible=False),
        off,
        False,
    )


def _minimize_theory() -> tuple:
    return gr.update(visible=False), _source_tab_btn_update(active=False), False


def _dismiss_welcome() -> tuple:
    return gr.update(visible=False), True


def _apply_preset(preset_key: str) -> tuple:
    p = get_preset_params(preset_key)
    meta = OPTIMIZATION_PRESETS.get(preset_key, OPTIMIZATION_PRESETS["standard"])
    est = estimate_runtime_sec(int(p["total_steps"]), int(p["steps_per_update"]))
    note = f"Preset: {meta['label']}{meta['description']} (~{est:.0f}s est.)"
    return (
        p["total_steps"],
        p["steps_per_update"],
        p["learning_rate"],
        p["burst_factor_max"],
        p["use_fisher_modulation"],
        note,
    )


def _apply_run_mode(mode: str) -> tuple:
    p = get_run_mode_params(mode)
    spec = RUN_MODES.get(mode, RUN_MODES["quick"])
    note = f"Run mode: {spec['label']}{spec['description']} ({spec['eta_hint']})"
    return (
        p["total_steps"],
        p["steps_per_update"],
        p["learning_rate"],
        p["burst_factor_max"],
        p["use_fisher_modulation"],
        p.get("compare_adam", False),
        p["audio_duration"],
        note,
        _runtime_hint(p["total_steps"], p["steps_per_update"], p.get("compare_adam", False)),
    )


def _runtime_hint(total_steps: float, steps_per_update: float, compare: bool) -> str:
    est = estimate_runtime_sec(int(total_steps), int(max(1, steps_per_update)), compare=bool(compare))
    suffix = " (×2 with RiemannianAdam compare)" if compare else ""
    return (
        f"**Estimated optimize time:** ~{est:.0f}s on HF cpu-basic"
        f" — approximate, varies with server load{suffix}"
    )


def _has_opt_history(history: dict | None) -> bool:
    return bool(history and history.get("step"))


def _trajectory_panel_visibility(
    run_mode: str,
    history: dict | None,
    traj_view: str,
    webgl_ok: bool,
    *,
    running: bool = False,
) -> tuple:
    """Hide WebGL 3D column during Quick runs; 2D stays visible live."""
    resolved = resolve_trajectory_mode(traj_view, webgl_ok)
    if run_mode == "quick" and resolved == "3d":
        if running or not _has_opt_history(history):
            return gr.update(visible=False), gr.update(visible=True)
    return gr.update(visible=True), gr.update(visible=False)


def _plot_3d_on_run_start(run_mode: str, traj_view: str, webgl_ok: bool) -> tuple:
    return _trajectory_panel_visibility(run_mode, None, traj_view, webgl_ok, running=True)


def _plot_3d_on_run_finish(run_mode: str, history: dict | None, traj_view: str, webgl_ok: bool) -> tuple:
    return _trajectory_panel_visibility(run_mode, history, traj_view, webgl_ok, running=False)


def _plot_3d_for_mode(run_mode: str, history: dict | None, traj_view: str, webgl_ok: bool) -> tuple:
    return _trajectory_panel_visibility(run_mode, history, traj_view, webgl_ok, running=False)


def _apply_run_mode_with_3d(mode: str, history: dict | None, traj_view: str, webgl_ok: bool) -> tuple:
    return _apply_run_mode(mode) + _plot_3d_for_mode(mode, history, traj_view, webgl_ok)


def _on_webgl_probe(probe: str) -> tuple:
    ok = str(probe).strip() != "0"
    if is_hf_space():
        view = "2d"
    elif not ok:
        view = "2d"
    else:
        view = "auto"
    return ok, gr.update(value=view), webgl_status_markdown(ok, view)


def _on_trajectory_view_change(view: str, webgl_ok: bool) -> str:
    return webgl_status_markdown(webgl_ok, view)


def _nav_to_page(page: str) -> tuple:
    """Switch between demo and animations screens; refresh Source tab highlights."""
    on_demo = page == "demo"
    closed = _close_links_panels()
    return (
        gr.update(visible=on_demo),
        gr.update(visible=not on_demo),
        _home_tab_update(on_demo_page=on_demo),
        _source_tab_btn_update(active=not on_demo),
        *closed,
        _home_tab_update(on_demo_page=on_demo),
        _source_tab_btn_update(active=not on_demo),
        page,
    )


def _toggle_newhere(is_open: bool) -> tuple:
    """Expand/collapse the beginner guide; close other link panels."""
    show = not is_open
    off = _source_tab_btn_update(active=False)
    return (
        gr.update(visible=show),
        _source_tab_btn_update(active=show),
        show,
        gr.update(visible=False),
        off,
        False,
        gr.update(visible=False),
        off,
        False,
    )


def _toggle_claims(is_open: bool) -> tuple:
    """Expand/collapse claims; close other link panels."""
    show = not is_open
    off = _source_tab_btn_update(active=False)
    return (
        gr.update(visible=show),
        _source_tab_btn_update(active=show),
        show,
        gr.update(visible=False),
        off,
        False,
        gr.update(visible=False),
        off,
        False,
    )


def _minimize_newhere() -> tuple:
    return (
        gr.update(visible=False),
        _source_tab_btn_update(active=False),
        False,
    )


def _minimize_claims() -> tuple:
    return (
        gr.update(visible=False),
        _source_tab_btn_update(active=False),
        False,
    )


def _build_vqc_theme() -> gr.themes.Base:
    """Dark transparent theme — mystery gold/purple (HF-safe)."""
    return (
        gr.themes.Base(
            primary_hue=gr.themes.colors.amber,
            secondary_hue=gr.themes.colors.purple,
            neutral_hue=gr.themes.colors.zinc,
        )
        .set(
            body_background_fill="transparent",
            body_background_fill_dark="transparent",
            background_fill_primary="transparent",
            background_fill_primary_dark="transparent",
            background_fill_secondary="transparent",
            background_fill_secondary_dark="transparent",
            block_background_fill=_VQC_FIELD_FILL,
            block_background_fill_dark=_VQC_FIELD_FILL,
            panel_background_fill=_VQC_FIELD_FILL,
            panel_background_fill_dark=_VQC_FIELD_FILL,
            input_background_fill=_VQC_FIELD_FILL,
            input_background_fill_dark=_VQC_FIELD_FILL,
            body_text_color="#e8e0f8",
            body_text_color_dark="#e8e0f8",
            block_label_text_color="#c9b8ff",
            block_label_text_color_dark="#c9b8ff",
            block_title_text_color="#f0e6ff",
            block_title_text_color_dark="#f0e6ff",
            border_color_primary="rgba(255, 255, 255, 0.12)",
            border_color_primary_dark="rgba(255, 255, 255, 0.12)",
            button_primary_background_fill="#c9a227",
            button_primary_background_fill_dark="#c9a227",
            button_primary_text_color="#ffffff",
            button_primary_text_color_dark="#ffffff",
            button_secondary_background_fill="rgba(28, 22, 48, 0.92)",
            button_secondary_background_fill_dark="rgba(28, 22, 48, 0.92)",
            button_secondary_text_color="#e8e0f8",
            button_secondary_text_color_dark="#e8e0f8",
            checkbox_label_background_fill="transparent",
            checkbox_label_background_fill_dark="transparent",
            checkbox_label_background_fill_hover="transparent",
            checkbox_label_background_fill_hover_dark="transparent",
            slider_color=_VQC_ACCENT,
            slider_color_dark=_VQC_ACCENT,
            link_text_color=_VQC_ACCENT,
            link_text_color_dark=_VQC_ACCENT,
            link_text_color_hover="#d4b8ff",
            link_text_color_hover_dark="#d4b8ff",
            link_text_color_active=_VQC_ACCENT,
            link_text_color_active_dark=_VQC_ACCENT,
            link_text_color_visited=_VQC_ACCENT,
            link_text_color_visited_dark=_VQC_ACCENT,
        )
    )


# Wallpaper: #vqc-wallpaper (body child) + body::before fallback — cover, fixed to viewport.
WALLPAPER_HEAD = f"""
<style id="vqc-wallpaper-style">
#vqc-wallpaper {{
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: -9999 !important;
    pointer-events: none !important;
    background-color: #0a0818 !important;
    background-image: url('{WALLPAPER_URL}') !important;
    background-size: cover !important;
    background-position: center center !important;
    background-repeat: no-repeat !important;
}}
</style>
<script>
(function() {{
    function mountWallpaper() {{
        if (document.getElementById('vqc-wallpaper')) return;
        var wp = document.createElement('div');
        wp.id = 'vqc-wallpaper';
        wp.setAttribute('aria-hidden', 'true');
        document.body.insertBefore(wp, document.body.firstChild);
    }}
    if (document.body) mountWallpaper();
    document.addEventListener('DOMContentLoaded', mountWallpaper);
    window.addEventListener('load', mountWallpaper);
}})();
</script>
<script>
(function() {{
    var KEY = '6string-optimizer-welcome-seen';
    function collapseLimitations() {{
        var acc = document.querySelector('.vqc-limitations-acc');
        if (!acc) return;
        var btn = acc.querySelector('button.label-wrap, summary, [aria-expanded]');
        if (btn && btn.getAttribute('aria-expanded') === 'true') btn.click();
    }}
    function markWelcomeSeen() {{
        try {{ localStorage.setItem(KEY, '1'); }} catch (e) {{}}
        collapseLimitations();
    }}
    function bindWelcomeTriggers() {{
        document.querySelectorAll('.vqc-welcome-seen-trigger').forEach(function(el) {{
            if (el.dataset.vqcWelcomeBound) return;
            el.dataset.vqcWelcomeBound = '1';
            el.addEventListener('click', markWelcomeSeen);
        }});
    }}
    function initReturningUser() {{
        try {{
            if (localStorage.getItem(KEY) === '1') collapseLimitations();
        }} catch (e) {{}}
        bindWelcomeTriggers();
    }}
    var obs = new MutationObserver(initReturningUser);
    function startReturningUX() {{
        initReturningUser();
        if (document.body) obs.observe(document.body, {{ childList: true, subtree: true }});
    }}
    if (document.readyState === 'loading') {{
        document.addEventListener('DOMContentLoaded', startReturningUX);
    }} else {{
        startReturningUX();
    }}
}})();
</script>
<script>
(function() {{
    function markWebGLFailed() {{
        try {{ localStorage.setItem('6string-webgl-failed', '1'); }} catch (e) {{}}
        var status = document.querySelector('.vqc-webgl-status');
        if (status) {{
            status.innerHTML = '⚠ <strong>WebGL error detected</strong> — switch <strong>Trajectory view</strong> to <strong>2D (WebGL-safe)</strong>.';
        }}
    }}
    function scanPlotlyWebGLErrors() {{
        var plots = document.querySelectorAll('.vqc-plot3d-panel, .js-plotly-plot');
        plots.forEach(function(plot) {{
            var text = plot.innerText || '';
            if (text.indexOf('WebGL is not supported') >= 0) markWebGLFailed();
        }});
    }}
    setInterval(scanPlotlyWebGLErrors, 2500);
    var obs = new MutationObserver(scanPlotlyWebGLErrors);
    function start() {{
        scanPlotlyWebGLErrors();
        if (document.body) obs.observe(document.body, {{ childList: true, subtree: true }});
    }}
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
    else start();
}})();
</script>
{KATEX_CDN}
"""

MOBILE_CSS = """
@media (max-width: 900px) {
  .gradio-container .vqc-optics-prog-row,
  .gradio-container .vqc-optics-dpad-row {
    flex-wrap: wrap !important;
    gap: 0.35rem !important;
  }
  .gradio-container .vqc-optics-prog-row button,
  .gradio-container .vqc-optics-dpad-row button {
    min-height: 2.6rem !important;
    font-size: 0.72rem !important;
    flex: 1 1 18% !important;
  }
  .gradio-container .vqc-optics-dial-row {
    flex-direction: column !important;
  }
  .gradio-container .vqc-nav-spreadsheet-row {
    flex-wrap: wrap !important;
  }
  .gradio-container .vqc-optics-terminal-wrap textarea {
    font-size: 0.7rem !important;
  }
  .gradio-container .vqc-screencast-wrap {
    grid-template-columns: 1fr !important;
  }
  .gradio-container .vqc-welcome-panel {
    padding: 0.5rem !important;
  }
}
@media (max-width: 480px) {
  .gradio-container .vqc-optics-brand {
    font-size: 1.1rem !important;
  }
  .gradio-container .vqc-receiver-preset {
    font-size: 0.65rem !important;
    padding: 0.35rem 0.4rem !important;
  }
}
"""

HFB_CSS = f"""
:root, :root .dark {{
    --body-background-fill: transparent !important;
    --background-fill-primary: transparent !important;
    --background-fill-secondary: transparent !important;
    --block-background-fill: {_VQC_FIELD_FILL} !important;
    --panel-background-fill: {_VQC_FIELD_FILL} !important;
    --input-background-fill: {_VQC_FIELD_FILL} !important;
    --body-text-color: #e8e0f8 !important;
    --block-label-text-color: #c9b8ff !important;
    --block-title-text-color: #f0e6ff !important;
    --border-color-primary: rgba(255, 255, 255, 0.12) !important;
    --link-text-color: {_VQC_ACCENT} !important;
    --link-text-color-hover: #d4b8ff !important;
    --link-text-color-active: {_VQC_ACCENT} !important;
    --link-text-color-visited: {_VQC_ACCENT} !important;
    color-scheme: dark;
}}
html {{
    background-color: #0a0818 !important;
    min-height: 100% !important;
}}
body {{
    background: transparent !important;
    background-color: transparent !important;
    color: #e8e0f8 !important;
    min-height: 100vh !important;
    width: 100% !important;
    overflow-x: hidden !important;
    position: relative !important;
}}
body::before {{
    content: "" !important;
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: -9998 !important;
    pointer-events: none !important;
    background-color: #0a0818 !important;
    background-image: url('{WALLPAPER_URL}') !important;
    background-size: cover !important;
    background-position: center center !important;
    background-repeat: no-repeat !important;
}}
#root, .app {{
    background: transparent !important;
    background-color: transparent !important;
    min-height: 0 !important;
    height: auto !important;
    width: 100% !important;
}}
.gradio-container {{
    position: relative !important;
    width: 100% !important;
    max-width: 100% !important;
    min-height: 0 !important;
    height: auto !important;
    background: transparent !important;
    background-color: transparent !important;
}}
footer {{
    background: transparent !important;
}}
.gradio-container .main,
.gradio-container .wrap,
.gradio-container .contain,
.gradio-container .tabs,
.gradio-container .tabitem,
.gradio-container .form,
.gradio-container .column,
.gradio-container .row,
.gradio-container .gr-group,
.gradio-container label.wrap,
.gradio-container .label-wrap {{
    background: transparent !important;
    background-color: transparent !important;
    box-shadow: none !important;
}}
.gradio-container .block {{
    width: 100% !important;
    max-width: 100% !important;
    box-sizing: border-box !important;
    background-color: {_VQC_FIELD_FILL} !important;
    border: 1px solid rgba(255, 255, 255, 0.08) !important;
    border-radius: 10px !important;
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
}}
.gradio-container .markdown,
.gradio-container .prose,
.gradio-container .markdown p,
.gradio-container .markdown h1,
.gradio-container .markdown h2,
.gradio-container .markdown li {{
    color: #e8e0f8 !important;
}}
.gradio-container .vqc-source-tabs-row {{
    display: flex !important;
    flex-wrap: wrap !important;
    align-items: center !important;
    gap: 0.45rem 0.65rem !important;
    margin: 0.35rem 0 0.1rem 0 !important;
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
}}
.gradio-container .vqc-source-nav-row {{
    margin: 0 0 0.1rem 0 !important;
}}
.gradio-container .vqc-links-panel {{
    margin: 0 0 0.35rem 0 !important;
    padding: 0.65rem 0.85rem !important;
}}
.gradio-container .vqc-links-panel .markdown h3 {{
    margin: 0 !important;
    font-size: 1rem !important;
    color: #f0e6ff !important;
}}
.gradio-container .intro-walkthrough {{
    position: relative;
    margin: 0.5rem 0 0.75rem 0;
    padding: 0.55rem 0.65rem 0.7rem 0.65rem;
    border: 1px solid rgba(255, 176, 0, 0.35);
    border-radius: 8px;
    background: rgba(10, 10, 10, 0.55);
    font-family: "Courier New", monospace;
    font-size: 0.82rem;
    color: #ffb000;
    overflow: hidden;
}}
.gradio-container .intro-step {{
    opacity: 0;
    transform: translateY(6px);
    padding: 0.15rem 0;
    animation: intro-step-cycle 20s infinite;
}}
.gradio-container .intro-step span {{
    color: #ff8800;
    margin-right: 0.35rem;
}}
.gradio-container .intro-step-1 {{ animation-delay: 0s; }}
.gradio-container .intro-step-2 {{ animation-delay: 5s; }}
.gradio-container .intro-step-3 {{ animation-delay: 10s; }}
.gradio-container .intro-step-4 {{ animation-delay: 15s; }}
.gradio-container .intro-progress {{
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    width: 0;
    background: linear-gradient(90deg, #ffb000, #ff6600);
    animation: intro-progress-bar 20s linear infinite;
}}
@keyframes intro-step-cycle {{
    0%, 18% {{ opacity: 1; transform: translateY(0); }}
    22%, 100% {{ opacity: 0; transform: translateY(-4px); }}
}}
@keyframes intro-progress-bar {{
    0% {{ width: 0; }}
    100% {{ width: 100%; }}
}}
.gradio-container .vqc-utility-row {{
    align-items: center !important;
    gap: 0.65rem !important;
    margin: 0.25rem 0 0.35rem 0 !important;
}}
.gradio-container .vqc-utility-row > .block,
.gradio-container .vqc-utility-row > .form {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
}}
.gradio-container button.vqc-utility-btn {{
    flex: 0 0 auto !important;
    opacity: 0.85 !important;
}}
.gradio-container .vqc-utility-hint {{
    font-size: 0.78rem !important;
    color: #a89cc8 !important;
    margin: 0 !important;
}}
.gradio-container .vqc-run-mode-radio label {{
    line-height: 1.35 !important;
}}
.gradio-container .vqc-webgl-status {{
    margin: 0.2rem 0 0.45rem 0 !important;
    padding: 0.45rem 0.65rem !important;
    border-radius: 8px !important;
    border: 1px solid rgba(255, 176, 0, 0.25) !important;
    background: rgba(10, 10, 10, 0.4) !important;
    font-size: 0.84rem !important;
    color: #c9b8ff !important;
}}
.gradio-container .vqc-webgl-status:empty {{
    display: none !important;
}}
.gradio-container .vqc-trajectory-view-radio label {{
    line-height: 1.3 !important;
}}
.gradio-container .vqc-panel-header-row {{
    display: flex !important;
    align-items: center !important;
    justify-content: space-between !important;
    gap: 0.5rem !important;
    width: 100% !important;
    margin: 0 0 0.35rem 0 !important;
}}
.gradio-container .vqc-panel-header-row > .block,
.gradio-container .vqc-panel-header-row > .form {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    flex: 1 1 auto !important;
    width: auto !important;
}}
.gradio-container button.vqc-panel-minimize {{
    flex: 0 0 auto !important;
    min-width: 2.1rem !important;
    padding: 0.2rem 0.6rem !important;
    border-radius: 999px !important;
    border: 1px solid {_VQC_TAB_GREEN_BORDER} !important;
    background: {_VQC_TAB_GREEN_BG} !important;
    color: {_VQC_TAB_GREEN_TEXT} !important;
    -webkit-text-fill-color: {_VQC_TAB_GREEN_TEXT} !important;
    font-weight: 700 !important;
    font-size: 0.85rem !important;
    line-height: 1 !important;
    box-shadow: none !important;
    opacity: 0.8 !important;
    cursor: pointer !important;
}}
.gradio-container button.vqc-panel-minimize:hover {{
    border-color: {_VQC_TAB_ORANGE_BORDER} !important;
    background: {_VQC_TAB_ORANGE_BG} !important;
    color: {_VQC_TAB_ORANGE_TEXT} !important;
    -webkit-text-fill-color: {_VQC_TAB_ORANGE_TEXT} !important;
}}
.gradio-container .vqc-source-tabs-row > .block,
.gradio-container .vqc-source-tabs-row > .form,
.gradio-container .vqc-source-tabs-row .block,
.gradio-container .vqc-source-tabs-row .form {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    min-width: 0 !important;
    width: auto !important;
    flex: 0 0 auto !important;
}}
.gradio-container .vqc-source-tabs-row .html-container {{
    padding: 0 !important;
    margin: 0 !important;
}}
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.secondary,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.secondary:hover,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.secondary:focus {{
    border: none !important;
    outline: none !important;
    background: transparent !important;
    box-shadow: none !important;
}}
.gradio-container .vqc-source-label {{
    color: #e8e0f8 !important;
    font-size: 0.92rem !important;
    font-weight: 600 !important;
    margin-right: 0.15rem !important;
    line-height: 1.2 !important;
}}
.gradio-container .vqc-source-tab,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab span,
.gradio-container .vqc-nav-cell a.vqc-source-tab {{
    display: inline !important;
    padding: 0 !important;
    border: none !important;
    border-radius: 0 !important;
    background: transparent !important;
    background-color: transparent !important;
    box-shadow: none !important;
    color: {_VQC_MATRIX_GREEN} !important;
    -webkit-text-fill-color: {_VQC_MATRIX_GREEN} !important;
    text-decoration: underline !important;
    text-decoration-color: {_VQC_MATRIX_GREEN} !important;
    text-underline-offset: 0.18em !important;
    font-weight: 600 !important;
    font-size: 0.92rem !important;
    line-height: 1.35 !important;
    letter-spacing: normal !important;
    text-transform: none !important;
    white-space: nowrap !important;
    min-height: unset !important;
    height: auto !important;
    width: auto !important;
    margin: 0 !important;
    opacity: 1 !important;
    text-shadow: 0 0 6px rgba(51, 255, 102, 0.25) !important;
    transition: color 0.15s ease, text-decoration-color 0.15s ease, opacity 0.15s ease;
}}
.gradio-container a.vqc-source-tab:hover,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab:not(.active):hover,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab:not(.active):hover span {{
    color: #7dff9a !important;
    -webkit-text-fill-color: #7dff9a !important;
    text-decoration-color: #7dff9a !important;
    background: transparent !important;
    text-decoration: underline !important;
}}
.gradio-container .vqc-source-tabs-row button.vqc-source-tab {{
    cursor: pointer !important;
    font-family: inherit !important;
}}
.gradio-container .vqc-source-tabs-row button.vqc-source-tab:disabled:not(.active),
.gradio-container .vqc-source-tabs-row button.vqc-source-tab[disabled]:not(.active),
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.secondary:disabled:not(.active),
.gradio-container .vqc-source-tabs-row button.vqc-source-tab:disabled:not(.active) span,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab[disabled]:not(.active) span {{
    cursor: pointer !important;
    color: {_VQC_MATRIX_GREEN} !important;
    -webkit-text-fill-color: {_VQC_MATRIX_GREEN} !important;
    text-decoration-color: {_VQC_MATRIX_GREEN} !important;
    background: transparent !important;
    text-decoration: underline !important;
}}
.gradio-container .vqc-source-tab.active,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active span,
.gradio-container .vqc-source-tab.active:hover,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active:hover,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active:hover span,
.gradio-container a.vqc-source-tab.active {{
    color: {_VQC_LOGO_GOLD} !important;
    -webkit-text-fill-color: {_VQC_LOGO_GOLD} !important;
    text-decoration-color: {_VQC_LOGO_GOLD} !important;
    background: transparent !important;
    text-decoration: underline !important;
    text-decoration-thickness: 2px !important;
    cursor: default !important;
    opacity: 1 !important;
    text-shadow: 0 0 8px rgba(201, 162, 39, 0.45) !important;
}}
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active:disabled,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active[disabled],
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active:disabled span,
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active[disabled] span {{
    color: {_VQC_LOGO_GOLD} !important;
    -webkit-text-fill-color: {_VQC_LOGO_GOLD} !important;
    text-decoration-color: {_VQC_LOGO_GOLD} !important;
    background: transparent !important;
    text-decoration: underline !important;
    text-decoration-thickness: 2px !important;
    cursor: default !important;
}}
.gradio-container .vqc-source-tabs-row button.vqc-source-tab.active::before {{
    content: none !important;
    display: none !important;
}}
.gradio-container a:hover:not(.vqc-source-tab),
.gradio-container .markdown a:hover:not(.vqc-source-tab),
.gradio-container .prose a:hover:not(.vqc-source-tab) {{
    color: #d4b8ff !important;
    -webkit-text-fill-color: #d4b8ff !important;
}}
.gradio-container .vqc-build-label {{
    color: #a89ec8 !important;
    font-size: 0.9rem;
    margin: 0 0 0.5rem 0;
}}
.gradio-container .vqc-animations-page .markdown h2 {{
    font-size: 1.35rem !important;
    margin: 0.15rem 0 0.35rem 0 !important;
}}
.gradio-container .vqc-animations-page .markdown p {{
    font-size: 0.92rem !important;
    margin: 0.15rem 0 0.35rem 0 !important;
    line-height: 1.45 !important;
}}
.gradio-container .vqc-animations-page,
.gradio-container .vqc-animations-page > .block,
.gradio-container .vqc-animations-page .html-container {{
    width: 100% !important;
    max-width: 100% !important;
}}
.gradio-container .vqc-screencast-wrap {{
    display: grid !important;
    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
    gap: 0.75rem !important;
    width: 100% !important;
    max-width: 100% !important;
    margin: 0.25rem 0 0.5rem 0 !important;
    padding: 0 !important;
    box-sizing: border-box !important;
}}
.gradio-container .vqc-screencast-video {{
    width: 100% !important;
    min-width: 0 !important;
    height: auto !important;
    aspect-ratio: 16 / 9 !important;
    max-height: min(36vh, 360px) !important;
    object-fit: contain !important;
    border-radius: 8px !important;
    display: block !important;
    background: rgba(10, 8, 24, 0.35) !important;
}}
.gradio-container .vqc-optics-panel {{
    background: linear-gradient(165deg, #2a1838 0%, #1a1028 38%, #120c18 100%) !important;
    border: 3px solid #6a4c93 !important;
    border-radius: 14px !important;
    box-shadow:
        inset 0 2px 8px rgba(255, 220, 150, 0.08),
        inset 0 -4px 14px rgba(0, 0, 0, 0.55),
        0 8px 22px rgba(0, 0, 0, 0.45) !important;
    padding: 0 1rem 1rem !important;
    margin: 0.5rem 0 0.75rem 0 !important;
    gap: 0 !important;
}}
.gradio-container .vqc-optics-panel > .gap {{
    display: none !important;
    height: 0 !important;
    margin: 0 !important;
    padding: 0 !important;
}}
.gradio-container .vqc-optics-panel > .block,
.gradio-container .vqc-optics-panel .block {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
}}
.gradio-container .vqc-optics-panel-header {{
    display: flex !important;
    flex-wrap: wrap !important;
    align-items: center !important;
    gap: 0.75rem 1.1rem !important;
    margin: 0 0 0 0 !important;
    padding: 0.7rem 0.85rem 1.35rem !important;
    border: none !important;
    border-bottom: 1px solid rgba(106, 76, 147, 0.55) !important;
    border-radius: 10px 10px 0 0 !important;
    background: linear-gradient(180deg, #1f1428 0%, #0f0a14 100%) !important;
    box-shadow: inset 0 0 18px rgba(0, 0, 0, 0.65) !important;
    width: 100% !important;
    min-height: 5.25rem !important;
}}
.gradio-container .vqc-optics-panel-header > .block,
.gradio-container .vqc-optics-panel-header > .form,
.gradio-container .vqc-optics-panel-header .block,
.gradio-container .vqc-optics-panel-header .form {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    min-width: 0 !important;
}}
.gradio-container .vqc-optics-panel-header > .block:first-child,
.gradio-container .vqc-optics-panel-header > .form:first-child {{
    flex: 0 0 auto !important;
    width: auto !important;
}}
.gradio-container .vqc-optics-panel-nav {{
    flex: 1 1 18rem !important;
    display: flex !important;
    flex-direction: column !important;
    gap: 0.28rem !important;
    justify-content: center !important;
    min-width: 0 !important;
    width: auto !important;
}}
.gradio-container .vqc-optics-panel-nav > .block,
.gradio-container .vqc-optics-panel-nav > .form {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    width: 100% !important;
}}
.gradio-container .vqc-optics-panel-nav .vqc-source-tabs-row {{
    margin: 0 !important;
}}
.gradio-container .vqc-nav-spreadsheet-row {{
    display: grid !important;
    grid-template-columns: 4.75rem repeat(5, minmax(4.5rem, 1fr)) !important;
    gap: 0.2rem 0.45rem !important;
    align-items: center !important;
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
}}
.gradio-container .vqc-nav-spreadsheet-row > .block,
.gradio-container .vqc-nav-spreadsheet-row > .form,
.gradio-container .vqc-nav-spreadsheet-row > .column {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
    min-width: 0 !important;
    width: 100% !important;
}}
.gradio-container .vqc-nav-row-label {{
    justify-self: end !important;
    align-self: center !important;
    text-align: right !important;
    padding-right: 0.15rem !important;
}}
.gradio-container .vqc-nav-cell,
.gradio-container .vqc-nav-cell > .block,
.gradio-container .vqc-nav-cell > .form {{
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    text-align: center !important;
    min-height: 1.55rem !important;
    width: 100% !important;
    margin: 0 auto !important;
    padding: 0.1rem 0.2rem !important;
}}
.gradio-container .vqc-nav-cell .html-container,
.gradio-container .vqc-nav-cell .html-container p {{
    margin: 0 !important;
    padding: 0 !important;
    text-align: center !important;
    width: 100% !important;
}}
.gradio-container .vqc-nav-cell-empty {{
    visibility: hidden !important;
}}
.gradio-container .vqc-optics-logo {{
    display: flex !important;
    flex-direction: column !important;
    align-items: flex-start !important;
    gap: 0.1rem !important;
    min-width: 10.5rem !important;
    padding-right: 0.65rem !important;
    border-right: 1px solid rgba(107, 79, 29, 0.45) !important;
}}
.gradio-container .vqc-optics-brand {{
    font-size: 0.62rem !important;
    letter-spacing: 0.28em !important;
    color: {_VQC_LOGO_GOLD} !important;
    font-weight: 700 !important;
}}
.gradio-container .vqc-optics-panel-title {{
    font-size: 1.15rem !important;
    letter-spacing: 0.12em !important;
    color: #f5e6c8 !important;
    font-weight: 700 !important;
    text-transform: uppercase !important;
    text-shadow: 0 0 10px rgba(255, 180, 80, 0.35) !important;
}}
.gradio-container .vqc-optics-subtitle {{
    font-size: 0.68rem !important;
    letter-spacing: 0.22em !important;
    color: #9a8458 !important;
}}
.gradio-container .vqc-optics-terminal-caption {{
    font-size: 0.58rem !important;
    letter-spacing: 0.18em !important;
    color: #3dff7a !important;
    text-shadow: 0 0 8px rgba(61, 255, 122, 0.45) !important;
    margin-top: 0.1rem !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-terminal textarea,
.gradio-container .vqc-optics-panel .vqc-optics-terminal input {{
    background: rgba(2, 10, 4, 0.1) !important;
    border: 2px inset #1a4d2a !important;
    color: #33ff66 !important;
    -webkit-text-fill-color: #33ff66 !important;
    font-family: "Courier New", Courier, monospace !important;
    font-size: 0.78rem !important;
    line-height: 1.45 !important;
    text-shadow: 0 0 6px rgba(51, 255, 102, 0.35) !important;
    box-shadow:
        inset 0 0 18px rgba(0, 40, 12, 0.65),
        0 0 12px rgba(51, 255, 102, 0.08) !important;
    border-radius: 6px !important;
    caret-color: #33ff66 !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-terminal .label-wrap span {{
    color: #3dff7a !important;
    letter-spacing: 0.14em !important;
    text-shadow: 0 0 6px rgba(61, 255, 122, 0.35) !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-terminal-wrap {{
    background: rgba(2, 10, 4, 0.1) !important;
    border: 1px solid #1a4d2a !important;
    border-radius: 10px !important;
    padding: 0.5rem 0.6rem 0.45rem !important;
    margin: 0.55rem 0 0.55rem 0 !important;
}}
.gradio-container .vqc-animations-nav-row {{
    margin: 0.35rem 0 0.65rem 0 !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-terminal textarea {{
    min-height: 13.5rem !important;
    white-space: pre !important;
    overflow-x: hidden !important;
}}
.gradio-container .myst-signal-scan {{
    position: relative !important;
    width: 100% !important;
    min-height: 14rem !important;
    margin: 0.55rem 0 !important;
    padding: 0.65rem 0.75rem !important;
    background: rgba(2, 10, 4, 0.45) !important;
    border: 2px inset #1a4d2a !important;
    border-radius: 6px !important;
    overflow: hidden !important;
    box-sizing: border-box !important;
}}
.gradio-container .myst-signal-scanlines {{
    position: absolute !important;
    inset: 0 !important;
    pointer-events: none !important;
    background: repeating-linear-gradient(
        0deg,
        transparent 0px,
        transparent 2px,
        rgba(51, 255, 102, 0.04) 2px,
        rgba(51, 255, 102, 0.04) 4px
    ) !important;
    animation: myst-scan-drift 12s linear infinite !important;
}}
.gradio-container .myst-signal-beam {{
    position: absolute !important;
    left: 0 !important;
    right: 0 !important;
    height: 18% !important;
    pointer-events: none !important;
    background: linear-gradient(
        180deg,
        transparent 0%,
        rgba(51, 255, 102, 0.12) 45%,
        rgba(51, 255, 102, 0.22) 50%,
        rgba(51, 255, 102, 0.12) 55%,
        transparent 100%
    ) !important;
    animation: myst-scan-beam 4s ease-in-out infinite !important;
}}
.gradio-container .myst-signal-body {{
    position: relative !important;
    z-index: 1 !important;
    margin: 0 !important;
    color: #33ff66 !important;
    font-family: "Courier New", Courier, monospace !important;
    font-size: 0.78rem !important;
    line-height: 1.45 !important;
    text-shadow: 0 0 6px rgba(51, 255, 102, 0.35) !important;
    white-space: pre-wrap !important;
    animation: myst-phosphor-flicker 3.5s ease-in-out infinite !important;
}}
@keyframes myst-scan-drift {{
    0% {{ transform: translateY(-8%); }}
    100% {{ transform: translateY(8%); }}
}}
@keyframes myst-scan-beam {{
    0%, 100% {{ top: -20%; }}
    50% {{ top: 85%; }}
}}
@keyframes myst-phosphor-flicker {{
    0%, 100% {{ opacity: 1; }}
    48% {{ opacity: 0.92; }}
    50% {{ opacity: 0.78; }}
    52% {{ opacity: 0.95; }}
}}
.gradio-container .vqc-optics-keypad {{
    background: linear-gradient(180deg, #16120c 0%, #0a0806 100%) !important;
    border: 2px inset #3d3020 !important;
    border-radius: 10px !important;
    padding: 0.42rem 0.38rem 0.48rem !important;
    margin: 0 0 0.65rem 0 !important;
    box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.55) !important;
}}
.gradio-container .vqc-optics-keypad > .block,
.gradio-container .vqc-optics-keypad .block {{
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    padding: 0 !important;
    margin: 0 !important;
}}
.gradio-container .vqc-optics-dpad-group {{
    margin: 0 0 0.28rem 0 !important;
    padding: 0 0 0.12rem 0 !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-dpad-row,
.gradio-container .vqc-optics-panel .vqc-optics-prog-row {{
    gap: 0.2rem !important;
    margin: 0 0 0.2rem 0 !important;
    justify-content: stretch !important;
    width: 100% !important;
}}
.gradio-container .vqc-optics-keypad button.vqc-optics-key,
.gradio-container .vqc-optics-keypad button.vqc-optics-key span {{
    font-family: "Courier New", Courier, monospace !important;
    font-size: 1.44rem !important;
    font-weight: 700 !important;
    line-height: 1.1 !important;
}}
.gradio-container .vqc-optics-keypad button.vqc-optics-key {{
    flex: 1 1 0 !important;
    min-width: 0 !important;
    max-width: none !important;
    min-height: 3rem !important;
    height: 3rem !important;
    max-height: 3rem !important;
    aspect-ratio: auto !important;
    background: #000000 !important;
    border: none !important;
    border-radius: 8px !important;
    color: #ffffff !important;
    -webkit-text-fill-color: #ffffff !important;
    letter-spacing: 0.03em !important;
    padding: 0.28rem 0.1rem !important;
    box-shadow: none !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-dpad-row button.vqc-optics-key-dpad,
.gradio-container .vqc-optics-panel .vqc-optics-dpad-row button.vqc-optics-key-dpad span {{
    font-family: system-ui, -apple-system, "Segoe UI", sans-serif !important;
    font-size: 1.44rem !important;
    font-weight: 700 !important;
    line-height: 1 !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-dpad-row button.vqc-optics-key-dpad:active,
.gradio-container .vqc-optics-panel .vqc-optics-dpad-row button.vqc-optics-key-dpad:active span {{
    background: {_VQC_MATRIX_GREEN} !important;
    color: #000000 !important;
    -webkit-text-fill-color: #000000 !important;
    box-shadow: 0 0 12px rgba(51, 255, 102, 0.45) !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-clear {{
    text-transform: lowercase !important;
    letter-spacing: 0.06em !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-home,
.gradio-container .vqc-optics-panel button.vqc-optics-key-home:hover {{
    background: {_VQC_HOME_KEY_BG} !important;
    box-shadow: none !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-home,
.gradio-container .vqc-optics-panel button.vqc-optics-key-home:hover,
.gradio-container .vqc-optics-panel button.vqc-optics-key-home span {{
    color: {_VQC_MATRIX_GREEN} !important;
    -webkit-text-fill-color: {_VQC_MATRIX_GREEN} !important;
    font-size: 1.44rem !important;
    font-weight: 700 !important;
    text-shadow: 0 0 6px rgba(51, 255, 102, 0.35) !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-home:hover {{
    background: #141414 !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-defined:not(.active),
.gradio-container .vqc-optics-panel button.vqc-optics-key-defined:not(.active) span {{
    color: {_VQC_MATRIX_GREEN} !important;
    -webkit-text-fill-color: {_VQC_MATRIX_GREEN} !important;
    text-shadow: 0 0 6px rgba(51, 255, 102, 0.35) !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-defined:not(.active):hover,
.gradio-container .vqc-optics-panel button.vqc-optics-key-defined:not(.active):hover span {{
    color: #7dff9a !important;
    -webkit-text-fill-color: #7dff9a !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key:not(.active):not(.vqc-optics-key-home):not(.vqc-optics-key-defined):hover {{
    background: #141414 !important;
    color: #ffffff !important;
    -webkit-text-fill-color: #ffffff !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key-defined:not(.active):hover {{
    background: #141414 !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key.active,
.gradio-container .vqc-optics-panel button.vqc-optics-key.active:hover {{
    background: {_VQC_MATRIX_GREEN} !important;
    box-shadow: 0 0 12px rgba(51, 255, 102, 0.45) !important;
}}
.gradio-container .vqc-optics-panel button.vqc-optics-key.active,
.gradio-container .vqc-optics-panel button.vqc-optics-key.active:hover,
.gradio-container .vqc-optics-panel button.vqc-optics-key.active span {{
    color: #000000 !important;
    -webkit-text-fill-color: #000000 !important;
    text-shadow: none !important;
    -webkit-text-stroke: none !important;
}}
.gradio-container .vqc-optics-panel .label-wrap span,
.gradio-container .vqc-optics-panel label span {{
    color: #e8d4a8 !important;
    font-size: 0.78rem !important;
    letter-spacing: 0.06em !important;
    text-transform: uppercase !important;
    font-weight: 700 !important;
}}
.gradio-container .vqc-optics-panel .info {{
    color: #9a8458 !important;
    font-size: 0.72rem !important;
    font-style: italic !important;
}}
.gradio-container .vqc-optics-panel input[type="text"],
.gradio-container .vqc-optics-panel textarea {{
    background: #120c06 !important;
    border: 2px inset #5c4a1f !important;
    color: #ffb347 !important;
    font-family: "Courier New", Courier, monospace !important;
    border-radius: 6px !important;
    box-shadow: inset 0 0 10px rgba(255, 140, 40, 0.12) !important;
}}
.gradio-container .vqc-optics-panel input[type="number"] {{
    background: #120c06 !important;
    border: 2px inset #5c4a1f !important;
    color: #ffb347 !important;
    font-family: "Courier New", Courier, monospace !important;
    font-weight: 700 !important;
    text-align: center !important;
    border-radius: 4px !important;
    box-shadow: inset 0 0 12px rgba(255, 140, 40, 0.18) !important;
    min-width: 4.2rem !important;
}}
.gradio-container .vqc-optics-panel input[type="range"] {{
    height: 6px !important;
    background: linear-gradient(90deg, #1a1208, #3d2e14, #1a1208) !important;
    border: 1px solid #5c4a1f !important;
    border-radius: 999px !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.6) !important;
}}
.gradio-container .vqc-optics-panel input[type="range"]::-webkit-slider-thumb {{
    -webkit-appearance: none !important;
    width: 24px !important;
    height: 24px !important;
    border-radius: 50% !important;
    background: radial-gradient(circle at 32% 28%, #fff2cc 0%, #c9a227 38%, #5c4212 72%, #2a1f08 100%) !important;
    border: 2px solid #1a1208 !important;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.55), inset 0 -2px 4px rgba(0, 0, 0, 0.35) !important;
    cursor: pointer !important;
}}
.gradio-container .vqc-optics-panel input[type="range"]::-moz-range-thumb {{
    width: 24px !important;
    height: 24px !important;
    border-radius: 50% !important;
    background: radial-gradient(circle at 32% 28%, #fff2cc 0%, #c9a227 38%, #5c4212 72%, #2a1f08 100%) !important;
    border: 2px solid #1a1208 !important;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.55) !important;
    cursor: pointer !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-dial-wrap {{
    background: rgba(0, 0, 0, 0.22) !important;
    border: 1px solid #4a3818 !important;
    border-radius: 10px !important;
    padding: 0.55rem 0.65rem 0.45rem !important;
    margin: 0 !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-tune-row {{
    gap: 0.65rem !important;
    margin-bottom: 0.55rem !important;
}}
.gradio-container .vqc-optics-panel .vqc-optics-dial-row {{
    gap: 0.65rem !important;
    align-items: stretch !important;
}}
.gradio-container .vqc-optics-panel fieldset {{
    background: rgba(0, 0, 0, 0.18) !important;
    border: 1px solid #4a3818 !important;
    border-radius: 10px !important;
    padding: 0.45rem 0.55rem !important;
}}
.gradio-container .vqc-optics-panel .vqc-band-switch button {{
    border: 1px solid #6b4f1d !important;
    background: #1a1208 !important;
    color: #c9a227 !important;
    border-radius: 6px !important;
    font-size: 0.78rem !important;
    letter-spacing: 0.05em !important;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.45) !important;
}}
.gradio-container .vqc-optics-panel .vqc-band-switch button.selected,
.gradio-container .vqc-optics-panel .vqc-band-switch button[aria-checked="true"] {{
    background: linear-gradient(180deg, #8b6914 0%, #4a3818 100%) !important;
    color: #fff2cc !important;
    box-shadow: 0 0 10px rgba(255, 160, 60, 0.35) !important;
}}
.gradio-container .vqc-optics-presets-label {{
    color: #c9a227 !important;
    font-size: 0.78rem !important;
    letter-spacing: 0.08em !important;
    text-transform: uppercase !important;
    margin: 0.45rem 0 0.35rem 0 !important;
    text-align: center !important;
}}
.gradio-container .vqc-optics-panel button.vqc-receiver-preset {{
    background: linear-gradient(180deg, #3d2e14 0%, #1f1608 100%) !important;
    border: 2px solid #6b4f1d !important;
    color: #f5e6c8 !important;
    border-radius: 8px !important;
    font-size: 0.78rem !important;
    letter-spacing: 0.04em !important;
    box-shadow: inset 0 1px 0 rgba(255, 220, 150, 0.15), 0 2px 4px rgba(0, 0, 0, 0.4) !important;
}}
.gradio-container .vqc-optics-panel button.vqc-receiver-preset:hover {{
    background: linear-gradient(180deg, #6b4f1d 0%, #3d2e14 100%) !important;
    color: #fff8e8 !important;
}}
.gradio-container .vqc-optics-panel .vqc-slm-toggle label {{
    color: #c9a227 !important;
    font-size: 0.76rem !important;
}}
.gradio-container .markdown blockquote {{
    border-left-color: rgba(255, 180, 80, 0.5) !important;
    background: transparent !important;
}}
.gradio-container .accordion,
.gradio-container details,
.gradio-container summary {{
    background-color: {_VQC_FIELD_FILL} !important;
    color: #e8e0f8 !important;
    border-radius: 10px;
}}
.gradio-container .image-container img,
.gradio-container .gr-image img,
.gradio-container video,
.gradio-container .plot-container {{
    background-color: transparent !important;
    opacity: 1 !important;
}}
.gradio-container button,
.gradio-container .gr-button {{
    opacity: 1 !important;
}}
.gradio-container input[type="range"] {{
    opacity: 1 !important;
}}
.gradio-container .vqc-full-width {{
    width: 100% !important;
}}
.gradio-container .main,
.gradio-container .wrap {{
    width: 100% !important;
    max-width: 100% !important;
    min-height: 0 !important;
    height: auto !important;
}}
.gradio-container .contain {{
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 auto !important;
    min-height: 0 !important;
    height: auto !important;
}}
.gradio-container .vqc-animation-panel,
.gradio-container .vqc-figure-panel,
.gradio-container .vqc-plot3d-panel {{
    width: 100% !important;
    max-width: 100% !important;
    min-height: 0 !important;
}}
.gradio-container .vqc-animation-panel video,
.gradio-container .vqc-animation-panel .image-container,
.gradio-container .vqc-animation-panel img,
.gradio-container .vqc-figure-panel .image-container,
.gradio-container .vqc-figure-panel img {{
    width: 100% !important;
    max-width: 100% !important;
    object-fit: contain;
}}
.gradio-container .vqc-plot3d-panel .plot-container {{
    width: 100% !important;
    min-height: 360px;
}}
.gradio-container .vqc-plot3d-hint {{
    min-height: 280px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    padding: 1rem 1.25rem !important;
    margin: 0 !important;
    border: 1px dashed rgba(255, 176, 0, 0.35) !important;
    border-radius: 10px !important;
    background: rgba(10, 10, 10, 0.45) !important;
    color: #c9b8ff !important;
    font-size: 0.88rem !important;
    line-height: 1.45 !important;
    text-align: center !important;
}}
.gradio-container .vqc-plot3d-hint p {{
    margin: 0 !important;
    color: #c9b8ff !important;
}}
.gradio-container .gr-video .empty,
.gradio-container .gr-image .empty,
.gradio-container .gr-image .icon-wrap {{
    min-height: 80px !important;
    background: transparent !important;
}}
footer {{ visibility: hidden; }}
{MOBILE_CSS}
"""


def _run_optimize(
    total_steps: float,
    steps_per_update: float,
    learning_rate: float,
    burst_factor_max: float,
    use_fisher_modulation: bool,
    compare_adam: bool,
    run_mode: str,
    trajectory_view: str,
    webgl_ok: bool,
    progress: gr.Progress = gr.Progress(track_tqdm=False),
):
    plot_cfg = PlotStreamConfig.for_run_mode(run_mode or "quick")
    traj_mode = resolve_trajectory_mode(trajectory_view, webgl_ok)
    webgl_fallback = trajectory_view == "3d" and not webgl_ok
    stream_fn = run_comparison_stream if compare_adam else run_optimization_stream
    try:
        yield from stream_fn(
            total_steps=int(total_steps),
            steps_per_update=int(steps_per_update),
            learning_rate=float(learning_rate),
            burst_factor_max=float(burst_factor_max),
            use_fisher_modulation=bool(use_fisher_modulation),
            plot_cfg=plot_cfg,
            trajectory_mode=traj_mode,
            trajectory_webgl_fallback=webgl_fallback,
            progress_cb=progress,
        )
    except Exception as exc:
        logger.exception("Optimization failed")
        empty = go.Figure()
        yield empty, empty, empty, empty, friendly_error("optimize", exc), {}


def _run_spectrum(
    audio_file,
    duration: float,
    use_sample: bool = False,
    progress: gr.Progress = gr.Progress(track_tqdm=False),
):
    try:
        path = audio_file if audio_file else None
        fig_wave, fig_spec, fig_partials, fig_energy, metrics = analyze_audio_signal(
            path,
            duration=float(duration),
            use_sample=use_sample,
            progress_cb=progress,
        )
        return fig_wave, fig_spec, fig_partials, fig_energy, metrics
    except Exception as exc:
        logger.exception("Audio analysis failed")
        empty = go.Figure()
        return empty, empty, empty, empty, friendly_error("spectrum", exc)


def _run_demo_guitar(duration: float, progress: gr.Progress = gr.Progress(track_tqdm=False)):
    return _run_spectrum(None, duration, use_sample=True, progress=progress)


def _run_physics_preview(progress: gr.Progress = gr.Progress(track_tqdm=False)):
    try:
        progress(0.2, desc="Rendering Smith chart preview…")
        smith = render_smith_chart_preview()
        overview = get_overview_composite_path()
        progress(0.8, desc="Loading overview composite…")
        metrics, smith_path, overview_path = run_analysis(0.85)
        progress(1.0, desc="Done")
        return metrics, smith_path or smith, overview_path
    except Exception as exc:
        logger.exception("Physics preview failed")
        return friendly_error("physics", exc), None, None


def build_app() -> gr.Blocks:
    with gr.Blocks(
        title="6-String Optimizer — Signal Analyzer",
        analytics_enabled=False,
        theme=_build_vqc_theme(),
        head=WALLPAPER_HEAD,
        css=HFB_CSS,
        fill_width=True,
    ) as demo:
        current_page = gr.State("demo")
        newhere_open = gr.State(False)
        claims_open = gr.State(False)
        theory_open = gr.State(False)
        welcome_dismissed = gr.State(False)
        with gr.Column(visible=True, elem_classes=["vqc-links-panel", "vqc-welcome-panel"]) as panel_welcome:
            with gr.Row(elem_classes=["vqc-panel-header-row"]):
                gr.Markdown("### Welcome — What is this project?")
                welcome_dismiss_btn = gr.Button(
                    "Dismiss ✕",
                    elem_classes=["vqc-panel-minimize", "vqc-welcome-seen-trigger"],
                    scale=0,
                    variant="secondary",
                )
            gr.Markdown(WHAT_IS_THIS_MD)
            gr.HTML(INTRO_WALKTHROUGH_HTML)
            gr.Markdown(LOCAL_RUN_MD)
            with gr.Accordion(
                "Known limitations (HF free tier)",
                open=True,
                elem_classes=["vqc-limitations-acc"],
            ):
                gr.Markdown(KNOWN_LIMITATIONS_BODY)
            with gr.Row():
                welcome_tour_btn = gr.Button(
                    "Start guided tour (keypad 11)",
                    variant="secondary",
                    size="sm",
                    elem_classes=["vqc-welcome-seen-trigger"],
                )
                welcome_skip_btn = gr.Button(
                    "Skip — go to workspace",
                    variant="primary",
                    size="sm",
                    elem_classes=["vqc-welcome-seen-trigger"],
                )
        with gr.Column(visible=False, elem_classes=["vqc-links-panel"]) as panel_theory:
            with gr.Row(elem_classes=["vqc-panel-header-row"]):
                gr.Markdown("### Theory — How it works")
                theory_minimize_btn = gr.Button(
                    "▲",
                    elem_classes=["vqc-panel-minimize"],
                    scale=0,
                    variant="secondary",
                )
            gr.Markdown(THEORY_MD)
            gr.HTML(THEORY_KATEX_HTML)
        with gr.Column(visible=False, elem_classes=["vqc-links-panel"]) as panel_claims:
            with gr.Row(elem_classes=["vqc-panel-header-row"]):
                gr.Markdown("### How this Space maps to the 6-string optimizer")
                claims_minimize_btn = gr.Button(
                    "▲",
                    elem_classes=["vqc-panel-minimize"],
                    scale=0,
                    variant="secondary",
                )
            gr.Markdown(CLAIMS_MD)
        with gr.Column(visible=False, elem_classes=["vqc-links-panel"]) as panel_newhere:
            with gr.Row(elem_classes=["vqc-panel-header-row"]):
                gr.Markdown("### New here? 60-second guide (six-string signal analyzer)")
                newhere_minimize_btn = gr.Button(
                    "▲",
                    elem_classes=["vqc-panel-minimize"],
                    scale=0,
                    variant="secondary",
                )
            gr.Markdown(ONBOARDING_MD)
        with gr.Column(visible=True) as page_demo:
            with gr.Group(elem_classes=["vqc-optics-panel"]):
                with gr.Row(elem_classes=["vqc-optics-panel-header"]):
                    gr.HTML(OPTICS_LOGO_HTML)
                    with gr.Column(elem_classes=["vqc-optics-panel-nav"], scale=1):
                        with gr.Row(elem_classes=["vqc-nav-spreadsheet-row"]):
                            gr.HTML('<span class="vqc-source-label vqc-nav-row-label">Source:</span>')
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                tab_demo_btn = gr.Button(
                                    "Workspace",
                                    elem_classes=["vqc-source-tab", "active"],
                                    interactive=False,
                                    scale=0,
                                    variant="secondary",
                                )
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                tab_anim_btn = gr.Button(
                                    "Figures",
                                    elem_classes=["vqc-source-tab"],
                                    scale=0,
                                    variant="secondary",
                                )
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                tab_claims_btn = gr.Button(
                                    "Claims",
                                    elem_classes=["vqc-source-tab"],
                                    scale=0,
                                    variant="secondary",
                                )
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                tab_newhere_btn = gr.Button(
                                    "New here?",
                                    elem_classes=["vqc-source-tab"],
                                    scale=0,
                                    variant="secondary",
                                )
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                tab_theory_btn = gr.Button(
                                    "Theory",
                                    elem_classes=["vqc-source-tab"],
                                    scale=0,
                                    variant="secondary",
                                )
                        with gr.Row(elem_classes=["vqc-nav-spreadsheet-row"]):
                            gr.HTML('<span class="vqc-source-label vqc-nav-row-label">Links:</span>')
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                gr.HTML(_external_tab_html("GitHub", GITHUB_URL, "github"))
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                gr.HTML(_external_tab_html("qvpic", QVPIC_URL, "qvpic"))
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                gr.HTML('<span class="vqc-nav-cell-empty" aria-hidden="true">&nbsp;</span>')
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                gr.HTML('<span class="vqc-nav-cell-empty" aria-hidden="true">&nbsp;</span>')
                            with gr.Column(elem_classes=["vqc-nav-cell"], scale=1, min_width=72):
                                gr.HTML('<span class="vqc-nav-cell-empty" aria-hidden="true">&nbsp;</span>')
                optics_terminal = gr.Textbox(
                    label="Matrix status display — selection menu · d-pad nav",
                    value="",
                    lines=14,
                    max_lines=24,
                    interactive=False,
                    elem_classes=["vqc-optics-terminal-wrap", "vqc-optics-terminal"],
                )
                term_signal_scan = gr.HTML(SIGNAL_SCANNER_HTML, visible=False, elem_classes=["myst-signal-host"])
                term_active_key = gr.State("")
                term_ui_state = gr.State(_default_term_ui_state())
                term_all_btns: dict[str, gr.Button] = {}
                _dpad_row_labels = {
                    "dpad_select": "enter",
                    "dpad_up": "▲",
                    "dpad_down": "▼",
                    "dpad_left": "◀",
                    "dpad_right": "▶",
                    "clear": "clear",
                }

                with gr.Column(elem_classes=["vqc-optics-keypad"]):
                    with gr.Row(elem_classes=["vqc-optics-dpad-row"], equal_height=True):
                        for nav_key in TERM_NAV_KEYS:
                            term_all_btns[nav_key] = gr.Button(
                                _dpad_row_labels[nav_key],
                                elem_classes=_term_key_btn_classes(nav_key, ""),
                                scale=1,
                                variant="secondary",
                            )
                    with gr.Row(elem_classes=["vqc-optics-prog-row"], equal_height=True):
                        for index in range(1, 13):
                            key_id = _term_key_id(index)
                            term_all_btns[key_id] = gr.Button(
                                _term_keypad_label(index),
                                elem_classes=_term_key_btn_classes(key_id, ""),
                                scale=1,
                                variant="secondary",
                            )
                    with gr.Row(elem_classes=["vqc-optics-prog-row"], equal_height=True):
                        for index in range(13, 25):
                            key_id = _term_key_id(index)
                            term_all_btns[key_id] = gr.Button(
                                _term_keypad_label(index),
                                elem_classes=_term_key_btn_classes(key_id, ""),
                                scale=1,
                                variant="secondary",
                            )
                term_keypad_outputs = [
                    optics_terminal,
                    term_signal_scan,
                    *[term_all_btns[key_id] for key_id in TERM_KEYPAD_CONTROL_ORDER],
                    term_active_key,
                    term_ui_state,
                ]
                gr.Markdown(SIMULATION_BANNER_MD)
                run_mode = gr.Radio(
                    choices=[
                        ("⭐ Quick Demo (~20s) — recommended first visit", "quick"),
                        ("Standard HF (~45s) — balanced public demo", "standard"),
                        ("Full Research (12k) — best run locally; may timeout on HF", "research"),
                    ],
                    value="quick",
                    label="Run mode",
                    info="Quick Demo throttles 3D trajectory redraws and subsamples points for faster streaming.",
                    elem_classes=["vqc-run-mode-radio"],
                )
                runtime_hint = gr.Markdown(
                    _runtime_hint(_DEFAULTS["total_steps"], _DEFAULTS["steps_per_update"], False),
                )
                with gr.Row(elem_classes=["vqc-optics-dial-row"]):
                    total_steps = gr.Slider(
                        1000, 30000, value=_DEFAULTS["total_steps"], step=500,
                        label="Total steps", elem_classes=["vqc-optics-dial-wrap"],
                        info=SLIDER_TOOLTIPS["total_steps"],
                    )
                    steps_per_update = gr.Slider(
                        20, 200, value=_DEFAULTS["steps_per_update"], step=10,
                        label="Steps / update", elem_classes=["vqc-optics-dial-wrap"],
                        info=SLIDER_TOOLTIPS["steps_per_update"],
                    )
                    learning_rate = gr.Slider(
                        0.005, 0.08, value=_DEFAULTS["learning_rate"], step=0.005,
                        label="Learning rate", elem_classes=["vqc-optics-dial-wrap"],
                        info=SLIDER_TOOLTIPS["learning_rate"],
                    )
                    burst_factor_max = gr.Slider(
                        2.0, 12.0, value=_DEFAULTS["burst_factor_max"], step=0.5,
                        label="Burst factor max", elem_classes=["vqc-optics-dial-wrap"],
                        info=SLIDER_TOOLTIPS["burst_factor_max"],
                    )
                    use_fisher = gr.Checkbox(
                        label="Fisher-Rao modulation",
                        value=_DEFAULTS["use_fisher_modulation"],
                        info=SLIDER_TOOLTIPS["use_fisher"],
                    )
                    compare_adam = gr.Checkbox(
                        label="Compare vs RiemannianAdam (side-by-side loss)",
                        value=False,
                        info="Runs both optimizers from identical S³ init — ~2× wall time.",
                    )
                    audio_duration = gr.Slider(
                        1.0, 6.0, value=_DEFAULTS["audio_duration"], step=0.5,
                        label="Audio duration (s)", elem_classes=["vqc-optics-dial-wrap"],
                        info=SLIDER_TOOLTIPS["audio_duration"],
                    )
                gr.HTML('<p class="vqc-optics-presets-label">Optimization presets — one click loads dials</p>')
                with gr.Row():
                    preset_standard_btn = gr.Button(
                        "Standard Burst", variant="secondary", size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
                    preset_fisher_btn = gr.Button(
                        "Fisher-Rao", variant="secondary", size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
                    preset_aggressive_btn = gr.Button(
                        "Aggressive", variant="secondary", size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
                preset_note = gr.Textbox(
                    label="Preset / status", lines=1, interactive=False,
                    value=OPTIMIZATION_PRESETS["standard"]["description"],
                )
                with gr.Row(elem_classes=["vqc-utility-row"]):
                    reset_btn = gr.Button(
                        "↺ RESET workspace",
                        variant="secondary",
                        size="sm",
                        elem_classes=["vqc-utility-btn"],
                    )
                    gr.Markdown(
                        "*Resets dials to **Quick Demo** — does not clear plot history.*",
                        elem_classes=["vqc-utility-hint"],
                    )
                gr.HTML(
                    '<p class="vqc-optics-presets-label">'
                    f"Audio: bundled demo guitar — {SAMPLE_GUITAR_NOTE}"
                    "</p>"
                )
                with gr.Row():
                    demo_guitar_btn = gr.Button(
                        "▶ DEMO GUITAR (G3)",
                        variant="primary",
                        size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
                    run_opt_btn = gr.Button(
                        "▶ RUN OPTIMIZATION",
                        variant="secondary",
                        size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
                    cancel_opt_btn = gr.Button(
                        "■ CANCEL",
                        variant="stop",
                        size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
                    physics_btn = gr.Button(
                        "Smith + Overview",
                        variant="secondary",
                        size="sm",
                        elem_classes=["vqc-receiver-preset"],
                    )
            # Shared cancels list — stops in-flight terminal streams on new keypress.
            term_cancels: list = []

            def _bind_term_event(btn: gr.Button, fn, *, inputs: list) -> None:
                term_cancels.append(
                    btn.click(
                        fn,
                        inputs=inputs,
                        outputs=term_keypad_outputs,
                        cancels=term_cancels,
                    )
                )

            scan_key = _term_key_id(8)
            _bind_term_event(
                term_all_btns[scan_key],
                _make_activate_signal_scan(scan_key),
                inputs=[term_ui_state],
            )
            _bind_term_event(
                term_all_btns["clear"],
                _make_term_clear_click("clear"),
                inputs=[optics_terminal, term_ui_state],
            )
            for hold_key in TERM_DPAD_HOLD_KEYS:
                _bind_term_event(
                    term_all_btns[hold_key],
                    _make_term_dpad_click(hold_key),
                    inputs=[optics_terminal, term_ui_state],
                )
            _bind_term_event(
                term_all_btns[TERM_KEYPAD_HOME_KEY],
                _make_term_home_momentary(),
                inputs=[term_active_key, term_ui_state],
            )
            for index in range(1, TERM_KEYPAD_COUNT + 1):
                key_id = _term_key_id(index)
                if index == 1 or index == 8:
                    continue
                if index in TERM_KEYPAD_DEFINED:
                    action = TERM_KEYPAD_DEFINED[index]
                    _bind_term_event(
                        term_all_btns[key_id],
                        _make_term_stream_click(
                            key_id,
                            TERM_KEYPAD_STREAMERS[action],
                            menu_action=action,
                        ),
                        inputs=[term_ui_state],
                    )
                else:
                    _bind_term_event(
                        term_all_btns[key_id],
                        _make_term_latch_click(key_id),
                        inputs=[optics_terminal, term_ui_state],
                    )

            opt_history_state = gr.State(None)
            webgl_ok_state = gr.State(True)
            webgl_probe = gr.Textbox(value="1", visible=False, elem_classes=["vqc-webgl-probe"])

            with gr.Tabs():
                with gr.Tab("OPTIMIZE"):
                    gr.Markdown(
                        "Watch the **stereographic Rosenbrock path** toward [1,1,1] — "
                        "colored by loss. **Burst events** (vertical ticks on loss plot) fire when "
                        "a virtual string's stagnation tension triggers a plateau escape."
                    )
                    trajectory_view = gr.Radio(
                        choices=TRAJECTORY_VIEW_CHOICES,
                        value=default_trajectory_view(),
                        label="Trajectory view",
                        info="2D is recommended on HF free tier. Choose 3D only if WebGL works in your browser.",
                        elem_classes=["vqc-trajectory-view-radio"],
                    )
                    webgl_status = gr.Markdown(
                        webgl_status_markdown(True, default_trajectory_view()),
                        elem_classes=["vqc-webgl-status"],
                    )
                    with gr.Row():
                        with gr.Column(
                            visible=False,
                            scale=1,
                            elem_classes=["vqc-plot3d-col"],
                        ) as plot_3d_col:
                            plot_3d = gr.Plot(
                                label="S³ Trajectory",
                                elem_classes=["vqc-plot3d-panel"],
                            )
                        with gr.Column(
                            visible=True,
                            scale=1,
                            elem_classes=["vqc-plot3d-hint-col"],
                        ) as plot_3d_hint_col:
                            plot_3d_hint = gr.Markdown(
                                "**S³ trajectory (Quick Demo + 3D)** — hidden during the run to cut "
                                "Plotly payload. **2D (WebGL-safe)** mode streams live projections here. "
                                "Full 3D path unlocks when optimization completes.",
                                elem_classes=["vqc-plot3d-hint"],
                            )
                        plot_loss = gr.Plot(label="Loss envelope")
                    with gr.Row():
                        plot_vu = gr.Plot(label="Six-string VU meters")
                        plot_twist = gr.Plot(label="Twist accumulation")
                    opt_status = gr.Textbox(label="Optimization status", lines=4)
                    with gr.Row():
                        dl_traj = gr.DownloadButton("↓ Trajectory PNG", variant="secondary")
                        dl_loss = gr.DownloadButton("↓ Loss PNG", variant="secondary")
                        dl_vu = gr.DownloadButton("↓ VU PNG", variant="secondary")
                with gr.Tab("SPECTRUM"):
                    gr.Markdown(
                        f"Upload WAV/MP3 or use bundled **{get_sample_guitar_path().name}** — {SAMPLE_GUITAR_NOTE}"
                    )
                    audio_input = gr.Audio(
                        label="Audio input",
                        type="filepath",
                        value=str(get_sample_guitar_path()),
                    )
                    analyze_btn = gr.Button("▶ ANALYZE UPLOAD", variant="secondary")
                    with gr.Row():
                        plot_wave = gr.Plot(label="Waveform")
                        plot_spec = gr.Plot(label="STFT spectrogram")
                    with gr.Row():
                        plot_partials = gr.Plot(label="Harmonic partial tracks")
                        plot_string_energy = gr.Plot(label="Per-string partial energy")
                    spec_metrics = gr.Textbox(label="Signal metrics", lines=12)
                    gr.Markdown("**Modal synthesis** — lite before/after from estimated partials (physics-audio preview)")
                    with gr.Row():
                        synth_btn = gr.Button("▶ SYNTHESIZE MODALS", variant="primary", size="sm")
                        inharm_b = gr.Slider(
                            0.0001, 0.002, value=0.0005, step=0.0001,
                            label="Inharmonicity B", info="Modal detuning coefficient B in f_k = k f₀ √(1 + Bk²)",
                        )
                    with gr.Row():
                        audio_before = gr.Audio(label="Original (before)", type="filepath")
                        audio_after = gr.Audio(label="Modal synthesis (after)", type="filepath")
                    synth_overlay = gr.Plot(label="Waveform overlay")
                    synth_metrics = gr.Textbox(label="Synthesis metrics", lines=8)
                with gr.Tab("STRINGS"):
                    gr.Markdown(STRING_TABLE_MD)
                    strings_vu_live = gr.Plot(label="Live VU — run OPTIMIZE to populate")
                    strings_note = gr.Textbox(
                        label="Status",
                        value="Press ▶ RUN OPTIMIZATION — meters mirror OPTIMIZE tab in real time.",
                        interactive=False,
                        lines=2,
                    )
                with gr.Tab("TENSION"):
                    gr.Markdown(
                        "Complementary **string tension calculator** for guitarists — "
                        "uses frequency–length–gauge approximation (not the S³ optimizer)."
                    )
                    tension_scale = gr.Slider(
                        24.0, 27.0, value=DEFAULT_SCALE_LENGTH_IN, step=0.1,
                        label="Scale length (inches)",
                        info="25.5\" = Fender Strat scale · 24.75\" = Gibson",
                    )
                    tension_string = gr.Dropdown(
                        choices=list(STANDARD_TUNING.keys()),
                        value="G",
                        label="String",
                    )
                    tension_gauge = gr.Slider(
                        0.008, 0.056, value=0.017, step=0.001,
                        label="Gauge override (in)",
                    )
                    tension_freq = gr.Slider(
                        70, 400, value=196.0, step=0.5,
                        label="Frequency override (Hz)",
                    )
                    tension_calc_btn = gr.Button("Calculate tension", variant="secondary")
                    tension_table_md = gr.Markdown(tension_calculator_table())
                    tension_result = gr.Textbox(label="Single-string result", lines=6)
                with gr.Tab("PHYSICS"):
                    with gr.Row(equal_height=True):
                        with gr.Column(scale=1):
                            physics_metrics = gr.Textbox(label="Physics-audio metrics", lines=14)
                        with gr.Column(scale=2):
                            figure_smith = gr.Image(
                                label="Smith chart Γ preview",
                                type="filepath",
                                elem_classes=["vqc-figure-panel"],
                            )
                    figure_overview = gr.Image(
                        label="Overview composite (pyramid)",
                        type="filepath",
                        elem_classes=["vqc-figure-panel"],
                    )

            def _export_traj(history):
                p, _, _ = export_optimization_plots(history)
                return p

            def _export_loss(history):
                _, p, _ = export_optimization_plots(history)
                return p

            def _export_vu(history):
                _, _, p = export_optimization_plots(history)
                return p

            def _run_synth(audio_file, duration, b, progress=gr.Progress(track_tqdm=False)):
                try:
                    path = audio_file if audio_file else None
                    use_sample = not (path and Path(path).is_file())
                    o, s, fig, m = synthesize_modal_comparison(
                        path, duration=float(duration), use_sample=use_sample,
                        inharmonicity_b=float(b), progress_cb=progress,
                    )
                    return o, s, fig, m
                except Exception as exc:
                    logger.exception("Modal synthesis failed")
                    return None, None, go.Figure(), friendly_error("synthesis", exc)

            def _reset_workspace(traj_view, webgl_ok):
                p = get_run_mode_params("quick")
                spec = RUN_MODES["quick"]
                plot_col, hint_col = _plot_3d_for_mode("quick", None, traj_view, webgl_ok)
                return (
                    p["total_steps"],
                    p["steps_per_update"],
                    p["learning_rate"],
                    p["burst_factor_max"],
                    p["use_fisher_modulation"],
                    p.get("compare_adam", False),
                    p["audio_duration"],
                    "quick",
                    f"Reset to Quick Demo — {spec['description']}",
                    _runtime_hint(p["total_steps"], p["steps_per_update"], False),
                    "Ready — try ▶ DEMO GUITAR or Quick Demo optimize.",
                    None,
                    plot_col,
                    hint_col,
                )

            def _update_tension_table(scale):
                return tension_calculator_table(float(scale))

            def _calc_tension(string_name, scale, gauge, freq):
                return tension_single_string(
                    string_name, float(scale), float(gauge), float(freq),
                )

            opt_cancels: list = []
            opt_event = (
                run_opt_btn.click(
                    _plot_3d_on_run_start,
                    [run_mode, trajectory_view, webgl_ok_state],
                    [plot_3d_col, plot_3d_hint_col],
                )
                .then(
                    _run_optimize,
                    [
                        total_steps, steps_per_update, learning_rate, burst_factor_max,
                        use_fisher, compare_adam, run_mode, trajectory_view, webgl_ok_state,
                    ],
                    [plot_3d, plot_loss, plot_vu, plot_twist, opt_status, opt_history_state],
                )
                .then(
                    lambda vu, st: (vu, st),
                    [plot_vu, opt_status],
                    [strings_vu_live, strings_note],
                )
                .then(
                    _plot_3d_on_run_finish,
                    [run_mode, opt_history_state, trajectory_view, webgl_ok_state],
                    [plot_3d_col, plot_3d_hint_col],
                )
            )
            opt_cancels.append(opt_event)
            cancel_opt_btn.click(None, None, None, cancels=opt_cancels)

            dl_traj.click(_export_traj, [opt_history_state], [dl_traj])
            dl_loss.click(_export_loss, [opt_history_state], [dl_loss])
            dl_vu.click(_export_vu, [opt_history_state], [dl_vu])

            preset_outputs = [
                total_steps, steps_per_update, learning_rate,
                burst_factor_max, use_fisher, preset_note,
            ]
            preset_standard_btn.click(
                lambda: _apply_preset("standard"), outputs=preset_outputs,
            )
            preset_fisher_btn.click(
                lambda: _apply_preset("fisher_rao"), outputs=preset_outputs,
            )
            preset_aggressive_btn.click(
                lambda: _apply_preset("aggressive"), outputs=preset_outputs,
            )

            run_mode_outputs = [
                total_steps, steps_per_update, learning_rate, burst_factor_max,
                use_fisher, compare_adam, audio_duration, preset_note, runtime_hint,
                plot_3d_col, plot_3d_hint_col,
            ]
            run_mode.change(
                _apply_run_mode_with_3d,
                [run_mode, opt_history_state, trajectory_view, webgl_ok_state],
                run_mode_outputs,
            )

            trajectory_view.change(
                _on_trajectory_view_change,
                [trajectory_view, webgl_ok_state],
                [webgl_status],
            )

            def _hint_on_dial_change(ts, spu, cmp):
                return _runtime_hint(ts, spu, cmp)

            for dial in (total_steps, steps_per_update):
                dial.release(_hint_on_dial_change, [total_steps, steps_per_update, compare_adam], [runtime_hint])
            compare_adam.change(_hint_on_dial_change, [total_steps, steps_per_update, compare_adam], [runtime_hint])

            reset_outputs = [
                total_steps, steps_per_update, learning_rate, burst_factor_max,
                use_fisher, compare_adam, audio_duration, run_mode, preset_note,
                runtime_hint, opt_status, opt_history_state, plot_3d_col, plot_3d_hint_col,
            ]
            reset_btn.click(
                _reset_workspace,
                [trajectory_view, webgl_ok_state],
                outputs=reset_outputs,
            )

            demo_guitar_btn.click(
                _run_demo_guitar,
                [audio_duration],
                [plot_wave, plot_spec, plot_partials, plot_string_energy, spec_metrics],
            )
            analyze_btn.click(
                _run_spectrum,
                [audio_input, audio_duration],
                [plot_wave, plot_spec, plot_partials, plot_string_energy, spec_metrics],
            )
            physics_btn.click(
                _run_physics_preview,
                [],
                [physics_metrics, figure_smith, figure_overview],
            )
            synth_btn.click(
                _run_synth,
                [audio_input, audio_duration, inharm_b],
                [audio_before, audio_after, synth_overlay, synth_metrics],
            )
            tension_scale.change(_update_tension_table, [tension_scale], [tension_table_md])
            tension_calc_btn.click(
                _calc_tension,
                [tension_string, tension_scale, tension_gauge, tension_freq],
                [tension_result],
            )

            welcome_outputs = [panel_welcome, welcome_dismissed]
            welcome_dismiss_btn.click(_dismiss_welcome, outputs=welcome_outputs)
            welcome_skip_btn.click(_dismiss_welcome, outputs=welcome_outputs)
            welcome_tour_btn.click(_dismiss_welcome, outputs=welcome_outputs).then(
                lambda: (gr.update(visible=True), _source_tab_btn_update(active=True), True),
                outputs=[panel_newhere, tab_newhere_btn, newhere_open],
            )

        with gr.Column(visible=False, elem_classes=["vqc-animations-page"]) as page_animations:
            with gr.Row(elem_classes=["vqc-source-tabs-row", "vqc-animations-nav-row"]):
                gr.HTML('<span class="vqc-source-label">Source:</span>')
                anim_tab_demo_btn = gr.Button(
                    "Workspace",
                    elem_classes=["vqc-source-tab"],
                    scale=0,
                    variant="secondary",
                )
                anim_tab_anim_btn = gr.Button(
                    "Figures",
                    elem_classes=["vqc-source-tab", "active"],
                    interactive=False,
                    scale=0,
                    variant="secondary",
                )
            gr.Markdown("## Reference figures")
            gr.Markdown(FIGURES_INTRO_MD_LOCAL)
            gr.HTML(_figures_grid_html())
            gr.Markdown(_figures_links_md())

        theory_outputs = [
            panel_theory, tab_theory_btn, theory_open,
            panel_newhere, tab_newhere_btn, newhere_open,
            panel_claims, tab_claims_btn, claims_open,
        ]
        newhere_outputs = [
            panel_newhere, tab_newhere_btn, newhere_open,
            panel_claims, tab_claims_btn, claims_open,
            panel_theory, tab_theory_btn, theory_open,
        ]
        claims_outputs = [
            panel_claims, tab_claims_btn, claims_open,
            panel_newhere, tab_newhere_btn, newhere_open,
            panel_theory, tab_theory_btn, theory_open,
        ]
        nav_outputs = [
            page_demo,
            page_animations,
            tab_demo_btn,
            tab_anim_btn,
            panel_newhere,
            tab_newhere_btn,
            newhere_open,
            panel_claims,
            tab_claims_btn,
            claims_open,
            panel_theory,
            tab_theory_btn,
            theory_open,
            anim_tab_demo_btn,
            anim_tab_anim_btn,
            current_page,
        ]
        tab_demo_btn.click(lambda: _nav_to_page("demo"), outputs=nav_outputs)
        tab_anim_btn.click(lambda: _nav_to_page("animations"), outputs=nav_outputs)
        anim_tab_demo_btn.click(lambda: _nav_to_page("demo"), outputs=nav_outputs)
        anim_tab_anim_btn.click(lambda: _nav_to_page("animations"), outputs=nav_outputs)
        tab_theory_btn.click(_toggle_theory, inputs=[theory_open], outputs=theory_outputs)
        tab_newhere_btn.click(_toggle_newhere, inputs=[newhere_open], outputs=newhere_outputs)
        tab_claims_btn.click(_toggle_claims, inputs=[claims_open], outputs=claims_outputs)
        theory_minimize_btn.click(_minimize_theory, outputs=theory_outputs[:3])
        newhere_minimize_btn.click(_minimize_newhere, outputs=newhere_outputs[:3])
        claims_minimize_btn.click(_minimize_claims, outputs=claims_outputs[:3])
        demo.load(_stream_term_boot, outputs=term_keypad_outputs)
        demo.load(
            _on_webgl_probe,
            inputs=[webgl_probe],
            outputs=[webgl_ok_state, trajectory_view, webgl_status],
            js=WEBGL_PROBE_JS,
        )

        gr.Markdown(
            "6-String Optimizer — mystery shell + physics-audio · "
            f"[GitHub]({GITHUB_URL}) · [Space]({HF_SPACE_URL})"
        )
    return demo


demo = build_app()


def main() -> None:
    logging.basicConfig(level=logging.INFO)

    try:
        demo.get_api_info()
        logger.info("Gradio API info check passed")
    except Exception:
        logger.exception("Gradio API info check failed")

    on_hf = bool(os.environ.get("SPACE_ID"))
    port = int(os.environ.get("GRADIO_SERVER_PORT", "7860"))

    launch_kwargs: dict = {
        "server_name": "0.0.0.0",
        "server_port": port,
        "show_error": True,
        "show_api": False,
        "inbrowser": False,
        "share": False if on_hf else True,
    }

    demo.queue(default_concurrency_limit=2).launch(**launch_kwargs)


if __name__ == "__main__":
    main()