File size: 126,348 Bytes
feb9f49
 
 
 
 
 
 
 
 
 
 
 
7235394
feb9f49
 
 
 
 
 
8d3bef6
feb9f49
505c280
7235394
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
feb9f49
 
 
 
 
 
 
 
eeb3b99
feb9f49
505c280
eeb3b99
 
feb9f49
505c280
 
eeb3b99
feb9f49
505c280
de86f76
505c280
feb9f49
 
 
eeb3b99
 
 
feb9f49
 
 
de86f76
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a25fd
 
feb9f49
 
42a25fd
 
feb9f49
 
 
 
 
 
 
 
 
 
42a25fd
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a25fd
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
8d3bef6
 
 
 
feb9f49
 
 
7235394
eeb3b99
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
 
feb9f49
 
8d3bef6
feb9f49
8d3bef6
 
505c280
 
 
 
 
b89b2d6
 
 
 
8d3bef6
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
feb9f49
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
de86f76
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
8d3bef6
 
 
 
505c280
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
 
505c280
eeb3b99
9d42da5
eeb3b99
 
505c280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
eeb3b99
 
 
 
 
feb9f49
 
8d3bef6
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
 
feb9f49
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
 
 
 
 
 
 
42a25fd
 
 
 
 
 
 
 
 
8d3bef6
 
42a25fd
8d3bef6
 
 
 
 
feb9f49
8d3bef6
 
 
 
 
 
feb9f49
 
 
 
 
 
 
8d3bef6
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
 
 
feb9f49
 
 
8d3bef6
eeb3b99
 
 
feb9f49
 
 
eeb3b99
8d3bef6
feb9f49
eeb3b99
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
feb9f49
 
 
 
8d3bef6
 
 
feb9f49
 
de86f76
7235394
 
 
 
 
8d3bef6
7235394
feb9f49
8d3bef6
 
 
 
 
 
 
7235394
feb9f49
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
de86f76
feb9f49
 
 
de86f76
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
 
8d3bef6
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de86f76
 
 
 
feb9f49
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
8d3bef6
 
eeb3b99
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
 
8d3bef6
 
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
 
 
 
8d3bef6
 
 
 
eeb3b99
 
 
 
 
8d3bef6
 
eeb3b99
8d3bef6
 
 
eeb3b99
 
 
8d3bef6
 
feb9f49
 
 
 
 
 
 
 
 
de86f76
feb9f49
 
 
 
 
 
 
8d3bef6
de86f76
feb9f49
de86f76
feb9f49
 
 
 
 
 
 
 
de86f76
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7235394
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
505c280
 
 
feb9f49
 
de86f76
 
 
 
 
 
 
 
 
 
feb9f49
de86f76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
 
 
 
de86f76
 
eeb3b99
feb9f49
 
de86f76
 
 
 
 
 
 
 
 
 
 
 
feb9f49
de86f76
 
 
 
 
 
 
feb9f49
de86f76
 
 
 
 
 
feb9f49
de86f76
 
 
 
 
 
8d3bef6
de86f76
 
 
feb9f49
de86f76
 
feb9f49
eeb3b99
 
 
 
de86f76
 
 
feb9f49
 
de86f76
feb9f49
de86f76
 
 
8d3bef6
de86f76
feb9f49
 
7235394
 
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7235394
 
 
 
 
 
 
 
eeb3b99
 
 
505c280
 
 
 
 
 
eeb3b99
7235394
 
 
 
 
 
505c280
7235394
 
 
505c280
 
 
 
 
7235394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
7235394
 
 
505c280
 
 
 
 
 
7235394
 
 
 
 
 
 
 
 
 
eeb3b99
 
7235394
 
eeb3b99
 
 
7235394
eeb3b99
7235394
eeb3b99
7235394
 
eeb3b99
7235394
eeb3b99
7235394
 
eeb3b99
 
7235394
 
 
 
eeb3b99
7235394
eeb3b99
7235394
 
 
eeb3b99
 
7235394
 
 
 
eeb3b99
7235394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
7235394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
7235394
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7235394
 
 
feb9f49
 
 
 
 
 
 
 
 
 
7235394
feb9f49
 
 
 
 
 
 
 
 
 
 
 
eeb3b99
de86f76
feb9f49
eeb3b99
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7235394
feb9f49
 
 
 
 
 
 
 
 
eeb3b99
 
feb9f49
eeb3b99
feb9f49
 
 
 
 
 
 
 
 
eeb3b99
 
 
 
 
 
 
 
 
feb9f49
 
 
eeb3b99
feb9f49
eeb3b99
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
eeb3b99
8d3bef6
feb9f49
42a25fd
feb9f49
 
 
de86f76
eeb3b99
 
 
feb9f49
 
 
de86f76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a25fd
 
 
 
 
de86f76
42a25fd
de86f76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
feb9f49
 
 
 
 
8d3bef6
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7235394
feb9f49
 
eeb3b99
 
feb9f49
 
 
 
 
eeb3b99
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
b89b2d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
feb9f49
 
 
 
 
 
 
 
7235394
 
 
 
feb9f49
 
8d3bef6
 
feb9f49
 
 
8d3bef6
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505c280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
8d3bef6
 
 
 
feb9f49
 
 
 
 
 
 
 
505c280
feb9f49
 
 
 
 
8d3bef6
 
 
 
 
 
 
 
 
feb9f49
8d3bef6
feb9f49
 
 
 
 
 
8d3bef6
 
 
 
b89b2d6
8d3bef6
 
 
 
 
feb9f49
 
 
 
505c280
 
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
8d3bef6
 
 
 
 
 
 
 
 
 
feb9f49
 
8d3bef6
 
feb9f49
 
 
 
 
 
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
b89b2d6
8d3bef6
feb9f49
 
 
 
 
 
 
 
505c280
 
 
 
 
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
feb9f49
 
de86f76
feb9f49
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
8d3bef6
feb9f49
 
 
8d3bef6
 
 
 
 
 
 
 
 
 
 
 
 
 
feb9f49
8d3bef6
 
 
 
feb9f49
 
 
8d3bef6
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
8d3bef6
 
 
 
 
 
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
7235394
feb9f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* --------------------------------------------------------------------------
   MASSFRONT — CINEMATIC EXPLORATION TEST-ROOM LIFECYCLE

   One owner coordinates the exploration, galaxy, survey, UGA cutaway, and
   local deployment scenes. The Three.js renderer belongs to ThreeSpaceEngine
   and is shared by every scene; no second canvas or animation loop is created.
   -------------------------------------------------------------------------- */

import { ThreeSpaceEngine } from './core/three_space_engine.js?v=20260822-phone2';
import { FlightPhysics } from './core/flight_physics.js';
import { SpaceAudio } from './audio/space_audio.js?v=20260906-release5';
import { UgaCommandScene } from './core/uga_command_scene.js?v=20260830-profilegrade1';
import { GalaxyMapEngine } from './galaxy/galaxy_map_engine.js?v=20260907-warfront1';
import { SpaceHud } from './ui/space_hud.js';
import {
  KEEL_HINT_EVENT,
  STORY_TRANSMISSION_EVENT,
  createStoryTransmissionController
} from './ui/story_transmission_controller.js?v=20260829-entryintro2';
import { createUgaCommand } from './ui/uga_command.js?v=20260908-uga81r1';
import { createUgaDeploymentArena } from './ui/uga_scene.js?v=20260906-hangar2';
import { deriveGroundControl, derivePlanetControl, isGroundAreaUnlocked } from './domain/ground_control.js';
import { PlanetarySurvey } from './systems/planetary_survey.js?v=20260907-wideorbit1';
import { SHOWCASE_LAYOUT, SHOWCASE_SYSTEMS } from './systems/showcase_systems.js';
import {
  LOCAL_EXPLORATION_CAMPAIGN_STORAGE_KEY,
  LocalSandboxHost as CanonicalLocalSandboxHost
} from './host/local_sandbox_host.js?v=20260825-host1';
import {
  COMMANDER_CATALOG,
  CONSTRUCTION_FACILITY_CATALOG,
  DEPLOYMENT_STRUCTURE_CATALOG,
  DEPLOYMENT_UNIT_CATALOG,
  DISCOVERY_CATALOG,
  DISTRICT_CATALOG,
  DOCTRINE_CATALOG,
  FACTION_CATALOG,
  MISSION_CATALOG,
  MODULE_CATALOG,
  OPERATION_MOD_CATALOG,
  RESEARCH_CATALOG,
  SALVAGE_CATALOG,
  WRECK_BOARDING_CATALOG,
  SITE_CATALOG,
  SPECIALIST_CATALOG,
  SUPPORT_CATALOG,
  SURVEY_CATALOG,
  SYSTEM_CATALOG,
  LocalDomainStore,
  advanceRecoveryCycles,
  cancelConstruction,
  cancelGroundOperation,
  applyGroundResult,
  assignSpecialistToDistrict,
  beginGroundOperation,
  calculateAdjacencySynergies,
  calculatePowerGridStatus,
  calculateShipExplorationRating,
  chooseGalaxyOperationId,
  commitResearch,
  createGroundOperation,
  createGroundResult,
  createInitialDomainState,
  createMemoryStorage,
  deployProbe,
  getMissionEligibility,
  getConstructionQuote,
  getCoreCommissionRescueQuote,
  getConstructionStatus,
  getDutyWatchQuote,
  getProbeResupplyQuote,
  getRefuelQuote,
  getSurveyEligibility,
  getContactSalvage,
  getWreckBoarding,
  getUgaGroundAreaOptions,
  grantFactionResidency,
  holdDutyWatch,
  recoverPlanetFind,
  recoverContactSalvage,
  enqueueConstruction,
  installDistrictModule,
  plotCourse,
  refuelShip,
  resupplyProbes,
  requisitionCoreCommissioning,
  reorderConstruction,
  setDomainRoute,
  simulateClassicModeLaunch,
  surveySensorProfile,
  unassignSpecialist,
  upgradeDistrict,
  validateExplorationHostV1
} from './domain/index.js';

// Compatibility export for direct consumers of the original module entry.
// The implementation itself lives exclusively in src/host and preserves the
// standalone campaign/profile storage keys used by existing module saves.
export { CanonicalLocalSandboxHost as LocalSandboxHost };

const STORAGE_KEY = LOCAL_EXPLORATION_CAMPAIGN_STORAGE_KEY;
const SCENES = new Set(['system', 'survey', 'galaxy', 'uga']);
const SPACE_INSTANCE_KEY = Symbol.for('massfront.space_exploration.instance');
const CONTEXT_RESTORE_TIMEOUT_MS = 6000;
export const SPACE_FIRST_ENTRY_CONTINUATION = Object.freeze({
  schema: 'massfront.new-career-sequence.v1',
  required: true,
  moduleImplemented: true,
  nextStep: 'faction-selection',
  afterTraining: 'faction-selection',
  sequence: Object.freeze(['faction-selection', 'starter-commander-1', 'full-uga-space']),
  catalogAuthority: 'base-game-faction-and-commander-catalog'
});

function gpuFailureCopy(error) {
  const code = error && error.code;
  if (code === 'THREE_RUNTIME_UNAVAILABLE') {
    return {
      title: 'LOCAL 3D RUNTIME UNAVAILABLE',
      status: 'THE PINNED THREE.JS RUNTIME DID NOT LOAD · RELOAD THE TEST ROOM'
    };
  }
  if (code && /WEBGL|SOFTWARE_RENDERER|THREE_RENDERER/.test(code)) {
    return {
      title: 'HARDWARE GPU REQUIRED',
      status: 'WEBGL2 HARDWARE ACCELERATION IS UNAVAILABLE · ENABLE GPU ACCELERATION OR OPEN IN HARDWARE CHROME'
    };
  }
  return {
    title: 'TEST ROOM COULD NOT START',
    status: (error && error.message ? error.message : 'UNKNOWN STARTUP FAILURE').toUpperCase()
  };
}

function setRenderVeil(frame, mode, title, status, retry = false) {
  const veil = frame.querySelector('#renderVeil');
  if (!veil) return;
  const entering = mode !== 'ready' && (veil.classList.contains('ready') || veil.classList.contains('failed'));
  if (entering) resetLoadingProgress(frame, { percent: 2, stage: 'COMMAND LINK', detail: status || 'PREPARING RUNTIME' });
  veil.classList.remove('ready', 'recovering', 'failed');
  if (mode) veil.classList.add(mode);
  veil.setAttribute('aria-busy', mode === 'ready' ? 'false' : 'true');
  const heading = veil.querySelector('#renderLoadTitle');
  const detail = veil.querySelector('#loadStatus');
  if (heading && title) heading.textContent = title;
  if (detail && status) detail.textContent = status;
  let button = veil.querySelector('[data-render-retry]');
  if (retry && !button) {
    button = document.createElement('button');
    button.type = 'button';
    button.dataset.renderRetry = 'true';
    button.textContent = 'RETRY GPU INITIALIZATION';
    button.addEventListener('click', () => window.location.reload());
    (veil.querySelector('.render-failure-actions') || veil.querySelector('.render-status') || veil).appendChild(button);
  }
  if (button) button.hidden = !retry;
}

function setLoadingProgress(frame, progress) {
  if (typeof window.__MASSFRONT_SET_LOAD_PROGRESS__ === 'function') {
    window.__MASSFRONT_SET_LOAD_PROGRESS__(progress);
    return;
  }
  const value = Math.max(0, Math.min(100, Number(progress?.percent) || 0));
  const bar = frame.querySelector('#loadProgressBar');
  const percent = frame.querySelector('#loadProgressPercent');
  const phase = frame.querySelector('#loadPhase');
  const detail = frame.querySelector('#loadStatus');
  if (bar) bar.style.width = `${value}%`;
  if (percent) percent.textContent = `${Math.round(value)}%`;
  if (phase && progress?.stage) phase.textContent = progress.stage;
  if (detail && progress?.detail) detail.textContent = progress.detail;
}

function resetLoadingProgress(frame, progress = {}) {
  if (typeof window.__MASSFRONT_RESET_LOAD_PROGRESS__ === 'function') {
    window.__MASSFRONT_RESET_LOAD_PROGRESS__(progress);
    return;
  }
  setLoadingProgress(frame, progress);
}

function showStartupFailure(frame, error) {
  const copy = gpuFailureCopy(error);
  setRenderVeil(frame, 'failed', copy.title, copy.status, true);
}

function catalogArray(catalog) {
  return Object.values(catalog);
}

function issueText(error) {
  if (!error) return 'Unknown test-room error.';
  if (Array.isArray(error.issues) && error.issues.length) {
    return error.issues.slice(0, 2).map(entry => entry.message || String(entry)).join(' · ');
  }
  return error.message || String(error);
}

function resourceSummary(resources = {}) {
  return Object.entries(resources).filter(([, amount]) => amount).map(([key, amount]) => `${amount} ${key}`).join(' · ');
}

function setButtonLabel(button, text) {
  const span = button && button.querySelector('span');
  if (span) span.textContent = text;
}

export function createSpaceExperience(container, options = {}) {
  if (!container) throw new TypeError('createSpaceExperience requires a container.');
  const frame = container.id === 'moduleFrame' ? container : container.querySelector('#moduleFrame');
  if (!frame) throw new Error('The MASSFRONT test-room shell is missing #moduleFrame.');
  const existingExperience = frame[SPACE_INSTANCE_KEY];
  if (existingExperience && !existingExperience.disposed) return existingExperience;

  const $ = id => frame.querySelector(`#${id}`) || document.getElementById(id);
  const host = options.host || new CanonicalLocalSandboxHost();
  const hostValidation = validateExplorationHostV1(host);
  if (!hostValidation.ok) {
    const missing = hostValidation.issues.map(entry => entry.code || entry.message).join(', ');
    throw new TypeError(`createSpaceExperience requires ExplorationHostV1 (${missing || 'invalid host'}).`);
  }
  const initialState = createInitialDomainState(host.commanderCatalogContext || null);
  if (options.seed !== undefined) initialState.seed = String(options.seed);
  let initialSnapshot = null;
  try {
    // The canonical host merges its separately stored account profile through
    // loadProfileSnapshot() before returning this campaign snapshot.
    const candidate = host.loadCampaignSnapshot();
    if (candidate && typeof candidate.then !== 'function') initialSnapshot = candidate;
  } catch (error) {
    setRenderVeil(frame, 'failed', 'GALACTIC SAVE NEEDS RECOVERY', 'YOUR EXISTING SAVE HAS BEEN PRESERVED. REOPEN WITH A COMPATIBLE BUILD OR RESTORE YOUR SAVE BACKUP.', true);
    throw error;
  }
  const store = options.store || new LocalDomainStore({
    storage: options.storage || host.storage || createMemoryStorage(),
    key: host.key || STORAGE_KEY,
    initialState: initialSnapshot || initialState,
    commanderCatalogContext: host.commanderCatalogContext || null
  });
  let state;
  try {
    state = store.load({ recover: false, snapshot: initialSnapshot });
  } catch (error) {
    setRenderVeil(frame, 'failed', 'GALACTIC SAVE NEEDS RECOVERY', 'YOUR EXISTING SAVE HAS BEEN PRESERVED. REOPEN WITH A COMPATIBLE BUILD OR RESTORE YOUR SAVE BACKUP.', true);
    throw error;
  }
  const savedRoute = { ...state.route };
  const initialEntryView = (options.entryView || host.ticket?.entryView) === 'campaign_hub'
    ? 'campaign_hub'
    : 'system';
  const exteriorRequired = initialEntryView !== 'campaign_hub';
  let sceneMode = 'system';
  let selectedTarget = null;
  let selectedGalaxyId = state.route.systemId;
  let selectedGalaxyMissionId = null;
  let selectedGalaxyPreferredAreaId = null;
  let galaxyMap = null;
  let paused = false;
  let disposed = false;
  let contextRecovering = false;
  let assetsReady = false;
  let raf = 0;
  let lastTime = performance.now();
  let toastTimer = 0;
  let transitTimer = 0;
  let contextRestoreTimer = 0;
  let startupTimer = 0;
  let startupTimedOut = false;
  let ugaLoadPromise = null;
  let ugaRequestedFocus = null;
  let resolveCampaignHubReady = null;
  const campaignHubReady = exteriorRequired ? null : new Promise(resolve => { resolveCampaignHubReady = resolve; });
  let systemLoadStarted = false;
  let hostRoutePending = false;
  let operationKind = 'ground';
  let operationBridgeNonce = null;
  let restoredPendingOperation = false;
  const removers = [];
  const pointer = { active: false, id: null, x: 0, y: 0, lastX: 0, lastY: 0, moved: false };
  const navPointers = new Map();
  /* Navigation is an RTS map view: mostly overhead, north-up, pannable.
     The old default (pitch 0.42) framed the hull against black — legible as a
     model, not as a place. High pitch reads the system as a chart; dist still
     reaches down to hull inspection. */
  const navCameraDefault = Object.freeze({ yaw: 0, pitch: 1.08, dist: 2.4, panX: 0, panZ: 0 });
  /* The old 2.5 ceiling was barely above the old default - there was almost
     nothing to pull back to. 4.5 lets a player actually survey the system
     instead of only inspecting the hull. */
  const NAV_CAM_MIN_DIST = 0.55, NAV_CAM_MAX_DIST = 4.5;
  const camState = { ...navCameraDefault };
  let pinchGap = 0;
  let raycaster = null;
  let pointerNdc = null;
  let firstEntryIntroStarted = false;
  let firstEntryChoicePending = false;
  let firstEntryChoice = '';
  const spaceAudio = new SpaceAudio({
    profileId: state.profileId,
    allowDocumentFallback: true
  });
  const storyTransmissions = createStoryTransmissionController($('storyRail'), {
    onPresent: cue => spaceAudio.playStory(cue),
    onDismiss: () => spaceAudio.endStory(),
    onError: error => showToast(`TRANSMISSION ACTION FAILED · ${issueText(error)}`, true)
  });

  const spatialHud = $('spatialHudLayer');
  let engine = null;
  let commandScene = null;
  let deploymentArena = null;
  try {
    engine = new ThreeSpaceEngine(spatialHud, {
      seed: state.seed,
      onSystemLoaded: () => {
        selectedTarget = arkTarget();
        if (hud) hud.setTargetInfo(selectedTarget, physics.ship);
      },
      onContextLost: handleContextLost,
      onContextRestored: handleContextRestored,
      onLoadProgress: progress => setLoadingProgress(frame, progress)
    });
  } catch (error) {
    showStartupFailure(frame, error);
    if (!options.host && typeof host.dispose === 'function') host.dispose();
    throw error;
  }
  raycaster = new THREE.Raycaster();
  pointerNdc = new THREE.Vector2();
  const physics = new FlightPhysics({ z: 120 }, {
    onWarpArrive: destination => {
      if (destination?.jumpTo) beginTransit(destination.jumpTo);
    }
  });
  const hud = new SpaceHud(spatialHud, target => selectTarget(target));
  try {
    commandScene = new UgaCommandScene(engine.renderer, {
      onDistrictSelected: id => ugaUi && ugaUi.selectDistrict(id, { emit: false }),
      onBuildPlotSelected: (id, plotId) => ugaUi && ugaUi.openConstructionPlot(id, plotId)
    });
    deploymentArena = createUgaDeploymentArena(commandScene, {
      onHotspot: station => ugaUi?.activateDeploymentHotspot(station)
    });
  } catch (error) {
    hud.dispose();
    engine.dispose();
    showStartupFailure(frame, error);
    if (!options.host && typeof host.dispose === 'function') host.dispose();
    throw error;
  }

  function handleContextLost() {
    if (disposed || contextRecovering) return;
    contextRecovering = true;
    if (raf) cancelAnimationFrame(raf);
    raf = 0;
    clearTimeout(contextRestoreTimer);
    setRenderVeil(
      frame,
      'recovering',
      'RESTORING GPU CONTEXT',
      'THE HARDWARE GRAPHICS CONTEXT WAS INTERRUPTED · SCENE STATE IS PRESERVED'
    );
    contextRestoreTimer = window.setTimeout(() => {
      if (!disposed && contextRecovering) {
        setRenderVeil(
          frame,
          'recovering',
          'REBUILDING WEBGL2 RENDERER',
          'THE GPU PROCESS RETURNED WITHOUT RESTORING ITS OLD CONTEXT · RECREATING ONE HARDWARE CONTEXT'
        );
        window.dispatchEvent(new CustomEvent('massfront:space-gpu-stalled'));
      }
    }, CONTEXT_RESTORE_TIMEOUT_MS);
  }

  function handleContextRestored() {
    if (disposed || !contextRecovering) return;
    clearTimeout(contextRestoreTimer);
    contextRestoreTimer = 0;
    // Rehydrate only what the next frame will render. Marking the system,
    // cutaway and galaxy together caused a restore-time upload/compile burst
    // that immediately killed the embedded browser context a second time.
    if (sceneMode === 'uga' && commandScene) {
      commandScene.handleContextRestored();
      engine.restoreSceneResources(commandScene.scene);
    }
    else if (sceneMode === 'galaxy' && galaxyMap?.scene) engine.restoreSceneResources(galaxyMap.scene);
    else engine.restoreSceneResources(engine.scene);
    contextRecovering = false;
    resize();
    if (!paused && (sceneMode === 'system' || sceneMode === 'survey')) engine.resume();
    if (!paused && sceneMode === 'galaxy' && galaxyMap) galaxyMap.resume();
    if (assetsReady || !exteriorRequired) setRenderVeil(frame, 'ready');
    else setRenderVeil(
      frame,
      '',
      'ASSEMBLING UGA EXPEDITION',
      'STREAMING AUTHORED SHIP GEOMETRY AND PBR MATERIALS'
    );
    lastTime = performance.now();
    scheduleFrame();
  }

  function listen(target, type, listener, optionsArg) {
    if (!target) return;
    target.addEventListener(type, listener, optionsArg);
    removers.push(() => target.removeEventListener(type, listener, optionsArg));
  }

  function arkTarget() {
    return {
      id: 'nexus_vii',
      name: 'NEXUS-VII',
      sub: 'WAYFARER · CIVILIZATION COMMAND VESSEL',
      kind: 'uga-ship', interaction: 'uga-command',
      x: physics.ship.x, y: physics.ship.y, z: physics.ship.z
    };
  }

  function getUiState() {
    const discoveries = state.discoveries.foundIds.map(id => ({
      ...DISCOVERY_CATALOG[id],
      description: `${DISCOVERY_CATALOG[id].category.replaceAll('_', ' ')} evidence archived by the expedition.`
    }));
    const commanders = Object.fromEntries(Object.entries(COMMANDER_CATALOG).map(([id, definition]) => [id, {
      ...definition, ...state.personnel.commanders[id]
    }]));
    const specialists = Object.fromEntries(Object.entries(SPECIALIST_CATALOG).map(([id, definition]) => [id, {
      ...definition, ...state.personnel.specialists[id]
    }]));
    return { ...state, discoveries, commanders, specialists };
  }

  function missionView(mission) {
    const eligibility = missionPlanningEligibility(mission);
    const system = SYSTEM_CATALOG[mission.systemId];
    const site = SITE_CATALOG[mission.siteId];
    return {
      ...mission,
      name: mission.title,
      description: mission.missionType === 'uga_brood_purge'
        ? `${site.name}: UGA containment authority has confirmed active Brood hive targets.`
        : `${site.name}: ${FACTION_CATALOG[mission.contractFactionId].name} requests a resident proxy operation in ${system.name}.`,
      sponsorFactionId: mission.sponsorId,
      contractFactionId: mission.contractFactionId,
      enemyFactionId: mission.opponentFactionId,
      opposition: mission.opponentFactionId,
      locks: eligibility.locks.map(entry => entry.message),
      defaults: eligibility.defaults
    };
  }

  function getCatalogView() {
    const missions = Object.fromEntries(Object.values(MISSION_CATALOG).map(mission => [mission.id, missionView(mission)]));
    return {
      DISTRICT_CATALOG, MODULE_CATALOG, FACTION_CATALOG, RESEARCH_CATALOG,
      COMMANDER_CATALOG, SPECIALIST_CATALOG, DOCTRINE_CATALOG, SUPPORT_CATALOG,
      DEPLOYMENT_UNIT_CATALOG, DEPLOYMENT_STRUCTURE_CATALOG, OPERATION_MOD_CATALOG,
      MISSION_CATALOG: missions,
      SURVEY_CATALOG,
      districts: DISTRICT_CATALOG,
      modules: MODULE_CATALOG,
      facilities: CONSTRUCTION_FACILITY_CATALOG,
      factions: FACTION_CATALOG,
      research: RESEARCH_CATALOG,
      commanders: COMMANDER_CATALOG,
      specialists: SPECIALIST_CATALOG,
      doctrines: DOCTRINE_CATALOG,
      supportPackages: SUPPORT_CATALOG,
      deploymentUnits: DEPLOYMENT_UNIT_CATALOG,
      deploymentStructures: DEPLOYMENT_STRUCTURE_CATALOG,
      operationMods: OPERATION_MOD_CATALOG,
      missions,
      surveys: SURVEY_CATALOG
    };
  }

  function commit(next, type) {
    state = store.save(next, { type });
    return state;
  }

  function transact(action, type) {
    try {
      const next = action(state);
      if (next && next !== state) commit(next, type);
      else refreshAll();
      return true;
    } catch (error) {
      showToast(issueText(error), true);
      return false;
    }
  }

  function showToast(message, danger = false) {
    const toast = $('toastBanner');
    if (!toast) return;
    clearTimeout(toastTimer);
    toast.textContent = String(message);
    toast.classList.toggle('danger', danger);
    toast.classList.add('show');
    toastTimer = setTimeout(() => toast.classList.remove('show'), 3300);
  }

  function waitForInterfacePaint() {
    return new Promise(resolve => requestAnimationFrame(() => resolve()));
  }

  function signalFirstEntryChoice(choice, outcome, routeId) {
    const detail = {
      schema: 'massfront.space-first-entry-choice.v1',
      profileId: state.profileId,
      choice,
      outcome,
      routeId,
      nextStep: choice === 'training' ? 'protected-planetary-training' : 'faction-selection',
      continuation: SPACE_FIRST_ENTRY_CONTINUATION
    };
    window.__MASSFRONT_SPACE_ONBOARDING_CHOICE__ = detail;
    try {
      window.dispatchEvent(new CustomEvent('massfront:space-first-entry-choice', { detail }));
    } catch (_) {}
    return detail;
  }

  async function routeFirstEntryChoice(choice) {
    if (firstEntryChoicePending) return false;
    const training = choice === 'training';
    const outcome = training ? 'protected-planetary-training' : 'required-faction-selection';
    const routeId = training ? 'mode-training' : 'new-career-faction';
    firstEntryChoicePending = true;
    firstEntryChoice = choice;
    signalFirstEntryChoice(choice, outcome, routeId);
    try {
      showToast(training
        ? 'BASIC TUTORIAL SELECTED · RETURNING TO MASSFRONT'
        : 'COMMANDER COMMISSIONING SELECTED · RETURNING TO MASSFRONT');
      await waitForInterfacePaint();
      await host.openBaseRoute(routeId, {
        systemId: state.route.systemId,
        targetId: selectedTarget?.id || state.route.targetId || null
      });
      firstEntryChoicePending = false;
      return true;
    } catch (error) {
      firstEntryChoicePending = false;
      firstEntryChoice = '';
      showToast(`CAREER ROUTE UNAVAILABLE · ${issueText(error)}`, true);
      storyTransmissions.present(firstEntryChoiceCue(), { replace: true });
      return false;
    }
  }

  function firstEntryChoiceCue() {
    return {
      id: 'first-entry-choice',
      context: 'space-intro',
      surface: 'space-story-rail',
      speaker: 'KEEL',
      speakerId: 'keel',
      affiliation: 'uga',
      speakerRole: 'UGA EXPEDITION GUIDE',
      channel: 'UGA PERSONNEL LINK',
      voiceId: 'keel',
      profileId: 'uga-keel-expedition-guide',
      animationId: 'keel-space-link',
      title: 'SELECT YOUR STARTING PATH',
      stageLabel: 'COMMAND DECISION',
      text: 'You command the UGA exploration ship. Survey points of interest, review an objective, then choose an available hired commander and deployment force. Return here after the mission to develop your ship. First, learn the field controls or arrange your first commander.',
      durationMs: 0,
      priority: 90,
      meta: { continuation: SPACE_FIRST_ENTRY_CONTINUATION },
      actions: [
        {
          id: 'begin-planetary-training',
          choice: 'training',
          label: 'BEGIN BASIC TUTORIAL',
          kind: 'primary',
          description: 'Protected planetary mission covering navigation, selection, economy, construction and combat.',
          metaLabel: 'RECOMMENDED · PROTECTED',
          outcome: 'protected-planetary-training',
          nextStep: 'protected-planetary-training',
          continuation: SPACE_FIRST_ENTRY_CONTINUATION,
          onSelect: () => routeFirstEntryChoice('training')
        },
        {
          id: 'skip-to-faction-selection',
          choice: 'skipped',
          label: 'ARRANGE FIRST COMMANDER',
          kind: 'secondary',
          description: 'Choose the faction supplying your first commander. Select that available commander when preparing an objective.',
          metaLabel: 'NO TRAINING MISSION',
          outcome: 'required-faction-selection',
          nextStep: 'faction-selection',
          continuation: SPACE_FIRST_ENTRY_CONTINUATION,
          onSelect: () => routeFirstEntryChoice('skipped')
        }
      ]
    };
  }

  function firstEntrySequence() {
    return [
      {
        id: 'first-entry-aelos',
        context: 'space-intro',
        surface: 'space-story-rail',
        speaker: 'KEEL',
        speakerId: 'keel',
        affiliation: 'uga',
        speakerRole: 'UGA EXPEDITION GUIDE',
        channel: 'UGA PERSONNEL LINK',
        voiceId: 'keel',
        voiceAction: 'greeting',
        profileId: 'uga-keel-expedition-guide',
        animationId: 'keel-space-link',
        title: 'WELCOME TO THE AELOS ANCHORAGE',
        stageLabel: 'ARRIVAL BRIEF',
        text: 'Welcome aboard your UGA exploration ship. I am KEEL. Drag to look around, select a contact, and use ALIGN or AUTOPILOT to approach. SURVEY opens the scanner for a selected planet.',
        // Essential instructions wait for the player, not a short voice timer.
        durationMs: 0,
        actions: [{ id: 'first-entry-next', label: 'NEXT · YOUR MISSION LOOP', kind: 'primary' }],
        priority: 90
      },
      {
        id: 'first-entry-keel',
        context: 'space-intro',
        surface: 'space-story-rail',
        speaker: 'KEEL',
        speakerId: 'keel',
        affiliation: 'uga',
        speakerRole: 'UGA EXPEDITION GUIDE',
        channel: 'UGA PERSONNEL LINK',
        voiceId: 'keel',
        profileId: 'uga-keel-expedition-guide',
        animationId: 'keel-space-link',
        title: 'YOUR FIRST COMMAND DECISION',
        stageLabel: 'PATH SELECTION',
        text: 'Scan for points of interest and prepare an objective with a hired commander. Your ship is home: return after deployment to upgrade, craft and equip. Classic modes remain available at its War Table. Protected planetary training teaches selection, economy and combat.',
        durationMs: 0,
        actions: [{ id: 'first-entry-continue', label: 'CONTINUE', kind: 'primary' }],
        priority: 90
      },
      firstEntryChoiceCue()
    ];
  }

  async function startFirstEntryIntro() {
    const entryView = host.ticket?.entryView || 'system';
    /* The base ticket can outlive the first visit. Replaying onboarding after
       commissioning forced every restored UGA/survey/galaxy save back to the
       system camera immediately after ready resolved. */
    if (disposed || firstEntryIntroStarted || state.commissioning?.completed
        || host.productionIntegrated !== true || entryView !== 'system') return false;
    if (!assetsReady) await ready;
    if (disposed || firstEntryIntroStarted) return false;
    firstEntryIntroStarted = true;
    setScene('system', { persist: false });
    const played = storyTransmissions.playSequence(firstEntrySequence(), { replace: true, priority: 90 });
    if (!played) firstEntryIntroStarted = false;
    return played;
  }

  function refreshResources() {
    $('statFuelVal').textContent = `${state.resources.fuel}`;
    $('statProbesVal').textContent = `${state.resources.probes}`;
    $('statResearchVal').textContent = state.resources.researchPoints.toLocaleString();
    $('statCreditsVal').textContent = state.resources.credits.toLocaleString();
  }

  function storyCopy() {
    const current = state.route.systemId;
    if (current === 'aelos' && !state.world.systems.veyra.discovered) return {
      title: 'Anchorage Departure',
      body: 'Select a planet and open SURVEY. Find the signal peak and deploy a probe to reveal discoveries. Prepare discovered objectives with an available hired commander; return to UGA COMMAND to build and equip.',
      steps: [['Inspect NEXUS-VII', true], ['Census orbital traffic', state.surveys.aelos_traffic_census.depleted], ['Resolve Veyra route', state.surveys.aelos_phase_trace.depleted]]
    };
    if (current === 'veyra' && !state.world.systems.karak.discovered) return {
      title: 'The Lensing Scar',
      body: 'Upgrade the Survey Lab, study the photon ring, and recover the distress echo hidden in Veyra’s derelict field.',
      steps: [['Reach Survey Lab II', state.ship.districts.survey.level >= 2], ['Archive photon ring', state.surveys.veyra_photon_ring.depleted], ['Resolve Karak vector', state.surveys.veyra_derelict_echo.depleted]]
    };
    if (current === 'karak' && !state.world.systems.karak.infestation.active) {
      const meridian = derivePlanetControl(state).karak_meridian;
      if (meridian?.controlled) return {
        title: 'Karak Reclamation',
        body: 'All Meridian K-4 regions are secure. The planetary infestation has been cleared.',
        steps: [['Secure Meridian K-4 regions', true], ['Clear the infestation', true]]
      };
      if (state.operations.history.some(entry => entry?.result?.missionId === 'uga_hive_heart' && entry.result.outcome === 'victory')) return {
        title: 'Karak Cleanup',
        body: 'The Hive Heart was struck, but uncleared colony maps still hold Brood nests. Finish the remaining surface operations.',
        steps: [['Strike the Hive Heart', true], [`Secure regions ${meridian?.controlledAreas || 0} / ${meridian?.totalAreas || 3}`, false]]
      };
      return {
        title: 'Dead Air',
        body: 'The colony traffic grid is silent. Triangulate its dark beacons before authorizing any surface operation.',
        steps: [['Enter Karak', true], ['Triangulate beacons', false], ['Identify the silence', false]]
      };
    }
    if (current === 'karak' && !state.world.systems.karak.infestation.hiveTargetsConfirmed) return {
      title: 'Something Beneath',
      body: 'The infestation is confirmed. Raise the Survey Lab to tier III and map viable hive targets for a UGA purge package.',
      steps: [['Confirm infestation', true], ['Reach Survey Lab III', state.ship.districts.survey.level >= 3], ['Map hive geometry', state.surveys.karak_hive_scan.depleted]]
    };
    if (current === 'karak') return {
      title: 'Containment Authority',
      body: 'Hive targets are confirmed. Complete Brood Containment research and prepare any ready resident faction as UGA’s proxy.',
      steps: [['Map hive targets', true], ['Research containment', state.research.completedIds.includes('uga_brood_containment')], ['Resolve UGA purge', state.missions.uga_pale_bloom.completions > 0]]
    };
    return {
      title: 'Expedition Continuity',
      body: 'Return to NEXUS-VII to review discoveries, research, residents, and operation readiness.',
      steps: [['Maintain route', true], ['Develop NEXUS-VII', false], ['Prepare operation', false]]
    };
  }

  function refreshHeaderAndStory() {
    const runtime = SHOWCASE_SYSTEMS[state.route.systemId] || SHOWCASE_SYSTEMS.aelos;
    // A broken route falls back to the home anchor. It used to name sombrero_i,
    // which did not exist in the catalog until the War Table systems arrived —
    // an invalid route must land on Aelos, not on a capital star.
    const catalog = SYSTEM_CATALOG[state.route.systemId] || SYSTEM_CATALOG.aelos;
    if (!runtime) return;
    $('crumbCluster').textContent = String(runtime.cluster || '').toUpperCase();
    $('crumbSystem').textContent = String(runtime.name || '').toUpperCase();
    $('crumbThreat').textContent = runtime.security || 'UNKNOWN';
    $('systemActivity').textContent = state.route.systemId === 'aelos'
      ? '428 CIVILIAN TRANSPONDERS'
      : state.route.systemId === 'veyra' ? '11 UNIDENTIFIED REFLECTIONS' : '0 CIVILIAN TRANSPONDERS';
    const story = storyCopy();
    $('storyTitle').textContent = story.title;
    $('storyBody').textContent = story.body;
    $('storySteps').innerHTML = story.steps.map(([label, complete], index) =>
      `<li class="${complete ? 'complete' : index === story.steps.findIndex(step => !step[1]) ? 'active' : ''}"><span>${String(index + 1).padStart(2, '0')}</span><b>${label}</b></li>`
    ).join('');
  }

  function setActionLabelForTarget(target) {
    const interact = $('actInteract');
    const runtime = SHOWCASE_SYSTEMS[state.route.systemId] || SHOWCASE_SYSTEMS.aelos;
    if (!target) setButtonLabel(interact, 'INTERACT');
    else if (target.id === 'nexus_base') setButtonLabel(interact, 'MANAGE NEXUS-VII');
    else if (target.id && runtime?.planets?.some(planet => planet.id === target.id)) setButtonLabel(interact, 'OPEN ORBITAL SURVEY');
  }

  function refreshTargetActions() {
    const interact = $('actInteract');
    const survey = $('actSurvey');
    const warp = $('actWarp');
    const target = selectedTarget;
    interact.disabled = !target;
    survey.disabled = !catalogArray(SURVEY_CATALOG).some(entry => entry.systemId === state.route.systemId);
    warp.disabled = !target;
    if (!target) {
      setButtonLabel(interact, 'SELECT CONTACT');
      return;
    }
    if (target.interaction === 'uga-command' || target.kind === 'uga-ship') setButtonLabel(interact, 'ENTER UGA MANAGEMENT');
    else if (target.interaction === 'faction-residency') setButtonLabel(interact, 'OPEN FACTION QUARTERS');
    else if (target.interaction === 'logistics') setButtonLabel(interact, 'OPEN LOGISTICS');
    else if (target.jumpTo) setButtonLabel(interact, 'PLOT SYSTEM COURSE');
    else if (target.id && SHOWCASE_SYSTEMS[state.route.systemId].planets.some(planet => planet.id === target.id)) setButtonLabel(interact, 'OPEN ORBITAL SURVEY');
    else if (target.id && SALVAGE_CATALOG[target.id]) {
      const boarding = getWreckBoarding(target.id);
      if (boarding && !state.discoveries.extractedDepositIds.includes(target.id)) setButtonLabel(interact, 'BOARD THE WRECK');
      else if (boarding) setButtonLabel(interact, 'REVIEW BOARDING AREA');
      else setButtonLabel(interact, state.discoveries.extractedDepositIds.includes(target.id) ? 'WRECK STRIPPED' : 'SALVAGE THE WRECK');
    }
    else setButtonLabel(interact, 'INSPECT CONTACT');
  }

  function refreshAll() {
    if (disposed) return;
    refreshResources();
    refreshHeaderAndStory();
    refreshTargetActions();
    if (ugaUi) ugaUi.setState(getUiState());
    if (commandScene.loaded) {
      for (const [id, district] of Object.entries(state.ship.districts)) {
        commandScene.setDistrictLevel(id, district.level);
        commandScene.setDistrictConstructionState(id, district, state.ship.constructionQueue);
      }
    }
    if (sceneMode === 'survey') refreshSurvey();
    if (sceneMode === 'galaxy') selectSystemInGalaxy(selectedGalaxyId);
    try {
      const saving = host.saveCampaignSnapshot(state);
      if (saving && typeof saving.catch === 'function') saving.catch(error => showToast(`SAVE FAILED · ${issueText(error)}`, true));
    } catch (error) {
      showToast(`SAVE FAILED · ${issueText(error)}`, true);
    }
  }

  const unsubscribeStore = store.subscribe(next => {
    state = next;
    refreshAll();
  });
  removers.push(unsubscribeStore);

  function applyCommandSceneState() {
    if (!commandScene.loaded) return;
    deploymentArena?.attach();
    for (const [id, district] of Object.entries(state.ship.districts)) {
      commandScene.setDistrictLevel(id, district.level);
      commandScene.setDistrictConstructionState(id, district, state.ship.constructionQueue);
    }
    if (sceneMode !== 'uga') return;
    if (ugaRequestedFocus) commandScene.focusDistrict(ugaRequestedFocus);
    else commandScene.focusOverview();
  }

  function requestUgaVisual(districtId = null) {
    ugaRequestedFocus = districtId || null;
    if (commandScene.loaded) {
      applyCommandSceneState();
      return Promise.resolve(true);
    }
    frame.dataset.ugaVisualState = 'streaming';
    if (!ugaLoadPromise) {
      showToast('INSIDE NEXUS-VII · OPENING SHIP INTERIOR');
      ugaLoadPromise = commandScene.ready().then(() => {
        if (disposed) return false;
        frame.dataset.ugaVisualState = 'ready';
        applyCommandSceneState();
        showToast('NEXUS-VII INTERIOR READY');
        return true;
      }).catch(error => {
        ugaLoadPromise = null;
        if (!disposed) {
          frame.dataset.ugaVisualState = 'failed';
          showToast('SHIP VIEW UNAVAILABLE · UGA CONTROLS REMAIN ONLINE · TAP VESSEL OVERVIEW TO RETRY', true);
          console.warn('[MASSFRONT UGA OPTIONAL VISUAL]', error);
        }
        return false;
      });
    }
    return ugaLoadPromise;
  }

  const ugaUi = createUgaCommand({
    container: $('ugaCommandMount'),
    visible: false,
    getState: getUiState,
    getCatalog: getCatalogView,
    getPowerGridStatus: s => calculatePowerGridStatus(s),
    getShipExplorationRating: s => calculateShipExplorationRating(s),
    getAdjacencySynergies: s => calculateAdjacencySynergies(s),
    getConstructionStatus: s => getConstructionStatus(s),
    // The UI projection replaces discoveries with display rows; quotes must
    // validate the authoritative domain state, not that presentation shape.
    getConstructionQuote: (_s, districtId, facilityId) => getConstructionQuote(state, districtId, facilityId),
    getCoreCommissionRescueQuote: () => getCoreCommissionRescueQuote(state),
    getProbeResupplyQuote: () => getProbeResupplyQuote(state),
    getRefuelQuote: () => getRefuelQuote(state),
    getDutyWatchQuote: () => getDutyWatchQuote(state),
    getResearchQuote: (researchId, amount) => commitResearch(state, researchId, amount),
    getMissionEligibility: (missionId, request = {}) => getMissionEligibility(state, missionId, request),
    onRefuel: () => transact(current => refuelShip(current), 'refuel:stores'),
    onProbeResupply: () => transact(current => resupplyProbes(current), 'probes:stores'),
    /* The strategic clock finally has a player-facing dial. The breach list
       rides the toast because the front panel itself re-renders from committed
       state; the toast is the only channel that survives that re-render. */
    onDutyWatch: () => {
      try {
        const watch = holdDutyWatch(state);
        if (!watch.advanced) { refreshAll(); return true; }
        const breach = Array.isArray(watch.breach) && watch.breach.length
          ? ` · FRONT BREACHED: ${watch.breach.map(id => String(id).toUpperCase()).join(', ')}` : '';
        commit(watch.state, 'watch:front');
        showToast(`DUTY WATCH · +2 EXPEDITION CYCLES${breach}`);
        return true;
      } catch (error) {
        showToast(issueText(error), true);
        return false;
      }
    },
    onConstructionStart: (districtId, facilityId) => transact(current => enqueueConstruction(current, districtId, facilityId), `construction:${districtId}:${facilityId || 'commission'}`),
    onCoreCommissionRescue: () => {
      const accepted = transact(current => requisitionCoreCommissioning(current), 'construction:core-rescue');
      if (accepted) showToast('REQUIRED CORE WORK REQUISITIONED · OPEN CONSTRUCTION QUEUE');
      return accepted;
    },
    onConstructionCancel: jobId => transact(current => cancelConstruction(current, jobId), `construction-cancel:${jobId}`),
    onConstructionReorder: (jobId, direction) => transact(current => reorderConstruction(current, jobId, direction), `construction-order:${jobId}`),
    onDistrictFocus: id => {
      requestUgaVisual(id);
      return commandScene.focusDistrict(id);
    },
    onOverviewFocus: () => commandScene.focusOverview(),
    onDistrictUpgrade: id => transact(current => upgradeDistrict(current, id), `upgrade:${id}`),
    onModuleInstall: (districtId, socketId, moduleId) => transact(current => installDistrictModule(current, districtId, socketId, moduleId), `module:${moduleId}`),
    onSpecialistAssign: (districtId, slotIndex, specialistId) => transact(current => assignSpecialistToDistrict(current, districtId, slotIndex, specialistId), `staff:${specialistId}`),
    onSpecialistUnassign: (districtId, slotIndex) => transact(current => unassignSpecialist(current, districtId, slotIndex), `unstaff:${districtId}:${slotIndex}`),
    onResearchAllocate: (researchId, amount) => transact(current => commitResearch(current, researchId, amount).state, `research:${researchId}`),
    onFactionResidency: factionId => transact(current => grantFactionResidency(current, factionId), `residency:${factionId}`),
    onCommanderPrepare: commanderId => {
      const person = state.personnel.commanders[commanderId];
      showToast(person?.injury ? 'Commander is in medical recovery.' : `${COMMANDER_CATALOG[commanderId]?.name || 'Commander'} is ready for assignment.`, Boolean(person?.injury));
    },
    onMissionSelect: missionId => {
      const mission = MISSION_CATALOG[missionId];
      const eligibility = mission ? missionPlanningEligibility(mission) : getMissionEligibility(state, missionId);
      showToast(eligibility.eligible ? 'Operation package unlocked.' : eligibility.locks[0]?.message || 'Operation is locked.', !eligibility.eligible);
    },
    onDeploymentPreview: draft => {
      deploymentArena?.attach();
      deploymentArena?.setDraft(draft);
    },
    onDeploy: payload => launchOperation(payload),
    /* Production modes belong to the base game. The isolated host deliberately
       receives no callback, which keeps every host-owned route visibly locked
       instead of turning a menu choice into a simulated success. */
    onHostRoute: typeof host.openBaseRoute === 'function'
      ? async routeId => {
          if (hostRoutePending) return false;
          hostRoutePending = true;
          const destination = routeId === 'mode-training' ? 'BASIC TUTORIAL'
            : routeId === 'mode-standard' ? 'STANDARD DEPLOYMENT'
              : routeId === 'mode-campaign' ? 'CAMPAIGN'
                : 'MASSFRONT';
          showToast(`${destination} SELECTED · OPENING BASE COMMAND`);
          await waitForInterfacePaint();
          try {
            /* A secured menu route carries its UGA ORIGIN and nothing else.
               Sending the current selection as targetId made every one of
               these tabs fail whenever the player had something selected that
               the host's location contract does not list: the host rejects an
               unrecognised target outright (it refuses to let a menu choice
               become a hidden RTS map choice), so openBaseRoute returned
               false and rejectMenuRoute dropped the player on startScreen.
               The Armory does not depend on which world is selected, so the
               system alone is the origin these routes are allowed to carry. */
            return await host.openBaseRoute(routeId, {
              systemId: state.route.systemId,
              targetId: null
            });
          } finally {
            hostRoutePending = false;
          }
        }
      : null,
    onError: (error, context = {}) => showToast(
      context.callback === 'onHostRoute'
        ? `BASE COMMAND UNAVAILABLE · ${issueText(error)} · PLAY REMAINS AVAILABLE`
        : `COMMAND FAILED · ${issueText(error)}`,
      true
    ),
    onOpenGalaxy: () => openGalaxy(),
    onExit: () => openSystem(),
  });

  function setScene(mode, { persist = true } = {}) {
    if (!SCENES.has(mode)) throw new Error(`Unknown scene: ${mode}`);
    const previousMode = sceneMode;
    if (previousMode !== mode) {
      clearTimeout(toastTimer);
      toastTimer = 0;
      $('toastBanner')?.classList.remove('show');
    }
    if (previousMode === 'survey' && mode !== 'survey') {
      stopSurveyScanner();
      planetarySurvey?.close();
    }
    if (previousMode !== mode) {
      const previousUsesSystem = previousMode === 'system' || previousMode === 'survey';
      const nextUsesSystem = mode === 'system' || mode === 'survey';
      if (previousUsesSystem && !nextUsesSystem) engine.releaseSceneGpuResources(engine.scene);
      else if (previousMode === 'uga') engine.releaseSceneGpuResources(commandScene.scene);
      else if (previousMode === 'galaxy' && galaxyMap?.scene) engine.releaseSceneGpuResources(galaxyMap.scene);

      if (nextUsesSystem && !previousUsesSystem) engine.restoreSceneResources(engine.scene);
      else if (mode === 'uga') engine.restoreSceneResources(commandScene.scene);
      else if (mode === 'galaxy' && galaxyMap?.scene) engine.restoreSceneResources(galaxyMap.scene);
    }
    sceneMode = mode;
    spaceAudio.setScene(mode === 'system' ? 'galactic' : mode === 'uga' ? 'rooms' : mode);
    frame.dataset.scene = mode;
    storyTransmissions.setScene(mode);
    $('surveyModal').classList.toggle('active', mode === 'survey');
    $('surveyModal').setAttribute('aria-hidden', mode === 'survey' ? 'false' : 'true');
    $('galaxyModal').classList.toggle('active', mode === 'galaxy');
    $('galaxyModal').setAttribute('aria-hidden', mode === 'galaxy' ? 'false' : 'true');
    $('ugaMode').classList.toggle('active', mode === 'uga');
    $('ugaMode').setAttribute('aria-hidden', mode === 'uga' ? 'false' : 'true');
    if (mode === 'uga') ugaUi.show(); else ugaUi.hide();
    if (mode === 'system' || mode === 'survey') {
      engine.resume();
      commandScene.exit();
    } else {
      engine.pause();
    }
    if (mode === 'uga') commandScene.enter();
    else commandScene.exit();
    const targetId = selectedTarget?.id || null;
    if (persist && (state.route.scene !== mode || state.route.targetId !== targetId)) {
      transact(current => setDomainRoute(current, { scene: mode, systemId: current.route.systemId, targetId }), `route:${mode}`);
    }
  }

  async function openSystem() {
    const systemId = state.route.systemId;
    const needsLoad = !systemLoadStarted || engine.currentSystem?.id !== systemId;
    if (needsLoad) {
      setRenderVeil(
        frame,
        '',
        `STREAMING ${SHOWCASE_SYSTEMS[systemId]?.name?.toUpperCase() || 'EXPEDITION SYSTEM'}`,
        'DECODING AUTHORED PLANET PBR MAPS AND ORBITAL SCENE ASSETS'
      );
    }
    try {
      // loadSystemBodies publishes currentSystem before its authored PBR assets
      // resolve. A matching ID alone cannot prove a failed load is usable.
      const loaded = needsLoad ? await loadSystem(systemId) : await engine.systemReady;
      if (disposed) return false;
      if (!loaded || engine.currentSystem?.id !== systemId) throw new Error('Orbital scene did not finish loading.');
    } catch (error) {
      if (disposed) return false;
      console.warn('[MASSFRONT ORBITAL SCENE]', error);
      destroyGalaxyMap();
      await openCampaignHub();
      showToast('ORBITAL SCENE UNAVAILABLE · RETURNED TO UGA COMMAND · RETRY FROM GALAXY', true);
      return false;
    }
    if (galaxyMap) destroyGalaxyMap();
    selectTarget(arkTarget(), { persist: false });
    setScene('system');
    if (!contextRecovering) setRenderVeil(frame, 'ready');
    return true;
  }

  async function openUga(districtId = null, { persist = true, loadVisual = true } = {}) {
    if (disposed) return;
    /* The War Table, social/settings routes, construction data and deployment
       controls are ordinary DOM and campaign state. Exposing them must never
       wait for the optional 70 MB authored cutaway to fetch, decode and build.
       Room art streams only after an explicit Ship/room action; failure leaves
       every strategic control usable and VESSEL OVERVIEW is the retry path. */
    setScene('uga', { persist });
    if (districtId) {
      ugaUi.selectDistrict(districtId, { emit: false });
    }
    if (!contextRecovering) setRenderVeil(frame, 'ready');
    if (commandScene.loaded) applyCommandSceneState();
    else if (loadVisual) requestUgaVisual(districtId);
    return true;
  }

  async function openCampaignHub({ persist = true } = {}) {
    /* The integrated entry ticket names the campaign hub because this panel is
       the shared War Table: it exposes Standard, Campaign, Training and the
       base-game service routes. Opening the separate galaxy scene here hid all
       of those host bridges even though explicit Galaxy navigation still
       worked from its own controls. */
    await openUga(null, { persist, loadVisual: false });
    if (disposed || sceneMode !== 'uga') return false;
    ugaUi.openView('campaign_hub');
    presentPendingOperation();
    await waitForInterfacePaint();
    if (resolveCampaignHubReady) {
      const resolveReady = resolveCampaignHubReady;
      resolveCampaignHubReady = null;
      resolveReady(true);
    }
    return true;
  }

  function presentPendingOperation() {
    if (restoredPendingOperation || !state.operations.pending) return;
    restoredPendingOperation = true;
    const rejectedNonce = isIntegratedGroundHost()
      ? new URLSearchParams(window.location.search).get('groundRejected')
      : null;
    const rejected = /^[A-Za-z0-9_-]{16,128}$/.test(rejectedNonce || '') &&
      (!host.pendingNonce || host.pendingNonce === rejectedNonce);
    showOperation(state.operations.pending, null, { restored: true, rejected });
    showToast(rejected ? 'TACTICAL LAUNCH REJECTED OR EXPIRED · REFUND AVAILABLE' : 'UNRESOLVED OPERATION RESTORED', rejected);
  }

  function selectTarget(target, { persist = true } = {}) {
    selectedTarget = target || null;
    hud.setTargetInfo(selectedTarget, physics.ship);
    refreshTargetActions();
    const targetId = selectedTarget?.id || null;
    if (persist && state.route.targetId !== targetId) {
      transact(current => setDomainRoute(current, {
        scene: current.route.scene,
        systemId: current.route.systemId,
        targetId
      }), `route:target:${targetId || 'none'}`);
    }
  }

  function pickArk(clientX, clientY) {
    if (!engine.shipVisualGroup || !engine.isShipReady) return false;
    const rect = engine.renderer.domElement.getBoundingClientRect();
    pointerNdc.x = ((clientX - rect.left) / rect.width) * 2 - 1;
    pointerNdc.y = -((clientY - rect.top) / rect.height) * 2 + 1;
    raycaster.setFromCamera(pointerNdc, engine.camera);
    if (!raycaster.intersectObject(engine.shipVisualGroup, true).length) return false;
    selectTarget(arkTarget());
    showToast('NEXUS-VII SELECTED');
    return true;
  }

  let oscAnimId = null;
  let scanAngleLon = 0;
  let scanAngleLat = 0;
  let scanSignalPct = 0;
  let planetarySurvey = null;
  let surveyAim = null;
  let activeSurveyPlanet = null;
  let surveyResultAction = null;

  function ensurePlanetarySurvey() {
    if (planetarySurvey) return planetarySurvey;
    const stage = $('survey3DStage');
    if (!stage) return null;
    planetarySurvey = new PlanetarySurvey(stage, () => {});
    return planetarySurvey;
  }

  function initSurveyScanner() {
    stopSurveyScanner();
    if (disposed || paused || sceneMode !== 'survey') return;
    const canvas = $('surveyOscilloscope');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    function renderOscilloscope() {
      oscAnimId = null;
      if (sceneMode === 'survey' && !disposed && !paused) {
        ctx.fillStyle = 'rgba(1, 8, 14, 0.4)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.strokeStyle = 'rgba(66, 221, 255, 0.08)';
        ctx.lineWidth = 1;
        ctx.beginPath();
        for (let x = 0; x < canvas.width; x += 20) {
          ctx.moveTo(x, 0); ctx.lineTo(x, canvas.height);
        }
        for (let y = 0; y < canvas.height; y += 16) {
          ctx.moveTo(0, y); ctx.lineTo(canvas.width, y);
        }
        ctx.stroke();

        const entries = surveyEntries();
        const next = entries.find(entry => !state.surveys[entry.id].depleted);
        const t = performance.now() * 0.003;

        if (planetarySurvey && planetarySurvey.active) {
          scanSignalPct = planetarySurvey.signalPct;
          const latDeg = Number(planetarySurvey.scanLat || 0).toFixed(1);
          const lonDeg = Number(planetarySurvey.scanLon || 0).toFixed(1);
          const coordsEl = $('me2ScanCoords');
          if (coordsEl) coordsEl.textContent = `LAT: ${latDeg >= 0 ? '+' : ''}${latDeg}° // LON: ${lonDeg}°`;
        } else {
          scanAngleLon = (scanAngleLon + 0.005) % (Math.PI * 2);
          const latDeg = (Math.sin(t * 0.5) * 45).toFixed(1);
          const lonDeg = ((scanAngleLon * 180 / Math.PI) % 360).toFixed(1);
          const coordsEl = $('me2ScanCoords');
          if (coordsEl) coordsEl.textContent = `LAT: ${latDeg >= 0 ? '+' : ''}${latDeg}° // LON: ${lonDeg}°`;
          const proximity = next ? Math.abs(Math.sin(scanAngleLon * 2 + t * 0.5)) : 0;
          scanSignalPct = Math.round(proximity * 100);
        }

        if (planetarySurvey && planetarySurvey.active) {
          const nextAim = planetarySurvey.evaluateAim();
          const changed = !surveyAim || surveyAim.hit !== nextAim.hit
            || surveyAim.kind !== nextAim.kind || surveyAim.name !== nextAim.name
            || Math.round(surveyAim.signal) !== Math.round(nextAim.signal);
          surveyAim = nextAim;
          if (changed) refreshSurveyAim();
        }

        const sigStrengthEl = $('me2SignalStrength');
        if (sigStrengthEl) sigStrengthEl.textContent = `${scanSignalPct}%`;
        const sigBarEl = $('me2SignalBar');
        if (sigBarEl) sigBarEl.style.width = `${scanSignalPct}%`;

        const statusEl = $('me2ScanStatus');
        if (statusEl) {
          if (scanSignalPct > 75) {
            statusEl.textContent = 'PEAK ANOMALY SPIKE';
            statusEl.style.color = 'var(--green)';
          } else if (scanSignalPct > 40) {
            statusEl.textContent = 'HARMONIC SIGNAL DETECTED';
            statusEl.style.color = 'var(--amber)';
          } else {
            statusEl.textContent = 'SWEEPING SURFACE';
            statusEl.style.color = 'var(--cyan)';
          }
        }

        ctx.beginPath();
        const baseAmp = 4 + (scanSignalPct / 100) * 24;
        const freq = 0.05 + (scanSignalPct / 100) * 0.15;
        const isSpike = scanSignalPct > 60;

        ctx.strokeStyle = isSpike ? '#74e0a2' : '#42ddff';
        ctx.shadowColor = isSpike ? '#74e0a2' : '#42ddff';
        ctx.shadowBlur = isSpike ? 8 : 4;
        ctx.lineWidth = isSpike ? 2.5 : 1.5;

        for (let x = 0; x < canvas.width; x++) {
          const noise = (Math.random() - 0.5) * (isSpike ? 6 : 2);
          const y = (canvas.height / 2) + Math.sin(x * freq + t * 3) * baseAmp + noise;
          if (x === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.stroke();
        ctx.shadowBlur = 0;
        oscAnimId = requestAnimationFrame(renderOscilloscope);
      }
    }

    oscAnimId = requestAnimationFrame(renderOscilloscope);
  }

  function stopSurveyScanner() {
    if (oscAnimId !== null) cancelAnimationFrame(oscAnimId);
    oscAnimId = null;
  }

  function surveyEntries(planetId = activeSurveyPlanet?.id || null) {
    return catalogArray(SURVEY_CATALOG)
      .filter(entry => entry.systemId === state.route.systemId)
      .filter(entry => !planetId || entry.planetId === planetId);
  }

  function clearSurveyResult() {
    surveyResultAction = null;
    const result = $('surveyResult');
    if (result) {
      result.hidden = true;
      delete result.dataset.nextActionKind;
      delete result.dataset.systemId;
      delete result.dataset.planetId;
      delete result.dataset.primaryAreaId;
    }
    const discoveryList = $('surveyDiscoveryList');
    const probeButton = $('btnSurveyLaunchProbe');
    if (discoveryList) discoveryList.hidden = false;
    if (probeButton) probeButton.hidden = false;
  }

  function showSurveyResult(title, rewards, nextAction) {
    const result = $('surveyResult');
    if (!result) return;
    const localSignalsRemain = surveyEntries().some(entry => !state.surveys[entry.id]?.depleted);
    surveyResultAction = nextAction || {
      kind: 'UgaScanNextActionV1',
      action: localSignalsRemain ? 'continue-survey' : 'review-frontier',
      label: localSignalsRemain ? 'CONTINUE ORBITAL SURVEY' : 'REVIEW FRONTIER STATUS',
      systemId: state.route.systemId,
      planetId: activeSurveyPlanet?.id || '',
      primaryAreaId: null,
      missionIds: []
    };
    result.dataset.nextActionKind = surveyResultAction.action;
    result.dataset.systemId = surveyResultAction.systemId || state.route.systemId;
    result.dataset.planetId = surveyResultAction.planetId || activeSurveyPlanet?.id || '';
    result.dataset.primaryAreaId = surveyResultAction.primaryAreaId || '';
    $('surveyResultTitle').textContent = String(title || 'DISCOVERY CONFIRMED').toUpperCase();
    $('surveyResultReward').textContent = resourceSummary(rewards) || 'INTELLIGENCE ARCHIVED';
    setButtonLabel($('surveyNextAction'), String(surveyResultAction.label || 'CONTINUE').toUpperCase());
    $('surveyContinueScan').hidden = surveyResultAction.action === 'continue-survey'
      || surveyResultAction.action === 'prepare-survey-lab';
    $('surveyDiscoveryList').hidden = true;
    $('btnSurveyLaunchProbe').hidden = true;
    result.hidden = false;
  }

  async function followSurveyNextAction() {
    const next = surveyResultAction;
    if (!next) return;
    if (next.action === 'inspect-ground-area') {
      clearSurveyResult();
      openGalaxy({ systemId: next.systemId, preferredAreaId: next.primaryAreaId });
      showToast('CHOOSE A PLANETARY AREA · THEN SELECT A MAP AND LOADOUT');
      return;
    }
    if (next.action === 'prepare-survey-lab') {
      clearSurveyResult();
      await openUga('survey');
      showToast('UPGRADE SURVEY LAB · RETURN TO MERIDIAN FOR THE HIVE SCAN');
      return;
    }
    if (next.action === 'plot-system-course') {
      const targetSystemId = next.targetSystemId;
      clearSurveyResult();
      openGalaxy({ systemId: targetSystemId });
      return;
    }
    if (next.action === 'review-frontier') {
      clearSurveyResult();
      openGalaxy();
      showToast('ALL SIGNALS ON THIS PLANET ARE ARCHIVED · REVIEW THE FRONTIER');
      return;
    }
    clearSurveyResult();
    showToast(next.targetSurveyId === 'karak_hive_scan'
      ? 'HIVE SIGNAL READY · SWEEP FOR CONFIRMED TARGETS'
      : 'SCANNER READY · CONTINUE SURFACE SWEEP');
  }

  function selectSurveyPlanet(event) {
    const switcher = $('surveyPlanetSelector');
    const button = event.target?.closest?.('.survey-planet-pill');
    if (!switcher || !button || !switcher.contains(button)) return;
    const sys = SHOWCASE_SYSTEMS[state.route.systemId] || SHOWCASE_SYSTEMS.aelos;
    const planet = sys.planets?.find(item => item.id === button.dataset.planetId);
    if (planet) openSurvey(planet);
  }

  function openSurvey(planetOverride, { persist = true } = {}) {
    const sys = SHOWCASE_SYSTEMS[state.route.systemId] || SHOWCASE_SYSTEMS.aelos;
    const currentPlanet = planetOverride
      || (selectedTarget && sys.planets && sys.planets.find(p => p.id === selectedTarget.id))
      || (sys.planets && sys.planets[0])
      || SHOWCASE_SYSTEMS.aelos.planets[0];

    activeSurveyPlanet = currentPlanet;
    clearSurveyResult();
    selectTarget(currentPlanet, { persist: false });

    setScene('survey', { persist });
    refreshSurvey();
    initSurveyScanner();

    const survey = ensurePlanetarySurvey();
    if (survey) {
      const stage = $('survey3DStage');
      const rect = stage ? stage.getBoundingClientRect() : { width: window.innerWidth, height: window.innerHeight };
      survey.resize(rect.width || window.innerWidth, rect.height || window.innerHeight);
      const extractedDepositIds = new Set(state.discoveries.extractedDepositIds);
      const surveyPlanet = {
        ...currentPlanet,
        mineralDeposits: (currentPlanet.mineralDeposits || []).map(deposit => ({
          ...deposit,
          extracted: deposit.surveyId
            ? Boolean(state.surveys[deposit.surveyId]?.depleted)
            : extractedDepositIds.has(deposit.id)
        }))
      };
      survey.open(surveyPlanet);
      survey.setSensorProfile({ ...surveySensorProfile(state), probes: state.resources.probes });
      surveyAim = survey.evaluateAim();
      refreshSurveyAim();
    }
  }

  function refreshSurvey() {
    const sys = SHOWCASE_SYSTEMS[state.route.systemId] || SHOWCASE_SYSTEMS.aelos;
    const planet = activeSurveyPlanet || (sys.planets && sys.planets[0]) || SHOWCASE_SYSTEMS.aelos.planets[0];
    const planetName = String(planet?.name || 'Caldris').toUpperCase();

    // Render Planet Selector Chips in Survey Modal
    const switcher = $('surveyPlanetSelector');
    if (switcher) {
      if (sys.planets && sys.planets.length > 1) {
        switcher.style.display = 'flex';
        switcher.innerHTML = sys.planets.map(p => `
          <button class="survey-planet-pill${p.id === planet.id ? ' active' : ''}" type="button" data-planet-id="${p.id}">
            <span>${String(p?.name || '').toUpperCase()}</span>
          </button>
        `).join('');
      } else {
        switcher.style.display = 'none';
        switcher.replaceChildren();
      }
    }

    const entries = surveyEntries();
    const complete = entries.filter(entry => state.surveys[entry.id].depleted).length;
    const next = entries.find(entry => !state.surveys[entry.id].depleted);

    $('surveyModalTitle').textContent = `${planetName} ORBITAL SURVEY`;
    $('surveyDescription').textContent = `${planet?.sub || planet?.name || 'Orbital scan active'}. Biome: ${String(planet?.biome || 'terrestrial').toUpperCase()}. Rotate the complete globe beneath the fixed spectrogram, then launch directed probes at signal peaks to reveal resources, intelligence, and operations.`;

    // Mineral Abundance Bars from active planet
    const alloys = planet.mineralDeposits?.find(d => d.type === 'alloys')?.amount || (planet.biome === 'volcanic' ? 820 : 600);
    const comps = planet.mineralDeposits?.find(d => d.type === 'components')?.amount || (planet.biome === 'cyber_purple' ? 750 : 450);
    const bio = planet.mineralDeposits?.find(d => d.type === 'bioSamples')?.amount || (planet.biome === 'golden_jade' ? 500 : 250);
    const alloyBar = $('me2MinAlloy');
    const compBar = $('me2MinComp');
    const bioBar = $('me2MinBio');
    if (alloyBar) alloyBar.style.width = `${Math.min(100, Math.max(20, alloys / 8))}%`;
    if (compBar) compBar.style.width = `${Math.min(100, Math.max(20, comps / 8))}%`;
    if (bioBar) bioBar.style.width = `${Math.min(100, Math.max(20, bio / 5))}%`;

    const pct = entries.length ? Math.round(complete / entries.length * 100) : 100;
    $('survPctVal').textContent = `${pct}%`;
    $('surveyProgressBar').style.width = `${pct}%`;
    $('survProbesVal').textContent = state.resources.probes;
    $('survSitesVal').textContent = `${complete} / ${entries.length}`;
    $('surveyDiscoveryList').innerHTML = entries.map(entry => {
      const found = state.surveys[entry.id].depleted;
      const eligibility = getSurveyEligibility(state, entry.id, { planetId: planet.id });
      const blocked = eligibility.issues?.[0]?.code;
      const check = found ? 'ARCHIVED' : eligibility.ok ? eligibility.emergency ? 'EMERGENCY' : 'READY'
        : blocked === 'PROBE_SHORTAGE' ? 'NO PROBES'
          : blocked === 'SURVEY_NOT_COMMISSIONED' ? 'LAB OFFLINE'
            : blocked === 'SURVEY_CHAIN_REQUIRED' ? 'ROUTE LOCKED'
              : blocked === 'PLANET_LADDER_REQUIRED' ? 'WORLD LOCKED'
                : blocked === 'SURVEY_LEVEL_REQUIRED' ? `LAB ${entry.requiredSurveyLevel}` : 'LOCKED';
      return `<div class="discovery-item${found ? ' found' : ''}"><i><svg><use href="#i-${found ? 'check' : 'probe'}"/></svg></i><div><b>${entry.name}</b><small>${found ? DISCOVERY_CATALOG[entry.discoveryId].name : 'Unresolved authored signal'}</small></div><em>${check}</em></div>`;
    }).join('');
    refreshSurveyAim();
  }

  /* THE SIGNAL IS THE GATE.
     The probe button used to fire on the next unresolved catalog entry no
     matter where the reticle sat, so a scan was one tap and the spectrogram was
     scenery. It now reads whatever the reticle is actually over: below the
     sensor threshold there is nothing to shoot at, at a peak it says which kind
     of find is under the crosshair, and firing resolves that exact site. */
  function refreshSurveyAim() {
    const button = $('btnSurveyLaunchProbe');
    if (!button) return;
    const probes = state.resources.probes || 0;
    const aim = surveyAim;
    const signal = Math.round(aim ? aim.signal : (planetarySurvey ? planetarySurvey.signalPct : 0));
    const threshold = Math.round(aim ? aim.threshold : 76);
    const sigEl = $('survSigVal');
    if (sigEl) sigEl.textContent = `${signal}%`;
    if (!aim || !aim.hit) {
      button.disabled = true;
      setButtonLabel(button, `SWEEP FOR A PEAK · ${signal}% / ${threshold}%`);
      return;
    }
    if (aim.kind === 'anomaly') {
      const eligibility = getSurveyEligibility(state, aim.surveyId, { planetId: activeSurveyPlanet?.id });
      if (!eligibility.ok) {
        button.disabled = true;
        setButtonLabel(button, String(eligibility.issues?.[0]?.message || 'SURVEY BLOCKED').toUpperCase());
        return;
      }
      button.disabled = false;
      setButtonLabel(button, `${eligibility.emergency ? 'EMERGENCY SIGNAL SCAN' : 'RESOLVE SIGNAL'} · ${String(aim.name || 'ANOMALY').toUpperCase()}`);
      return;
    }
    if (!probes) {
      button.disabled = true;
      setButtonLabel(button, 'NO PROBES · DEPOSITS REQUIRE RESUPPLY');
      return;
    }
    button.disabled = false;
    setButtonLabel(button, `EXTRACT DEPOSIT · SIGNAL ${signal}%`);
  }

  function flashSurveyReticle() {
    const reticle = $('surveyScannerHud');
    if (!reticle) return;
    reticle.style.filter = 'brightness(2.2)';
    setTimeout(() => { if (reticle) reticle.style.filter = ''; }, 300);
  }

  /* A locked peak resolves exactly what is buried under the reticle - a mineral
     deposit pays resources, while an authored signal opens routes, confirms
     the infestation and hands the player their next objective. The launch
     button is disabled below threshold, and this function repeats that gate so
     a synthetic/programmatic click cannot spend a probe on empty coordinates. */
  function launchProbe() {
    if (!planetarySurvey || !planetarySurvey.active) return;
    const aim = planetarySurvey.evaluateAim();
    if (!aim.hit) {
      refreshSurveyAim();
      showToast(`NO SIGNAL LOCK · SWEEP TO ${Math.round(aim.threshold)}% BEFORE LAUNCH`, true);
      return;
    }

    if (aim.kind === 'anomaly') {
      const surveyId = aim.surveyId;
      const eligibility = getSurveyEligibility(state, surveyId, { planetId: activeSurveyPlanet?.id });
      if (!eligibility.ok) {
        showToast(String(eligibility.issues?.[0]?.message || 'SURVEY BLOCKED').toUpperCase(), true);
        return;
      }
      try {
        const result = deployProbe(state, surveyId);
        commit(result.state, `survey:${surveyId}`);
        planetarySurvey.launchProbe();
        flashSurveyReticle();
        refreshSurvey();
        showSurveyResult(result.discovery.name, result.rewards, result.nextAction);
        showToast(`SIGNAL RESOLVED: ${result.discovery.name.toUpperCase()} · ${resourceSummary(result.rewards)}`);
      } catch (error) {
        showToast(issueText(error), true);
      }
      return;
    }

    if ((state.resources.probes || 0) < 1) {
      showToast('DEPOSIT EXTRACTION REQUIRES A PROBE · RESUPPLY IN STORES', true);
      return;
    }
    const find = { id: aim.deposit?.id, type: aim.deposit?.type, amount: aim.deposit?.amount };
    try {
      commit(recoverPlanetFind(state, find), `survey:deposit:${aim.deposit?.id || 'unnamed'}`);
    } catch (error) {
      showToast(issueText(error), true);
      return;
    }
    planetarySurvey.launchProbe();
    flashSurveyReticle();
    refreshSurvey();
    showSurveyResult('MINERAL DEPOSIT EXTRACTED', { [find.type]: find.amount }, null);
    showToast(`DEPOSIT EXTRACTED · ${resourceSummary({ [find.type]: find.amount })}`);
  }

  function encodeUiText(value) {
    return String(value == null ? '' : value).replace(/[&<>"']/g, character => ({
      '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
    }[character]));
  }

  function missionsInSystem(systemId) {
    return catalogArray(MISSION_CATALOG).filter(mission => mission.systemId === systemId);
  }

  function missionPlanningEligibility(mission) {
    // Galaxy and contract availability ask whether a loadout CAN be prepared,
    // not whether the first proxy and first support happen to be launchable.
    // The deployment draft still goes through exact request validation.
    const residentIds = Object.entries(state.factions || {})
      .filter(([id, faction]) => faction?.resident && FACTION_CATALOG[id]?.hireable)
      .map(([id]) => id)
      .sort((a, b) => Number(b === state.commissioning?.factionId) - Number(a === state.commissioning?.factionId));
    const proxyIds = mission.access?.type === 'faction_exclusive'
      ? [mission.access.factionId]
      : residentIds.length ? residentIds : [null];
    const supportIds = mission.supportIds?.length ? mission.supportIds : [null];
    let closest = null;
    for (const proxyFactionId of proxyIds) {
      for (const supportId of supportIds) {
        const request = { ...(proxyFactionId ? { proxyFactionId } : {}), ...(supportId ? { supportId } : {}) };
        const eligibility = getMissionEligibility(state, mission.id, request);
        if (eligibility.eligible) return eligibility;
        if (!closest || eligibility.locks.length < closest.locks.length) closest = eligibility;
      }
    }
    return closest;
  }

  function frontStatusForSystem(systemId) {
    const discovered = Boolean(state.world.systems[systemId]?.discovered);
    const liveFront = state.world.systems[systemId]?.soloFront;
    const pressure = Math.max(0, Math.min(100, Number(liveFront?.pressure) || 0));
    const control = 100 - pressure;
    if (!discovered) return {
      state: 'unknown', shortLabel: 'UNCHARTED', badge: 'INTELLIGENCE VOID', directive: 'ROUTE NOT CONFIRMED', control: 0, pressure
    };
    // A replay can raise a mission's completion count without clearing a new
    // map. Only the settled ground ledger can prove every planet is held.
    const planets = Object.values(derivePlanetControl(state)).filter(planet => planet.systemId === systemId);
    // This function is extracted and evaluated standalone by the
    // front-status regression test, so it must only touch imports and its
    // arguments — never sibling closures like missionsInSystem().
    const regionsOpen = !Object.values(MISSION_CATALOG).some(mission => mission.systemId === systemId
      && mission.groundAreaId && !isGroundAreaUnlocked(state, mission.groundAreaId));
    const resolved = planets.length > 0 && planets.every(planet => planet.controlled) && regionsOpen;
    if (resolved) return {
      state: 'protected', shortLabel: systemId === 'karak' ? 'LIBERATED' : 'SECURED',
      badge: systemId === 'karak' ? 'LIBERATED' : 'SECURED',
      directive: systemId === 'veyra' ? 'ALLIED RESEARCH CORRIDOR' : systemId === 'karak' ? 'UGA CONTAINMENT HOLDING' : 'ALLIED ANCHORAGE',
      control, pressure
    };
    const frontState = control >= 70 ? 'protected' : control >= 40 ? 'contested' : 'enemy';
    const directive = systemId === 'aelos' || systemId === 'sombrero_i'
      ? frontState === 'protected' ? 'ALLIED ANCHORAGE' : 'ANCHORAGE DEFENSE REQUIRED'
      : systemId === 'veyra'
        ? 'FRONTIER DEFENSE ACTIVE'
        : systemId === 'andromeda_iv'
          ? 'DOMINION FOUNDRY WATCH'
          : systemId === 'orion_arc'
            ? 'GRID WATCH ACTIVE'
            : frontState === 'enemy' ? 'BROOD OCCUPATION' : 'CONTAINMENT OFFENSIVE';
    const label = frontState === 'protected' ? 'PROTECTED' : frontState === 'contested' ? 'UNDER ATTACK' : 'ENEMY CONTROL';
    return {
      state: frontState, shortLabel: label, badge: label === 'UNDER ATTACK' ? 'CONTESTED' : label, directive, control, pressure
    };
  }

  function galaxyFrontStatuses() {
    return Object.fromEntries(Object.keys(SHOWCASE_SYSTEMS).map(id => [id, frontStatusForSystem(id)]));
  }

  function operationVerb(mission) {
    if (mission.missionType === 'uga_brood_purge') return 'LIBERATE';
    const type = String(mission.objective?.type || 'intervene');
    if (/hold|secure|defend/.test(type)) return 'DEFEND';
    if (/recover|extract/.test(type)) return 'RECOVER';
    return 'INTERVENE';
  }

  function unresolvedSurveysInSystem(systemId) {
    // Ladder tiers 1-2 — surveys that are chain- or planet-gated still count as
    // unresolved so the front card keeps pointing at the live rung.
    return catalogArray(SURVEY_CATALOG).filter(entry => entry.systemId === systemId && !state.surveys[entry.id]?.depleted);
  }

  function missionRegionLocked(mission) {
    // Tier 3 — a region-gated contract reads as still-open work on the front
    // card; the galaxy operation board shows the chain reason from locks[0].
    return Boolean(mission?.groundAreaId) && !isGroundAreaUnlocked(state, mission.groundAreaId);
  }

  function refreshGalaxyFrontLabels() {
    const statuses = galaxyFrontStatuses();
    galaxyMap?.setSystemStatuses(statuses);
    for (const label of $('galaxyLabelsLayer')?.querySelectorAll?.('.galaxy-system-label') || []) {
      label.dataset.frontState = statuses[label.dataset.id]?.state || 'unknown';
    }
  }

  function refreshGalaxyOperations(systemId, current) {
    const missions = missionsInSystem(systemId);
    const eligibilityById = new Map(missions.map(mission => [mission.id, missionPlanningEligibility(mission)]));
    const eligibleMissionIds = missions.filter(mission => eligibilityById.get(mission.id)?.eligible).map(mission => mission.id);
    const missionStillVisible = missions.some(mission => mission.id === selectedGalaxyMissionId);
    if (!missionStillVisible) {
      const controlledAreaIds = Object.values(deriveGroundControl(state).areas)
        .filter(area => area.controlled).map(area => area.areaId);
      selectedGalaxyMissionId = chooseGalaxyOperationId(missions, eligibleMissionIds, controlledAreaIds, selectedGalaxyPreferredAreaId);
    }
    selectedGalaxyPreferredAreaId = null;
    const board = $('galaxyOperations');
    const readyCount = eligibleMissionIds.length;
    $('galaxyOperationAvailability').textContent = `${readyCount} READY · ${missions.length} KNOWN`;
    board.innerHTML = missions.map(mission => {
      const eligibility = eligibilityById.get(mission.id);
      const site = SITE_CATALOG[mission.siteId];
      const area = getUgaGroundAreaOptions(mission.id);
      const selected = mission.id === selectedGalaxyMissionId;
      const outcome = state.missions[mission.id]?.completions ? `${state.missions[mission.id].completions} COMPLETED` : eligibility.eligible ? 'READY FOR LOADOUT' : eligibility.locks[0]?.message || 'LOCKED';
      return `<button type="button" class="galaxy-operation-card${selected ? ' is-selected' : ''}${eligibility.eligible ? ' is-ready' : ' is-locked'}" data-galaxy-mission="${encodeUiText(mission.id)}" data-planet-id="${encodeUiText(area?.planetId || '')}" data-area-id="${encodeUiText(area?.areaId || '')}" aria-label="${encodeUiText(`${area?.planetName || 'Planet'}, ${area?.areaName || site?.name || 'area'}: ${mission.title}. ${outcome}`)}" aria-pressed="${selected}">
        <span><em>THREAT ${Number(mission.difficulty) || 1}</em><b>${operationVerb(mission)}</b></span><strong>${encodeUiText(mission.title)}</strong><small>${encodeUiText(String(mission.objective?.type || 'operation').replaceAll('_', ' '))}</small><i>${encodeUiText(`${area?.planetName || 'Planet'} · ${area?.areaName || site?.name || mission.siteId}`)}<br>${encodeUiText(outcome)}</i>
      </button>`;
    }).join('');

    const mission = MISSION_CATALOG[selectedGalaxyMissionId];
    const eligibility = mission ? eligibilityById.get(mission.id) : null;
    const site = mission ? SITE_CATALOG[mission.siteId] : null;
    const area = mission ? getUgaGroundAreaOptions(mission.id) : null;
    const brief = $('galaxyMissionBrief');
    brief.textContent = mission
      ? eligibility.eligible
        ? `${area?.planetName || 'Planet'} · ${area?.areaName || site?.name || mission.siteId}: ${mission.title} is ready. Choose its map and loadout before deployment.`
        : `${area?.planetName || 'Planet'} · ${area?.areaName || site?.name || mission.siteId}: ${mission.title} is pending: ${eligibility.locks[0]?.message || 'complete reconnaissance and command preparation.'}`
      : 'No authored ground operations are registered in this system.';

    const loadout = $('galaxyLoadoutBtn');
    loadout.disabled = !current || !mission || eligibility?.eligible !== true;
    setButtonLabel(loadout, !current ? 'ENTER SYSTEM TO PREPARE' : eligibility?.eligible ? 'CHOOSE MAP & LOADOUT' : 'OPERATION LOCKED');
  }

  function refreshGalaxyWarfront(systemId, current) {
    const front = frontStatusForSystem(systemId);
    const pane = $('galaxyInfoPane');
    pane.dataset.frontState = front.state;
    $('galaxyControlBadge').textContent = front.badge;
    $('galaxyFrontDirective').textContent = front.state === 'unknown'
      ? front.directive
      : `${front.directive} · FRONT PRESSURE ${front.pressure}`;
    $('galaxyControlValue').textContent = `${front.control}%`;
    $('galaxyControlFill').style.width = `${front.control}%`;
    document.querySelector('.galaxy-control-track')?.setAttribute('aria-label', front.state === 'unknown'
      ? 'Allied control unknown'
      : `Allied control ${front.control} percent; enemy pressure ${front.pressure}`);
    const unresolved = unresolvedSurveysInSystem(systemId);
    const scan = $('galaxyScanBtn');
    scan.disabled = !current;
    setButtonLabel(scan, current
      ? unresolved.length ? `SCAN FOR INTELLIGENCE · ${unresolved.length}` : 'ORBITAL SURVEY'
      : 'ENTER SYSTEM TO SCAN');
    const flagship = $('galaxyFlagshipBtn');
    setButtonLabel(flagship, state.commissioning?.completed ? 'FLAGSHIP' : 'HIRE FIRST COMMANDER');
    flagship.dataset.resolver = state.commissioning?.completed ? '' : 'new-career-faction';
    refreshGalaxyOperations(systemId, current);
    refreshGalaxyFrontLabels();
  }

  function selectGalaxyOperation(event) {
    const button = event.target?.closest?.('[data-galaxy-mission]');
    if (!button || !$('galaxyOperations')?.contains(button)) return;
    selectedGalaxyMissionId = button.dataset.galaxyMission;
    selectSystemInGalaxy(selectedGalaxyId);
  }

  function openGalaxyRecon() {
    if (selectedGalaxyId !== state.route.systemId) {
      showToast('ENTER THE SELECTED SYSTEM BEFORE SCANNING', true);
      return;
    }
    const system = SHOWCASE_SYSTEMS[selectedGalaxyId] || SHOWCASE_SYSTEMS.aelos;
    const nextSurvey = unresolvedSurveysInSystem(selectedGalaxyId)[0];
    const planet = system.planets?.find(item => item.id === nextSurvey?.planetId) || system.planets?.[0];
    if (!planet) {
      showToast('NO PLANETARY SURVEY TARGET REGISTERED', true);
      return;
    }
    destroyGalaxyMap();
    openSurvey(planet);
  }

  async function openGalaxyLoadout() {
    const mission = MISSION_CATALOG[selectedGalaxyMissionId];
    if (!mission || mission.systemId !== state.route.systemId) {
      showToast('ENTER THE OPERATION SYSTEM BEFORE PREPARING A DROP', true);
      return;
    }
    const eligibility = missionPlanningEligibility(mission);
    if (!eligibility.eligible) {
      showToast(eligibility.locks[0]?.message || 'OPERATION LOCKED', true);
      return;
    }
    destroyGalaxyMap();
    await openUga('mission_ops');
    if (!disposed) ugaUi.openMission(mission.id);
  }

  async function openGalaxyFlagship() {
    destroyGalaxyMap();
    if (!state.commissioning?.completed && host.productionIntegrated === true && typeof host.openBaseRoute === 'function') {
      if (hostRoutePending) return;
      hostRoutePending = true;
      showToast('FIRST COMMANDER REQUIRED · OPENING FACTION HIRING');
      await waitForInterfacePaint();
      try {
        await host.openBaseRoute('new-career-faction', {
          systemId: state.route.systemId,
          targetId: state.route.targetId || null
        });
      } catch (error) {
        showToast(`COMMANDER HIRING UNAVAILABLE · ${issueText(error)}`, true);
        await openUga('factions', { loadVisual: false });
      } finally {
        hostRoutePending = false;
      }
      return;
    }
    if (!state.commissioning?.completed) {
      await openUga('factions', { loadVisual: false });
      return;
    }
    await openUga('command');
  }

  function createGalaxyMap() {
    if (galaxyMap) return;
    galaxyMap = new GalaxyMapEngine($('galaxy3DContainer'), $('galaxyLabelsLayer'), {
      renderer: engine.renderer,
      inputElement: engine.renderer.domElement,
      externalLoop: true,
      currentSystemId: state.route.systemId,
      seed: state.seed,
      data: SHOWCASE_SYSTEMS,
      layout: SHOWCASE_LAYOUT,
      systemStatuses: galaxyFrontStatuses(),
      onSystemClick: id => selectSystemInGalaxy(id)
    });
    galaxyMap.resize(frame.clientWidth || window.innerWidth, frame.clientHeight || window.innerHeight);
  }

  function destroyGalaxyMap() {
    if (!galaxyMap) return;
    galaxyMap.dispose();
    galaxyMap = null;
    $('galaxyLabelsLayer').innerHTML = '';
  }

  function openGalaxy({ persist = true, systemId = null, preferredAreaId = null } = {}) {
    setScene('galaxy', { persist });
    createGalaxyMap();
    selectedGalaxyId = SHOWCASE_SYSTEMS[systemId] ? systemId : state.route.systemId;
    selectedGalaxyMissionId = null;
    selectedGalaxyPreferredAreaId = preferredAreaId;
    selectSystemInGalaxy(selectedGalaxyId);
  }

  function selectSystemInGalaxy(id) {
    if (!SHOWCASE_SYSTEMS[id]) return;
    selectedGalaxyId = id;
    if (galaxyMap) galaxyMap.setSelected(id);
    const runtime = SHOWCASE_SYSTEMS[id];
    const catalog = SYSTEM_CATALOG[id];
    const current = id === state.route.systemId;
    const direct = SHOWCASE_LAYOUT.systems[state.route.systemId].relays.includes(id);
    const discovered = state.world.systems[id].discovered;
    $('galaxyInfoName').textContent = runtime.name.toUpperCase();
    $('galaxyInfoCluster').textContent = runtime.cluster;
    $('galaxyInfoSecurity').textContent = runtime.security.split(' · ')[0];
    $('galaxyInfoPlanets').textContent = runtime.planets.length;
    $('galaxyInfoContacts').textContent = runtime.contacts.length;
    $('galaxyInfoRelays').textContent = SHOWCASE_LAYOUT.systems[id].relays.length;
    $('galaxyInfoDesc').textContent = catalog.description;
    const status = $('galaxyInfoStatus');
    // Preview the pure domain transition so price, commissioning and fuel gates
    // cannot disagree with the action the Jump button actually executes.
    let courseError = '', courseFuel = 0;
    if (!current && discovered && direct) {
      try { courseFuel = state.resources.fuel - plotCourse(state, id).resources.fuel; }
      catch (error) { courseError = error.message || 'Route unavailable'; }
    }
    status.className = 'route-status';
    if (current) {
      status.textContent = 'CURRENT SYSTEM';
      status.classList.add('current');
    } else if (!discovered) {
      status.textContent = 'LOCKED · DISCOVERY VECTOR REQUIRED';
    } else if (!direct) {
      status.textContent = 'NO DIRECT PHASE CORRIDOR';
    } else if (courseError) {
      status.textContent = courseError;
    } else {
      status.textContent = `ROUTE READY · ${courseFuel} FUEL`;
      status.classList.add('jumpable');
    }
    $('galaxyJumpBtn').disabled = current || !discovered || !direct || Boolean(courseError);
    refreshGalaxyWarfront(id, current);
  }

  function beginTransit(systemId) {
    if (transitTimer || systemId === state.route.systemId) return;
    if (!SHOWCASE_LAYOUT.systems[state.route.systemId].relays.includes(systemId)) {
      showToast('NO DIRECT PHASE CORRIDOR', true);
      return;
    }
    try {
      const originSystemId = state.route.systemId;
      plotCourse(state, systemId); // Validate fuel and route without saving either yet.
      if (galaxyMap) galaxyMap.flyToSystem(systemId);
      showToast(`AUTOPILOT ALIGNING · ${SHOWCASE_SYSTEMS[systemId].name.toUpperCase()}`);
      setRenderVeil(
        frame,
        '',
        `STREAMING ${SHOWCASE_SYSTEMS[systemId].name.toUpperCase()}`,
        'DECODING AUTHORED PLANET PBR MAPS AND ORBITAL SCENE ASSETS'
      );
      transitTimer = setTimeout(async () => {
        transitTimer = -1;
        try {
          const loaded = await loadSystem(systemId, { refresh: false });
          if (disposed) return;
          if (!loaded || engine.currentSystem?.id !== systemId || contextRecovering || engine.contextLost) {
            throw new Error('Destination visuals did not finish loading.');
          }
          if (state.route.systemId !== originSystemId) throw new Error('Departure route changed during asset loading.');
          // Revalidate against current state in case resources changed during
          // streaming. The course, fuel and recovery cycles settle atomically.
          commit(plotCourse(state, systemId), `course:${systemId}`);
          destroyGalaxyMap();
          setScene('system', { persist: false });
          if (!contextRecovering) setRenderVeil(frame, 'ready');
          showToast(`TRANSIT COMPLETE · ${SHOWCASE_SYSTEMS[systemId].name.toUpperCase()}`);
        } catch (error) {
          if (disposed) return;
          console.warn('[MASSFRONT TRANSIT]', error);
          destroyGalaxyMap();
          await openCampaignHub();
          showToast(state.route.systemId === originSystemId
            ? `TRANSIT ABORTED · ${SHOWCASE_SYSTEMS[systemId].name.toUpperCase()} UNAVAILABLE · NO TRANSIT FUEL SPENT`
            : 'TRANSIT SETTLED · RETURNED TO UGA COMMAND', true);
        } finally {
          transitTimer = 0;
        }
      }, 850);
    } catch (error) {
      showToast(issueText(error), true);
    }
  }

  function loadSystem(systemId, { refresh = true } = {}) {
    systemLoadStarted = true;
    physics.stop();
    if (typeof engine.resetLoadProgress === 'function') engine.resetLoadProgress(0);
    Object.assign(physics.ship, { x: 0, y: 0, z: 120, yaw: 0.3, pitch: 0, roll: 0 });
    const systemReady = engine.loadSystemBodies(SHOWCASE_SYSTEMS[systemId]);
    if (galaxyMap) galaxyMap.setCurrentSystem(systemId);
    selectTarget(arkTarget(), { persist: false });
    // Staged transit must not re-save the origin snapshot while destination
    // assets stream; the eventual course commit notifies and refreshes once.
    if (refresh) refreshAll();
    return systemReady;
  }

  function savedTarget(systemId, targetId) {
    if (!targetId) return null;
    if (targetId === 'nexus_vii') return arkTarget();
    const bodies = engine.getProjectedBodies();
    const projected = [...bodies.planets, ...bodies.contacts].find(body => body.id === targetId);
    if (projected) return projected;
    const system = SHOWCASE_SYSTEMS[systemId];
    const planet = system?.planets?.find(item => item.id === targetId);
    if (planet) return planet;
    const contact = system?.contacts?.find(item => item.id === targetId);
    if (contact) return {
      ...contact,
      x: Math.cos(contact.angle || 0) * (contact.dist || 0),
      y: 0,
      z: Math.sin(contact.angle || 0) * (contact.dist || 0)
    };
    return null;
  }

  async function restoreSavedLocation() {
    const entryView = host.ticket?.entryView || 'system';
    const target = savedTarget(savedRoute.systemId, savedRoute.targetId) || arkTarget();
    selectTarget(target, { persist: false });
    if (entryView === 'campaign_hub') {
      await openCampaignHub({ persist: false });
      return;
    }
    /* A saved 'uga' scene does NOT override a door that asked for space.
       The ship interior is a UI mode, not a place in the galaxy: resuming into
       it is not the same as resuming a survey or a galaxy selection, which are
       positions the player navigated to and expects back. UGA COMMAND opens on
       the ship in space, every time, and the interior is one tap from there. */
    if (savedRoute.scene === 'uga') {
      setScene('system', { persist: false });
      return;
    }
    if (savedRoute.scene === 'galaxy') {
      openGalaxy({ persist: false });
      return;
    }
    if (savedRoute.scene === 'survey') {
      const system = SHOWCASE_SYSTEMS[savedRoute.systemId] || SHOWCASE_SYSTEMS.aelos;
      const planet = system.planets?.find(item => item.id === savedRoute.targetId) || system.planets?.[0];
      openSurvey(planet, { persist: false });
      return;
    }
    setScene('system', { persist: false });
  }

  function isLocalGroundSimulator() {
    // Diagnostic outcomes must never become player-facing mission actions.
    return ['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)
      && new URLSearchParams(location.search).get('localGroundSimulator') === '1'
      && host.kind === 'LocalSandboxHostV1' && host.productionIntegrated === false;
  }

  function isIntegratedGroundHost() {
    return host.productionIntegrated === true;
  }

  function groundOperationRequest(payload) {
    return {
      missionId: payload.missionId,
      proxyFactionId: payload.proxyFactionId || payload.factionId,
      commanderId: payload.commanderId,
      specialistIds: payload.specialistIds || payload.specialists,
      landingZoneId: payload.landingZoneId || payload.landingZone,
      supportId: payload.supportId || payload.support,
      doctrineId: payload.doctrineId || payload.doctrine,
      mapId: payload.mapId,
      deploymentManifest: payload.deploymentManifest
    };
  }

  function previewGroundOperation(payload) {
    return createGroundOperation(state, groundOperationRequest(payload));
  }

  function snapshotCarriesPendingOperation(snapshot, operation) {
    const pending = snapshot?.operations?.pending;
    return Boolean(pending && operation &&
      pending.operationId === operation.operationId &&
      pending.returnToken === operation.returnToken &&
      pending.missionId === operation.missionId &&
      snapshot.profileId === state.profileId);
  }

  async function persistHostSnapshotAndReadBack(snapshot, expectedOperation = null) {
    await Promise.resolve(host.saveCampaignSnapshot(snapshot));
    const restored = await Promise.resolve(host.loadCampaignSnapshot());
    const matches = expectedOperation
      ? snapshotCarriesPendingOperation(restored, expectedOperation)
      : restored?.profileId === snapshot.profileId && restored?.operations?.pending === null;
    if (!matches) {
      throw new Error(expectedOperation
        ? 'Launch stopped: the host could not prove the matching pending operation was saved.'
        : 'Abandonment stopped: the host could not prove the refunded operation state was saved.');
    }
    return restored;
  }

  async function launchOperation(payload) {
    const request = groundOperationRequest(payload);
    let started = null;
    let prepared = null;
    try {
      started = beginGroundOperation(state, request);
      prepared = await host.prepareGroundOperation(started.operation);
      if (!prepared?.accepted || !prepared.adapter) throw new Error('ExplorationHostV1 rejected the operation package or omitted its adapter identity.');
      commit(started.state, `operation:${started.operation.operationId}`);
      await persistHostSnapshotAndReadBack(state, started.operation);
      operationBridgeNonce = prepared.nonce || host.pendingNonce || null;
      if (isIntegratedGroundHost()) {
        if (prepared.productionIntegrated !== true || !prepared.launchUrl) throw new Error('Launch stopped: the integrated host did not provide a production ground-operation destination.');
        if (typeof host.openGroundOperation !== 'function') throw new Error('Launch stopped: the integrated host cannot open the prepared ground operation.');
        await Promise.resolve(host.openGroundOperation(prepared));
        return;
      }
      showOperation(started.operation, prepared);
    } catch (error) {
      const pendingSavedInMemory = started && snapshotCarriesPendingOperation(state, started.operation);
      if (prepared?.nonce && isIntegratedGroundHost() && !pendingSavedInMemory && typeof host.abandonGroundOperation === 'function') {
        try {
          await Promise.resolve(host.abandonGroundOperation(prepared.nonce));
        } catch (_) {
          // The launch error remains authoritative. A later host restore can
          // still find and abandon a durable mirror if best-effort cleanup fails.
        }
      }
      if (pendingSavedInMemory && isIntegratedGroundHost()) {
        showOperation(started.operation, prepared, { restored: true, error: issueText(error) });
      }
      showToast(issueText(error), true);
    }
  }

  function setOperationModalState(mode, result = null) {
    const modal = $('operationModal');
    modal.dataset.operationState = mode;
    modal.dataset.debriefState = mode === 'debrief' ? 'ready' : 'none';
    modal.dataset.tacticalRejection = mode === 'launch-rejected' ? 'true' : 'false';
    if (result?.resultId) modal.dataset.resultId = result.resultId;
    else delete modal.dataset.resultId;
    if (result?.outcome) modal.dataset.outcome = result.outcome;
    else delete modal.dataset.outcome;
    modal.dataset.exactlyOnce = mode === 'debrief' ? 'true' : 'false';
    const retry = $('btnRetryGroundOperation');
    if (retry) {
      /* A settled UGA report is immutable. Retry opens a new planner after
         debrief, where eligibility and cost are checked for a fresh ticket. */
      retry.hidden = !(mode === 'debrief' && result?.outcome === 'setback');
      retry.disabled = retry.hidden;
      if (retry.hidden) delete retry.dataset.missionId;
      else retry.dataset.missionId = result.missionId;
    }
  }

  function showOperation(operation, prepared = null, optionsArg = {}) {
    operationKind = 'ground';
    const mission = MISSION_CATALOG[operation.missionId];
    const localSimulator = isLocalGroundSimulator();
    const integrated = isIntegratedGroundHost();
    const restored = optionsArg.restored === true || (!prepared && integrated);
    const rejected = optionsArg.rejected === true;
    const modal = $('operationModal');
    operationBridgeNonce = prepared?.nonce || operationBridgeNonce || host.pendingNonce || null;
    setOperationModalState(rejected ? 'launch-rejected' : integrated ? 'awaiting-result' : 'simulator');
    modal.querySelector('.eyebrow').textContent = rejected
      ? 'GALACTIC OPERATIONS // TACTICAL RECOVERY'
      : integrated ? 'GALACTIC OPERATIONS // RECOVERY' : 'LOCAL GROUND-OPERATION ADAPTER';
    modal.classList.add('active');
    modal.setAttribute('aria-hidden', 'false');
    $('operationTitle').textContent = rejected ? `${mission.title} · LAUNCH REJECTED` : mission.title;
    $('operationSummary').textContent = optionsArg.error
      ? `${optionsArg.error} The operation remains safely pending; abandon it below to refund the deployment cost.`
      : rejected
        ? 'TACTICAL LAUNCH REJECTED OR EXPIRED. No result was accepted. Use ABANDON & REFUND to restore the deployment cost and return to Mission Operations.'
      : localSimulator
      ? `${FACTION_CATALOG[operation.proxyFactionId].name} deploys under UGA authority against ${FACTION_CATALOG[operation.opponentFactionId].name}. This is an explicitly local result simulator; its versioned package is stored behind an opaque nonce and never launches production MASSFRONT.`
      : restored
        ? `${FACTION_CATALOG[operation.proxyFactionId].name} has a saved operation with no accepted result. Abandon and refund this pending package to continue mission planning.`
        : `${FACTION_CATALOG[operation.proxyFactionId].name} deploys under UGA authority against ${FACTION_CATALOG[operation.opponentFactionId].name}. The package remains unresolved until a validated unique result is applied.`;
    const payload = $('operationPayload');
    delete payload.dataset.debriefResultId;
    delete payload.dataset.debriefOutcome;
    delete payload.dataset.debriefApplied;
    payload.textContent = JSON.stringify({
      operationId: operation.operationId,
      sponsor: operation.sponsorId,
      proxyFaction: operation.proxyFactionId,
      commander: operation.commanderId,
      specialists: operation.specialistIds,
      landingZone: operation.landingZoneId,
      support: operation.supportId,
      doctrine: operation.doctrineId,
      deploymentManifest: operation.deploymentManifest,
      intelligence: operation.intelligence,
      battlefield: operation.battlefield,
      returnRoute: operation.returnRoute,
      bridge: prepared ? {
        adapter: prepared.adapter,
        localOnly: prepared.localOnly === true,
        productionIntegrated: prepared.productionIntegrated === true,
        expiresAt: prepared.expiresAt
      } : null
    }, null, 2);
    $('btnSimVictory').hidden = !localSimulator;
    $('btnSimSetback').hidden = !localSimulator;
    $('btnCancelOperation').disabled = false;
    setButtonLabel($('btnCancelOperation'), integrated ? 'ABANDON & REFUND' : 'LEAVE UNRESOLVED');
  }

  function appendDebriefSection(target, title, rows) {
    const section = document.createElement('section');
    section.className = 'operation-debrief-section';
    const heading = document.createElement('h3');
    heading.textContent = title;
    section.appendChild(heading);
    const list = document.createElement('dl');
    for (const [label, value] of rows) {
      const group = document.createElement('div');
      const term = document.createElement('dt');
      const detail = document.createElement('dd');
      term.textContent = label;
      detail.textContent = value;
      group.append(term, detail);
      list.appendChild(group);
    }
    section.appendChild(list);
    target.appendChild(section);
  }

  function personnelDebriefRows(result) {
    const deltas = [result.personnelDelta?.commander, ...(result.personnelDelta?.specialists || [])].filter(Boolean);
    const rows = deltas.filter(delta => delta.injury).map(delta => {
      const definition = COMMANDER_CATALOG[delta.id] || SPECIALIST_CATALOG[delta.id];
      return [definition?.name || delta.id, `${String(delta.injury.severity).toUpperCase()} // ${delta.injury.recoveryCycles} RECOVERY CYCLE${delta.injury.recoveryCycles === 1 ? '' : 'S'}`];
    });
    if (!rows.length) rows.push(['Personnel', 'NO RECOVERY INJURIES']);
    rows.push(['Faction recovery', `${result.factionDelta?.recoveryCycles || 0} CYCLES`]);
    return rows;
  }

  function showDebrief(result, applied) {
    operationKind = 'debrief';
    operationBridgeNonce = null;
    const historyEntry = [...(state.operations?.history || [])].reverse().find(entry => entry?.result?.resultId === result.resultId);
    const operation = historyEntry?.operation;
    const mission = MISSION_CATALOG[result.missionId];
    const modal = $('operationModal');
    const payload = $('operationPayload');
    const location = operation?.battlefield?.location?.display;
    const locationLabel = location
      ? [location.planetName, location.areaName, location.mapName].filter(Boolean).join(' · ')
      : String(operation?.battlefield?.siteName || operation?.siteId || 'the operation area').replaceAll('_', ' ');
    setOperationModalState('debrief', result);
    modal.querySelector('.eyebrow').textContent = 'UGA MISSION OPERATIONS // DEBRIEF';
    modal.classList.add('active');
    modal.setAttribute('aria-hidden', 'false');
    $('operationTitle').textContent = `${mission?.title || result.missionId} · DEBRIEF`;
    $('operationSummary').textContent = `${FACTION_CATALOG[result.proxyFactionId]?.name || result.proxyFactionId} returned from ${locationLabel} with a ${String(result.outcome).toUpperCase()} result.`;
    payload.replaceChildren();
    payload.dataset.debriefResultId = result.resultId;
    payload.dataset.debriefOutcome = result.outcome;
    payload.dataset.debriefApplied = applied ? 'applied' : 'duplicate-ignored';
    const grid = document.createElement('div');
    grid.className = 'operation-debrief-grid';
    appendDebriefSection(grid, 'MISSION RESULT', [
      ['Outcome', String(result.outcome).toUpperCase()],
      ['Score', `${result.score} / 100`],
      ['Primary objective', result.primaryObjectiveComplete ? 'COMPLETE' : 'FAILED'],
      ['Secondary objectives', `${result.secondaryObjectivesComplete} / 3`]
    ]);
    const rewardRows = Object.entries(result.rewards || {}).filter(([, value]) => Number(value) !== 0)
      .map(([key, value]) => [key.replaceAll(/([A-Z])/g, ' $1').replaceAll('_', ' ').toUpperCase(), `+${Number(value).toLocaleString()}`]);
    rewardRows.push(['Faction reputation', `${result.factionDelta?.reputation >= 0 ? '+' : ''}${result.factionDelta?.reputation || 0}`]);
    appendDebriefSection(grid, 'REWARDS', rewardRows);
    appendDebriefSection(grid, 'INJURIES & RECOVERY', personnelDebriefRows(result));
    const world = result.worldDelta || {};
    appendDebriefSection(grid, 'WORLD EFFECT', [
      ['Front pressure', world.soloFrontPressure ? `${world.soloFrontPressure > 0 ? '+' : ''}${world.soloFrontPressure}` : 'NO CHANGE'],
      ['Infestation severity', world.infestationSeverity ? `${world.infestationSeverity > 0 ? '+' : ''}${world.infestationSeverity}` : 'NO CHANGE'],
      ['Hive targets purged', `${(world.hiveTargetsPurged || []).length}`],
      ['Infestation cleared', operation?.missionType === 'uga_brood_purge'
        ? (state.world.systems.karak.infestation.active ? 'NO' : 'YES') : 'N/A']
    ]);
    payload.appendChild(grid);
    $('btnSimVictory').hidden = true;
    $('btnSimSetback').hidden = true;
    $('btnCancelOperation').disabled = false;
    setButtonLabel($('btnCancelOperation'), 'RETURN TO SHIP · REVIEW EXPEDITION STORES');
  }

  function launchClassicSimulation(modeId, setup = {}) {
    const authoredSetup = setup && typeof setup === 'object' ? setup : {};
    if (!transact(current => simulateClassicModeLaunch(current, modeId, {
      ...authoredSetup,
      issuedFromSystemId: state.route.systemId,
      isolation: 'no-exploration-rewards',
      returnRoute: { scene: 'uga', systemId: state.route.systemId, districtId: 'command' }
    }), `classic:${modeId}`)) return;
    operationKind = 'classic';
    operationBridgeNonce = null;
    setOperationModalState('classic');
    $('operationModal').classList.add('active');
    $('operationModal').setAttribute('aria-hidden', 'false');
    $('operationModal').querySelector('.eyebrow').textContent = 'COMMAND CORE // ISOLATED SIMULATION';
    $('operationTitle').textContent = `${modeId.replaceAll('_', ' ').toUpperCase()} · SIMULATED LAUNCH`;
    $('operationSummary').textContent = 'Command Core sandbox only. This interactive setup does not open the production game or modify exploration rewards.';
    const payload = $('operationPayload');
    delete payload.dataset.debriefResultId;
    delete payload.dataset.debriefOutcome;
    delete payload.dataset.debriefApplied;
    payload.textContent = JSON.stringify(state.classicModes.lastSimulation, null, 2);
    $('btnSimVictory').hidden = true;
    $('btnSimSetback').hidden = true;
    $('btnCancelOperation').disabled = false;
    setButtonLabel($('btnCancelOperation'), 'RETURN TO COMMAND CORE');
  }

  async function resolvePending(outcome) {
    const operation = state.operations.pending;
    if (!operation) {
      showToast('NO PENDING OPERATION', true);
      return;
    }
    if (!isLocalGroundSimulator()) {
      showToast('LOCAL RESULT SIMULATOR DISABLED FOR NON-SANDBOX HOST', true);
      return;
    }
    const report = outcome === 'victory' ? {
      outcome: 'victory', score: 86, primaryObjectiveComplete: true,
      secondaryObjectivesComplete: 2, injuryBand: 'light', injuredPersonnelIds: [operation.specialistIds[0]]
    } : {
      outcome: 'setback', score: 29, primaryObjectiveComplete: false,
      secondaryObjectivesComplete: 0, injuryBand: 'severe', injuredPersonnelIds: [operation.commanderId, operation.specialistIds[0]]
    };
    try {
      const result = createGroundResult(operation, report);
      const consumed = await host.consumeGroundResult(result);
      if (consumed?.duplicate) showToast('DUPLICATE RESULT IGNORED');
    } catch (error) {
      showToast(issueText(error), true);
    }
  }

  function applyResult(result) {
    try {
      const applied = applyGroundResult(state, result);
      if (applied.applied) commit(applied.state, `result:${result.resultId}`);
      showDebrief(result, applied.applied);
      showToast(applied.applied ? `${result.outcome.toUpperCase()} · RESULT APPLIED ONCE` : 'DUPLICATE RESULT IGNORED');
    } catch (error) {
      showToast(issueText(error), true);
      // The host receipt may already be durable. Propagate application failure
      // so its recovery path can re-emit only while this campaign is pending.
      throw error;
    }
  }

  function closeOperationModal() {
    $('operationModal').classList.remove('active');
    $('operationModal').setAttribute('aria-hidden', 'true');
  }

  async function openMissionOperations() {
    await openUga();
    ugaUi.openView('contracts');
  }

  async function retryDebriefMission() {
    const retry = $('btnRetryGroundOperation');
    const missionId = retry?.dataset.missionId;
    if (operationKind !== 'debrief' || retry?.hidden || retry?.disabled || !MISSION_CATALOG[missionId]) return false;
    retry.disabled = true;
    try {
      await openUga('command');
      closeOperationModal();
      ugaUi.openMission(missionId);
      return true;
    } catch (error) {
      retry.disabled = false;
      showToast(issueText(error), true);
      return false;
    }
  }

  async function abandonIntegratedOperation() {
    const pending = state.operations.pending;
    if (!pending) {
      showToast('NO PENDING OPERATION TO ABANDON', true);
      return;
    }
    const button = $('btnCancelOperation');
    button.disabled = true;
    try {
      const cancelled = cancelGroundOperation(state, pending.operationId);
      await persistHostSnapshotAndReadBack(cancelled);
      commit(cancelled, `operation-abandon:${pending.operationId}`);
      let cleanupError = null;
      if (typeof host.abandonGroundOperation === 'function') {
        try {
          await Promise.resolve(host.abandonGroundOperation(operationBridgeNonce || undefined));
        } catch (error) {
          cleanupError = error;
        }
      }
      operationBridgeNonce = null;
      closeOperationModal();
      await openMissionOperations();
      showToast(cleanupError
        ? `DEPLOYMENT REFUNDED · BRIDGE CLEANUP WARNING: ${issueText(cleanupError)}`
        : 'OPERATION ABANDONED · DEPLOYMENT COST REFUNDED', Boolean(cleanupError));
    } catch (error) {
      button.disabled = false;
      showToast(issueText(error), true);
    }
  }

  async function handleOperationModalAction() {
    if (operationKind === 'debrief') {
      closeOperationModal();
      await openUga('command');
      ugaUi.openView('return-services');
      return;
    }
    if (operationKind === 'ground' && isIntegratedGroundHost()) {
      await abandonIntegratedOperation();
      return;
    }
    closeOperationModal();
    showToast(operationKind === 'ground' ? 'OPERATION REMAINS PENDING' : 'CLASSIC SIMULATION CLOSED');
  }

  function recoverGroundOperation(error) {
    const pending = state.operations?.pending;
    if (!pending || !isIntegratedGroundHost()) return false;
    showOperation(pending, null, { restored: true, rejected: true, error: issueText(error) });
    showToast('TACTICAL RESULT REJECTED · OPERATION REMAINS PENDING · REFUND AVAILABLE', true);
    return true;
  }

  if (typeof host.subscribeResult === 'function') {
    const unsubscribeResult = host.subscribeResult(applyResult);
    if (typeof unsubscribeResult === 'function') removers.push(unsubscribeResult);
  }

  function bindControls() {
    /* Every Galactic/room control enters through one shared effects bus. The
       first real tap also unlocks the standalone test-room fallback; integrated
       MASSFRONT delegates to the already-installed base bridge. */
    listen(frame, 'click', event => {
      if (event.target?.closest?.('button')) spaceAudio.play('click');
    });
    listen(window, STORY_TRANSMISSION_EVENT, event => storyTransmissions.receiveEvent(event));
    listen(window, KEEL_HINT_EVENT, event => {
      const surface = event.detail?.surface || '';
      if (surface && surface !== 'space-hud' && surface !== 'space-story-rail') return;
      storyTransmissions.receiveEvent(event);
    });
    // UGA COMMAND is the persistent strategic home, not a resume button for a
    // previously hidden ship inspector. Room art still streams only when the
    // player explicitly chooses a vessel/room action from that hub.
    /* Mail, social and settings exist in the base game and are already routable
       through openBaseRoute - the module simply never offered a way in, so a
       player in space could not reach their inbox without leaving the module
       entirely. These open the real base screens rather than module copies;
       duplicating them here would be two implementations of one feature. When
       there is no host (standalone module) the controls are hidden rather than
       dead, matching how host-owned routes are handled everywhere else. */
    const hostChrome = typeof host.openBaseRoute === 'function';
    const openHostChrome = routeId => host.openBaseRoute(routeId, {
      systemId: state.route.systemId,
      targetId: selectedTarget?.id || state.route.targetId || null
    });
    for (const [id, routeId] of [['btnSpaceInbox', 'inbox'], ['btnSpaceSocial', 'social'], ['btnSpaceSettings', 'settings']]) {
      const button = $(id);
      if (!button) continue;
      if (!hostChrome) { button.hidden = true; continue; }
      listen(button, 'click', () => { openHostChrome(routeId); });
    }
    listen($('btnUgaCommand'), 'click', () => openCampaignHub());
    listen($('btnGalaxyMap'), 'click', openGalaxy);
    listen($('btnAutopilotMap'), 'click', openGalaxy);
    listen($('btnAutopilotHold'), 'click', () => {
      physics.stop();
      showToast('AUTOPILOT HOLDING ORBIT');
    });
    listen($('btnCloseGalaxy'), 'click', openSystem);
    listen($('galaxyJumpBtn'), 'click', () => beginTransit(selectedGalaxyId));
    listen($('galaxyOperations'), 'click', selectGalaxyOperation);
    listen($('galaxyScanBtn'), 'click', openGalaxyRecon);
    listen($('galaxyLoadoutBtn'), 'click', () => openGalaxyLoadout());
    listen($('galaxyFlagshipBtn'), 'click', () => openGalaxyFlagship());
    listen($('btnCloseSurvey'), 'click', openSystem);
    listen($('btnSurveyLaunchProbe'), 'click', launchProbe);
    listen($('surveyNextAction'), 'click', () => followSurveyNextAction());
    listen($('surveyContinueScan'), 'click', clearSurveyResult);
    listen($('surveyPlanetSelector'), 'click', selectSurveyPlanet);
    listen($('btnExitUga'), 'click', openSystem);
    listen($('btnUgaOverview'), 'click', () => {
      requestUgaVisual();
      commandScene.focusOverview();
      ugaUi.selectDistrict('command', { emit: false });
    });
    listen($('actAlign'), 'click', () => selectedTarget && physics.alignTo(selectedTarget.x || 0, selectedTarget.y || 0, selectedTarget.z || 0));
    listen($('actWarp'), 'click', () => {
      if (!selectedTarget) return;
      if (selectedTarget.jumpTo) beginTransit(selectedTarget.jumpTo);
      else physics.startWarp(selectedTarget);
    });
    // Do not pass the PointerEvent as a planet override. That produced an
    // object with no id and attempted to stream `undefined-*.png` PBR maps.
    listen($('actSurvey'), 'click', () => openSurvey());
    listen($('actInteract'), 'click', () => {
      if (!selectedTarget) return;
      if (selectedTarget.kind === 'uga-ship' || selectedTarget.interaction === 'uga-command') openUga();
      else if (selectedTarget.interaction === 'faction-residency') openUga('factions');
      else if (selectedTarget.interaction === 'logistics') openUga('logistics');
      else if (selectedTarget.jumpTo) beginTransit(selectedTarget.jumpTo);
      else if ((SHOWCASE_SYSTEMS[state.route.systemId] || SHOWCASE_SYSTEMS.aelos).planets?.some(planet => planet.id === selectedTarget.id)) openSurvey();
      else if (getContactSalvage(selectedTarget.id)) {
        const salvageId = selectedTarget.id;
        const boarding = getWreckBoarding(salvageId);
        if (boarding && !state.discoveries.extractedDepositIds.includes(salvageId)) {
          /* Interior X-S is a reserved theatre: the boarding area is authored
             and the wreck interior can be reviewed, but the small-unit battle
             runtime does not exist yet. The hull still pays its one-time
             salvage, so the approach is never a dead end. */
          showToast(`BOARDING AREA AUTHORED · ${boarding.name.toUpperCase()} · ${boarding.templateId.replaceAll('_', ' ').toUpperCase()} · INTERIOR BATTLE RUNTIME PENDING`);
          const result = recoverContactSalvage(state, salvageId);
          commit(result.state, `salvage:${salvageId}`);
          showToast(`SALVAGE RECOVERED: ${result.salvage.name.toUpperCase()} · ${resourceSummary(result.rewards)}`);
          refreshAll();
          return;
        }
        if (state.discoveries.extractedDepositIds.includes(salvageId)) {
          showToast(boarding
            ? `BOARDING AREA: ${boarding.name.toUpperCase()} · ${boarding.sizeClass} ${boarding.envelope.replaceAll('_', ' ').toUpperCase()} · AWAITING INTERIOR BATTLE RUNTIME`
            : 'THIS WRECK HAS ALREADY BEEN STRIPPED');
          return;
        }
        try {
          const result = recoverContactSalvage(state, salvageId);
          commit(result.state, `salvage:${salvageId}`);
          showToast(`SALVAGE RECOVERED: ${result.salvage.name.toUpperCase()} · ${resourceSummary(result.rewards)}`);
          refreshAll();
        } catch (error) {
          showToast(issueText(error), true);
        }
      }
      else showToast('CONTACT INTELLIGENCE ARCHIVED');
    });
    listen($('btnToggleFullscreen'), 'click', () => {
      frame.classList.toggle('fullscreen');
      resize();
    });
    listen($('btnRecenterView'), 'click', () => {
      Object.assign(camState, navCameraDefault);
      showToast('NAVIGATION CAMERA RECENTERED');
    });
    listen($('btnResetRoom'), 'click', () => {
      state = store.reset();
      loadSystem('aelos');
      openSystem();
      showToast('ISOLATED TEST ROOM RESET');
    });
    listen($('btnSimVictory'), 'click', () => resolvePending('victory'));
    listen($('btnSimSetback'), 'click', () => resolvePending('setback'));
    listen($('btnRetryGroundOperation'), 'click', () => retryDebriefMission());
    listen($('btnCancelOperation'), 'click', () => handleOperationModalAction());

    const canvas = engine.renderer.domElement;
    listen(canvas, 'pointerdown', event => {
      if (sceneMode === 'galaxy') return;
      if (sceneMode === 'system') {
        navPointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
        if (navPointers.size > 1) {
          const points = [...navPointers.values()];
          pinchGap = Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
          pointer.moved = true;
          return;
        }
      }
      pointer.active = true;
      pointer.id = event.pointerId;
      pointer.x = pointer.lastX = event.clientX;
      pointer.y = pointer.lastY = event.clientY;
      pointer.moved = false;
    });
    listen(window, 'pointermove', event => {
      if (!pointer.active || sceneMode !== 'system') return;
      if (navPointers.has(event.pointerId)) navPointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
      if (navPointers.size > 1) {
        const points = [...navPointers.values()];
        const nextGap = Math.max(12, Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y));
        if (pinchGap > 0) camState.dist = Math.max(NAV_CAM_MIN_DIST, Math.min(NAV_CAM_MAX_DIST, camState.dist * pinchGap / nextGap));
        pinchGap = nextGap;
        pointer.moved = true;
        return;
      }
      if (pointer.id !== event.pointerId) return;
      const dx = event.clientX - pointer.lastX;
      const dy = event.clientY - pointer.lastY;
      if (Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) > 5) pointer.moved = true;
      if (pointer.moved) {
        /* Top-down RTS convention: dragging moves the map under the finger
           (pan), it does not orbit the camera. Spinning a north-up chart
           scrambles the mental compass that is the whole point of the view.
           Drag down = look further down-chart, like every mobile RTS map.
           Speed tracks the camera's altitude over the chart — the zoom rig
           sits at 90 + dist*170 world units, and a 40° FOV puts roughly
           (0.16 + dist*0.18) world units under one CSS pixel — so the map
           moves 1:1 with the finger at every zoom level. */
        const panScale = 0.16 + camState.dist * 0.18;
        camState.panX -= (dx * Math.cos(camState.yaw) - dy * Math.sin(camState.yaw)) * panScale;
        camState.panZ += (dx * Math.sin(camState.yaw) + dy * Math.cos(camState.yaw)) * panScale;
      }
      pointer.lastX = event.clientX;
      pointer.lastY = event.clientY;
    });
    listen(window, 'pointerup', event => {
      if (!pointer.active) return;
      navPointers.delete(event.pointerId);
      if (navPointers.size) {
        const [id, position] = navPointers.entries().next().value;
        pointer.id = id;
        pointer.x = pointer.lastX = position.x;
        pointer.y = pointer.lastY = position.y;
        pointer.moved = true;
        pinchGap = 0;
        return;
      }
      const wasMoved = pointer.moved;
      pointer.active = false;
      pointer.id = null;
      pinchGap = 0;
      if (wasMoved) return;
      if (sceneMode === 'uga') {
        const rect = engine.renderer.domElement.getBoundingClientRect();
        if (!deploymentArena?.pick(event.clientX, event.clientY, rect)) commandScene.pick(event.clientX, event.clientY, rect);
      }
      else if (sceneMode === 'system') pickArk(event.clientX, event.clientY);
    });
    listen(window, 'pointercancel', event => {
      navPointers.delete(event.pointerId);
      if (!navPointers.size) {
        pointer.active = false;
        pointer.id = null;
        pinchGap = 0;
      }
    });
    listen(canvas, 'wheel', event => {
      if (sceneMode !== 'system') return;
      if (event.cancelable) event.preventDefault();
      camState.dist = Math.max(NAV_CAM_MIN_DIST, Math.min(NAV_CAM_MAX_DIST, camState.dist + event.deltaY * 0.0015));
    }, { passive: false });

    bindAutopilotDock();
    listen(window, 'resize', resize);
  }

  function bindAutopilotDock() {
    listen(window, 'keydown', event => {
      if (event.key === 'Escape' && sceneMode === 'system') physics.stop();
      /* Chart panning without touching the canvas: arrows/WASD slide the
         look-at target while the compass stays north-up. */
      const panStep = {
        ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1],
        KeyA: [-1, 0], KeyD: [1, 0], KeyW: [0, -1], KeyS: [0, 1]
      }[event.code];
      if (panStep && sceneMode === 'system') {
        camState.panX += panStep[0] * 26;
        camState.panZ += panStep[1] * 26;
      }
    });
    pollKeyboard = () => physics.setJoystick(false, 0, 0);
  }

  let pollKeyboard = () => {};

  function resize() {
    if (disposed) return;
    const rect = frame.getBoundingClientRect();
    const width = Math.max(1, rect.width || window.innerWidth);
    const height = Math.max(1, rect.height || window.innerHeight);
    engine.resize(width, height);
    commandScene.resize(width, height);
    if (galaxyMap) galaxyMap.resize(width, height);
    if (planetarySurvey && planetarySurvey.active) planetarySurvey.resize(width, height);
  }

  function updateTelemetry() {
    $('telemSpeed').textContent = `${Math.round(physics.ship.speed)} m/s`;
    const degrees = (physics.ship.yaw * 180 / Math.PI + 360) % 360;
    $('telemHeading').textContent = `${String(Math.round(degrees)).padStart(3, '0')}°`;
    $('telemSystemStatus').textContent = physics.ship.warpState > 0 ? 'TRANSIT' : 'READY';
  }

  function loop(now) {
    raf = 0;
    if (disposed || paused || contextRecovering || engine.contextLost) return;
    const dt = Math.min(0.1, Math.max(0, (now - lastTime) / 1000));
    lastTime = now;
    if (sceneMode === 'system') {
      pollKeyboard();
      physics.update(dt);
      engine.update(dt, now, physics.ship, camState);
      const bodies = engine.getProjectedBodies();
      if (engine.currentSystem) hud.updateCallouts({
        ...engine.currentSystem,
        planets: bodies.planets,
        contacts: bodies.contacts
      }, engine, physics.ship);
      updateTelemetry();
    } else if (sceneMode === 'survey') {
      if (planetarySurvey && planetarySurvey.active) {
        planetarySurvey.update(dt);
      }
    } else if (sceneMode === 'uga') {
      deploymentArena?.update(dt, now);
      commandScene.update(dt, now);
      commandScene.render();
    } else if (sceneMode === 'galaxy' && galaxyMap) {
      galaxyMap.renderFrame(now);
    }
    scheduleFrame();
  }

  function scheduleFrame() {
    if (disposed || paused || contextRecovering || engine.contextLost || raf) return;
    raf = requestAnimationFrame(loop);
  }

  function pause() {
    if (disposed || paused) return;
    paused = true;
    stopSurveyScanner();
    if (raf) cancelAnimationFrame(raf);
    raf = 0;
    engine.pause();
    if (galaxyMap) galaxyMap.pause();
  }

  function resume() {
    if (disposed || !paused) return;
    paused = false;
    lastTime = performance.now();
    if (!contextRecovering && (sceneMode === 'system' || sceneMode === 'survey')) engine.resume();
    if (!contextRecovering && galaxyMap) galaxyMap.resume();
    if (sceneMode === 'survey') initSurveyScanner();
    scheduleFrame();
  }

  function dispose() {
    if (disposed) return;
    disposed = true;
    stopSurveyScanner();
    if (raf) cancelAnimationFrame(raf);
    raf = 0;
    clearTimeout(toastTimer);
    clearTimeout(transitTimer);
    clearTimeout(contextRestoreTimer);
    clearTimeout(startupTimer);
    for (const remove of removers.splice(0)) {
      try { remove(); } catch (_) {}
    }
    planetarySurvey?.dispose();
    planetarySurvey = null;
    activeSurveyPlanet = null;
    $('surveyPlanetSelector')?.replaceChildren();
    destroyGalaxyMap();
    storyTransmissions.destroy();
    spaceAudio.dispose();
    ugaUi.destroy();
    deploymentArena?.dispose();
    deploymentArena = null;
    hud.dispose();
    commandScene.dispose();
    engine.dispose();
    if (!options.host && typeof host.dispose === 'function') host.dispose();
    if (frame[SPACE_INSTANCE_KEY] === api) delete frame[SPACE_INSTANCE_KEY];
  }

  bindControls();
  /* Campaign Hub entry is a strategic DOM surface. Starting six PBR decodes
     per planet plus the authored contact pack here made its first tap inherit
     the entire exterior boot even though no orbital pixels were visible. */
  if (initialEntryView !== 'campaign_hub') loadSystem(savedRoute.systemId);
  resize();
  refreshAll();
  selectTarget(arkTarget(), { persist: false });

  if (exteriorRequired) {
    startupTimer = window.setTimeout(() => {
      if (disposed || assetsReady) return;
      startupTimedOut = true;
      pause();
      setRenderVeil(
        frame,
        'failed',
        'EXPEDITION DOWNLOAD TIMED OUT',
        'THE AUTHORED PACKAGE DID NOT FINISH WITHIN 90 SECONDS · CHECK SIGNAL AND RETRY',
        true
      );
    }, 90000);
  }

  const exteriorReady = engine.ready().then(async ark => {
    clearTimeout(startupTimer);
    startupTimer = 0;
    if (startupTimedOut) throw new Error('Expedition startup exceeded the 90 second mobile loading limit.');
    if (!ark) {
      if (exteriorRequired) throw new Error('The authored NEXUS-VII exterior GLB did not load.');
      frame.dataset.exteriorVisualState = 'failed';
    } else {
      assetsReady = true;
      frame.dataset.exteriorVisualState = 'ready';
      setLoadingProgress(frame, {
        percent: 100,
        stage: 'EXPEDITION READY',
        detail: initialEntryView === 'campaign_hub'
          ? 'GALACTIC COMMAND ONLINE · SHIP VISUALS LOAD ON DEMAND'
          : 'AELOS NAVIGATION AND UGA COMMAND ONLINE'
      });
      for (const [id, district] of Object.entries(state.ship.districts)) commandScene.setDistrictLevel(id, district.level);
    }
    if (exteriorRequired) await restoreSavedLocation();
    if (!contextRecovering && (assetsReady || !exteriorRequired)) setRenderVeil(frame, 'ready');
    presentPendingOperation();
    return ark;
  }).catch(error => {
    clearTimeout(startupTimer);
    startupTimer = 0;
    if (!exteriorRequired) {
      frame.dataset.exteriorVisualState = 'failed';
      if (!contextRecovering && sceneMode === 'uga') setRenderVeil(frame, 'ready');
      console.warn('[MASSFRONT UGA OPTIONAL EXTERIOR]', error);
      return null;
    }
    pause();
    setRenderVeil(
      frame,
      'failed',
      'AUTHORED ASSET LOAD FAILED',
      `THE AUTHORED EXPLORATION PACKAGE COULD NOT LOAD · ${error.message}`.toUpperCase(),
      true
    );
    throw error;
  });
  /* Campaign Hub readiness means its required state and controls survived one
     paint. The exterior promise remains observed in the background, but it is
     not the readiness owner and cannot later replace this usable home with a
     fatal loader. System entry still requires the authored exterior exactly as
     before. */
  const ready = campaignHubReady ? campaignHubReady.then(() => api) : exteriorReady.then(() => api);

  const api = {
    ready,
    pause,
    resume,
    dispose,
    getState: () => store.getState(),
    get disposed() { return disposed; },
    get recovering() { return contextRecovering; },
    get scene() { return sceneMode; },
    get engine() { return engine; },
    get audio() { return spaceAudio; },
    get commandScene() { return commandScene; },
    get deploymentArena() { return deploymentArena; },
    get planetarySurvey() { return planetarySurvey; },
    get transmissions() { return storyTransmissions; },
    get firstEntryIntro() {
      return {
        started: firstEntryIntroStarted,
        choice: firstEntryChoice,
        choicePending: firstEntryChoicePending,
        continuation: SPACE_FIRST_ENTRY_CONTINUATION
      };
    },
    previewGroundOperation,
    recoverGroundOperation,
    get galaxyMap() { return galaxyMap; },
    openUga,
    openCampaignHub,
    openGalaxy,
    openSurvey,
    openSystem,
    startFirstEntryIntro
  };
  frame[SPACE_INSTANCE_KEY] = api;
  scheduleFrame();
  return api;
}